{"version":3,"file":"index-Bu6_b9Ic.js","sources":["../../node_modules/react/cjs/react.production.min.js","../../node_modules/react/index.js","../../node_modules/react/cjs/react-jsx-runtime.production.min.js","../../node_modules/react/jsx-runtime.js","../../node_modules/@sentry/core/build/esm/debug-build.js","../../node_modules/@sentry/core/build/esm/utils-hoist/worldwide.js","../../node_modules/@sentry/core/build/esm/utils-hoist/debug-build.js","../../node_modules/@sentry/core/build/esm/utils-hoist/version.js","../../node_modules/@sentry/core/build/esm/carrier.js","../../node_modules/@sentry/core/build/esm/utils-hoist/logger.js","../../node_modules/@sentry/core/build/esm/utils-hoist/stacktrace.js","../../node_modules/@sentry/core/build/esm/utils-hoist/instrument/handlers.js","../../node_modules/@sentry/core/build/esm/utils-hoist/instrument/globalError.js","../../node_modules/@sentry/core/build/esm/utils-hoist/instrument/globalUnhandledRejection.js","../../node_modules/@sentry/core/build/esm/utils-hoist/is.js","../../node_modules/@sentry/core/build/esm/utils-hoist/browser.js","../../node_modules/@sentry/core/build/esm/utils-hoist/string.js","../../node_modules/@sentry/core/build/esm/utils-hoist/object.js","../../node_modules/@sentry/core/build/esm/utils-hoist/time.js","../../node_modules/@sentry/core/build/esm/utils-hoist/misc.js","../../node_modules/@sentry/core/build/esm/utils-hoist/syncpromise.js","../../node_modules/@sentry/core/build/esm/session.js","../../node_modules/@sentry/core/build/esm/utils-hoist/propagationContext.js","../../node_modules/@sentry/core/build/esm/utils/merge.js","../../node_modules/@sentry/core/build/esm/utils/spanOnScope.js","../../node_modules/@sentry/core/build/esm/scope.js","../../node_modules/@sentry/core/build/esm/defaultScopes.js","../../node_modules/@sentry/core/build/esm/asyncContext/stackStrategy.js","../../node_modules/@sentry/core/build/esm/asyncContext/index.js","../../node_modules/@sentry/core/build/esm/currentScopes.js","../../node_modules/@sentry/core/build/esm/semanticAttributes.js","../../node_modules/@sentry/core/build/esm/tracing/spanstatus.js","../../node_modules/@sentry/core/build/esm/tracing/utils.js","../../node_modules/@sentry/core/build/esm/utils/parseSampleRate.js","../../node_modules/@sentry/core/build/esm/utils-hoist/baggage.js","../../node_modules/@sentry/core/build/esm/utils-hoist/tracing.js","../../node_modules/@sentry/core/build/esm/utils/spanUtils.js","../../node_modules/@sentry/core/build/esm/tracing/errors.js","../../node_modules/@sentry/core/build/esm/utils/hasSpansEnabled.js","../../node_modules/@sentry/core/build/esm/constants.js","../../node_modules/@sentry/core/build/esm/tracing/dynamicSamplingContext.js","../../node_modules/@sentry/core/build/esm/tracing/sentryNonRecordingSpan.js","../../node_modules/@sentry/core/build/esm/tracing/logSpans.js","../../node_modules/@sentry/core/build/esm/tracing/sampling.js","../../node_modules/@sentry/core/build/esm/utils-hoist/dsn.js","../../node_modules/@sentry/core/build/esm/utils-hoist/normalize.js","../../node_modules/@sentry/core/build/esm/utils-hoist/envelope.js","../../node_modules/@sentry/core/build/esm/envelope.js","../../node_modules/@sentry/core/build/esm/tracing/measurement.js","../../node_modules/@sentry/core/build/esm/tracing/sentrySpan.js","../../node_modules/@sentry/core/build/esm/tracing/trace.js","../../node_modules/@sentry/core/build/esm/tracing/idleSpan.js","../../node_modules/@sentry/core/build/esm/eventProcessors.js","../../node_modules/@sentry/core/build/esm/utils-hoist/debug-ids.js","../../node_modules/@sentry/core/build/esm/utils/applyScopeDataToEvent.js","../../node_modules/@sentry/core/build/esm/utils/prepareEvent.js","../../node_modules/@sentry/core/build/esm/exports.js","../../node_modules/@sentry/core/build/esm/api.js","../../node_modules/@sentry/core/build/esm/integration.js","../../node_modules/@sentry/core/build/esm/utils-hoist/clientreport.js","../../node_modules/@sentry/core/build/esm/utils-hoist/error.js","../../node_modules/@sentry/core/build/esm/utils/eventUtils.js","../../node_modules/@sentry/core/build/esm/utils/transactionEvent.js","../../node_modules/@sentry/core/build/esm/client.js","../../node_modules/@sentry/core/build/esm/sdk.js","../../node_modules/@sentry/core/build/esm/utils-hoist/promisebuffer.js","../../node_modules/@sentry/core/build/esm/utils-hoist/ratelimit.js","../../node_modules/@sentry/core/build/esm/transports/base.js","../../node_modules/@sentry/core/build/esm/utils/isSentryRequestUrl.js","../../node_modules/@sentry/core/build/esm/utils/ipAddress.js","../../node_modules/@sentry/core/build/esm/utils/sdkMetadata.js","../../node_modules/@sentry/core/build/esm/utils/traceData.js","../../node_modules/@sentry/core/build/esm/breadcrumbs.js","../../node_modules/@sentry/core/build/esm/integrations/functiontostring.js","../../node_modules/@sentry/core/build/esm/integrations/inboundfilters.js","../../node_modules/@sentry/core/build/esm/utils-hoist/aggregate-errors.js","../../node_modules/@sentry/core/build/esm/utils-hoist/instrument/console.js","../../node_modules/@sentry/core/build/esm/utils-hoist/severity.js","../../node_modules/@sentry/core/build/esm/integrations/dedupe.js","../../node_modules/@sentry/core/build/esm/utils-hoist/url.js","../../node_modules/@sentry/core/build/esm/fetch.js","../../node_modules/@sentry/core/build/esm/utils-hoist/breadcrumb-log-level.js","../../node_modules/@sentry/core/build/esm/utils-hoist/supports.js","../../node_modules/@sentry/core/build/esm/utils-hoist/instrument/fetch.js","../../node_modules/@sentry/core/build/esm/utils-hoist/env.js","../../node_modules/@sentry/core/build/esm/utils-hoist/node.js","../../node_modules/@sentry/core/build/esm/utils-hoist/isBrowser.js","../../node_modules/@sentry/browser/build/npm/esm/helpers.js","../../node_modules/@sentry/browser/build/npm/esm/eventbuilder.js","../../node_modules/@sentry/browser/build/npm/esm/client.js","../../node_modules/@sentry-internal/browser-utils/build/esm/debug-build.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/bindReporter.js","../../node_modules/@sentry-internal/browser-utils/build/esm/types.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/generateUniqueID.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/getNavigationEntry.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/getActivationStart.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/initMetric.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/observe.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/onHidden.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/runOnce.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/getVisibilityWatcher.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/whenActivated.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/onFCP.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getCLS.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getFID.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/polyfills/interactionCountPolyfill.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/interactions.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/lib/whenIdle.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getINP.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/getLCP.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/web-vitals/onTTFB.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/instrument.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/utils.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/cls.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/browserMetrics.js","../../node_modules/@sentry-internal/browser-utils/build/esm/instrument/dom.js","../../node_modules/@sentry-internal/browser-utils/build/esm/instrument/history.js","../../node_modules/@sentry-internal/browser-utils/build/esm/getNativeImplementation.js","../../node_modules/@sentry-internal/browser-utils/build/esm/instrument/xhr.js","../../node_modules/@sentry-internal/browser-utils/build/esm/networkUtils.js","../../node_modules/@sentry-internal/browser-utils/build/esm/metrics/inp.js","../../node_modules/@sentry/browser/build/npm/esm/transports/fetch.js","../../node_modules/@sentry/browser/build/npm/esm/stack-parsers.js","../../node_modules/@sentry/browser/build/npm/esm/debug-build.js","../../node_modules/@sentry/browser/build/npm/esm/integrations/breadcrumbs.js","../../node_modules/@sentry/browser/build/npm/esm/integrations/browserapierrors.js","../../node_modules/@sentry/browser/build/npm/esm/integrations/browsersession.js","../../node_modules/@sentry/browser/build/npm/esm/integrations/globalhandlers.js","../../node_modules/@sentry/browser/build/npm/esm/integrations/httpcontext.js","../../node_modules/@sentry/browser/build/npm/esm/integrations/linkederrors.js","../../node_modules/@sentry/browser/build/npm/esm/sdk.js","../../node_modules/@sentry-internal/replay/build/npm/esm/index.js","../../node_modules/@sentry/browser/build/npm/esm/tracing/request.js","../../node_modules/@sentry/browser/build/npm/esm/tracing/backgroundtab.js","../../node_modules/@sentry/browser/build/npm/esm/tracing/browserTracingIntegration.js","../../node_modules/@sentry/react/build/esm/sdk.js","../../node_modules/hoist-non-react-statics/node_modules/react-is/cjs/react-is.production.min.js","../../node_modules/hoist-non-react-statics/node_modules/react-is/index.js","../../node_modules/hoist-non-react-statics/dist/hoist-non-react-statics.cjs.js","../../node_modules/@aws-amplify/core/dist/esm/constants.mjs","../../node_modules/@aws-amplify/core/dist/esm/Logger/types.mjs","../../node_modules/@aws-amplify/core/dist/esm/Logger/ConsoleLogger.mjs","../../node_modules/@aws-amplify/core/dist/esm/errors/AmplifyError.mjs","../../node_modules/@aws-amplify/core/dist/esm/types/errors.mjs","../../node_modules/@aws-amplify/core/dist/esm/errors/createAssertionFunction.mjs","../../node_modules/@aws-amplify/core/dist/esm/Hub/index.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/globalHelpers/index.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/convert/base64/base64Decoder.mjs","../../node_modules/@aws-amplify/core/dist/esm/singleton/Auth/utils/errorHelpers.mjs","../../node_modules/@aws-amplify/core/dist/esm/singleton/Auth/utils/index.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/retry/isNonRetryableError.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/retry/retry.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/deepFreeze.mjs","../../node_modules/@aws-amplify/core/dist/esm/parseAWSExports.mjs","../../node_modules/@aws-amplify/core/dist/esm/singleton/constants.mjs","../../node_modules/uuid/dist/esm-browser/rng.js","../../node_modules/uuid/dist/esm-browser/stringify.js","../../node_modules/uuid/dist/esm-browser/native.js","../../node_modules/uuid/dist/esm-browser/v4.js","../../node_modules/@aws-amplify/core/dist/esm/parseAmplifyOutputs.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/parseAmplifyConfig.mjs","../../node_modules/tslib/tslib.es6.mjs","../../node_modules/@aws-crypto/sha256-js/build/module/constants.js","../../node_modules/@aws-crypto/sha256-js/build/module/RawSha256.js","../../node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js","../../node_modules/@aws-crypto/util/build/module/convertToBuffer.js","../../node_modules/@aws-crypto/util/build/module/isEmptyData.js","../../node_modules/@aws-crypto/util/build/module/numToUint8.js","../../node_modules/@aws-crypto/util/build/module/uint32ArrayFrom.js","../../node_modules/@aws-crypto/sha256-js/build/module/jsSha256.js","../../node_modules/@smithy/util-hex-encoding/dist-es/index.js","../../node_modules/@aws-amplify/core/dist/esm/Platform/types.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/version.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/detection/helpers.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/detection/React.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Vue.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Svelte.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Next.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Nuxt.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Angular.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/detection/ReactNative.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Expo.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/detection/Web.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/detection/index.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/detectFramework.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/customUserAgent.mjs","../../node_modules/@aws-amplify/core/dist/esm/Platform/index.mjs","../../node_modules/@aws-amplify/core/dist/esm/BackgroundProcessManager/types.mjs","../../node_modules/rxjs/dist/esm5/internal/util/isFunction.js","../../node_modules/rxjs/dist/esm5/internal/util/createErrorClass.js","../../node_modules/rxjs/dist/esm5/internal/util/UnsubscriptionError.js","../../node_modules/rxjs/dist/esm5/internal/util/arrRemove.js","../../node_modules/rxjs/dist/esm5/internal/Subscription.js","../../node_modules/rxjs/dist/esm5/internal/config.js","../../node_modules/rxjs/dist/esm5/internal/scheduler/timeoutProvider.js","../../node_modules/rxjs/dist/esm5/internal/util/reportUnhandledError.js","../../node_modules/rxjs/dist/esm5/internal/util/noop.js","../../node_modules/rxjs/dist/esm5/internal/util/errorContext.js","../../node_modules/rxjs/dist/esm5/internal/Subscriber.js","../../node_modules/rxjs/dist/esm5/internal/symbol/observable.js","../../node_modules/rxjs/dist/esm5/internal/util/identity.js","../../node_modules/rxjs/dist/esm5/internal/util/pipe.js","../../node_modules/rxjs/dist/esm5/internal/Observable.js","../../node_modules/rxjs/dist/esm5/internal/util/lift.js","../../node_modules/rxjs/dist/esm5/internal/operators/OperatorSubscriber.js","../../node_modules/rxjs/dist/esm5/internal/util/ObjectUnsubscribedError.js","../../node_modules/rxjs/dist/esm5/internal/Subject.js","../../node_modules/rxjs/dist/esm5/internal/util/isScheduler.js","../../node_modules/rxjs/dist/esm5/internal/util/args.js","../../node_modules/rxjs/dist/esm5/internal/util/isArrayLike.js","../../node_modules/rxjs/dist/esm5/internal/util/isPromise.js","../../node_modules/rxjs/dist/esm5/internal/util/isInteropObservable.js","../../node_modules/rxjs/dist/esm5/internal/util/isAsyncIterable.js","../../node_modules/rxjs/dist/esm5/internal/util/throwUnobservableError.js","../../node_modules/rxjs/dist/esm5/internal/symbol/iterator.js","../../node_modules/rxjs/dist/esm5/internal/util/isIterable.js","../../node_modules/rxjs/dist/esm5/internal/util/isReadableStreamLike.js","../../node_modules/rxjs/dist/esm5/internal/observable/innerFrom.js","../../node_modules/rxjs/dist/esm5/internal/util/executeSchedule.js","../../node_modules/rxjs/dist/esm5/internal/operators/observeOn.js","../../node_modules/rxjs/dist/esm5/internal/operators/subscribeOn.js","../../node_modules/rxjs/dist/esm5/internal/scheduled/scheduleObservable.js","../../node_modules/rxjs/dist/esm5/internal/scheduled/schedulePromise.js","../../node_modules/rxjs/dist/esm5/internal/scheduled/scheduleArray.js","../../node_modules/rxjs/dist/esm5/internal/scheduled/scheduleIterable.js","../../node_modules/rxjs/dist/esm5/internal/scheduled/scheduleAsyncIterable.js","../../node_modules/rxjs/dist/esm5/internal/scheduled/scheduleReadableStreamLike.js","../../node_modules/rxjs/dist/esm5/internal/scheduled/scheduled.js","../../node_modules/rxjs/dist/esm5/internal/observable/from.js","../../node_modules/rxjs/dist/esm5/internal/observable/of.js","../../node_modules/rxjs/dist/esm5/internal/operators/map.js","../../node_modules/rxjs/dist/esm5/internal/operators/filter.js","../../node_modules/rxjs/dist/esm5/internal/operators/catchError.js","../../node_modules/@aws-amplify/core/dist/esm/utils/isWebWorker.mjs","../../node_modules/@aws-amplify/core/dist/esm/Reachability/Reachability.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/isBrowser.mjs","../../node_modules/@aws-amplify/core/dist/esm/singleton/Auth/index.mjs","../../node_modules/@aws-amplify/core/dist/esm/singleton/Amplify.mjs","../../node_modules/@aws-amplify/core/dist/esm/singleton/apis/internal/fetchAuthSession.mjs","../../node_modules/@aws-amplify/core/dist/esm/singleton/apis/fetchAuthSession.mjs","../../node_modules/@aws-amplify/core/dist/esm/singleton/apis/clearCredentials.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/serde/responseInfo.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/serde/json.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/internal/composeServiceApi.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/endpoints/partitions.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/endpoints/getDnsSuffix.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/retry/middleware.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/userAgent/middleware.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/internal/composeTransferHandler.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/utils/memoization.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/handlers/fetch.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/handlers/unauthenticated.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/retry/constants.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/retry/jitteredBackoff.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/retry/jitteredBackoff.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/retry/isClockSkewError.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/retry/defaultRetryDecider.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/amplifyUrl/index.mjs","../../node_modules/@aws-amplify/core/dist/esm/awsClients/cognitoIdentity/base.mjs","../../node_modules/@aws-amplify/core/dist/esm/awsClients/cognitoIdentity/getId.mjs","../../node_modules/@aws-amplify/core/dist/esm/awsClients/cognitoIdentity/getCredentialsForIdentity.mjs","../../node_modules/@aws-amplify/core/dist/esm/errors/PlatformNotSupportedError.mjs","../../node_modules/@aws-amplify/core/dist/esm/storage/KeyValueStorage.mjs","../../node_modules/@aws-amplify/core/dist/esm/storage/InMemoryStorage.mjs","../../node_modules/@aws-amplify/core/dist/esm/storage/utils.mjs","../../node_modules/@aws-amplify/core/dist/esm/storage/DefaultStorage.mjs","../../node_modules/@aws-amplify/core/dist/esm/storage/SessionStorage.mjs","../../node_modules/@aws-amplify/core/dist/esm/storage/SyncKeyValueStorage.mjs","../../node_modules/@aws-amplify/core/dist/esm/storage/SyncSessionStorage.mjs","../../node_modules/js-cookie/dist/js.cookie.mjs","../../node_modules/@aws-amplify/core/dist/esm/storage/CookieStorage.mjs","../../node_modules/@aws-amplify/core/dist/esm/storage/index.mjs","../../node_modules/@aws-amplify/core/dist/esm/Cache/constants.mjs","../../node_modules/@aws-amplify/core/dist/esm/Cache/utils/cacheHelpers.mjs","../../node_modules/@aws-amplify/core/dist/esm/Cache/utils/errorHelpers.mjs","../../node_modules/@aws-amplify/core/dist/esm/Cache/StorageCacheCommon.mjs","../../node_modules/@aws-amplify/core/dist/esm/Cache/StorageCache.mjs","../../node_modules/@aws-amplify/core/dist/esm/Cache/index.mjs","../../node_modules/@aws-amplify/core/dist/esm/I18n/I18n.mjs","../../node_modules/@aws-amplify/core/dist/esm/I18n/errorHelpers.mjs","../../node_modules/@aws-amplify/core/dist/esm/I18n/index.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/amplifyUuid/index.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getSignedHeaders.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/constants.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getCredentialScope.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getFormattedDates.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getSigningValues.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/dataHashHelpers.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalHeaders.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalQueryString.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalUri.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getHashedPayload.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getCanonicalRequest.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getSigningKey.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getStringToSign.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/utils/getSignature.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/signer/signatureV4/signRequest.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/utils/getSkewCorrectedDate.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/utils/isClockSkewed.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/utils/getUpdatedSystemClockOffset.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/middleware/signing/middleware.mjs","../../node_modules/@aws-amplify/core/dist/esm/clients/handlers/authenticated.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/generateRandomString.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/retry/NonRetryableError.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/retry/jitteredExponentialRetry.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/urlSafeDecode.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/urlSafeEncode.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/deDupeAsyncFunction.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/isTokenExpired.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/deviceName/getDeviceName.mjs","../../node_modules/@aws-amplify/core/dist/esm/errors/APIError.mjs","../../node_modules/@aws-amplify/core/dist/esm/BackgroundProcessManager/BackgroundManagerNotOpenError.mjs","../../node_modules/@aws-amplify/core/dist/esm/BackgroundProcessManager/BackgroundProcessManager.mjs","../../node_modules/@aws-amplify/core/dist/esm/Mutex/Mutex.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/convert/base64/bytesToString.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/convert/base64/base64Encoder.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/cryptoSecureRandomInt.mjs","../../node_modules/@aws-amplify/core/dist/esm/utils/WordArray.mjs","../../node_modules/@aws-amplify/auth/dist/esm/errors/types/validation.mjs","../../node_modules/@aws-amplify/auth/dist/esm/common/AuthErrorStrings.mjs","../../node_modules/@aws-amplify/auth/dist/esm/errors/AuthError.mjs","../../node_modules/@aws-amplify/auth/dist/esm/errors/utils/assertValidationError.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/parsers/regionParsers.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/apiHelpers.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/types/errors.mjs","../../node_modules/@aws-amplify/auth/dist/esm/errors/constants.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/types.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/internal/getCurrentUser.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/getCurrentUser.mjs","../../node_modules/@aws-amplify/auth/dist/esm/utils/getAuthUserAgentValue.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolSerializer.mjs","../../node_modules/@aws-amplify/auth/dist/esm/errors/utils/assertServiceError.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/shared/serde/createUserPoolDeserializer.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/constants.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/cognitoUserPoolEndpointResolver.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/factories/createCognitoUserPoolEndpointResolver.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/userContextData.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/refreshAuthTokens.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/tokenProvider/types.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/tokenProvider/errorHelpers.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/tokenProvider/constants.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/tokenProvider/TokenStore.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/signInWithRedirectStore.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/oAuthStore.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/inflightPromise.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/tokenProvider/TokenOrchestrator.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/tokenProvider/CognitoUserPoolsTokenProvider.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/tokenProvider/tokenProvider.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/tokenProvider/cacheTokens.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/dispatchSignedInHubEvent.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/utils/store/autoSignInStore.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/utils/store/signInStore.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/utils/passkey/errors.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/utils/passkey/getIsPasskeySupported.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/convert/base64url/convertArrayBufferToBase64Url.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/convert/base64url/convertBase64UrlToArrayBuffer.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/utils/passkey/serde.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/utils/passkey/types/index.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/utils/passkey/getPasskey.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/textEncoder/index.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/BigInteger/BigInteger.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/calculate/calculateS.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/constants.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/getBytesFromHex.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/getHexFromBytes.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/getHashFromData.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/getHashFromHex.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/getPaddedHex.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/calculate/calculateU.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/getHkdfKey.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/getRandomBytes.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/getRandomString.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/AuthenticationHelper/AuthenticationHelper.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/calculate/calculateA.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/getAuthenticationHelper.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/getNewDeviceMetadata.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/flows/userAuth/handleWebAuthnSignInResult.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/getNowString.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/srp/getSignatureString.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/handleDeviceSRPAuth.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/handlePasswordVerifierChallenge.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/retryOnResourceNotFoundException.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/setActiveSignInUsername.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/flows/shared/handlePasswordSRP.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/flows/userAuth/handleSelectChallenge.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/flows/userAuth/handleSelectChallengeWithPassword.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/flows/userAuth/handleSelectChallengeWithPasswordSRP.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/signInHelpers.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/signInWithCustomAuth.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/signInWithCustomSRPAuth.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/autoSignIn.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/signInWithSRP.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/signInWithUserPassword.mjs","../../node_modules/@aws-amplify/auth/dist/esm/client/flows/userAuth/handleUserAuthFlow.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/signInWithUserAuth.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/signIn.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/signUpHelpers.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/signUp.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/resetPassword.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/confirmResetPassword.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/resendSignUpCode.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/confirmSignUp.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/confirmSignIn.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/confirmUserAttribute.mjs","../../node_modules/@aws-amplify/auth/dist/esm/Errors.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/createOAuthError.mjs","../../node_modules/@aws-amplify/auth/dist/esm/types/Auth.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/validateState.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/completeOAuthFlow.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/getRedirectUrl.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/handleFailure.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/attemptCompleteOAuthFlow.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/enableOAuthListener.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/types/models.mjs","../../node_modules/@aws-amplify/auth/dist/esm/utils/openAuthSession.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/generateCodeVerifier.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/generateState.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/cancelOAuthFlow.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/signInWithRedirect.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/internal/fetchUserAttributes.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/fetchUserAttributes.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/completeOAuthSignOut.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/oAuthSignOutRedirect.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/utils/oauth/handleOAuthSignOut.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/signOut.mjs","../../node_modules/@aws-amplify/auth/dist/esm/foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/apis/sendUserAttributeVerificationCode.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/credentialsProvider/types.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/credentialsProvider/IdentityIdStore.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/credentialsProvider/utils.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/credentialsProvider/IdentityIdProvider.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/credentialsProvider/credentialsProvider.mjs","../../node_modules/@aws-amplify/auth/dist/esm/providers/cognito/credentialsProvider/index.mjs","../../node_modules/aws-amplify/dist/esm/initSingleton.mjs","../../node_modules/scheduler/cjs/scheduler.production.min.js","../../node_modules/scheduler/index.js","../../node_modules/react-dom/cjs/react-dom.production.min.js","../../node_modules/react-dom/index.js","../../node_modules/react-dom/client.js","../../node_modules/lodash/_listCacheClear.js","../../node_modules/lodash/eq.js","../../node_modules/lodash/_assocIndexOf.js","../../node_modules/lodash/_listCacheDelete.js","../../node_modules/lodash/_listCacheGet.js","../../node_modules/lodash/_listCacheHas.js","../../node_modules/lodash/_listCacheSet.js","../../node_modules/lodash/_ListCache.js","../../node_modules/lodash/_stackClear.js","../../node_modules/lodash/_stackDelete.js","../../node_modules/lodash/_stackGet.js","../../node_modules/lodash/_stackHas.js","../../node_modules/lodash/_freeGlobal.js","../../node_modules/lodash/_root.js","../../node_modules/lodash/_Symbol.js","../../node_modules/lodash/_getRawTag.js","../../node_modules/lodash/_objectToString.js","../../node_modules/lodash/_baseGetTag.js","../../node_modules/lodash/isObject.js","../../node_modules/lodash/isFunction.js","../../node_modules/lodash/_coreJsData.js","../../node_modules/lodash/_isMasked.js","../../node_modules/lodash/_toSource.js","../../node_modules/lodash/_baseIsNative.js","../../node_modules/lodash/_getValue.js","../../node_modules/lodash/_getNative.js","../../node_modules/lodash/_Map.js","../../node_modules/lodash/_nativeCreate.js","../../node_modules/lodash/_hashClear.js","../../node_modules/lodash/_hashDelete.js","../../node_modules/lodash/_hashGet.js","../../node_modules/lodash/_hashHas.js","../../node_modules/lodash/_hashSet.js","../../node_modules/lodash/_Hash.js","../../node_modules/lodash/_mapCacheClear.js","../../node_modules/lodash/_isKeyable.js","../../node_modules/lodash/_getMapData.js","../../node_modules/lodash/_mapCacheDelete.js","../../node_modules/lodash/_mapCacheGet.js","../../node_modules/lodash/_mapCacheHas.js","../../node_modules/lodash/_mapCacheSet.js","../../node_modules/lodash/_MapCache.js","../../node_modules/lodash/_stackSet.js","../../node_modules/lodash/_Stack.js","../../node_modules/lodash/_setCacheAdd.js","../../node_modules/lodash/_setCacheHas.js","../../node_modules/lodash/_SetCache.js","../../node_modules/lodash/_arraySome.js","../../node_modules/lodash/_cacheHas.js","../../node_modules/lodash/_equalArrays.js","../../node_modules/lodash/_Uint8Array.js","../../node_modules/lodash/_mapToArray.js","../../node_modules/lodash/_setToArray.js","../../node_modules/lodash/_equalByTag.js","../../node_modules/lodash/_arrayPush.js","../../node_modules/lodash/isArray.js","../../node_modules/lodash/_baseGetAllKeys.js","../../node_modules/lodash/_arrayFilter.js","../../node_modules/lodash/stubArray.js","../../node_modules/lodash/_getSymbols.js","../../node_modules/lodash/_baseTimes.js","../../node_modules/lodash/isObjectLike.js","../../node_modules/lodash/_baseIsArguments.js","../../node_modules/lodash/isArguments.js","../../node_modules/lodash/stubFalse.js","../../node_modules/lodash/isBuffer.js","../../node_modules/lodash/_isIndex.js","../../node_modules/lodash/isLength.js","../../node_modules/lodash/_baseIsTypedArray.js","../../node_modules/lodash/_baseUnary.js","../../node_modules/lodash/_nodeUtil.js","../../node_modules/lodash/isTypedArray.js","../../node_modules/lodash/_arrayLikeKeys.js","../../node_modules/lodash/_isPrototype.js","../../node_modules/lodash/_overArg.js","../../node_modules/lodash/_nativeKeys.js","../../node_modules/lodash/_baseKeys.js","../../node_modules/lodash/isArrayLike.js","../../node_modules/lodash/keys.js","../../node_modules/lodash/_getAllKeys.js","../../node_modules/lodash/_equalObjects.js","../../node_modules/lodash/_DataView.js","../../node_modules/lodash/_Promise.js","../../node_modules/lodash/_Set.js","../../node_modules/lodash/_WeakMap.js","../../node_modules/lodash/_getTag.js","../../node_modules/lodash/_baseIsEqualDeep.js","../../node_modules/lodash/_baseIsEqual.js","../../node_modules/lodash/isEqual.js","../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.js","../../node_modules/use-sync-external-store/shim/index.js","../../node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.js","../../node_modules/use-sync-external-store/shim/with-selector.js","../../node_modules/xstate/es/_virtual/_tslib.js","../../node_modules/xstate/es/types.js","../../node_modules/xstate/es/actionTypes.js","../../node_modules/xstate/es/constants.js","../../node_modules/xstate/es/utils.js","../../node_modules/xstate/es/actions.js","../../node_modules/xstate/es/serviceScope.js","../../node_modules/xstate/es/Actor.js","../../node_modules/xstate/es/stateUtils.js","../../node_modules/xstate/es/State.js","../../node_modules/xstate/es/scheduler.js","../../node_modules/xstate/es/registry.js","../../node_modules/xstate/es/devTools.js","../../node_modules/xstate/es/behaviors.js","../../node_modules/xstate/es/interpreter.js","../../node_modules/xstate/es/invokeUtils.js","../../node_modules/xstate/es/StateNode.js","../../node_modules/xstate/es/Machine.js","../../node_modules/xstate/es/index.js","../../node_modules/use-isomorphic-layout-effect/dist/use-isomorphic-layout-effect.browser.esm.js","../../node_modules/@xstate/react/es/useConstant.js","../../node_modules/@xstate/react/es/useInterpret.js","../../node_modules/@xstate/react/es/utils.js","../../node_modules/@xstate/react/es/useActor.js","../../node_modules/@xstate/react/es/useSelector.js","../../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/actor.mjs","../../node_modules/@aws-amplify/ui/dist/esm/utils/setUserAgent/constants.mjs","../../node_modules/@aws-amplify/ui/dist/esm/utils/utils.mjs","../../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/defaultAuthHubHandler.mjs","../../node_modules/@aws-amplify/ui/dist/esm/i18n/country-dial-codes.mjs","../../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/constants.mjs","../../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/getRoute.mjs","../../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/facade.mjs","../../node_modules/@aws-amplify/ui/dist/esm/types/authenticator/user.mjs","../../node_modules/@aws-amplify/ui/dist/esm/types/authenticator/attributes.mjs","../../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/form.mjs","../../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/utils.mjs","../../node_modules/@aws-amplify/ui/dist/esm/i18n/dictionaries/authenticator/defaultTexts.mjs","../../node_modules/@aws-amplify/ui/dist/esm/i18n/dictionaries/index.mjs","../../node_modules/@aws-amplify/ui/dist/esm/i18n/translations.mjs","../../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/formFields/utils.mjs","../../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/formFields/defaults.mjs","../../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/formFields/formFields.mjs","../../node_modules/@aws-amplify/ui/dist/esm/helpers/authenticator/textUtil.mjs","../../node_modules/lodash/_arrayMap.js","../../node_modules/lodash/_baseIsMatch.js","../../node_modules/lodash/_isStrictComparable.js","../../node_modules/lodash/_getMatchData.js","../../node_modules/lodash/_matchesStrictComparable.js","../../node_modules/lodash/_baseMatches.js","../../node_modules/lodash/isSymbol.js","../../node_modules/lodash/_isKey.js","../../node_modules/lodash/memoize.js","../../node_modules/lodash/_memoizeCapped.js","../../node_modules/lodash/_stringToPath.js","../../node_modules/lodash/_baseToString.js","../../node_modules/lodash/toString.js","../../node_modules/lodash/_castPath.js","../../node_modules/lodash/_toKey.js","../../node_modules/lodash/_baseGet.js","../../node_modules/lodash/get.js","../../node_modules/lodash/_baseHasIn.js","../../node_modules/lodash/_hasPath.js","../../node_modules/lodash/hasIn.js","../../node_modules/lodash/_baseMatchesProperty.js","../../node_modules/lodash/identity.js","../../node_modules/lodash/_baseProperty.js","../../node_modules/lodash/_basePropertyDeep.js","../../node_modules/lodash/property.js","../../node_modules/lodash/_baseIteratee.js","../../node_modules/lodash/_defineProperty.js","../../node_modules/lodash/_baseAssignValue.js","../../node_modules/lodash/_assignValue.js","../../node_modules/lodash/_baseSet.js","../../node_modules/lodash/_basePickBy.js","../../node_modules/lodash/_getPrototype.js","../../node_modules/lodash/_getSymbolsIn.js","../../node_modules/lodash/_nativeKeysIn.js","../../node_modules/lodash/_baseKeysIn.js","../../node_modules/lodash/keysIn.js","../../node_modules/lodash/_getAllKeysIn.js","../../node_modules/lodash/pickBy.js","../../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/utils.mjs","../../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actions.mjs","../../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/guards.mjs","../../node_modules/lodash/_assignMergeValue.js","../../node_modules/lodash/_createBaseFor.js","../../node_modules/lodash/_baseFor.js","../../node_modules/lodash/_cloneBuffer.js","../../node_modules/lodash/_cloneArrayBuffer.js","../../node_modules/lodash/_cloneTypedArray.js","../../node_modules/lodash/_copyArray.js","../../node_modules/lodash/_baseCreate.js","../../node_modules/lodash/_initCloneObject.js","../../node_modules/lodash/isArrayLikeObject.js","../../node_modules/lodash/isPlainObject.js","../../node_modules/lodash/_safeGet.js","../../node_modules/lodash/_copyObject.js","../../node_modules/lodash/toPlainObject.js","../../node_modules/lodash/_baseMergeDeep.js","../../node_modules/lodash/_baseMerge.js","../../node_modules/lodash/_apply.js","../../node_modules/lodash/_overRest.js","../../node_modules/lodash/constant.js","../../node_modules/lodash/_baseSetToString.js","../../node_modules/lodash/_shortOut.js","../../node_modules/lodash/_setToString.js","../../node_modules/lodash/_baseRest.js","../../node_modules/lodash/_isIterateeCall.js","../../node_modules/lodash/_createAssigner.js","../../node_modules/lodash/merge.js","../../node_modules/@aws-amplify/ui/dist/esm/validators/index.mjs","../../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/defaultServices.mjs","../../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actors/forgotPassword.mjs","../../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actors/utils.mjs","../../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actors/signIn.mjs","../../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actors/signUp.mjs","../../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actors/signOut.mjs","../../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/actors/verifyUserAttributes.mjs","../../node_modules/@aws-amplify/ui/dist/esm/machines/authenticator/index.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/borderWidths.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/colors.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/alert.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/aiConversation.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/autocomplete.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/authenticator.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/avatar.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/badge.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/breadcrumbs.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/button.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/card.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/checkbox.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/checkboxField.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/collection.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/copy.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/dialCodeSelect.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/divider.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/dropZone.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/accordion.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/field.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/fieldControl.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/fieldGroup.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/fieldset.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/fieldMessages.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/fileuploader.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/flex.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/heading.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/highlightMatch.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/icon.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/input.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/image.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/inAppMessaging.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/link.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/liveness.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/loader.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/menu.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/message.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/pagination.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/passwordField.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/phoneNumberField.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/placeholder.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/radio.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/radioGroup.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/rating.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/searchField.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/select.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/selectField.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/sliderField.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/stepperField.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/storagemanager.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/switchField.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/table.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/tabs.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/text.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/textAreaField.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/textField.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/toggleButton.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/toggleButtonGroup.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/components/index.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/fonts.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/fontSizes.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/fontWeights.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/lineHeights.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/opacities.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/outlineOffsets.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/outlineWidths.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/radii.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/shadows.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/space.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/time.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/transforms.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/tokens/index.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/breakpoints.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/defaultTheme.mjs","../../node_modules/lodash/_arrayReduce.js","../../node_modules/lodash/_basePropertyOf.js","../../node_modules/lodash/_deburrLetter.js","../../node_modules/lodash/deburr.js","../../node_modules/lodash/_asciiWords.js","../../node_modules/lodash/_hasUnicodeWord.js","../../node_modules/lodash/_unicodeWords.js","../../node_modules/lodash/words.js","../../node_modules/lodash/_createCompounder.js","../../node_modules/lodash/kebabCase.js","../../node_modules/@aws-amplify/ui/dist/esm/theme/createTheme/constants.mjs","../../node_modules/@aws-amplify/ui/dist/esm/utils/references.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/createTheme/utils.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/createTheme/createColorPalette.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/createTheme/createAnimationCSS.mjs","../../node_modules/@aws-amplify/ui/dist/esm/theme/createTheme/createTheme.mjs","../../node_modules/@aws-amplify/ui/dist/esm/utils/classNames.mjs","../../node_modules/@aws-amplify/ui/dist/esm/types/primitives/componentClassName.mjs","../../node_modules/@aws-amplify/ui/dist/esm/utils/setUserAgent/setUserAgent.mjs","../../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/context/AuthenticatorContext.mjs","../../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/context/AuthenticatorProvider.mjs","../../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/hooks/useAuthenticator/constants.mjs","../../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/hooks/constants.mjs","../../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/hooks/utils.mjs","../../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/hooks/useAuthenticator/utils.mjs","../../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/hooks/useAuthenticator/useAuthenticator.mjs","../../node_modules/react-hook-form/dist/index.esm.mjs","../../node_modules/@aws-amplify/ui-react-core/dist/esm/Authenticator/hooks/useAuthenticatorInitMachine/useAuthenticatorInitMachine.mjs","../../node_modules/@aws-amplify/ui-react-core/dist/esm/hooks/useDeprecationWarning.mjs","../../node_modules/@aws-amplify/ui-react-core/dist/esm/hooks/useSetUserAgent.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/ThemeProvider/ThemeContext.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/types/style.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/constants.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/types/theme.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/utils.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/responsive/utils.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/responsive/getMediaQueries.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/responsive/useBreakpoint.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/hooks/useTheme.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/getStyleValue.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/shared/styleUtils.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/utils/primitiveWithForwardRef.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/View/View.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/Icon.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/context/IconsContext.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/context/useIcons.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconCheckCircle.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconError.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconInfo.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconWarning.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Alert/AlertIcon.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/utils/useLayoutEffect.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/utils/useStableId.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Fieldset/useFieldset.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Flex/Flex.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Loader/Loader.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Button/Button.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconClose.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Text/Text.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Field/FieldDescription.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Field/FieldErrorMessage.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Label/Label.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Alert/Alert.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/utils/getUniqueComponentId.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/FieldGroup/FieldGroup.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Input/Input.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/utils/splitPrimitiveProps.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/utils/createSpaceSeparatedIds.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/helpers/constants.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/TextField/TextField.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/VisuallyHidden/VisuallyHidden.mjs","../../node_modules/lodash/now.js","../../node_modules/lodash/_trimmedEndIndex.js","../../node_modules/lodash/_baseTrim.js","../../node_modules/lodash/toNumber.js","../../node_modules/lodash/debounce.js","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Divider/Divider.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconExpandMore.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Fieldset/Fieldset.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Heading/Heading.mjs","../../node_modules/@babel/runtime/helpers/esm/extends.js","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconVisibilityOff.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Icon/icons/IconVisibility.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/PasswordField/ShowPasswordButton.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/PasswordField/PasswordField.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Select/Select.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/SelectField/SelectField.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/PhoneNumberField/DialCodeSelect.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/PhoneNumberField/PhoneNumberField.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/RadioGroupField/context.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Radio/Radio.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/RadioGroupField/RadioGroupField.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/TabsContext.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/constants.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/TabsItem.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/TabsList.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/TabsPanel.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/TabsContainer.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/primitives/Tabs/Tabs.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/shared/ValidationErrors.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/version.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/hooks/useDeprecationWarning.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/hooks/useCustomComponents/useCustomComponents.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/helpers/utils.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/hooks/useFormHandlers/useFormHandlers.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/shared/RemoteErrorMessage.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/shared/FormField.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/shared/FormFields.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/RouteContainer/RouteContainer.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/ConfirmSignUp/ConfirmSignUp.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/ForceNewPassword/ForceNewPassword.mjs","../../node_modules/qrcode/lib/can-promise.js","../../node_modules/qrcode/lib/core/utils.js","../../node_modules/qrcode/lib/core/error-correction-level.js","../../node_modules/qrcode/lib/core/bit-buffer.js","../../node_modules/qrcode/lib/core/bit-matrix.js","../../node_modules/qrcode/lib/core/alignment-pattern.js","../../node_modules/qrcode/lib/core/finder-pattern.js","../../node_modules/qrcode/lib/core/mask-pattern.js","../../node_modules/qrcode/lib/core/error-correction-code.js","../../node_modules/qrcode/lib/core/galois-field.js","../../node_modules/qrcode/lib/core/polynomial.js","../../node_modules/qrcode/lib/core/reed-solomon-encoder.js","../../node_modules/qrcode/lib/core/version-check.js","../../node_modules/qrcode/lib/core/regex.js","../../node_modules/qrcode/lib/core/mode.js","../../node_modules/qrcode/lib/core/version.js","../../node_modules/qrcode/lib/core/format-info.js","../../node_modules/qrcode/lib/core/numeric-data.js","../../node_modules/qrcode/lib/core/alphanumeric-data.js","../../node_modules/encode-utf8/index.js","../../node_modules/qrcode/lib/core/byte-data.js","../../node_modules/qrcode/lib/core/kanji-data.js","../../node_modules/dijkstrajs/dijkstra.js","../../node_modules/qrcode/lib/core/segments.js","../../node_modules/qrcode/lib/core/qrcode.js","../../node_modules/qrcode/lib/renderer/utils.js","../../node_modules/qrcode/lib/renderer/canvas.js","../../node_modules/qrcode/lib/renderer/svg-tag.js","../../node_modules/qrcode/lib/browser.js","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/shared/ConfirmSignInFooter.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/SetupTotp/SetupTotp.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/FederatedSignIn/FederatedSignInButtons/FederatedSignInButton.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/FederatedSignIn/FederatedSignIn.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/SignIn/SignIn.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/SignUp/SignUp.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/shared/SignInSignUpTabs.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/shared/TwoButtonSubmitFooter.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/VerifyUser/ConfirmVerifyUser.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/VerifyUser/VerifyUser.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/ConfirmSignIn/ConfirmSignIn.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/ForgotPassword/ConfirmResetPassword.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/ForgotPassword/ForgotPassword.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/utils.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/Router/Router.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/hooks/useCustomComponents/defaultComponents.mjs","../../node_modules/@aws-amplify/ui-react/dist/esm/components/Authenticator/Authenticator.mjs","../../node_modules/@tanstack/query-core/build/modern/subscribable.js","../../node_modules/@tanstack/query-core/build/modern/utils.js","../../node_modules/@tanstack/query-core/build/modern/focusManager.js","../../node_modules/@tanstack/query-core/build/modern/onlineManager.js","../../node_modules/@tanstack/query-core/build/modern/thenable.js","../../node_modules/@tanstack/query-core/build/modern/retryer.js","../../node_modules/@tanstack/query-core/build/modern/notifyManager.js","../../node_modules/@tanstack/query-core/build/modern/removable.js","../../node_modules/@tanstack/query-core/build/modern/query.js","../../node_modules/@tanstack/query-core/build/modern/queryCache.js","../../node_modules/@tanstack/query-core/build/modern/mutation.js","../../node_modules/@tanstack/query-core/build/modern/mutationCache.js","../../node_modules/@tanstack/query-core/build/modern/infiniteQueryBehavior.js","../../node_modules/@tanstack/query-core/build/modern/queryClient.js","../../node_modules/@tanstack/query-core/build/modern/queryObserver.js","../../node_modules/@tanstack/query-core/build/modern/queriesObserver.js","../../node_modules/@tanstack/query-core/build/modern/infiniteQueryObserver.js","../../node_modules/@tanstack/query-core/build/modern/mutationObserver.js","../../node_modules/@tanstack/react-query/build/modern/QueryClientProvider.js","../../node_modules/@tanstack/react-query/build/modern/isRestoring.js","../../node_modules/@tanstack/react-query/build/modern/QueryErrorResetBoundary.js","../../node_modules/@tanstack/react-query/build/modern/utils.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/useQueries.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/mqtt/dist/mqtt.esm.js","../../node_modules/ulid/dist/index.esm.js","../../node_modules/immer/dist/immer.esm.js","../../node_modules/@aws-amplify/datastore/dist/esm/types.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/predicates/sort.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/predicates/index.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/util.mjs","../../node_modules/graphql/jsutils/isObjectLike.mjs","../../node_modules/graphql/polyfills/symbols.mjs","../../node_modules/graphql/language/location.mjs","../../node_modules/graphql/language/printLocation.mjs","../../node_modules/graphql/error/GraphQLError.mjs","../../node_modules/graphql/error/syntaxError.mjs","../../node_modules/graphql/language/kinds.mjs","../../node_modules/graphql/jsutils/invariant.mjs","../../node_modules/graphql/jsutils/nodejsCustomInspectSymbol.mjs","../../node_modules/graphql/jsutils/defineInspect.mjs","../../node_modules/graphql/language/ast.mjs","../../node_modules/graphql/language/tokenKind.mjs","../../node_modules/graphql/jsutils/inspect.mjs","../../node_modules/graphql/jsutils/devAssert.mjs","../../node_modules/graphql/jsutils/instanceOf.mjs","../../node_modules/graphql/language/source.mjs","../../node_modules/graphql/language/directiveLocation.mjs","../../node_modules/graphql/language/blockString.mjs","../../node_modules/graphql/language/lexer.mjs","../../node_modules/graphql/language/parser.mjs","../../node_modules/graphql/language/visitor.mjs","../../node_modules/graphql/language/printer.mjs","../../node_modules/@aws-amplify/api-rest/dist/esm/errors/RestApiError.mjs","../../node_modules/@aws-amplify/api-rest/dist/esm/errors/CanceledError.mjs","../../node_modules/@aws-amplify/api-rest/dist/esm/errors/validation.mjs","../../node_modules/@aws-amplify/api-rest/dist/esm/utils/serviceError.mjs","../../node_modules/@aws-amplify/api-rest/dist/esm/utils/logger.mjs","../../node_modules/@aws-amplify/api-rest/dist/esm/utils/createCancellableOperation.mjs","../../node_modules/@aws-amplify/api-rest/dist/esm/utils/constants.mjs","../../node_modules/@aws-amplify/api-rest/dist/esm/utils/parseSigningInfo.mjs","../../node_modules/@aws-amplify/api-rest/dist/esm/utils/isIamAuthApplicable.mjs","../../node_modules/@aws-amplify/api-rest/dist/esm/utils/resolveHeaders.mjs","../../node_modules/@aws-amplify/api-rest/dist/esm/apis/common/handler.mjs","../../node_modules/@aws-amplify/api-rest/dist/esm/apis/common/internalPost.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/Providers/constants.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/types/PubSub.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/utils/ReachabilityMonitor/index.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/utils/ConnectionStateMonitor.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/utils/ReconnectionMonitor.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/Providers/AWSWebSocketProvider/appsyncUrl.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/Providers/AWSWebSocketProvider/authHeaders.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/Providers/AWSWebSocketProvider/index.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/utils/errors/GraphQLApiError.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/utils/errors/validation.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/utils/errors/assertValidationError.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/utils/resolveConfig.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/utils/resolveLibraryOptions.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/utils/errors/repackageAuthError.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/types/index.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/utils/errors/constants.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/utils/errors/createGraphQLResultWithError.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/internals/utils/runtimeTypeGuards/isGraphQLResponseWithErrors.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/internals/graphqlAuth.mjs","../../node_modules/@aws-amplify/api-graphql/dist/esm/internals/InternalGraphQLAPI.mjs","../../node_modules/@aws-amplify/api/dist/esm/internals/InternalAPI.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/authModeStrategies/defaultAuthStrategy.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/authModeStrategies/multiAuthStrategy.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/sync/utils.mjs","../../node_modules/idb/build/esm/wrap-idb-value.js","../../node_modules/idb/build/esm/index.js","../../node_modules/@aws-amplify/datastore/dist/esm/storage/relationship.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/storage/adapter/StorageAdapterBase.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/storage/adapter/IndexedDBAdapter.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/storage/adapter/InMemoryStore.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/storage/adapter/AsyncStorageDatabase.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/storage/adapter/AsyncStorageAdapter.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/storage/adapter/getDefaultAdapter/index.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/storage/storage.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/sync/datastoreReachability/index.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/sync/datastoreConnectivity.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/sync/merger.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/sync/outbox.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/sync/processors/errorMaps.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/sync/processors/mutation.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/sync/processors/subscription.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/sync/processors/sync.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/sync/index.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/predicates/next.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/datastore/utils.mjs","../../node_modules/@aws-amplify/datastore/dist/esm/datastore/datastore.mjs","../../src/models/schema.js","../../src/models/index.js","../../src/context/user/userProvider.tsx","../../src/context/user/useUser.tsx","../../src/context/flespi/FlespiContext.tsx","../../node_modules/@babel/runtime/helpers/esm/objectWithoutPropertiesLoose.js","../../node_modules/clsx/dist/clsx.mjs","../../node_modules/prop-types/lib/ReactPropTypesSecret.js","../../node_modules/prop-types/factoryWithThrowingShims.js","../../node_modules/prop-types/index.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/formatMuiErrorMessage/formatMuiErrorMessage.js","../../node_modules/@mui/material/styles/identifier.js","../../node_modules/@emotion/sheet/dist/emotion-sheet.esm.js","../../node_modules/stylis/src/Enum.js","../../node_modules/stylis/src/Utility.js","../../node_modules/stylis/src/Tokenizer.js","../../node_modules/stylis/src/Parser.js","../../node_modules/stylis/src/Serializer.js","../../node_modules/stylis/src/Middleware.js","../../node_modules/@emotion/memoize/dist/emotion-memoize.esm.js","../../node_modules/@emotion/cache/dist/emotion-cache.browser.esm.js","../../node_modules/@emotion/utils/dist/emotion-utils.browser.esm.js","../../node_modules/@emotion/hash/dist/emotion-hash.esm.js","../../node_modules/@emotion/unitless/dist/emotion-unitless.esm.js","../../node_modules/@emotion/serialize/dist/emotion-serialize.esm.js","../../node_modules/@emotion/use-insertion-effect-with-fallbacks/dist/emotion-use-insertion-effect-with-fallbacks.browser.esm.js","../../node_modules/@emotion/react/dist/emotion-element-f0de968e.browser.esm.js","../../node_modules/@babel/runtime/helpers/extends.js","../../node_modules/@emotion/react/dist/emotion-react.browser.esm.js","../../node_modules/@emotion/is-prop-valid/dist/emotion-is-prop-valid.esm.js","../../node_modules/@emotion/styled/base/dist/emotion-styled-base.browser.esm.js","../../node_modules/@emotion/styled/dist/emotion-styled.browser.esm.js","../../node_modules/@mui/material/node_modules/@mui/styled-engine/StyledEngineProvider/StyledEngineProvider.js","../../node_modules/@mui/material/node_modules/@mui/styled-engine/GlobalStyles/GlobalStyles.js","../../node_modules/@mui/material/node_modules/@mui/styled-engine/index.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/deepmerge/deepmerge.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/createTheme/createBreakpoints.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/createTheme/shape.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/merge.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/breakpoints.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/capitalize/capitalize.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/style.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/memoize.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/spacing.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/createTheme/createSpacing.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/compose.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/borders.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/cssGrid.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/palette.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/sizing.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/styleFunctionSx/defaultSxConfig.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/styleFunctionSx/styleFunctionSx.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/createTheme/applyStyles.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/createTheme/createTheme.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/useThemeWithoutDefault.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/useTheme.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/GlobalStyles/GlobalStyles.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/styleFunctionSx/extendSxProp.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/ClassNameGenerator/ClassNameGenerator.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/createBox.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/generateUtilityClass/generateUtilityClass.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/generateUtilityClasses/generateUtilityClasses.js","../../node_modules/react-is/cjs/react-is.production.js","../../node_modules/react-is/index.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/getDisplayName/getDisplayName.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/createStyled.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/styled.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/resolveProps/resolveProps.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/useThemeProps/getThemeProps.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/useThemeProps/useThemeProps.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/useEnhancedEffect/useEnhancedEffect.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/useMediaQuery/useMediaQuery.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/clamp/clamp.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/colorManipulator.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/createChainedFunction/createChainedFunction.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/debounce/debounce.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/deprecatedPropType/deprecatedPropType.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/isMuiElement/isMuiElement.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/ownerDocument/ownerDocument.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/ownerWindow/ownerWindow.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/requirePropFactory/requirePropFactory.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/setRef/setRef.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/useId/useId.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/unsupportedProp/unsupportedProp.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/useControlled/useControlled.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/useEventCallback/useEventCallback.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/useForkRef/useForkRef.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/useLazyRef/useLazyRef.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/useOnMount/useOnMount.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/useTimeout/useTimeout.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/useIsFocusVisible/useIsFocusVisible.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/getScrollbarSize/getScrollbarSize.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/scrollLeft/scrollLeft.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/usePreviousProps/usePreviousProps.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/composeClasses/composeClasses.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/isHostComponent/isHostComponent.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/appendOwnerState/appendOwnerState.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/extractEventHandlers/extractEventHandlers.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/omitEventHandlers/omitEventHandlers.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/mergeSlotProps/mergeSlotProps.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/resolveComponentProps/resolveComponentProps.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/useSlotProps/useSlotProps.js","../../node_modules/@mui/material/node_modules/@mui/utils/esm/getReactElementRef/getReactElementRef.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/RtlProvider/index.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/DefaultPropsProvider/DefaultPropsProvider.js","../../node_modules/@babel/runtime/helpers/esm/typeof.js","../../node_modules/@babel/runtime/helpers/esm/toPrimitive.js","../../node_modules/@babel/runtime/helpers/esm/toPropertyKey.js","../../node_modules/@mui/material/node_modules/@mui/system/esm/Stack/createStack.js","../../node_modules/@mui/material/styles/createMixins.js","../../node_modules/@babel/runtime/helpers/interopRequireDefault.js","../../node_modules/@mui/material/node_modules/@mui/system/colorManipulator.js","../../node_modules/@mui/material/colors/common.js","../../node_modules/@mui/material/colors/grey.js","../../node_modules/@mui/material/colors/purple.js","../../node_modules/@mui/material/colors/red.js","../../node_modules/@mui/material/colors/orange.js","../../node_modules/@mui/material/colors/blue.js","../../node_modules/@mui/material/colors/lightBlue.js","../../node_modules/@mui/material/colors/green.js","../../node_modules/@mui/material/styles/createPalette.js","../../node_modules/@mui/material/styles/createTypography.js","../../node_modules/@mui/material/styles/shadows.js","../../node_modules/@mui/material/styles/createTransitions.js","../../node_modules/@mui/material/styles/zIndex.js","../../node_modules/@mui/material/styles/createTheme.js","../../node_modules/@mui/material/styles/cssUtils.js","../../node_modules/@mui/material/styles/defaultTheme.js","../../node_modules/@mui/material/styles/useTheme.js","../../node_modules/@mui/material/styles/useThemeProps.js","../../node_modules/@babel/runtime/helpers/objectWithoutPropertiesLoose.js","../../node_modules/@mui/material/node_modules/@mui/system/createStyled.js","../../node_modules/@mui/material/styles/slotShouldForwardProp.js","../../node_modules/@mui/material/styles/rootShouldForwardProp.js","../../node_modules/@mui/material/styles/styled.js","../../node_modules/@mui/material/styles/getOverlayAlpha.js","../../node_modules/@mui/utils/esm/deepmerge/deepmerge.js","../../node_modules/@mui/utils/esm/formatMuiErrorMessage/formatMuiErrorMessage.js","../../node_modules/@mui/utils/esm/refType/refType.js","../../node_modules/@mui/utils/esm/capitalize/capitalize.js","../../node_modules/@mui/utils/esm/createChainedFunction/createChainedFunction.js","../../node_modules/@mui/utils/esm/debounce/debounce.js","../../node_modules/@mui/utils/esm/isMuiElement/isMuiElement.js","../../node_modules/@mui/utils/esm/ownerDocument/ownerDocument.js","../../node_modules/@mui/utils/esm/ownerWindow/ownerWindow.js","../../node_modules/@mui/utils/esm/setRef/setRef.js","../../node_modules/@mui/utils/esm/useEnhancedEffect/useEnhancedEffect.js","../../node_modules/@mui/utils/esm/useId/useId.js","../../node_modules/@mui/utils/esm/useControlled/useControlled.js","../../node_modules/@mui/utils/esm/useEventCallback/useEventCallback.js","../../node_modules/@mui/utils/esm/useForkRef/useForkRef.js","../../node_modules/@mui/utils/esm/useLazyRef/useLazyRef.js","../../node_modules/@mui/utils/esm/useOnMount/useOnMount.js","../../node_modules/@mui/utils/esm/useTimeout/useTimeout.js","../../node_modules/@mui/utils/esm/isFocusVisible/isFocusVisible.js","../../node_modules/@mui/utils/esm/getScrollbarSize/getScrollbarSize.js","../../node_modules/@mui/utils/esm/usePreviousProps/usePreviousProps.js","../../node_modules/@mui/utils/esm/visuallyHidden/visuallyHidden.js","../../node_modules/@mui/utils/esm/resolveProps/resolveProps.js","../../node_modules/@mui/utils/esm/composeClasses/composeClasses.js","../../node_modules/@mui/utils/esm/ClassNameGenerator/ClassNameGenerator.js","../../node_modules/@mui/utils/esm/generateUtilityClass/generateUtilityClass.js","../../node_modules/@mui/utils/esm/generateUtilityClasses/generateUtilityClasses.js","../../node_modules/@mui/utils/esm/clamp/clamp.js","../../node_modules/@mui/utils/esm/isHostComponent/isHostComponent.js","../../node_modules/@mui/utils/esm/appendOwnerState/appendOwnerState.js","../../node_modules/@mui/utils/esm/extractEventHandlers/extractEventHandlers.js","../../node_modules/@mui/utils/esm/omitEventHandlers/omitEventHandlers.js","../../node_modules/@mui/utils/esm/mergeSlotProps/mergeSlotProps.js","../../node_modules/@mui/utils/esm/resolveComponentProps/resolveComponentProps.js","../../node_modules/@mui/utils/esm/useSlotProps/useSlotProps.js","../../node_modules/@mui/utils/esm/getReactElementRef/getReactElementRef.js","../../node_modules/@mui/x-date-pickers/LocalizationProvider/LocalizationProvider.js","../../node_modules/@mui/x-date-pickers/locales/utils/getPickersLocalization.js","../../node_modules/@mui/x-date-pickers/locales/enUS.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useUtils.js","../../node_modules/@mui/x-date-pickers/hooks/usePickersTranslations.js","../../node_modules/@mui/material/DefaultPropsProvider/DefaultPropsProvider.js","../../node_modules/@mui/material/Typography/typographyClasses.js","../../node_modules/@mui/material/Typography/Typography.js","../../node_modules/@mui/system/esm/RtlProvider/index.js","../../node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js","../../node_modules/@babel/runtime/helpers/esm/inheritsLoose.js","../../node_modules/dom-helpers/esm/hasClass.js","../../node_modules/dom-helpers/esm/addClass.js","../../node_modules/dom-helpers/esm/removeClass.js","../../node_modules/react-transition-group/esm/config.js","../../node_modules/react-transition-group/esm/TransitionGroupContext.js","../../node_modules/react-transition-group/esm/utils/reflow.js","../../node_modules/react-transition-group/esm/Transition.js","../../node_modules/react-transition-group/esm/CSSTransition.js","../../node_modules/@babel/runtime/helpers/esm/assertThisInitialized.js","../../node_modules/react-transition-group/esm/utils/ChildMapping.js","../../node_modules/react-transition-group/esm/TransitionGroup.js","../../node_modules/@mui/material/ButtonBase/Ripple.js","../../node_modules/@mui/material/ButtonBase/touchRippleClasses.js","../../node_modules/@mui/material/ButtonBase/TouchRipple.js","../../node_modules/@mui/material/ButtonBase/buttonBaseClasses.js","../../node_modules/@mui/material/ButtonBase/ButtonBase.js","../../node_modules/@mui/material/IconButton/iconButtonClasses.js","../../node_modules/@mui/material/IconButton/IconButton.js","../../node_modules/@mui/material/SvgIcon/svgIconClasses.js","../../node_modules/@mui/material/SvgIcon/SvgIcon.js","../../node_modules/@mui/material/utils/createSvgIcon.js","../../node_modules/@mui/material/utils/index.js","../../node_modules/@mui/x-date-pickers/icons/index.js","../../node_modules/@mui/x-date-pickers/internals/components/PickersArrowSwitcher/pickersArrowSwitcherClasses.js","../../node_modules/@mui/x-date-pickers/internals/components/PickersArrowSwitcher/PickersArrowSwitcher.js","../../node_modules/@mui/x-date-pickers/internals/utils/views.js","../../node_modules/@mui/x-date-pickers/internals/utils/time-utils.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useViews.js","../../node_modules/@mui/x-date-pickers/internals/hooks/date-helpers-hooks.js","../../node_modules/@mui/x-date-pickers/internals/constants/dimensions.js","../../node_modules/@mui/x-date-pickers/internals/components/PickerViewRoot/PickerViewRoot.js","../../node_modules/@mui/x-date-pickers/TimeClock/timeClockClasses.js","../../node_modules/@mui/x-date-pickers/TimeClock/shared.js","../../node_modules/@mui/x-date-pickers/TimeClock/clockPointerClasses.js","../../node_modules/@mui/x-date-pickers/TimeClock/ClockPointer.js","../../node_modules/@mui/x-date-pickers/TimeClock/clockClasses.js","../../node_modules/@mui/x-date-pickers/internals/utils/date-utils.js","../../node_modules/@mui/x-date-pickers/TimeClock/Clock.js","../../node_modules/@mui/x-date-pickers/TimeClock/clockNumberClasses.js","../../node_modules/@mui/x-date-pickers/TimeClock/ClockNumber.js","../../node_modules/@mui/x-date-pickers/TimeClock/ClockNumbers.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useValueWithTimezone.js","../../node_modules/@mui/x-date-pickers/internals/utils/getDefaultReferenceDate.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useField/useField.utils.js","../../node_modules/@mui/x-date-pickers/internals/utils/valueManagers.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useClockReferenceDate.js","../../node_modules/@mui/x-date-pickers/TimeClock/TimeClock.js","../../node_modules/@mui/material/List/ListContext.js","../../node_modules/@mui/material/Divider/dividerClasses.js","../../node_modules/@mui/material/Divider/Divider.js","../../node_modules/@mui/material/ListItemIcon/listItemIconClasses.js","../../node_modules/@mui/material/ListItemIcon/ListItemIcon.js","../../node_modules/@mui/material/ListItemText/listItemTextClasses.js","../../node_modules/@mui/material/ListItemText/ListItemText.js","../../node_modules/@mui/material/MenuItem/menuItemClasses.js","../../node_modules/@mui/material/MenuItem/MenuItem.js","../../node_modules/@mui/material/List/listClasses.js","../../node_modules/@mui/material/List/List.js","../../node_modules/@mui/material/MenuList/MenuList.js","../../node_modules/@mui/x-date-pickers/DigitalClock/digitalClockClasses.js","../../node_modules/@mui/x-date-pickers/internals/utils/utils.js","../../node_modules/@mui/x-date-pickers/DigitalClock/DigitalClock.js","../../node_modules/@mui/x-date-pickers/MultiSectionDigitalClock/multiSectionDigitalClockClasses.js","../../node_modules/@mui/x-date-pickers/MultiSectionDigitalClock/multiSectionDigitalClockSectionClasses.js","../../node_modules/@mui/x-date-pickers/MultiSectionDigitalClock/MultiSectionDigitalClockSection.js","../../node_modules/@mui/x-date-pickers/MultiSectionDigitalClock/MultiSectionDigitalClock.utils.js","../../node_modules/@mui/x-date-pickers/MultiSectionDigitalClock/MultiSectionDigitalClock.js","../../node_modules/@mui/x-date-pickers/PickersDay/pickersDayClasses.js","../../node_modules/@mui/x-date-pickers/PickersDay/PickersDay.js","../../node_modules/@mui/material/TextareaAutosize/TextareaAutosize.js","../../node_modules/@mui/material/FormControl/formControlState.js","../../node_modules/@mui/material/FormControl/FormControlContext.js","../../node_modules/@mui/material/FormControl/useFormControl.js","../../node_modules/@mui/material/GlobalStyles/GlobalStyles.js","../../node_modules/@mui/material/InputBase/utils.js","../../node_modules/@mui/material/InputBase/inputBaseClasses.js","../../node_modules/@mui/material/InputBase/InputBase.js","../../node_modules/@mui/material/Input/inputClasses.js","../../node_modules/@mui/material/Input/Input.js","../../node_modules/@mui/material/FilledInput/filledInputClasses.js","../../node_modules/@mui/material/FilledInput/FilledInput.js","../../node_modules/@mui/material/OutlinedInput/NotchedOutline.js","../../node_modules/@mui/material/OutlinedInput/outlinedInputClasses.js","../../node_modules/@mui/material/OutlinedInput/OutlinedInput.js","../../node_modules/@mui/material/FormLabel/formLabelClasses.js","../../node_modules/@mui/material/FormLabel/FormLabel.js","../../node_modules/@mui/material/InputLabel/inputLabelClasses.js","../../node_modules/@mui/material/InputLabel/InputLabel.js","../../node_modules/@mui/material/FormControl/formControlClasses.js","../../node_modules/@mui/material/FormControl/FormControl.js","../../node_modules/@mui/material/FormHelperText/formHelperTextClasses.js","../../node_modules/@mui/material/FormHelperText/FormHelperText.js","../../node_modules/@mui/material/transitions/utils.js","../../node_modules/@mui/material/Grow/Grow.js","../../node_modules/@mui/material/Modal/ModalManager.js","../../node_modules/@mui/material/Unstable_TrapFocus/FocusTrap.js","../../node_modules/@mui/material/Portal/Portal.js","../../node_modules/@mui/material/Fade/Fade.js","../../node_modules/@mui/material/Backdrop/backdropClasses.js","../../node_modules/@mui/material/Backdrop/Backdrop.js","../../node_modules/@mui/material/Modal/useModal.js","../../node_modules/@mui/material/Modal/modalClasses.js","../../node_modules/@mui/material/Modal/Modal.js","../../node_modules/@mui/material/Paper/paperClasses.js","../../node_modules/@mui/material/Paper/Paper.js","../../node_modules/@mui/material/Popover/popoverClasses.js","../../node_modules/@mui/material/Popover/Popover.js","../../node_modules/@mui/material/Menu/menuClasses.js","../../node_modules/@mui/material/Menu/Menu.js","../../node_modules/@mui/material/NativeSelect/nativeSelectClasses.js","../../node_modules/@mui/material/NativeSelect/NativeSelectInput.js","../../node_modules/@mui/material/Select/selectClasses.js","../../node_modules/@mui/material/Select/SelectInput.js","../../node_modules/@mui/material/internal/svg-icons/ArrowDropDown.js","../../node_modules/@mui/material/Select/Select.js","../../node_modules/@mui/material/TextField/textFieldClasses.js","../../node_modules/@mui/material/TextField/TextField.js","../../node_modules/@mui/x-date-pickers/validation/validateDate.js","../../node_modules/@mui/x-date-pickers/validation/validateTime.js","../../node_modules/@mui/x-date-pickers/validation/validateDateTime.js","../../node_modules/@mui/x-date-pickers/validation/extractValidationProps.js","../../node_modules/@mui/x-date-pickers/validation/useValidation.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useField/buildSectionsFromFormat.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useField/useFieldState.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useField/useFieldCharacterEditing.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useField/useFieldV7TextField.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useField/useFieldV6TextField.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useField/useField.js","../../node_modules/@mui/material/InputAdornment/inputAdornmentClasses.js","../../node_modules/@mui/material/InputAdornment/InputAdornment.js","../../node_modules/@mui/x-date-pickers/hooks/useClearableField.js","../../node_modules/@mui/x-date-pickers/hooks/useSplitFieldProps.js","../../node_modules/@mui/x-date-pickers/internals/components/PickersProvider.js","../../node_modules/@mui/x-date-pickers/internals/hooks/defaultizedFieldProps.js","../../node_modules/@mui/x-date-pickers/DateField/useDateField.js","../../node_modules/@mui/x-date-pickers/PickersTextField/pickersTextFieldClasses.js","../../node_modules/@mui/x-date-pickers/PickersTextField/PickersInputBase/pickersInputBaseClasses.js","../../node_modules/@mui/x-date-pickers/PickersSectionList/pickersSectionListClasses.js","../../node_modules/@mui/x-date-pickers/PickersSectionList/PickersSectionList.js","../../node_modules/@mui/x-date-pickers/PickersTextField/PickersInputBase/PickersInputBase.js","../../node_modules/@mui/x-date-pickers/PickersTextField/PickersOutlinedInput/pickersOutlinedInputClasses.js","../../node_modules/@mui/x-date-pickers/PickersTextField/PickersOutlinedInput/Outline.js","../../node_modules/@mui/x-date-pickers/PickersTextField/PickersOutlinedInput/PickersOutlinedInput.js","../../node_modules/@mui/styled-engine/GlobalStyles/GlobalStyles.js","../../node_modules/@mui/styled-engine/index.js","../../node_modules/@mui/system/esm/createBreakpoints/createBreakpoints.js","../../node_modules/@mui/system/esm/cssContainerQueries/cssContainerQueries.js","../../node_modules/@mui/system/esm/createTheme/shape.js","../../node_modules/@mui/system/esm/merge/merge.js","../../node_modules/@mui/system/esm/breakpoints/breakpoints.js","../../node_modules/@mui/system/esm/style/style.js","../../node_modules/@mui/system/esm/memoize/memoize.js","../../node_modules/@mui/system/esm/spacing/spacing.js","../../node_modules/@mui/system/esm/createTheme/createSpacing.js","../../node_modules/@mui/system/esm/compose/compose.js","../../node_modules/@mui/system/esm/borders/borders.js","../../node_modules/@mui/system/esm/cssGrid/cssGrid.js","../../node_modules/@mui/system/esm/palette/palette.js","../../node_modules/@mui/system/esm/sizing/sizing.js","../../node_modules/@mui/system/esm/styleFunctionSx/defaultSxConfig.js","../../node_modules/@mui/system/esm/styleFunctionSx/styleFunctionSx.js","../../node_modules/@mui/system/esm/createTheme/applyStyles.js","../../node_modules/@mui/system/esm/createTheme/createTheme.js","../../node_modules/@mui/system/esm/useThemeWithoutDefault/useThemeWithoutDefault.js","../../node_modules/@mui/system/esm/useTheme/useTheme.js","../../node_modules/@mui/system/esm/GlobalStyles/GlobalStyles.js","../../node_modules/@mui/system/esm/styleFunctionSx/extendSxProp.js","../../node_modules/@mui/system/esm/createBox/createBox.js","../../node_modules/@mui/system/esm/preprocessStyles.js","../../node_modules/@mui/system/esm/createStyled/createStyled.js","../../node_modules/@mui/system/esm/styled/styled.js","../../node_modules/@mui/system/esm/useThemeProps/getThemeProps.js","../../node_modules/@mui/system/esm/useThemeProps/useThemeProps.js","../../node_modules/@mui/system/esm/useMediaQuery/useMediaQuery.js","../../node_modules/@mui/system/esm/colorManipulator/colorManipulator.js","../../node_modules/@mui/private-theming/useTheme/ThemeContext.js","../../node_modules/@mui/private-theming/useTheme/useTheme.js","../../node_modules/@mui/private-theming/ThemeProvider/nested.js","../../node_modules/@mui/private-theming/ThemeProvider/ThemeProvider.js","../../node_modules/@mui/system/esm/DefaultPropsProvider/DefaultPropsProvider.js","../../node_modules/@mui/system/esm/ThemeProvider/ThemeProvider.js","../../node_modules/@mui/system/esm/memoTheme.js","../../node_modules/@mui/system/esm/InitColorSchemeScript/InitColorSchemeScript.js","../../node_modules/@mui/system/esm/cssVars/localStorageManager.js","../../node_modules/@mui/system/esm/cssVars/useCurrentColorScheme.js","../../node_modules/@mui/system/esm/cssVars/createCssVarsProvider.js","../../node_modules/@mui/system/esm/cssVars/createGetCssVar.js","../../node_modules/@mui/system/esm/cssVars/cssVarsParser.js","../../node_modules/@mui/system/esm/cssVars/prepareCssVars.js","../../node_modules/@mui/system/esm/cssVars/getColorSchemeSelector.js","../../node_modules/@mui/system/esm/Stack/createStack.js","../../node_modules/@mui/x-date-pickers/PickersTextField/PickersFilledInput/pickersFilledInputClasses.js","../../node_modules/@mui/x-date-pickers/PickersTextField/PickersFilledInput/PickersFilledInput.js","../../node_modules/@mui/x-date-pickers/PickersTextField/PickersInput/pickersInputClasses.js","../../node_modules/@mui/x-date-pickers/PickersTextField/PickersInput/PickersInput.js","../../node_modules/@mui/x-date-pickers/PickersTextField/PickersTextField.js","../../node_modules/@mui/x-date-pickers/internals/utils/convertFieldResponseIntoMuiTextFieldProps.js","../../node_modules/@mui/x-date-pickers/DateField/DateField.js","../../node_modules/@mui/x-date-pickers/DateTimeField/useDateTimeField.js","../../node_modules/@mui/x-date-pickers/DateTimeField/DateTimeField.js","../../node_modules/@mui/x-date-pickers/DateCalendar/useIsDateDisabled.js","../../node_modules/@mui/x-date-pickers/DateCalendar/useCalendarState.js","../../node_modules/@mui/x-date-pickers/DateCalendar/pickersFadeTransitionGroupClasses.js","../../node_modules/@mui/x-date-pickers/DateCalendar/PickersFadeTransitionGroup.js","../../node_modules/@mui/x-date-pickers/DateCalendar/pickersSlideTransitionClasses.js","../../node_modules/@mui/x-date-pickers/DateCalendar/PickersSlideTransition.js","../../node_modules/@mui/x-date-pickers/DateCalendar/dayCalendarClasses.js","../../node_modules/@mui/x-date-pickers/DateCalendar/DayCalendar.js","../../node_modules/@mui/x-date-pickers/MonthCalendar/pickersMonthClasses.js","../../node_modules/@mui/x-date-pickers/MonthCalendar/PickersMonth.js","../../node_modules/@mui/x-date-pickers/MonthCalendar/monthCalendarClasses.js","../../node_modules/@mui/x-date-pickers/MonthCalendar/MonthCalendar.js","../../node_modules/@mui/x-date-pickers/YearCalendar/pickersYearClasses.js","../../node_modules/@mui/x-date-pickers/YearCalendar/PickersYear.js","../../node_modules/@mui/x-date-pickers/YearCalendar/yearCalendarClasses.js","../../node_modules/@mui/x-date-pickers/YearCalendar/YearCalendar.js","../../node_modules/@mui/x-date-pickers/PickersCalendarHeader/pickersCalendarHeaderClasses.js","../../node_modules/@mui/x-date-pickers/PickersCalendarHeader/PickersCalendarHeader.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useDefaultReduceAnimations.js","../../node_modules/@mui/x-date-pickers/DateCalendar/dateCalendarClasses.js","../../node_modules/@mui/x-date-pickers/DateCalendar/DateCalendar.js","../../node_modules/@mui/material/Skeleton/skeletonClasses.js","../../node_modules/@mui/material/Skeleton/Skeleton.js","../../node_modules/@mui/x-date-pickers/internals/components/pickersToolbarClasses.js","../../node_modules/@mui/x-date-pickers/internals/components/PickersToolbar.js","../../node_modules/@mui/x-date-pickers/DatePicker/datePickerToolbarClasses.js","../../node_modules/@mui/x-date-pickers/DatePicker/DatePickerToolbar.js","../../node_modules/@mui/x-date-pickers/DatePicker/shared.js","../../node_modules/@mui/material/node_modules/@mui/system/useThemeWithoutDefault.js","../../node_modules/@popperjs/core/lib/enums.js","../../node_modules/@popperjs/core/lib/dom-utils/getNodeName.js","../../node_modules/@popperjs/core/lib/dom-utils/getWindow.js","../../node_modules/@popperjs/core/lib/dom-utils/instanceOf.js","../../node_modules/@popperjs/core/lib/modifiers/applyStyles.js","../../node_modules/@popperjs/core/lib/utils/getBasePlacement.js","../../node_modules/@popperjs/core/lib/utils/math.js","../../node_modules/@popperjs/core/lib/utils/userAgent.js","../../node_modules/@popperjs/core/lib/dom-utils/isLayoutViewport.js","../../node_modules/@popperjs/core/lib/dom-utils/getBoundingClientRect.js","../../node_modules/@popperjs/core/lib/dom-utils/getLayoutRect.js","../../node_modules/@popperjs/core/lib/dom-utils/contains.js","../../node_modules/@popperjs/core/lib/dom-utils/getComputedStyle.js","../../node_modules/@popperjs/core/lib/dom-utils/isTableElement.js","../../node_modules/@popperjs/core/lib/dom-utils/getDocumentElement.js","../../node_modules/@popperjs/core/lib/dom-utils/getParentNode.js","../../node_modules/@popperjs/core/lib/dom-utils/getOffsetParent.js","../../node_modules/@popperjs/core/lib/utils/getMainAxisFromPlacement.js","../../node_modules/@popperjs/core/lib/utils/within.js","../../node_modules/@popperjs/core/lib/utils/getFreshSideObject.js","../../node_modules/@popperjs/core/lib/utils/mergePaddingObject.js","../../node_modules/@popperjs/core/lib/utils/expandToHashMap.js","../../node_modules/@popperjs/core/lib/modifiers/arrow.js","../../node_modules/@popperjs/core/lib/utils/getVariation.js","../../node_modules/@popperjs/core/lib/modifiers/computeStyles.js","../../node_modules/@popperjs/core/lib/modifiers/eventListeners.js","../../node_modules/@popperjs/core/lib/utils/getOppositePlacement.js","../../node_modules/@popperjs/core/lib/utils/getOppositeVariationPlacement.js","../../node_modules/@popperjs/core/lib/dom-utils/getWindowScroll.js","../../node_modules/@popperjs/core/lib/dom-utils/getWindowScrollBarX.js","../../node_modules/@popperjs/core/lib/dom-utils/getViewportRect.js","../../node_modules/@popperjs/core/lib/dom-utils/getDocumentRect.js","../../node_modules/@popperjs/core/lib/dom-utils/isScrollParent.js","../../node_modules/@popperjs/core/lib/dom-utils/getScrollParent.js","../../node_modules/@popperjs/core/lib/dom-utils/listScrollParents.js","../../node_modules/@popperjs/core/lib/utils/rectToClientRect.js","../../node_modules/@popperjs/core/lib/dom-utils/getClippingRect.js","../../node_modules/@popperjs/core/lib/utils/computeOffsets.js","../../node_modules/@popperjs/core/lib/utils/detectOverflow.js","../../node_modules/@popperjs/core/lib/utils/computeAutoPlacement.js","../../node_modules/@popperjs/core/lib/modifiers/flip.js","../../node_modules/@popperjs/core/lib/modifiers/hide.js","../../node_modules/@popperjs/core/lib/modifiers/offset.js","../../node_modules/@popperjs/core/lib/modifiers/popperOffsets.js","../../node_modules/@popperjs/core/lib/utils/getAltAxis.js","../../node_modules/@popperjs/core/lib/modifiers/preventOverflow.js","../../node_modules/@popperjs/core/lib/dom-utils/getHTMLElementScroll.js","../../node_modules/@popperjs/core/lib/dom-utils/getNodeScroll.js","../../node_modules/@popperjs/core/lib/dom-utils/getCompositeRect.js","../../node_modules/@popperjs/core/lib/utils/orderModifiers.js","../../node_modules/@popperjs/core/lib/utils/debounce.js","../../node_modules/@popperjs/core/lib/utils/mergeByName.js","../../node_modules/@popperjs/core/lib/createPopper.js","../../node_modules/@popperjs/core/lib/popper.js","../../node_modules/@mui/material/Popper/popperClasses.js","../../node_modules/@mui/material/Popper/BasePopper.js","../../node_modules/@mui/material/Popper/Popper.js","../../node_modules/@mui/x-date-pickers/internals/components/pickersPopperClasses.js","../../node_modules/@mui/x-date-pickers/internals/components/PickersPopper.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useOpenState.js","../../node_modules/@mui/x-date-pickers/internals/hooks/usePicker/usePickerValue.js","../../node_modules/@mui/x-date-pickers/internals/hooks/usePicker/usePickerViews.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useIsLandscape.js","../../node_modules/@mui/x-date-pickers/internals/hooks/usePicker/usePickerLayoutProps.js","../../node_modules/@mui/x-date-pickers/internals/hooks/usePicker/usePickerOwnerState.js","../../node_modules/@mui/x-date-pickers/internals/hooks/usePicker/usePicker.js","../../node_modules/@mui/x-date-pickers/PickersLayout/pickersLayoutClasses.js","../../node_modules/@mui/material/Button/buttonClasses.js","../../node_modules/@mui/material/ButtonGroup/ButtonGroupContext.js","../../node_modules/@mui/material/ButtonGroup/ButtonGroupButtonContext.js","../../node_modules/@mui/material/Button/Button.js","../../node_modules/@mui/material/DialogActions/dialogActionsClasses.js","../../node_modules/@mui/material/DialogActions/DialogActions.js","../../node_modules/@mui/x-date-pickers/PickersActionBar/PickersActionBar.js","../../node_modules/@mui/material/ListItem/listItemClasses.js","../../node_modules/@mui/material/ListItemButton/listItemButtonClasses.js","../../node_modules/@mui/material/ListItemSecondaryAction/listItemSecondaryActionClasses.js","../../node_modules/@mui/material/ListItemSecondaryAction/ListItemSecondaryAction.js","../../node_modules/@mui/material/ListItem/ListItem.js","../../node_modules/@mui/material/internal/svg-icons/Cancel.js","../../node_modules/@mui/material/Chip/chipClasses.js","../../node_modules/@mui/material/Chip/Chip.js","../../node_modules/@mui/x-date-pickers/PickersShortcuts/PickersShortcuts.js","../../node_modules/@mui/x-date-pickers/PickersLayout/usePickerLayout.js","../../node_modules/@mui/x-date-pickers/PickersLayout/PickersLayout.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useDesktopPicker/useDesktopPicker.js","../../node_modules/@mui/x-date-pickers/dateViewRenderers/dateViewRenderers.js","../../node_modules/@mui/x-date-pickers/DesktopDatePicker/DesktopDatePicker.js","../../node_modules/@mui/material/DialogContent/dialogContentClasses.js","../../node_modules/@mui/material/DialogTitle/dialogTitleClasses.js","../../node_modules/@mui/material/DialogContent/DialogContent.js","../../node_modules/@mui/material/Dialog/dialogClasses.js","../../node_modules/@mui/material/Dialog/DialogContext.js","../../node_modules/@mui/material/Dialog/Dialog.js","../../node_modules/@mui/x-date-pickers/internals/components/PickersModalDialog.js","../../node_modules/@mui/x-date-pickers/internals/hooks/useMobilePicker/useMobilePicker.js","../../node_modules/@mui/x-date-pickers/MobileDatePicker/MobileDatePicker.js","../../node_modules/@mui/x-date-pickers/DatePicker/DatePicker.js","../../node_modules/@mui/x-date-pickers/internals/components/pickersToolbarTextClasses.js","../../node_modules/@mui/x-date-pickers/internals/components/PickersToolbarText.js","../../node_modules/@mui/x-date-pickers/internals/components/PickersToolbarButton.js","../../node_modules/@mui/x-date-pickers/timeViewRenderers/timeViewRenderers.js","../../node_modules/@mui/x-date-pickers/internals/utils/date-time-utils.js","../../node_modules/@mui/material/Tab/tabClasses.js","../../node_modules/@mui/material/Tab/Tab.js","../../node_modules/@mui/material/internal/animate.js","../../node_modules/@mui/material/Tabs/ScrollbarSize.js","../../node_modules/@mui/material/internal/svg-icons/KeyboardArrowLeft.js","../../node_modules/@mui/material/internal/svg-icons/KeyboardArrowRight.js","../../node_modules/@mui/material/TabScrollButton/tabScrollButtonClasses.js","../../node_modules/@mui/material/TabScrollButton/TabScrollButton.js","../../node_modules/@mui/material/Tabs/tabsClasses.js","../../node_modules/@mui/material/Tabs/Tabs.js","../../node_modules/@mui/x-date-pickers/DateTimePicker/dateTimePickerTabsClasses.js","../../node_modules/@mui/x-date-pickers/DateTimePicker/DateTimePickerTabs.js","../../node_modules/@mui/x-date-pickers/DateTimePicker/dateTimePickerToolbarClasses.js","../../node_modules/@mui/x-date-pickers/DateTimePicker/DateTimePickerToolbar.js","../../node_modules/@mui/x-date-pickers/DateTimePicker/shared.js","../../node_modules/@mui/x-date-pickers/DesktopDateTimePicker/DesktopDateTimePickerLayout.js","../../node_modules/@mui/x-date-pickers/DesktopDateTimePicker/DesktopDateTimePicker.js","../../node_modules/@mui/x-date-pickers/MobileDateTimePicker/MobileDateTimePicker.js","../../node_modules/@mui/x-date-pickers/DateTimePicker/DateTimePicker.js","../../node_modules/dayjs/dayjs.min.js","../../node_modules/dayjs/plugin/weekOfYear.js","../../node_modules/dayjs/plugin/customParseFormat.js","../../node_modules/dayjs/plugin/localizedFormat.js","../../node_modules/dayjs/plugin/isBetween.js","../../node_modules/dayjs/plugin/advancedFormat.js","../../node_modules/@mui/x-date-pickers/AdapterDayjs/AdapterDayjs.js","../../node_modules/dayjs/locale/en-gb.js","../../node_modules/ra-core/dist/esm/auth/AuthContext.js","../../node_modules/ra-core/dist/esm/auth/useAuthProvider.js","../../node_modules/cookie/dist/index.js","../../node_modules/react-router/dist/development/chunk-HA7DTUK3.mjs","../../node_modules/react-router/dist/development/dom-export.mjs","../../node_modules/ra-core/dist/esm/store/localStorageStore.js","../../node_modules/lodash/set.js","../../node_modules/lodash/last.js","../../node_modules/lodash/_baseSlice.js","../../node_modules/lodash/_parent.js","../../node_modules/lodash/_baseUnset.js","../../node_modules/lodash/unset.js","../../node_modules/ra-core/dist/esm/store/memoryStore.js","../../node_modules/ra-core/dist/esm/store/StoreContext.js","../../node_modules/ra-core/dist/esm/store/StoreContextProvider.js","../../node_modules/ra-core/dist/esm/store/useStoreContext.js","../../node_modules/ra-core/dist/esm/i18n/substituteTokens.js","../../node_modules/ra-core/dist/esm/i18n/I18nContext.js","../../node_modules/ra-core/dist/esm/notification/AddNotificationContext.js","../../node_modules/ra-core/dist/esm/notification/NotificationContext.js","../../node_modules/ra-core/dist/esm/notification/NotificationContextProvider.js","../../node_modules/ra-core/dist/esm/notification/useAddNotificationContext.js","../../node_modules/ra-core/dist/esm/notification/useNotificationContext.js","../../node_modules/ra-core/dist/esm/notification/useNotify.js","../../node_modules/ra-core/dist/esm/i18n/I18nContextProvider.js","../../node_modules/ra-core/dist/esm/i18n/useI18nProvider.js","../../node_modules/ra-core/dist/esm/i18n/useLocaleState.js","../../node_modules/ra-core/dist/esm/i18n/useLocale.js","../../node_modules/ra-core/dist/esm/i18n/useLocales.js","../../node_modules/lodash/_arrayEach.js","../../node_modules/lodash/_baseAssign.js","../../node_modules/lodash/_baseAssignIn.js","../../node_modules/lodash/_copySymbols.js","../../node_modules/lodash/_copySymbolsIn.js","../../node_modules/lodash/_initCloneArray.js","../../node_modules/lodash/_cloneDataView.js","../../node_modules/lodash/_cloneRegExp.js","../../node_modules/lodash/_cloneSymbol.js","../../node_modules/lodash/_initCloneByTag.js","../../node_modules/lodash/_baseIsMap.js","../../node_modules/lodash/isMap.js","../../node_modules/lodash/_baseIsSet.js","../../node_modules/lodash/isSet.js","../../node_modules/lodash/_baseClone.js","../../node_modules/lodash/cloneDeep.js","../../node_modules/ra-core/dist/esm/i18n/useTranslate.js","../../node_modules/ra-core/dist/esm/routing/BasenameContext.js","../../node_modules/ra-core/dist/esm/routing/BasenameContextProvider.js","../../node_modules/ra-core/dist/esm/routing/AdminRouter.js","../../node_modules/ra-core/dist/esm/routing/useRestoreScrollPosition.js","../../node_modules/ra-core/dist/esm/routing/RestoreScrollPosition.js","../../node_modules/ra-core/dist/esm/routing/useBasename.js","../../node_modules/ra-core/dist/esm/routing/useCreatePath.js","../../node_modules/ra-core/dist/esm/core/ResourceContext.js","../../node_modules/ra-core/dist/esm/core/useResourceContext.js","../../node_modules/ra-core/dist/esm/controller/record/RecordContext.js","../../node_modules/ra-core/dist/esm/controller/record/useRecordContext.js","../../node_modules/ra-core/dist/esm/routing/useGetPathForRecord.js","../../node_modules/ra-core/dist/esm/core/ResourceDefinitionContext.js","../../node_modules/ra-core/dist/esm/core/useResourceDefinitionContext.js","../../node_modules/ra-core/dist/esm/core/useResourceDefinitions.js","../../node_modules/ra-core/dist/esm/auth/useCanAccessCallback.js","../../node_modules/ra-core/dist/esm/routing/useGetPathForRecordCallback.js","../../node_modules/ra-core/dist/esm/routing/useRedirect.js","../../node_modules/ra-core/dist/esm/routing/useResetErrorBoundaryOnLocationChange.js","../../node_modules/ra-core/dist/esm/routing/useScrollToTop.js","../../node_modules/ra-core/dist/esm/routing/useSplatPathBase.js","../../node_modules/ra-core/dist/esm/dataProvider/dataFetchActions.js","../../node_modules/ra-core/dist/esm/dataProvider/defaultDataProvider.js","../../node_modules/ra-core/dist/esm/dataProvider/convertLegacyDataProvider.js","../../node_modules/ra-core/dist/esm/dataProvider/DataProviderContext.js","../../node_modules/ra-core/dist/esm/dataProvider/HttpError.js","../../node_modules/strict-uri-encode/index.js","../../node_modules/decode-uri-component/index.js","../../node_modules/split-on-first/index.js","../../node_modules/filter-obj/index.js","../../node_modules/query-string/index.js","../../node_modules/ra-core/dist/esm/dataProvider/fetch.js","../../node_modules/eventemitter3/index.js","../../node_modules/ra-core/dist/esm/dataProvider/undoableEventEmitter.js","../../node_modules/ra-core/dist/esm/dataProvider/combineDataProviders.js","../../node_modules/ra-core/dist/esm/auth/useLogoutIfAccessDenied.js","../../node_modules/ra-core/dist/esm/dataProvider/populateQueryCache.js","../../node_modules/ra-core/dist/esm/dataProvider/useDataProvider.js","../../node_modules/ra-core/dist/esm/dataProvider/useLoading.js","../../node_modules/ra-core/dist/esm/dataProvider/useRefresh.js","../../node_modules/ra-core/dist/esm/dataProvider/useGetOne.js","../../node_modules/ra-core/dist/esm/dataProvider/useGetList.js","../../node_modules/lodash/_isFlattenable.js","../../node_modules/lodash/_baseFlatten.js","../../node_modules/lodash/_baseFindIndex.js","../../node_modules/lodash/_baseIsNaN.js","../../node_modules/lodash/_strictIndexOf.js","../../node_modules/lodash/_baseIndexOf.js","../../node_modules/lodash/_arrayIncludes.js","../../node_modules/lodash/_arrayIncludesWith.js","../../node_modules/lodash/noop.js","../../node_modules/lodash/_createSet.js","../../node_modules/lodash/_baseUniq.js","../../node_modules/lodash/union.js","../../node_modules/ra-core/dist/esm/dataProvider/useGetManyAggregate.js","../../node_modules/ra-core/dist/esm/dataProvider/useGetManyReference.js","../../node_modules/ra-core/dist/esm/util/shallowEqual.js","../../node_modules/ra-core/dist/esm/util/removeEmpty.js","../../node_modules/ra-core/dist/esm/util/removeKey.js","../../node_modules/ra-core/dist/esm/controller/list/queryReducer.js","../../node_modules/ra-core/dist/esm/controller/useSortState.js","../../node_modules/ra-core/dist/esm/controller/usePaginationState.js","../../node_modules/ra-core/dist/esm/controller/checkMinimumRequiredProps.js","../../node_modules/ra-core/dist/esm/controller/button/useDeleteWithUndoController.js","../../node_modules/ra-core/dist/esm/controller/button/useDeleteWithConfirmController.js","../../node_modules/ra-core/dist/esm/controller/saveContext/SaveContext.js","../../node_modules/ra-core/dist/esm/controller/saveContext/SaveContextProvider.js","../../node_modules/lodash/_basePick.js","../../node_modules/lodash/flatten.js","../../node_modules/lodash/_flatRest.js","../../node_modules/lodash/pick.js","../../node_modules/ra-core/dist/esm/controller/saveContext/usePickSaveContext.js","../../node_modules/ra-core/dist/esm/controller/saveContext/useSaveContext.js","../../node_modules/ra-core/dist/esm/controller/saveContext/useMutationMiddlewares.js","../../node_modules/ra-core/dist/esm/controller/create/useCreateController.js","../../node_modules/ra-core/dist/esm/controller/create/CreateContext.js","../../node_modules/ra-core/dist/esm/controller/create/CreateContextProvider.js","../../node_modules/ra-core/dist/esm/controller/create/CreateBase.js","../../node_modules/ra-core/dist/esm/controller/create/useCreateContext.js","../../node_modules/ra-core/dist/esm/controller/edit/useEditController.js","../../node_modules/ra-core/dist/esm/controller/record/OptionalRecordContextProvider.js","../../node_modules/ra-core/dist/esm/controller/record/RecordRepresentation.js","../../node_modules/ra-core/dist/esm/controller/edit/EditContext.js","../../node_modules/ra-core/dist/esm/controller/edit/EditContextProvider.js","../../node_modules/ra-core/dist/esm/controller/edit/EditBase.js","../../node_modules/ra-core/dist/esm/controller/edit/useEditContext.js","../../node_modules/ra-core/dist/esm/controller/field/ReferenceFieldContext.js","../../node_modules/ra-core/dist/esm/controller/useReference.js","../../node_modules/ra-core/dist/esm/controller/field/useReferenceFieldController.js","../../node_modules/ra-core/dist/esm/controller/field/ReferenceFieldBase.js","../../node_modules/jsonexport/dist/core/eol.js","../../node_modules/jsonexport/dist/core/helper.js","../../node_modules/jsonexport/dist/core/join-rows.js","../../node_modules/jsonexport/dist/parser/handler.js","../../node_modules/jsonexport/dist/core/escape-delimiters.js","../../node_modules/jsonexport/dist/parser/csv.js","../../node_modules/jsonexport/dist/core/stream.js","../../node_modules/jsonexport/dist/index.js","../../node_modules/ra-core/dist/esm/export/downloadCSV.js","../../node_modules/ra-core/dist/esm/export/defaultExporter.js","../../node_modules/ra-core/dist/esm/export/getRelatedIds.js","../../node_modules/ra-core/dist/esm/export/fetchRelatedRecords.js","../../node_modules/ra-core/dist/esm/controller/list/useRecordSelection.js","../../node_modules/ra-core/dist/esm/util/hooks.js","../../node_modules/ra-core/dist/esm/controller/list/useListParams.js","../../node_modules/ra-core/dist/esm/controller/list/useSelectAll.js","../../node_modules/ra-core/dist/esm/controller/list/useInfiniteListController.js","../../node_modules/ra-core/dist/esm/controller/list/ListContext.js","../../node_modules/ra-core/dist/esm/controller/list/ListFilterContext.js","../../node_modules/ra-core/dist/esm/controller/list/ListSortContext.js","../../node_modules/ra-core/dist/esm/controller/list/ListPaginationContext.js","../../node_modules/ra-core/dist/esm/controller/list/ListContextProvider.js","../../node_modules/ra-core/dist/esm/controller/list/InfinitePaginationContext.js","../../node_modules/ra-core/dist/esm/controller/list/InfiniteListBase.js","../../node_modules/ra-core/dist/esm/controller/list/useListController.js","../../node_modules/ra-core/dist/esm/controller/list/ListBase.js","../../node_modules/ra-core/dist/esm/controller/list/useExpanded.js","../../node_modules/ra-core/dist/esm/controller/list/useInfinitePaginationContext.js","../../node_modules/ra-core/dist/esm/controller/list/useList.js","../../node_modules/ra-core/dist/esm/controller/list/useListContext.js","../../node_modules/lodash/defaults.js","../../node_modules/ra-core/dist/esm/controller/list/useListContextWithProps.js","../../node_modules/ra-core/dist/esm/controller/list/useListPaginationContext.js","../../node_modules/ra-core/dist/esm/controller/list/useUnselect.js","../../node_modules/ra-core/dist/esm/controller/field/useReferenceArrayFieldController.js","../../node_modules/ra-core/dist/esm/controller/field/useReferenceManyFieldController.js","../../node_modules/ra-core/dist/esm/controller/input/useReferenceParams.js","../../node_modules/ra-core/dist/esm/controller/input/useReferenceArrayInputController.js","../../node_modules/ra-core/dist/esm/controller/input/useReferenceInputController.js","../../node_modules/ra-core/dist/esm/form/choices/ChoicesContext.js","../../node_modules/ra-core/dist/esm/form/choices/ChoicesContextProvider.js","../../node_modules/ra-core/dist/esm/form/choices/useChoicesContext.js","../../node_modules/ra-core/dist/esm/form/choices/useChoices.js","../../node_modules/ra-core/dist/esm/form/groups/FormGroupsContext.js","../../node_modules/ra-core/dist/esm/form/groups/FormGroupsProvider.js","../../node_modules/ra-core/dist/esm/form/useWarnWhenUnsavedChanges.js","../../node_modules/ra-core/dist/esm/form/WarnWhenUnsavedChanges.js","../../node_modules/ra-core/dist/esm/form/getFormInitialValues.js","../../node_modules/ra-core/dist/esm/form/validation/getSimpleValidationResolver.js","../../node_modules/ra-core/dist/esm/form/validation/setSubmissionErrors.js","../../node_modules/ra-core/dist/esm/form/validation/useNotifyIsFormInvalid.js","../../node_modules/ra-core/dist/esm/form/sanitizeEmptyValues.js","../../node_modules/ra-core/dist/esm/form/useRecordFromLocation.js","../../node_modules/ra-core/dist/esm/form/useAugmentedForm.js","../../node_modules/ra-core/dist/esm/form/Form.js","../../node_modules/ra-core/dist/esm/form/useFormValues.js","../../node_modules/ra-core/dist/esm/form/FormDataConsumer.js","../../node_modules/ra-core/dist/esm/form/groups/FormGroupContext.js","../../node_modules/ra-core/dist/esm/form/groups/useFormGroups.js","../../node_modules/ra-core/dist/esm/form/groups/useFormGroupContext.js","../../node_modules/ra-core/dist/esm/form/useApplyInputDefaultValues.js","../../node_modules/ra-core/dist/esm/form/validation/validate.js","../../node_modules/ra-core/dist/esm/form/validation/useUnique.js","../../node_modules/ra-core/dist/esm/form/validation/ValidationError.js","../../node_modules/ra-core/dist/esm/form/useInput.js","../../node_modules/ra-core/dist/esm/form/useSuggestions.js","../../node_modules/ra-core/dist/esm/form/FilterLiveForm.js","../../node_modules/ra-core/dist/esm/controller/input/ReferenceInputBase.js","../../node_modules/ra-core/dist/esm/controller/show/useShowController.js","../../node_modules/ra-core/dist/esm/controller/show/ShowContext.js","../../node_modules/ra-core/dist/esm/controller/show/ShowContextProvider.js","../../node_modules/ra-core/dist/esm/controller/show/ShowBase.js","../../node_modules/ra-core/dist/esm/controller/show/useShowContext.js","../../node_modules/ra-core/dist/esm/dataProvider/useCreate.js","../../node_modules/ra-core/dist/esm/dataProvider/undo/AddUndoableMutationContext.js","../../node_modules/ra-core/dist/esm/dataProvider/undo/useAddUndoableMutation.js","../../node_modules/ra-core/dist/esm/dataProvider/useUpdate.js","../../node_modules/ra-core/dist/esm/dataProvider/useDelete.js","../../node_modules/ra-core/dist/esm/dataProvider/useDeleteMany.js","../../node_modules/ra-core/dist/esm/dataProvider/useInfiniteGetList.js","../../node_modules/ra-core/dist/esm/dataProvider/undo/TakeUndoableMutationContext.js","../../node_modules/ra-core/dist/esm/dataProvider/undo/UndoableMutationsContextProvider.js","../../node_modules/ra-core/dist/esm/dataProvider/undo/useTakeUndoableMutation.js","../../node_modules/ra-core/dist/esm/preferences/PreferencesEditorContext.js","../../node_modules/ra-core/dist/esm/preferences/PreferencesEditorContextProvider.js","../../node_modules/ra-core/dist/esm/core/CoreAdminContext.js","../../node_modules/react-error-boundary/dist/react-error-boundary.esm.js","../../node_modules/ra-core/dist/esm/auth/usePermissions.js","../../node_modules/ra-core/dist/esm/core/useConfigureAdminRouterFromChildren.js","../../node_modules/ra-core/dist/esm/core/HasDashboardContext.js","../../node_modules/ra-core/dist/esm/auth/useCanAccessResources.js","../../node_modules/ra-core/dist/esm/core/useFirstResourceWithListAccess.js","../../node_modules/ra-core/dist/esm/core/NavigateToFirstResource.js","../../node_modules/ra-core/dist/esm/core/CoreAdminRoutes.js","../../node_modules/ra-core/dist/esm/core/DefaultTitleContext.js","../../node_modules/ra-core/dist/esm/core/CoreAdminUI.js","../../node_modules/ra-core/dist/esm/core/CustomRoutes.js","../../node_modules/ra-core/dist/esm/core/ResourceContextProvider.js","../../node_modules/ra-core/dist/esm/core/OptionalResourceContextProvider.js","../../node_modules/ra-core/dist/esm/core/Resource.js","../../node_modules/ra-core/dist/esm/core/SourceContext.js","../../node_modules/inflection/lib/inflection.js","../../node_modules/ra-core/dist/esm/core/useGetResourceLabel.js","../../node_modules/ra-core/dist/esm/core/useResourceDefinition.js","../../node_modules/ra-core/dist/esm/core/useGetRecordRepresentation.js","../../node_modules/ra-core/dist/esm/core/useWrappedSource.js","../../node_modules/ra-core/dist/esm/i18n/useTranslateLabel.js","../../node_modules/ra-core/dist/esm/util/FieldTitle.js","../../node_modules/ra-core/dist/esm/util/Ready.js","../../node_modules/ra-core/dist/esm/util/warning.js","../../node_modules/ra-core/dist/esm/util/getFieldLabelTranslationArgs.js","../../node_modules/ra-core/dist/esm/util/mergeRefs.js","../../node_modules/ra-core/dist/esm/util/useEvent.js","../../node_modules/ra-core/dist/esm/util/useDebouncedEvent.js","../../node_modules/ra-core/dist/esm/util/useFieldValue.js","../../node_modules/ra-core/dist/esm/util/asyncDebounce.js","../../node_modules/ra-core/dist/esm/util/useCheckForApplicationUpdate.js","../../node_modules/ra-core/dist/esm/store/useStore.js","../../node_modules/ra-core/dist/esm/store/useRemoveFromStore.js","../../node_modules/ra-core/dist/esm/store/useRemoveItemsFromStore.js","../../node_modules/ra-core/dist/esm/store/useResetStore.js","../../node_modules/ra-core/dist/esm/auth/useLogout.js","../../node_modules/ra-core/dist/esm/auth/useAuthState.js","../../node_modules/ra-core/dist/esm/auth/useAuthenticated.js","../../node_modules/ra-core/dist/esm/auth/WithPermissions.js","../../node_modules/ra-core/dist/esm/auth/useLogin.js","../../node_modules/ra-core/dist/esm/auth/types.js","../../node_modules/ra-core/dist/esm/auth/convertLegacyAuthProvider.js","../../node_modules/ra-core/dist/esm/auth/useCanAccess.js","../../node_modules/ra-core/dist/esm/auth/LogoutOnMount.js","../../node_modules/ra-core/dist/esm/auth/useCheckAuth.js","../../node_modules/ra-core/dist/esm/auth/useGetIdentity.js","../../node_modules/ra-core/dist/esm/auth/useHandleAuthCallback.js","../../node_modules/ra-core/dist/esm/auth/useIsAuthPending.js","../../node_modules/ra-core/dist/esm/auth/useRequireAccess.js","../../node_modules/ra-core/dist/esm/preferences/PreferenceKeyContext.js","../../node_modules/ra-core/dist/esm/preferences/usePreference.js","../../node_modules/ra-core/dist/esm/preferences/usePreferencesEditor.js","../../node_modules/ra-core/dist/esm/preferences/usePreferenceInput.js","../../node_modules/ra-core/dist/esm/preferences/useSetInspectorTitle.js","../../node_modules/react-admin/node_modules/@mui/material/colors/common.js","../../node_modules/react-admin/node_modules/@mui/material/colors/red.js","../../node_modules/react-admin/node_modules/@mui/material/colors/purple.js","../../node_modules/react-admin/node_modules/@mui/material/colors/blue.js","../../node_modules/react-admin/node_modules/@mui/material/colors/lightBlue.js","../../node_modules/react-admin/node_modules/@mui/material/colors/green.js","../../node_modules/react-admin/node_modules/@mui/material/colors/orange.js","../../node_modules/react-admin/node_modules/@mui/material/colors/grey.js","../../node_modules/react-admin/node_modules/@mui/material/styles/identifier.js","../../node_modules/react-admin/node_modules/@mui/material/styles/createPalette.js","../../node_modules/@mui/system/esm/cssVars/prepareTypographyVars.js","../../node_modules/react-admin/node_modules/@mui/material/styles/createMixins.js","../../node_modules/react-admin/node_modules/@mui/material/styles/createTypography.js","../../node_modules/react-admin/node_modules/@mui/material/styles/shadows.js","../../node_modules/react-admin/node_modules/@mui/material/styles/createTransitions.js","../../node_modules/react-admin/node_modules/@mui/material/styles/zIndex.js","../../node_modules/react-admin/node_modules/@mui/material/styles/stringifyTheme.js","../../node_modules/react-admin/node_modules/@mui/material/styles/createThemeNoVars.js","../../node_modules/react-admin/node_modules/@mui/material/styles/getOverlayAlpha.js","../../node_modules/react-admin/node_modules/@mui/material/styles/createColorScheme.js","../../node_modules/react-admin/node_modules/@mui/material/styles/shouldSkipGeneratingVar.js","../../node_modules/react-admin/node_modules/@mui/material/styles/excludeVariablesFromRoot.js","../../node_modules/react-admin/node_modules/@mui/material/styles/createGetSelector.js","../../node_modules/react-admin/node_modules/@mui/material/styles/createThemeWithVars.js","../../node_modules/react-admin/node_modules/@mui/material/styles/createTheme.js","../../node_modules/react-admin/node_modules/@mui/material/styles/defaultTheme.js","../../node_modules/react-admin/node_modules/@mui/material/styles/useTheme.js","../../node_modules/react-admin/node_modules/@mui/material/styles/useThemeProps.js","../../node_modules/react-admin/node_modules/@mui/material/styles/slotShouldForwardProp.js","../../node_modules/react-admin/node_modules/@mui/material/styles/rootShouldForwardProp.js","../../node_modules/react-admin/node_modules/@mui/material/styles/styled.js","../../node_modules/react-admin/node_modules/@mui/material/styles/ThemeProviderNoVars.js","../../node_modules/react-admin/node_modules/@mui/material/InitColorSchemeScript/InitColorSchemeScript.js","../../node_modules/react-admin/node_modules/@mui/material/styles/ThemeProviderWithVars.js","../../node_modules/react-admin/node_modules/@mui/material/styles/ThemeProvider.js","../../node_modules/react-admin/node_modules/@mui/material/GlobalStyles/GlobalStyles.js","../../node_modules/react-admin/node_modules/@mui/material/zero-styled/index.js","../../node_modules/react-admin/node_modules/@mui/material/utils/memoTheme.js","../../node_modules/react-admin/node_modules/@mui/material/DefaultPropsProvider/DefaultPropsProvider.js","../../node_modules/react-admin/node_modules/@mui/material/SvgIcon/svgIconClasses.js","../../node_modules/react-admin/node_modules/@mui/material/SvgIcon/SvgIcon.js","../../node_modules/react-admin/node_modules/@mui/material/utils/createSvgIcon.js","../../node_modules/react-admin/node_modules/@mui/material/utils/mergeSlotProps.js","../../node_modules/react-admin/node_modules/@mui/material/transitions/utils.js","../../node_modules/react-admin/node_modules/@mui/material/Paper/paperClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Paper/Paper.js","../../node_modules/react-admin/node_modules/@mui/material/utils/useSlot.js","../../node_modules/react-admin/node_modules/@mui/material/useLazyRipple/useLazyRipple.js","../../node_modules/react-admin/node_modules/@mui/material/ButtonBase/Ripple.js","../../node_modules/react-admin/node_modules/@mui/material/ButtonBase/touchRippleClasses.js","../../node_modules/react-admin/node_modules/@mui/material/ButtonBase/TouchRipple.js","../../node_modules/react-admin/node_modules/@mui/material/ButtonBase/buttonBaseClasses.js","../../node_modules/react-admin/node_modules/@mui/material/ButtonBase/ButtonBase.js","../../node_modules/react-admin/node_modules/@mui/material/utils/createSimplePaletteValueFilter.js","../../node_modules/react-admin/node_modules/@mui/material/Alert/alertClasses.js","../../node_modules/react-admin/node_modules/@mui/material/CircularProgress/circularProgressClasses.js","../../node_modules/react-admin/node_modules/@mui/material/CircularProgress/CircularProgress.js","../../node_modules/react-admin/node_modules/@mui/material/IconButton/iconButtonClasses.js","../../node_modules/react-admin/node_modules/@mui/material/IconButton/IconButton.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/SuccessOutlined.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/ReportProblemOutlined.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/ErrorOutline.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/InfoOutlined.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/Close.js","../../node_modules/react-admin/node_modules/@mui/material/Alert/Alert.js","../../node_modules/react-admin/node_modules/@mui/material/Typography/typographyClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Typography/Typography.js","../../node_modules/react-admin/node_modules/@mui/material/AppBar/appBarClasses.js","../../node_modules/react-admin/node_modules/@mui/material/AppBar/AppBar.js","../../node_modules/react-admin/node_modules/@mui/material/useAutocomplete/useAutocomplete.js","../../node_modules/react-admin/node_modules/@mui/material/Portal/Portal.js","../../node_modules/react-admin/node_modules/@mui/material/Popper/popperClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Popper/BasePopper.js","../../node_modules/react-admin/node_modules/@mui/material/Popper/Popper.js","../../node_modules/react-admin/node_modules/@mui/material/ListSubheader/listSubheaderClasses.js","../../node_modules/react-admin/node_modules/@mui/material/ListSubheader/ListSubheader.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/Cancel.js","../../node_modules/react-admin/node_modules/@mui/material/Chip/chipClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Chip/Chip.js","../../node_modules/react-admin/node_modules/@mui/material/TextareaAutosize/TextareaAutosize.js","../../node_modules/react-admin/node_modules/@mui/material/utils/isHostComponent.js","../../node_modules/react-admin/node_modules/@mui/material/FormControl/formControlState.js","../../node_modules/react-admin/node_modules/@mui/material/FormControl/FormControlContext.js","../../node_modules/react-admin/node_modules/@mui/material/FormControl/useFormControl.js","../../node_modules/react-admin/node_modules/@mui/material/InputBase/utils.js","../../node_modules/react-admin/node_modules/@mui/material/InputBase/inputBaseClasses.js","../../node_modules/react-admin/node_modules/@mui/material/InputBase/InputBase.js","../../node_modules/react-admin/node_modules/@mui/material/Input/inputClasses.js","../../node_modules/react-admin/node_modules/@mui/material/OutlinedInput/outlinedInputClasses.js","../../node_modules/react-admin/node_modules/@mui/material/FilledInput/filledInputClasses.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/ArrowDropDown.js","../../node_modules/react-admin/node_modules/@mui/material/Autocomplete/autocompleteClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Autocomplete/Autocomplete.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/Person.js","../../node_modules/react-admin/node_modules/@mui/material/Avatar/avatarClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Avatar/Avatar.js","../../node_modules/react-admin/node_modules/@mui/material/Fade/Fade.js","../../node_modules/react-admin/node_modules/@mui/material/Backdrop/backdropClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Backdrop/Backdrop.js","../../node_modules/react-admin/node_modules/@mui/material/Box/boxClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Box/Box.js","../../node_modules/react-admin/node_modules/@mui/material/Button/buttonClasses.js","../../node_modules/react-admin/node_modules/@mui/material/ButtonGroup/ButtonGroupContext.js","../../node_modules/react-admin/node_modules/@mui/material/ButtonGroup/ButtonGroupButtonContext.js","../../node_modules/react-admin/node_modules/@mui/material/Button/Button.js","../../node_modules/react-admin/node_modules/@mui/material/Card/cardClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Card/Card.js","../../node_modules/react-admin/node_modules/@mui/material/CardContent/cardContentClasses.js","../../node_modules/react-admin/node_modules/@mui/material/CardContent/CardContent.js","../../node_modules/react-admin/node_modules/@mui/material/internal/switchBaseClasses.js","../../node_modules/react-admin/node_modules/@mui/material/internal/SwitchBase.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/CheckBoxOutlineBlank.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/CheckBox.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/IndeterminateCheckBox.js","../../node_modules/react-admin/node_modules/@mui/material/Checkbox/checkboxClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Checkbox/Checkbox.js","../../node_modules/react-admin/node_modules/@mui/material/ClickAwayListener/ClickAwayListener.js","../../node_modules/react-admin/node_modules/@mui/material/CssBaseline/CssBaseline.js","../../node_modules/react-admin/node_modules/@mui/material/Modal/ModalManager.js","../../node_modules/react-admin/node_modules/@mui/material/Unstable_TrapFocus/FocusTrap.js","../../node_modules/react-admin/node_modules/@mui/material/Modal/useModal.js","../../node_modules/react-admin/node_modules/@mui/material/Modal/modalClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Modal/Modal.js","../../node_modules/react-admin/node_modules/@mui/material/Dialog/dialogClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Dialog/DialogContext.js","../../node_modules/react-admin/node_modules/@mui/material/Dialog/Dialog.js","../../node_modules/react-admin/node_modules/@mui/material/DialogActions/dialogActionsClasses.js","../../node_modules/react-admin/node_modules/@mui/material/DialogActions/DialogActions.js","../../node_modules/react-admin/node_modules/@mui/material/DialogContent/dialogContentClasses.js","../../node_modules/react-admin/node_modules/@mui/material/DialogTitle/dialogTitleClasses.js","../../node_modules/react-admin/node_modules/@mui/material/DialogContent/DialogContent.js","../../node_modules/react-admin/node_modules/@mui/material/DialogContentText/dialogContentTextClasses.js","../../node_modules/react-admin/node_modules/@mui/material/DialogContentText/DialogContentText.js","../../node_modules/react-admin/node_modules/@mui/material/DialogTitle/DialogTitle.js","../../node_modules/react-admin/node_modules/@mui/material/Divider/dividerClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Divider/Divider.js","../../node_modules/react-admin/node_modules/@mui/material/Slide/Slide.js","../../node_modules/react-admin/node_modules/@mui/material/Drawer/drawerClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Drawer/Drawer.js","../../node_modules/react-admin/node_modules/@mui/material/Fab/fabClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Fab/Fab.js","../../node_modules/react-admin/node_modules/@mui/material/FilledInput/FilledInput.js","../../node_modules/react-admin/node_modules/@mui/material/FormControl/formControlClasses.js","../../node_modules/react-admin/node_modules/@mui/material/FormControl/FormControl.js","../../node_modules/react-admin/node_modules/@mui/material/FormControlLabel/formControlLabelClasses.js","../../node_modules/react-admin/node_modules/@mui/material/FormControlLabel/FormControlLabel.js","../../node_modules/react-admin/node_modules/@mui/material/FormGroup/formGroupClasses.js","../../node_modules/react-admin/node_modules/@mui/material/FormGroup/FormGroup.js","../../node_modules/react-admin/node_modules/@mui/material/FormHelperText/formHelperTextClasses.js","../../node_modules/react-admin/node_modules/@mui/material/FormHelperText/FormHelperText.js","../../node_modules/react-admin/node_modules/@mui/material/FormLabel/formLabelClasses.js","../../node_modules/react-admin/node_modules/@mui/material/FormLabel/FormLabel.js","../../node_modules/react-admin/node_modules/@mui/material/Grow/Grow.js","../../node_modules/react-admin/node_modules/@mui/material/useMediaQuery/index.js","../../node_modules/react-admin/node_modules/@mui/material/Input/Input.js","../../node_modules/react-admin/node_modules/@mui/material/InputAdornment/inputAdornmentClasses.js","../../node_modules/react-admin/node_modules/@mui/material/InputAdornment/InputAdornment.js","../../node_modules/react-admin/node_modules/@mui/material/InputLabel/inputLabelClasses.js","../../node_modules/react-admin/node_modules/@mui/material/InputLabel/InputLabel.js","../../node_modules/react-admin/node_modules/@mui/material/LinearProgress/linearProgressClasses.js","../../node_modules/react-admin/node_modules/@mui/material/LinearProgress/LinearProgress.js","../../node_modules/react-admin/node_modules/@mui/material/Link/linkClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Link/getTextDecoration.js","../../node_modules/react-admin/node_modules/@mui/material/Link/Link.js","../../node_modules/react-admin/node_modules/@mui/material/List/ListContext.js","../../node_modules/react-admin/node_modules/@mui/material/List/listClasses.js","../../node_modules/react-admin/node_modules/@mui/material/List/List.js","../../node_modules/react-admin/node_modules/@mui/material/ListItemIcon/listItemIconClasses.js","../../node_modules/react-admin/node_modules/@mui/material/ListItemIcon/ListItemIcon.js","../../node_modules/react-admin/node_modules/@mui/material/ListItemText/listItemTextClasses.js","../../node_modules/react-admin/node_modules/@mui/material/ListItemText/ListItemText.js","../../node_modules/react-admin/node_modules/@mui/material/MenuList/MenuList.js","../../node_modules/react-admin/node_modules/@mui/material/Popover/popoverClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Popover/Popover.js","../../node_modules/react-admin/node_modules/@mui/material/Menu/menuClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Menu/Menu.js","../../node_modules/react-admin/node_modules/@mui/material/MenuItem/menuItemClasses.js","../../node_modules/react-admin/node_modules/@mui/material/MenuItem/MenuItem.js","../../node_modules/react-admin/node_modules/@mui/material/NativeSelect/nativeSelectClasses.js","../../node_modules/react-admin/node_modules/@mui/material/NativeSelect/NativeSelectInput.js","../../node_modules/react-admin/node_modules/@mui/material/OutlinedInput/NotchedOutline.js","../../node_modules/react-admin/node_modules/@mui/material/OutlinedInput/OutlinedInput.js","../../node_modules/react-admin/node_modules/@mui/material/Pagination/paginationClasses.js","../../node_modules/react-admin/node_modules/@mui/material/usePagination/usePagination.js","../../node_modules/react-admin/node_modules/@mui/material/PaginationItem/paginationItemClasses.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/FirstPage.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/LastPage.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/NavigateBefore.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/NavigateNext.js","../../node_modules/react-admin/node_modules/@mui/material/PaginationItem/PaginationItem.js","../../node_modules/react-admin/node_modules/@mui/material/Pagination/Pagination.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/RadioButtonUnchecked.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/RadioButtonChecked.js","../../node_modules/react-admin/node_modules/@mui/material/Radio/RadioButtonIcon.js","../../node_modules/react-admin/node_modules/@mui/material/RadioGroup/RadioGroupContext.js","../../node_modules/react-admin/node_modules/@mui/material/RadioGroup/useRadioGroup.js","../../node_modules/react-admin/node_modules/@mui/material/Radio/radioClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Radio/Radio.js","../../node_modules/react-admin/node_modules/@mui/material/RadioGroup/radioGroupClasses.js","../../node_modules/react-admin/node_modules/@mui/material/RadioGroup/RadioGroup.js","../../node_modules/react-admin/node_modules/@mui/material/Select/selectClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Select/SelectInput.js","../../node_modules/react-admin/node_modules/@mui/material/Select/Select.js","../../node_modules/react-admin/node_modules/@mui/material/Snackbar/useSnackbar.js","../../node_modules/react-admin/node_modules/@mui/material/SnackbarContent/snackbarContentClasses.js","../../node_modules/react-admin/node_modules/@mui/material/SnackbarContent/SnackbarContent.js","../../node_modules/react-admin/node_modules/@mui/material/Snackbar/snackbarClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Snackbar/Snackbar.js","../../node_modules/react-admin/node_modules/@mui/material/Tooltip/tooltipClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Tooltip/Tooltip.js","../../node_modules/react-admin/node_modules/@mui/material/Stack/Stack.js","../../node_modules/react-admin/node_modules/@mui/material/Switch/switchClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Switch/Switch.js","../../node_modules/react-admin/node_modules/@mui/material/Tab/tabClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Tab/Tab.js","../../node_modules/react-admin/node_modules/@mui/material/Table/TableContext.js","../../node_modules/react-admin/node_modules/@mui/material/Table/tableClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Table/Table.js","../../node_modules/react-admin/node_modules/@mui/material/Table/Tablelvl2Context.js","../../node_modules/react-admin/node_modules/@mui/material/TableBody/tableBodyClasses.js","../../node_modules/react-admin/node_modules/@mui/material/TableBody/TableBody.js","../../node_modules/react-admin/node_modules/@mui/material/TableCell/tableCellClasses.js","../../node_modules/react-admin/node_modules/@mui/material/TableCell/TableCell.js","../../node_modules/react-admin/node_modules/@mui/material/TableHead/tableHeadClasses.js","../../node_modules/react-admin/node_modules/@mui/material/TableHead/TableHead.js","../../node_modules/react-admin/node_modules/@mui/material/Toolbar/toolbarClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Toolbar/Toolbar.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/KeyboardArrowLeft.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/KeyboardArrowRight.js","../../node_modules/react-admin/node_modules/@mui/material/TablePagination/TablePaginationActions.js","../../node_modules/react-admin/node_modules/@mui/material/TablePagination/tablePaginationClasses.js","../../node_modules/react-admin/node_modules/@mui/material/TablePagination/TablePagination.js","../../node_modules/react-admin/node_modules/@mui/material/TableRow/tableRowClasses.js","../../node_modules/react-admin/node_modules/@mui/material/TableRow/TableRow.js","../../node_modules/react-admin/node_modules/@mui/material/internal/svg-icons/ArrowDownward.js","../../node_modules/react-admin/node_modules/@mui/material/TableSortLabel/tableSortLabelClasses.js","../../node_modules/react-admin/node_modules/@mui/material/TableSortLabel/TableSortLabel.js","../../node_modules/react-admin/node_modules/@mui/material/internal/animate.js","../../node_modules/react-admin/node_modules/@mui/material/Tabs/ScrollbarSize.js","../../node_modules/react-admin/node_modules/@mui/material/TabScrollButton/tabScrollButtonClasses.js","../../node_modules/react-admin/node_modules/@mui/material/TabScrollButton/TabScrollButton.js","../../node_modules/react-admin/node_modules/@mui/material/Tabs/tabsClasses.js","../../node_modules/react-admin/node_modules/@mui/material/Tabs/Tabs.js","../../node_modules/react-admin/node_modules/@mui/material/TextField/textFieldClasses.js","../../node_modules/react-admin/node_modules/@mui/material/TextField/TextField.js","../../node_modules/react-admin/node_modules/@mui/material/useScrollTrigger/useScrollTrigger.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Lock.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Queue.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/Button.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/CloneButton.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Add.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/CreateButton.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/RemoveRedEye.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/ShowButton.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Delete.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/AccessDenied.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Menu.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/useSidebarState.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/SidebarToggleButton.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/LoadingIndicator.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/AccountCircle.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/PowerSettingsNew.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/auth/Logout.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/UserMenuContext.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/UserMenuContextProvider.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/UserMenu.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/HideOnScroll.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/TitlePortal.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/theme/ThemesContext.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/theme/useThemesContext.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Brightness4.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Brightness7.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/theme/useTheme.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/theme/ThemeProvider.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/theme/defaultTheme.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/theme/nanoTheme.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/ToggleThemeButton.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/AppBar.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/ApplicationUpdatedNotification.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/WarningAmber.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/PageTitle.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Settings.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/preferences/Configurable.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/DragIndicator.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/preferences/FieldToggle.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/preferences/FieldsSelector.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/CancelOutlined.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/DeleteOutline.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/preferences/InspectorRoot.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/preferences/Inspector.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/PageTitleConfigurable.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/Title.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/AuthenticationError.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/CheckForApplicationUpdate.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/CheckCircle.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/ErrorOutline.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/Confirm.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Dashboard.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/MenuItemLink.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/DashboardMenuItem.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Report.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/ExpandMore.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/History.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/Error.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/Sidebar.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/ViewList.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/ResourceMenuItem.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/ResourceMenuItems.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/Menu.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/Loading.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/Layout.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/LinearProgress.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/LoadingPage.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/HotTub.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/NotFound.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/Notification.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/layout/TopToolbar.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/BulkDeleteWithConfirmButton.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/BulkDeleteWithUndoButton.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/BulkDeleteButton.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/GetApp.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/DeleteWithUndoButton.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/DeleteWithConfirmButton.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/DeleteButton.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Create.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/EditButton.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/ExportButton.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Translate.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/LocalesMenuButton.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Error.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Refresh.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/RefreshIconButton.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Save.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/SaveButton.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/SelectAllButton.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/button/SkipNavigationButton.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/auth/AuthError.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/auth/AuthCallback.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/InputHelperText.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/sanitizeInputRestProps.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/Labeled.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/RemoveCircleOutline.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/useSupportCreateSuggestion.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/AutocompleteInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/AutocompleteArrayInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/BooleanInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/CheckboxGroupInputItem.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/CheckboxGroupInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/useDatagridStyles.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/DatagridCell.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/ExpandRowButton.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/DatagridContext.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/useDatagridContext.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/DatagridRow.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/DatagridBody.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/DatagridHeaderCell.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/Placeholder.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/DatagridLoading.js","../../node_modules/lodash/_baseDifference.js","../../node_modules/lodash/difference.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/ExpandAllButton.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/DatagridHeader.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/DatagridContextProvider.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Close.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/BulkActionsToolbar.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/ListNoResults.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/Datagrid.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/DatagridEditor.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/datagrid/DatagridConfigurable.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/FilterContext.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/filter/FilterFormInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/filter/FilterForm.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Clear.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/BookmarkAdd.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/BookmarkRemove.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/BookmarkBorder.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/FilterList.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/CheckBoxOutlineBlank.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/CheckBox.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/filter/FilterButtonMenuItem.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/filter/useSavedQueries.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/filter/AddSavedQueryDialog.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/filter/RemoveSavedQueryDialog.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/filter/FilterButton.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Search.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/pagination/InfinitePagination.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/pagination/PaginationActions.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/pagination/Pagination.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/DateInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/ResettableTextField.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/LoadingInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/NullableBooleanInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/NumberInput.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Visibility.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/VisibilityOff.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/TextInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/PasswordInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/RadioButtonGroupInputItem.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/RadioButtonGroupInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/ReferenceArrayInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/ReferenceInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/SearchInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/SelectArrayInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/input/SelectInput.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/auth/LoginForm.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/auth/Login.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/detail/CreateView.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/detail/Create.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/detail/EditActions.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/detail/EditView.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/detail/Edit.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/form/Toolbar.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/form/SimpleForm.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/detail/ShowActions.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/detail/ShowView.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/detail/Show.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/genericMemo.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/ArrayField.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Done.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/sanitizeFieldRestProps.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/BooleanField.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/ChipField.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/DateField.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/FunctionField.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/NumberField.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/Link.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/SingleFieldList.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/ReferenceArrayField.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/ReferenceField.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/ReferenceManyCount.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/ReferenceManyField.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/field/TextField.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/detail/SimpleShowLayout.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/detail/TabbedShowLayoutTabs.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/detail/Tab.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/detail/TabbedShowLayout.js","../../node_modules/react-admin/node_modules/@mui/icons-material/esm/Inbox.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/Empty.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/ListToolbar.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/ListActions.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/ListView.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/InfiniteList.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/list/List.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/AdminUI.js","../../node_modules/react-admin/node_modules/ra-ui-materialui/dist/esm/AdminContext.js","../../node_modules/ra-language-english/dist/esm/index.js","../../node_modules/object-keys/isArguments.js","../../node_modules/object-keys/implementation.js","../../node_modules/object-keys/index.js","../../node_modules/es-define-property/index.js","../../node_modules/es-errors/syntax.js","../../node_modules/es-errors/type.js","../../node_modules/gopd/gOPD.js","../../node_modules/gopd/index.js","../../node_modules/define-data-property/index.js","../../node_modules/has-property-descriptors/index.js","../../node_modules/define-properties/index.js","../../node_modules/function-bind/implementation.js","../../node_modules/function-bind/index.js","../../node_modules/es-object-atoms/index.js","../../node_modules/es-errors/index.js","../../node_modules/es-errors/eval.js","../../node_modules/es-errors/range.js","../../node_modules/es-errors/ref.js","../../node_modules/es-errors/uri.js","../../node_modules/math-intrinsics/abs.js","../../node_modules/math-intrinsics/floor.js","../../node_modules/math-intrinsics/max.js","../../node_modules/math-intrinsics/min.js","../../node_modules/math-intrinsics/pow.js","../../node_modules/math-intrinsics/round.js","../../node_modules/math-intrinsics/isNaN.js","../../node_modules/math-intrinsics/sign.js","../../node_modules/has-symbols/shams.js","../../node_modules/has-symbols/index.js","../../node_modules/get-proto/Reflect.getPrototypeOf.js","../../node_modules/get-proto/Object.getPrototypeOf.js","../../node_modules/call-bind-apply-helpers/functionCall.js","../../node_modules/call-bind-apply-helpers/functionApply.js","../../node_modules/call-bind-apply-helpers/reflectApply.js","../../node_modules/call-bind-apply-helpers/actualApply.js","../../node_modules/call-bind-apply-helpers/index.js","../../node_modules/dunder-proto/get.js","../../node_modules/get-proto/index.js","../../node_modules/hasown/index.js","../../node_modules/get-intrinsic/index.js","../../node_modules/set-function-length/index.js","../../node_modules/call-bind/index.js","../../node_modules/es-object-atoms/RequireObjectCoercible.js","../../node_modules/call-bind/callBound.js","../../node_modules/object.entries/implementation.js","../../node_modules/object.entries/polyfill.js","../../node_modules/object.entries/shim.js","../../node_modules/object.entries/index.js","../../node_modules/node-polyglot/index.js","../../node_modules/ra-i18n-polyglot/dist/esm/index.js","../../node_modules/react-admin/dist/esm/defaultI18nProvider.js","../../node_modules/react-admin/dist/esm/Admin.js","../../node_modules/@mui/icons-material/utils/createSvgIcon.js","../../node_modules/@mui/icons-material/ShareLocation.js","../../node_modules/@mui/material/internal/svg-icons/Close.js","../../node_modules/@mui/material/useAutocomplete/useAutocomplete.js","../../node_modules/@mui/material/ListSubheader/listSubheaderClasses.js","../../node_modules/@mui/material/ListSubheader/ListSubheader.js","../../node_modules/@mui/material/Autocomplete/autocompleteClasses.js","../../node_modules/@mui/material/Autocomplete/Autocomplete.js","../../node_modules/@mui/material/Badge/useBadge.js","../../node_modules/@mui/material/Badge/badgeClasses.js","../../node_modules/@mui/material/Badge/Badge.js","../../node_modules/@mui/material/Box/boxClasses.js","../../node_modules/@mui/material/Box/Box.js","../../node_modules/@mui/material/internal/svg-icons/MoreHoriz.js","../../node_modules/@mui/material/Breadcrumbs/BreadcrumbCollapsed.js","../../node_modules/@mui/material/Breadcrumbs/breadcrumbsClasses.js","../../node_modules/@mui/material/Breadcrumbs/Breadcrumbs.js","../../node_modules/@mui/material/Card/cardClasses.js","../../node_modules/@mui/material/Card/Card.js","../../node_modules/@mui/material/CardContent/cardContentClasses.js","../../node_modules/@mui/material/CardContent/CardContent.js","../../node_modules/@mui/material/CardHeader/cardHeaderClasses.js","../../node_modules/@mui/material/CardHeader/CardHeader.js","../../node_modules/@mui/material/internal/switchBaseClasses.js","../../node_modules/@mui/material/internal/SwitchBase.js","../../node_modules/@mui/material/internal/svg-icons/CheckBoxOutlineBlank.js","../../node_modules/@mui/material/internal/svg-icons/CheckBox.js","../../node_modules/@mui/material/internal/svg-icons/IndeterminateCheckBox.js","../../node_modules/@mui/material/Checkbox/checkboxClasses.js","../../node_modules/@mui/material/Checkbox/Checkbox.js","../../node_modules/@mui/material/CircularProgress/circularProgressClasses.js","../../node_modules/@mui/material/CircularProgress/CircularProgress.js","../../node_modules/@mui/material/ClickAwayListener/ClickAwayListener.js","../../node_modules/@mui/material/DialogContentText/dialogContentTextClasses.js","../../node_modules/@mui/material/DialogContentText/DialogContentText.js","../../node_modules/@mui/material/DialogTitle/DialogTitle.js","../../node_modules/@mui/material/Stack/Stack.js","../../node_modules/@mui/material/FormControlLabel/formControlLabelClasses.js","../../node_modules/@mui/material/FormControlLabel/FormControlLabel.js","../../node_modules/@mui/material/FormGroup/formGroupClasses.js","../../node_modules/@mui/material/FormGroup/FormGroup.js","../../node_modules/@mui/material/Grid/GridContext.js","../../node_modules/@mui/material/Grid/gridClasses.js","../../node_modules/@mui/material/Grid/Grid.js","../../node_modules/@mui/material/LinearProgress/linearProgressClasses.js","../../node_modules/@mui/material/LinearProgress/LinearProgress.js","../../node_modules/@mui/material/Link/linkClasses.js","../../node_modules/@mui/material/Link/getTextDecoration.js","../../node_modules/@mui/material/Link/Link.js","../../node_modules/@mui/material/NoSsr/NoSsr.js","../../node_modules/@mui/material/internal/svg-icons/FirstPage.js","../../node_modules/@mui/material/internal/svg-icons/LastPage.js","../../node_modules/@mui/material/internal/svg-icons/RadioButtonUnchecked.js","../../node_modules/@mui/material/internal/svg-icons/RadioButtonChecked.js","../../node_modules/@mui/material/Radio/RadioButtonIcon.js","../../node_modules/@mui/material/RadioGroup/RadioGroupContext.js","../../node_modules/@mui/material/RadioGroup/useRadioGroup.js","../../node_modules/@mui/material/Radio/radioClasses.js","../../node_modules/@mui/material/Radio/Radio.js","../../node_modules/@mui/material/RadioGroup/radioGroupClasses.js","../../node_modules/@mui/material/RadioGroup/RadioGroup.js","../../node_modules/@mui/material/Tooltip/tooltipClasses.js","../../node_modules/@mui/material/Tooltip/Tooltip.js","../../node_modules/@mui/material/Switch/switchClasses.js","../../node_modules/@mui/material/Switch/Switch.js","../../node_modules/@mui/material/Table/TableContext.js","../../node_modules/@mui/material/Table/Tablelvl2Context.js","../../node_modules/@mui/material/TableCell/tableCellClasses.js","../../node_modules/@mui/material/TableCell/TableCell.js","../../node_modules/@mui/material/Toolbar/toolbarClasses.js","../../node_modules/@mui/material/Toolbar/Toolbar.js","../../node_modules/@mui/material/TablePagination/TablePaginationActions.js","../../node_modules/@mui/material/TablePagination/tablePaginationClasses.js","../../node_modules/@mui/material/TablePagination/TablePagination.js","../../node_modules/@turf/helpers/dist/es/index.js","../../node_modules/@turf/meta/dist/es/index.js","../../node_modules/@turf/bbox/dist/es/index.js","../../node_modules/@react-leaflet/core/lib/attribution.js","../../node_modules/@react-leaflet/core/lib/circle.js","../../node_modules/@react-leaflet/core/lib/context.js","../../node_modules/@react-leaflet/core/lib/component.js","../../node_modules/@react-leaflet/core/lib/control.js","../../node_modules/@react-leaflet/core/lib/events.js","../../node_modules/@react-leaflet/core/lib/pane.js","../../node_modules/@react-leaflet/core/lib/div-overlay.js","../../node_modules/leaflet/dist/leaflet-src.js","../../node_modules/@react-leaflet/core/lib/dom.js","../../node_modules/@react-leaflet/core/lib/element.js","../../node_modules/@react-leaflet/core/lib/layer.js","../../node_modules/@react-leaflet/core/lib/path.js","../../node_modules/@react-leaflet/core/lib/generic.js","../../node_modules/@react-leaflet/core/lib/grid-layer.js","../../node_modules/@react-leaflet/core/lib/media-overlay.js","../../node_modules/react-leaflet/lib/hooks.js","../../node_modules/react-leaflet/lib/Circle.js","../../node_modules/react-leaflet/lib/FeatureGroup.js","../../node_modules/react-leaflet/lib/GeoJSON.js","../../node_modules/react-leaflet/lib/LayersControl.js","../../node_modules/react-leaflet/lib/MapContainer.js","../../node_modules/react-leaflet/lib/Marker.js","../../node_modules/react-leaflet/lib/Polygon.js","../../node_modules/react-leaflet/lib/Polyline.js","../../node_modules/react-leaflet/lib/Popup.js","../../node_modules/react-leaflet/lib/TileLayer.js","../../node_modules/react-leaflet/lib/Tooltip.js","../../node_modules/leaflet-draw/dist/leaflet.draw.js","../../node_modules/fast-deep-equal/index.js","../../node_modules/react-leaflet-draw/dist/esm/EditControl.js","../../node_modules/@mui/icons-material/CenterFocusWeakRounded.js","../../node_modules/react-leaflet-custom-control/lib/Control.js","../../src/components/CustomMap/FocusControl.tsx","../../src/components/CustomMap/CustomMap.tsx","../../src/components/CustomMap/FocussedGeoJson.tsx","../../node_modules/@turf/area/dist/es/index.js","../../node_modules/@turf/invariant/dist/es/index.js","../../node_modules/geojson-rbush/node_modules/rbush/rbush.min.js","../../node_modules/geojson-rbush/index.js","../../node_modules/@turf/line-segment/dist/es/index.js","../../node_modules/@turf/bearing/dist/es/index.js","../../node_modules/@turf/distance/dist/es/index.js","../../node_modules/@turf/destination/dist/es/index.js","../../node_modules/@turf/line-intersect/dist/es/index.js","../../node_modules/@turf/nearest-point-on-line/dist/es/index.js","../../node_modules/@turf/boolean-point-on-line/dist/es/index.js","../../node_modules/has-tostringtag/shams.js","../../node_modules/is-arguments/index.js","../../node_modules/object-is/implementation.js","../../node_modules/object-is/polyfill.js","../../node_modules/object-is/shim.js","../../node_modules/object-is/index.js","../../node_modules/call-bound/index.js","../../node_modules/is-regex/index.js","../../node_modules/functions-have-names/index.js","../../node_modules/set-function-name/index.js","../../node_modules/regexp.prototype.flags/implementation.js","../../node_modules/regexp.prototype.flags/polyfill.js","../../node_modules/regexp.prototype.flags/shim.js","../../node_modules/regexp.prototype.flags/index.js","../../node_modules/is-date-object/index.js","../../node_modules/deep-equal/index.js","../../node_modules/@turf/line-overlap/dist/es/index.js","../../node_modules/geojson-equality/index.js","../../node_modules/@turf/boolean-overlap/dist/es/index.js","../../node_modules/@turf/kinks/dist/es/index.js","../../src/components/CustomMap/utils.ts","../../src/components/CustomMap/PolygonEditMap/index.tsx","../../src/components/CustomMap/PolygonEditMap/GeoJsonInput.tsx","../../src/routes/areasOfOperation/AreaOfOperationGeoJsonInput.tsx","../../src/routes/common/fieldRenderers.ts","../../src/routes/areasOfOperation/AreaOfOperationCreate.tsx","../../src/routes/areasOfOperation/AreaOfOperationEdit.tsx","../../src/routes/areasOfOperation/AreaOfOperationList.tsx","../../node_modules/@mui/icons-material/Create.js","../../node_modules/@mui/icons-material/Visibility.js","../../src/components/CustomMap/FarmsGeoJson.tsx","../../src/routes/areasOfOperation/AreaOfOperationShow/AreaOfOperationShowDetails.tsx","../../src/routes/areasOfOperation/AreaOfOperationShow/index.tsx","../../src/routes/areasOfOperation/index.tsx","../../node_modules/@mui/icons-material/Person.js","../../src/routes/cognitoUsers/CognitoUserCreate.tsx","../../src/routes/cognitoUsers/CognitoUserList.tsx","../../src/routes/cognitoUsers/CognitoUserShow.tsx","../../src/routes/cognitoUsers/index.ts","../../node_modules/@mui/icons-material/Grass.js","../../src/routes/crops/CropGeoJsonInput.tsx","../../src/routes/crops/utils.ts","../../src/routes/crops/CropCreate.tsx","../../src/routes/crops/CropEdit.tsx","../../src/routes/crops/CropActiveField.tsx","../../src/routes/crops/CropList.tsx","../../src/components/CustomMap/CropsGeoJson.tsx","../../src/components/CustomMap/FieldsGeoJson.tsx","../../src/routes/crops/CropShow/CropShowDetails.tsx","../../src/routes/crops/CropShow/index.tsx","../../src/routes/crops/index.tsx","../../node_modules/@mui/icons-material/Assessment.js","../../node_modules/@mui/icons-material/Settings.js","../../src/routes/CustomLayout.tsx","../../node_modules/@mui/x-charts/constants/index.js","../../node_modules/@mui/x-charts/context/HighlightedProvider/HighlightedContext.js","../../node_modules/@mui/x-charts/context/HighlightedProvider/createIsFaded.js","../../node_modules/@mui/x-charts/context/HighlightedProvider/createIsHighlighted.js","../../node_modules/@mui/x-charts/internals/defaultizeColor.js","../../node_modules/@mui/x-charts/context/SeriesProvider/processSeries.js","../../node_modules/@mui/x-charts/colorPalettes/colorPalettes.js","../../node_modules/@mui/x-charts/context/SeriesProvider/SeriesContext.js","../../node_modules/@mui/x-charts/context/PluginProvider/PluginContext.js","../../node_modules/@mui/x-charts/BarChart/extremums.js","../../node_modules/d3-shape/src/constant.js","../../node_modules/d3-shape/src/math.js","../../node_modules/d3-path/src/path.js","../../node_modules/d3-shape/src/path.js","../../node_modules/d3-shape/src/arc.js","../../node_modules/d3-shape/src/array.js","../../node_modules/d3-shape/src/descending.js","../../node_modules/d3-shape/src/identity.js","../../node_modules/d3-shape/src/pie.js","../../node_modules/d3-shape/src/offset/none.js","../../node_modules/d3-shape/src/order/none.js","../../node_modules/d3-shape/src/stack.js","../../node_modules/d3-shape/src/offset/expand.js","../../node_modules/d3-shape/src/offset/diverging.js","../../node_modules/d3-shape/src/offset/silhouette.js","../../node_modules/d3-shape/src/offset/wiggle.js","../../node_modules/d3-shape/src/order/appearance.js","../../node_modules/d3-shape/src/order/ascending.js","../../node_modules/d3-shape/src/order/descending.js","../../node_modules/d3-shape/src/order/insideOut.js","../../node_modules/d3-shape/src/order/reverse.js","../../node_modules/@mui/x-charts/internals/stackSeries.js","../../node_modules/@mui/x-charts/internals/defaultizeValueFormatter.js","../../node_modules/@mui/x-charts/BarChart/formatter.js","../../node_modules/@mui/x-charts/BarChart/getColor.js","../../node_modules/@mui/x-charts/BarChart/plugin.js","../../node_modules/@mui/x-charts/ScatterChart/extremums.js","../../node_modules/@mui/x-charts/ScatterChart/formatter.js","../../node_modules/@mui/x-charts/ScatterChart/getColor.js","../../node_modules/@mui/x-charts/ScatterChart/plugin.js","../../node_modules/@mui/x-charts/LineChart/extremums.js","../../node_modules/@mui/x-charts/LineChart/formatter.js","../../node_modules/@mui/x-charts/LineChart/getColor.js","../../node_modules/@mui/x-charts/LineChart/plugin.js","../../node_modules/@mui/x-charts/internals/getLabel.js","../../node_modules/@mui/x-charts/PieChart/formatter.js","../../node_modules/@mui/x-charts/PieChart/getColor.js","../../node_modules/@mui/x-charts/PieChart/plugin.js","../../node_modules/@mui/x-charts/context/PluginProvider/mergePlugins.js","../../node_modules/@mui/x-charts/context/PluginProvider/PluginProvider.js","../../node_modules/@mui/x-charts/context/PluginProvider/useColorProcessor.js","../../node_modules/@mui/x-charts/context/PluginProvider/useSeriesFormatter.js","../../node_modules/@mui/x-charts/context/PluginProvider/useXExtremumGetter.js","../../node_modules/@mui/x-charts/context/PluginProvider/useYExtremumGetter.js","../../node_modules/@mui/x-charts/context/SeriesProvider/SeriesProvider.js","../../node_modules/@mui/x-charts/hooks/useSeries.js","../../node_modules/@mui/x-charts/context/HighlightedProvider/HighlightedProvider.js","../../node_modules/@mui/x-charts/context/HighlightedProvider/useHighlighted.js","../../node_modules/@mui/x-charts/context/HighlightedProvider/useItemHighlighted.js","../../node_modules/d3-array/src/ascending.js","../../node_modules/d3-array/src/descending.js","../../node_modules/d3-array/src/bisector.js","../../node_modules/d3-array/src/number.js","../../node_modules/d3-array/src/bisect.js","../../node_modules/internmap/src/index.js","../../node_modules/d3-array/src/ticks.js","../../node_modules/d3-array/src/range.js","../../node_modules/d3-scale/src/init.js","../../node_modules/d3-scale/src/ordinal.js","../../node_modules/d3-scale/src/band.js","../../node_modules/d3-color/src/define.js","../../node_modules/d3-color/src/color.js","../../node_modules/d3-interpolate/src/constant.js","../../node_modules/d3-interpolate/src/color.js","../../node_modules/d3-interpolate/src/rgb.js","../../node_modules/d3-interpolate/src/numberArray.js","../../node_modules/d3-interpolate/src/array.js","../../node_modules/d3-interpolate/src/date.js","../../node_modules/d3-interpolate/src/number.js","../../node_modules/d3-interpolate/src/object.js","../../node_modules/d3-interpolate/src/string.js","../../node_modules/d3-interpolate/src/value.js","../../node_modules/d3-interpolate/src/round.js","../../node_modules/d3-scale/src/constant.js","../../node_modules/d3-scale/src/number.js","../../node_modules/d3-scale/src/continuous.js","../../node_modules/d3-format/src/formatDecimal.js","../../node_modules/d3-format/src/exponent.js","../../node_modules/d3-format/src/formatGroup.js","../../node_modules/d3-format/src/formatNumerals.js","../../node_modules/d3-format/src/formatSpecifier.js","../../node_modules/d3-format/src/formatTrim.js","../../node_modules/d3-format/src/formatPrefixAuto.js","../../node_modules/d3-format/src/formatRounded.js","../../node_modules/d3-format/src/formatTypes.js","../../node_modules/d3-format/src/identity.js","../../node_modules/d3-format/src/locale.js","../../node_modules/d3-format/src/defaultLocale.js","../../node_modules/d3-format/src/precisionFixed.js","../../node_modules/d3-format/src/precisionPrefix.js","../../node_modules/d3-format/src/precisionRound.js","../../node_modules/d3-scale/src/tickFormat.js","../../node_modules/d3-scale/src/linear.js","../../node_modules/d3-scale/src/nice.js","../../node_modules/d3-scale/src/log.js","../../node_modules/d3-scale/src/pow.js","../../node_modules/d3-scale/src/threshold.js","../../node_modules/d3-time/src/interval.js","../../node_modules/d3-time/src/millisecond.js","../../node_modules/d3-time/src/duration.js","../../node_modules/d3-time/src/second.js","../../node_modules/d3-time/src/minute.js","../../node_modules/d3-time/src/hour.js","../../node_modules/d3-time/src/day.js","../../node_modules/d3-time/src/week.js","../../node_modules/d3-time/src/month.js","../../node_modules/d3-time/src/year.js","../../node_modules/d3-time/src/ticks.js","../../node_modules/d3-time-format/src/locale.js","../../node_modules/d3-time-format/src/defaultLocale.js","../../node_modules/d3-scale/src/time.js","../../node_modules/d3-scale/src/utcTime.js","../../node_modules/d3-scale/src/sequential.js","../../node_modules/@mui/x-charts/internals/colorScale.js","../../node_modules/@mui/x-charts/context/ZAxisContextProvider.js","../../node_modules/@mui/x-charts/hooks/useChartDimensions.js","../../node_modules/@mui/x-charts/context/DrawingProvider.js","../../node_modules/@mui/x-charts/hooks/useDrawingArea.js","../../node_modules/@mui/x-charts/hooks/useChartId.js","../../node_modules/@mui/x-charts/internals/isBandScale.js","../../node_modules/@mui/x-charts/models/axis.js","../../node_modules/@mui/x-charts/internals/isInfinity.js","../../node_modules/@mui/x-charts/hooks/useTicks.js","../../node_modules/@mui/x-charts/internals/getScale.js","../../node_modules/@mui/x-charts/context/CartesianProvider/zoom.js","../../node_modules/@mui/x-charts/context/CartesianProvider/getAxisExtremum.js","../../node_modules/@mui/x-charts/internals/computeAxisValue.js","../../node_modules/@mui/x-charts/context/CartesianProvider/CartesianContext.js","../../node_modules/@mui/x-charts/context/CartesianProvider/CartesianProvider.js","../../node_modules/@mui/x-charts/context/CartesianProvider/useCartesianContext.js","../../node_modules/@mui/x-charts/hooks/useScale.js","../../node_modules/@mui/x-charts/hooks/useSvgRef.js","../../node_modules/@mui/x-charts/ChartsClipPath/ChartsClipPath.js","../../node_modules/@mui/x-charts/internals/domUtils.js","../../node_modules/@mui/x-charts/internals/getWordsByLines.js","../../node_modules/@mui/x-charts/ChartsText/ChartsText.js","../../node_modules/@mui/x-charts/ChartsAxis/axisClasses.js","../../node_modules/@mui/x-charts/internals/components/AxisSharedComponents.js","../../node_modules/@mui/x-charts/internals/geometry.js","../../node_modules/@mui/x-charts/hooks/useMounted.js","../../node_modules/@mui/x-charts/ChartsXAxis/ChartsXAxis.js","../../node_modules/@mui/x-charts/ChartsYAxis/ChartsYAxis.js","../../node_modules/@mui/x-charts/ChartsAxis/ChartsAxis.js","../../node_modules/@mui/x-charts/ChartsGrid/chartsGridClasses.js","../../node_modules/@mui/x-charts/ChartsGrid/styledCommonents.js","../../node_modules/@mui/x-charts/ChartsGrid/ChartsVerticalGrid.js","../../node_modules/@mui/x-charts/ChartsGrid/ChartsHorizontalGrid.js","../../node_modules/@mui/x-charts/ChartsGrid/ChartsGrid.js","../../node_modules/@mui/x-charts/context/InteractionProvider.js","../../node_modules/@mui/x-charts/ChartsTooltip/utils.js","../../node_modules/@mui/x-charts/ChartsTooltip/chartsTooltipClasses.js","../../node_modules/@mui/x-charts/ChartsTooltip/ChartsTooltipTable.js","../../node_modules/@mui/x-charts/ChartsTooltip/DefaultChartsItemTooltipContent.js","../../node_modules/@mui/x-charts/ChartsTooltip/ChartsItemTooltipContent.js","../../node_modules/@mui/x-charts/internals/configInit.js","../../node_modules/@mui/x-charts/internals/isCartesian.js","../../node_modules/@mui/x-charts/ChartsTooltip/DefaultChartsAxisTooltipContent.js","../../node_modules/@mui/x-charts/ChartsTooltip/ChartsAxisTooltipContent.js","../../node_modules/@mui/x-charts/ChartsTooltip/ChartsTooltip.js","../../node_modules/@mui/x-charts/BarChart/legend.js","../../node_modules/@mui/x-charts/ScatterChart/legend.js","../../node_modules/@mui/x-charts/LineChart/legend.js","../../node_modules/@mui/x-charts/PieChart/legend.js","../../node_modules/@mui/x-charts/ChartsLegend/utils.js","../../node_modules/@mui/x-charts/ChartsLegend/chartsLegendClasses.js","../../node_modules/@mui/x-charts/ChartsLegend/legendItemsPlacement.js","../../node_modules/@mui/x-charts/ChartsLegend/ChartsLegendItem.js","../../node_modules/@mui/x-charts/ChartsLegend/LegendPerItem.js","../../node_modules/@mui/x-charts/ChartsLegend/DefaultChartsLegend.js","../../node_modules/@mui/x-charts/ChartsLegend/ChartsLegend.js","../../node_modules/@mui/x-charts/internals/components/ChartsAxesGradients/ChartsContinuousGradient.js","../../node_modules/@mui/x-charts/internals/getPercentageValue.js","../../node_modules/@mui/x-charts/ChartsAxisHighlight/ChartsAxisHighlight.js","../../node_modules/@mui/x-charts/internals/getSVGPoint.js","../../node_modules/@mui/x-charts/ChartsOnAxisClickHandler/ChartsOnAxisClickHandler.js","../../node_modules/@react-spring/rafz/dist/react-spring_rafz.modern.mjs","../../node_modules/@react-spring/shared/dist/react-spring_shared.modern.mjs","../../node_modules/@react-spring/animated/dist/react-spring_animated.modern.mjs","../../node_modules/@react-spring/core/dist/react-spring_core.modern.mjs","../../node_modules/@react-spring/web/dist/react-spring_web.modern.mjs","../../node_modules/@mui/x-charts/hooks/useInteractionItemProps.js","../../node_modules/@mui/x-charts/BarChart/BarElement.js","../../node_modules/@mui/x-charts/BarChart/getRadius.js","../../node_modules/@mui/x-charts/BarChart/BarClipPath.js","../../node_modules/@mui/x-charts/BarChart/BarLabel/barLabelClasses.js","../../node_modules/@mui/x-charts/BarChart/BarLabel/getBarLabel.js","../../node_modules/@mui/x-charts/BarChart/BarLabel/BarLabel.js","../../node_modules/@mui/x-charts/BarChart/BarLabel/BarLabelItem.js","../../node_modules/@mui/x-charts/BarChart/BarLabel/BarLabelPlot.js","../../node_modules/@mui/x-charts/BarChart/checkScaleErrors.js","../../node_modules/@mui/x-charts/context/AnimationProvider/AnimationContext.js","../../node_modules/@mui/x-charts/context/AnimationProvider/AnimationProvider.js","../../node_modules/@mui/x-charts/context/AnimationProvider/useSkipAnimation.js","../../node_modules/@mui/x-charts/BarChart/BarPlot.js","../../node_modules/@mui/x-charts/hooks/useAxisEvents.js","../../node_modules/@mui/x-charts/ChartsSurface/ChartsSurface.js","../../node_modules/@mui/x-charts/internals/components/ChartsAxesGradients/ChartsPiecewiseGradient.js","../../node_modules/@mui/x-charts/internals/components/ChartsAxesGradients/ChartsAxesGradients.js","../../node_modules/@mui/x-charts/ChartContainer/useDefaultizeAxis.js","../../node_modules/@mui/x-charts/ChartContainer/useChartContainerProps.js","../../node_modules/@mui/x-charts/ChartContainer/ChartContainer.js","../../node_modules/@mui/x-charts/ResponsiveChartContainer/ResizableContainer.js","../../node_modules/@mui/x-charts/ResponsiveChartContainer/useChartContainerDimensions.js","../../node_modules/@mui/x-charts/ResponsiveChartContainer/useResponsiveChartContainerProps.js","../../node_modules/@mui/x-charts/ResponsiveChartContainer/ResponsiveChartContainer.js","../../node_modules/@mui/x-charts/ChartsOverlay/ChartsLoadingOverlay.js","../../node_modules/@mui/x-charts/ChartsOverlay/ChartsNoDataOverlay.js","../../node_modules/@mui/x-charts/ChartsOverlay/ChartsOverlay.js","../../node_modules/@mui/x-charts/BarChart/useBarChartProps.js","../../node_modules/@mui/x-charts/BarChart/BarChart.js","../../node_modules/@mui/x-charts/PieChart/PieArc.js","../../node_modules/@mui/x-charts/PieChart/dataTransform/transition.js","../../node_modules/@mui/x-charts/PieChart/dataTransform/useTransformData.js","../../node_modules/@mui/x-charts/PieChart/PieArcPlot.js","../../node_modules/@mui/x-charts/PieChart/PieArcLabel.js","../../node_modules/@mui/x-charts/PieChart/PieArcLabelPlot.js","../../node_modules/@mui/x-charts/PieChart/getPieCoordinates.js","../../node_modules/@mui/x-charts/PieChart/PiePlot.js","../../node_modules/@mui/x-charts/PieChart/PieChart.js","../../node_modules/@mui/x-charts/Gauge/utils.js","../../node_modules/@mui/x-charts/Gauge/GaugeProvider.js","../../node_modules/@mui/x-charts/Gauge/GaugeContainer.js","../../node_modules/@mui/x-charts/Gauge/GaugeValueArc.js","../../node_modules/@mui/x-charts/Gauge/GaugeReferenceArc.js","../../node_modules/@mui/x-charts/Gauge/gaugeClasses.js","../../node_modules/@mui/x-charts/Gauge/GaugeValueText.js","../../node_modules/@mui/x-charts/Gauge/Gauge.js","../../src/components/TelemetryCards/GenericCards/BaseCard.tsx","../../src/components/TelemetryCards/GenericCards/GaugeCard.tsx","../../src/utils/tankVolumes.ts","../../src/components/TelemetryCards/FuelTankLevel.tsx","../../src/context/flespi/useFlespi.ts","../../src/routes/dashboard/FuelTanks.tsx","../../node_modules/leaflet.markercluster/dist/leaflet.markercluster-src.js","../../node_modules/react-leaflet-cluster/lib/assets/marker-icon-2x.png","../../node_modules/react-leaflet-cluster/lib/assets/marker-icon.png","../../node_modules/react-leaflet-cluster/lib/assets/marker-shadow.png","../../node_modules/react-leaflet-cluster/lib/index.js","../../src/routes/dashboard/VehicleLocations.tsx","../../src/routes/dashboard/index.tsx","../../node_modules/@mui/icons-material/Badge.js","../../src/routes/employees/EmployeeCreate.tsx","../../src/routes/employees/EmployeeEdit.tsx","../../src/routes/employees/EmployeeList.tsx","../../src/routes/employees/EmployeeShow.tsx","../../src/routes/employees/index.tsx","../../node_modules/@mui/icons-material/RvHookupSharp.js","../../src/routes/farmImplements/utils.ts","../../src/routes/farmImplements/FarmImplementCreate.tsx","../../src/routes/farmImplements/FarmImplementEdit.tsx","../../src/routes/farmImplements/FarmImplementList.tsx","../../src/routes/farmImplements/FarmImplementShow.tsx","../../src/routes/farmImplements/index.tsx","../../src/components/CustomInputs/SARSCodes.tsx","../../src/routes/farmImplementType/FarmImplementTypeCreate.tsx","../../src/routes/farmImplementType/FarmImplementTypeEdit.tsx","../../src/routes/farmImplementType/FarmImplementTypeList.tsx","../../src/routes/farmImplementType/FarmImplementTypeShow.tsx","../../src/routes/farmImplementType/index.tsx","../../node_modules/@mui/icons-material/House.js","../../src/routes/farms/FarmGeoJsonInput.tsx","../../src/routes/farms/FarmCreate.tsx","../../src/routes/farms/FarmEdit.tsx","../../src/routes/farms/FarmList.tsx","../../src/routes/farms/FarmShow/FarmFields.tsx","../../src/routes/farms/FarmShow/FarmShowDetails.tsx","../../src/routes/farms/FarmShow/index.tsx","../../src/routes/farms/index.tsx","../../node_modules/@mui/icons-material/Terrain.js","../../src/routes/fields/FieldGeoJsonInput.tsx","../../src/routes/fields/FieldCreate.tsx","../../src/routes/fields/FieldEdit.tsx","../../src/routes/fields/FieldList.tsx","../../src/routes/fields/FieldShow/FieldCrops.tsx","../../src/routes/fields/FieldShow/FieldShowDetails.tsx","../../src/routes/fields/FieldShow/index.tsx","../../src/routes/fields/index.tsx","../../node_modules/@mui/icons-material/LocalGasStation.js","../../src/assets/horizontal-cylindrical.png","../../src/assets/horizontal-elliptical.png","../../src/routes/fuelDispensers/TankShapeInput.tsx","../../src/routes/fuelDispensers/FuelDispenserCreate.tsx","../../src/routes/fuelDispensers/FuelDispenserEdit.tsx","../../src/routes/fuelDispensers/utils.ts","../../src/routes/fuelDispensers/FuelDispenserList.tsx","../../src/components/TelemetryCards/BatteryLevel.tsx","../../node_modules/@mui/icons-material/SatelliteAlt.js","../../src/components/TelemetryCards/GenericCards/BooleanIconCard.tsx","../../src/components/TelemetryCards/GPS.tsx","../../node_modules/@mui/icons-material/Key.js","../../src/components/TelemetryCards/Ignition.tsx","../../src/components/TelemetryCards/GenericCards/BarChartLevelCard.tsx","../../src/components/TelemetryCards/SignalLevel.tsx","../../src/routes/fuelDispensers/FuelDispenserShow/FuelDispenserTelemetryCard/index.tsx","../../node_modules/@mui/icons-material/Add.js","../../node_modules/@mui/icons-material/ArrowBackIos.js","../../node_modules/@mui/icons-material/ArrowForwardIos.js","../../node_modules/@mui/x-data-grid/components/GridApiContext.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridApiContext.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridApiRef.js","../../node_modules/@mui/x-data-grid/context/GridRootPropsContext.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridRootProps.js","../../node_modules/@mui/x-data-grid/node_modules/@mui/x-internals/esm/reactMajor.js","../../node_modules/@mui/x-data-grid/node_modules/@mui/x-internals/esm/forwardRef/forwardRef.js","../../node_modules/reselect/dist/reselect.mjs","../../node_modules/@mui/x-data-grid/node_modules/@mui/x-internals/esm/fastObjectShallowCompare/fastObjectShallowCompare.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridSelector.js","../../node_modules/@mui/x-data-grid/utils/createSelector.js","../../node_modules/@mui/x-data-grid/hooks/features/dimensions/gridDimensionsSelectors.js","../../node_modules/@mui/x-data-grid/node_modules/@mui/x-internals/esm/fastMemo/fastMemo.js","../../node_modules/@mui/x-data-grid/constants/localeTextConstants.js","../../node_modules/@mui/x-data-grid/constants/gridClasses.js","../../node_modules/@mui/x-data-grid/utils/cleanupTracking/TimerBasedCleanupTracking.js","../../node_modules/@mui/x-data-grid/utils/cleanupTracking/FinalizationRegistryBasedCleanupTracking.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridApiEventHandler.js","../../node_modules/@mui/x-data-grid/hooks/features/density/densitySelector.js","../../node_modules/@mui/x-data-grid/components/cell/GridEditInputCell.js","../../node_modules/@mui/x-data-grid/hooks/features/rows/gridRowsSelector.js","../../node_modules/@mui/x-data-grid/hooks/features/sorting/gridSortingUtils.js","../../node_modules/@mui/x-data-grid/components/panel/filterPanel/GridFilterInputValue.js","../../node_modules/@mui/x-data-grid/utils/utils.js","../../node_modules/@mui/x-data-grid/components/panel/filterPanel/GridFilterInputMultipleValue.js","../../node_modules/@mui/x-data-grid/models/gridEditRowModel.js","../../node_modules/@mui/x-data-grid/models/gridFilterItem.js","../../node_modules/@mui/x-data-grid/models/params/gridEditCellParams.js","../../node_modules/@mui/x-data-grid/models/params/gridRowParams.js","../../node_modules/@mui/x-data-grid/models/gridColumnGrouping.js","../../node_modules/@mui/x-data-grid/hooks/features/filter/gridFilterState.js","../../node_modules/@mui/x-data-grid/utils/getPublicApiRef.js","../../node_modules/@mui/x-data-grid/hooks/features/columns/gridColumnsInterfaces.js","../../node_modules/@mui/x-data-grid/hooks/core/gridCoreSelector.js","../../node_modules/@mui/x-data-grid/hooks/features/columns/gridColumnsSelector.js","../../node_modules/@mui/x-data-grid/hooks/features/filter/gridFilterUtils.js","../../node_modules/@mui/x-data-grid/colDef/gridStringOperators.js","../../node_modules/@mui/x-data-grid/colDef/gridStringColDef.js","../../node_modules/@mui/x-data-grid/components/menu/GridMenu.js","../../node_modules/@mui/x-data-grid/components/cell/GridActionsCell.js","../../node_modules/@mui/x-data-grid/colDef/gridActionsColDef.js","../../node_modules/@mui/x-data-grid/hooks/features/rows/gridRowsUtils.js","../../node_modules/@mui/x-data-grid/internals/constants.js","../../node_modules/@mui/x-data-grid/components/cell/GridBooleanCell.js","../../node_modules/@mui/x-data-grid/components/cell/GridEditBooleanCell.js","../../node_modules/@mui/x-data-grid/components/panel/filterPanel/GridFilterInputBoolean.js","../../node_modules/@mui/x-data-grid/colDef/gridBooleanOperators.js","../../node_modules/@mui/x-data-grid/colDef/gridBooleanColDef.js","../../node_modules/@mui/x-data-grid/hooks/features/sorting/gridSortingSelector.js","../../node_modules/@mui/x-data-grid/hooks/features/filter/gridFilterSelector.js","../../node_modules/@mui/x-data-grid/hooks/features/rowSelection/gridRowSelectionSelector.js","../../node_modules/@mui/x-data-grid/hooks/features/rowSelection/utils.js","../../node_modules/@mui/x-data-grid/components/columnSelection/GridCellCheckboxRenderer.js","../../node_modules/@mui/x-data-grid/hooks/features/focus/gridFocusStateSelector.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridApiMethod.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridLogger.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridNativeEventListener.js","../../node_modules/@mui/x-data-grid/hooks/utils/useFirstRender.js","../../node_modules/@mui/x-data-grid/hooks/utils/useRunOnce.js","../../node_modules/@mui/x-data-grid/hooks/features/pagination/gridPaginationUtils.js","../../node_modules/@mui/x-data-grid/hooks/features/pagination/gridPaginationSelector.js","../../node_modules/@mui/x-data-grid/components/columnSelection/GridHeaderCheckbox.js","../../node_modules/@mui/x-data-grid/hooks/core/gridPropsSelectors.js","../../node_modules/@mui/x-data-grid/colDef/gridCheckboxSelectionColDef.js","../../node_modules/@mui/x-data-grid/components/panel/filterPanel/GridFilterInputDate.js","../../node_modules/@mui/x-data-grid/colDef/gridDateOperators.js","../../node_modules/@mui/x-data-grid/components/cell/GridEditDateCell.js","../../node_modules/@mui/x-data-grid/colDef/gridDateColDef.js","../../node_modules/@mui/x-data-grid/colDef/gridNumericOperators.js","../../node_modules/@mui/x-data-grid/colDef/gridNumericColDef.js","../../node_modules/@mui/x-data-grid/components/panel/filterPanel/filterPanelUtils.js","../../node_modules/@mui/x-data-grid/components/cell/GridEditSingleSelectCell.js","../../node_modules/@mui/x-data-grid/components/panel/filterPanel/GridFilterInputSingleSelect.js","../../node_modules/@mui/x-data-grid/components/panel/filterPanel/GridFilterInputMultipleSingleSelect.js","../../node_modules/@mui/x-data-grid/colDef/gridSingleSelectOperators.js","../../node_modules/@mui/x-data-grid/colDef/gridSingleSelectColDef.js","../../node_modules/@mui/x-data-grid/colDef/gridDefaultColumnTypes.js","../../node_modules/@mui/x-data-grid/hooks/features/headerFiltering/gridHeaderFilteringSelectors.js","../../node_modules/@mui/x-data-grid/hooks/features/columnGrouping/gridColumnGroupsSelector.js","../../node_modules/@mui/x-data-grid/hooks/features/columns/gridColumnsUtils.js","../../node_modules/@mui/x-data-grid/components/GridScrollArea.js","../../node_modules/@babel/runtime/helpers/typeof.js","../../node_modules/@babel/runtime/helpers/interopRequireWildcard.js","../../node_modules/@mui/x-data-grid/node_modules/@mui/x-internals/reactMajor.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridPrivateApiContext.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridVisibleRows.js","../../node_modules/@mui/x-data-grid/utils/platform.js","../../node_modules/@mui/x-data-grid/hooks/features/rows/gridRowsMetaSelector.js","../../node_modules/@mui/x-data-grid/hooks/features/virtualization/gridVirtualizationSelectors.js","../../node_modules/@mui/x-data-grid/hooks/features/virtualization/useGridVirtualization.js","../../node_modules/@mui/x-data-grid/hooks/features/rows/gridRowSpanningSelectors.js","../../node_modules/@mui/x-data-grid/hooks/features/listView/gridListViewSelectors.js","../../node_modules/@mui/x-data-grid/hooks/features/virtualization/gridFocusedVirtualCellSelector.js","../../node_modules/@mui/x-data-grid/utils/roundToDecimalPlaces.js","../../node_modules/@mui/x-data-grid/utils/isJSDOM.js","../../node_modules/@mui/x-data-grid/hooks/features/virtualization/useGridVirtualScroller.js","../../node_modules/@mui/x-data-grid/hooks/features/overlays/useGridOverlays.js","../../node_modules/@mui/x-data-grid/components/base/GridOverlays.js","../../node_modules/@mui/x-data-grid/hooks/features/columnMenu/columnMenuSelector.js","../../node_modules/@mui/x-data-grid/components/GridHeaders.js","../../node_modules/@mui/x-data-grid/components/GridConfigurationContext.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridConfiguration.js","../../node_modules/@mui/x-data-grid/components/virtualization/GridMainContainer.js","../../node_modules/@mui/x-data-grid/components/virtualization/GridTopContainer.js","../../node_modules/@mui/x-data-grid/components/virtualization/GridBottomContainer.js","../../node_modules/@mui/x-data-grid/components/virtualization/GridVirtualScrollerContent.js","../../node_modules/@mui/x-data-grid/components/virtualization/GridVirtualScrollerFiller.js","../../node_modules/@mui/x-data-grid/components/virtualization/GridVirtualScrollerRenderZone.js","../../node_modules/@mui/x-data-grid/hooks/features/columnResize/gridColumnResizeApi.js","../../node_modules/@mui/x-data-grid/hooks/features/editing/gridEditingSelectors.js","../../node_modules/@mui/x-data-grid/hooks/features/preferencesPanel/gridPreferencePanelSelector.js","../../node_modules/@mui/x-data-grid/hooks/features/preferencesPanel/gridPreferencePanelsValue.js","../../node_modules/@mui/x-data-grid/components/virtualization/GridVirtualScrollbar.js","../../node_modules/@mui/x-data-grid/components/virtualization/GridVirtualScroller.js","../../node_modules/@mui/x-data-grid/components/base/GridFooterPlaceholder.js","../../node_modules/@mui/x-data-grid/utils/doesSupportPreventScroll.js","../../node_modules/@mui/x-data-grid/internals/utils/computeSlots.js","../../node_modules/@mui/x-data-grid/internals/utils/useProps.js","../../node_modules/@mui/x-data-grid/internals/utils/gridRowGroupingUtils.js","../../node_modules/@mui/x-data-grid/utils/rtlFlipSide.js","../../node_modules/@mui/x-data-grid/internals/utils/attachPinnedStyle.js","../../node_modules/@mui/x-data-grid/components/cell/GridCell.js","../../node_modules/@mui/x-data-grid/components/cell/GridSkeletonCell.js","../../node_modules/@mui/x-data-grid/components/containers/GridRootStyles.js","../../node_modules/@mui/x-data-grid/hooks/utils/useIsSSR.js","../../node_modules/@mui/x-data-grid/components/panel/GridPreferencesPanel.js","../../node_modules/@mui/x-data-grid/components/GridHeader.js","../../node_modules/@mui/x-data-grid/components/containers/GridRoot.js","../../node_modules/@mui/x-data-grid/components/containers/GridFooterContainer.js","../../node_modules/@mui/x-data-grid/components/containers/GridOverlay.js","../../node_modules/@mui/x-data-grid/components/containers/GridToolbarContainer.js","../../node_modules/@mui/x-data-grid/components/columnHeaders/ColumnHeaderMenuIcon.js","../../node_modules/@mui/x-data-grid/components/menu/columnMenu/GridColumnHeaderMenu.js","../../node_modules/@mui/x-data-grid/utils/domUtils.js","../../node_modules/@mui/x-data-grid/components/columnHeaders/GridColumnHeaderTitle.js","../../node_modules/@mui/x-data-grid/components/columnHeaders/GridColumnHeaderSeparator.js","../../node_modules/@mui/x-data-grid/components/columnHeaders/GridGenericColumnHeaderItem.js","../../node_modules/@mui/x-data-grid/components/columnHeaders/GridColumnHeaderItem.js","../../node_modules/@mui/x-data-grid/components/columnHeaders/GridIconButtonContainer.js","../../node_modules/@mui/x-data-grid/components/columnHeaders/GridColumnHeaderSortIcon.js","../../node_modules/@mui/x-data-grid/components/columnHeaders/GridColumnHeaderFilterIconButton.js","../../node_modules/@mui/x-data-grid/material/icons/index.js","../../node_modules/@mui/x-data-grid/utils/keyboardUtils.js","../../node_modules/@mui/x-data-grid/components/menu/columnMenu/GridColumnMenuContainer.js","../../node_modules/@mui/x-data-grid/hooks/features/columnMenu/useGridColumnMenuSlots.js","../../node_modules/@mui/x-data-grid/components/menu/columnMenu/menuItems/GridColumnMenuHideItem.js","../../node_modules/@mui/x-data-grid/components/menu/columnMenu/menuItems/GridColumnMenuManageItem.js","../../node_modules/@mui/x-data-grid/components/menu/columnMenu/menuItems/GridColumnMenuColumnsItem.js","../../node_modules/@mui/x-data-grid/components/menu/columnMenu/menuItems/GridColumnMenuFilterItem.js","../../node_modules/@mui/x-data-grid/components/menu/columnMenu/menuItems/GridColumnMenuSortItem.js","../../node_modules/@mui/x-data-grid/components/menu/columnMenu/GridColumnMenu.js","../../node_modules/@mui/x-data-grid/components/panel/GridPanelWrapper.js","../../node_modules/@mui/x-data-grid/components/panel/GridColumnsPanel.js","../../node_modules/@mui/x-data-grid/components/panel/GridPanel.js","../../node_modules/@mui/x-data-grid/components/panel/GridPanelContent.js","../../node_modules/@mui/x-data-grid/components/panel/GridPanelFooter.js","../../node_modules/@mui/x-data-grid/components/panel/filterPanel/GridFilterForm.js","../../node_modules/@mui/x-data-grid/components/panel/filterPanel/GridFilterPanel.js","../../node_modules/@mui/x-data-grid/components/columnsManagement/utils.js","../../node_modules/@mui/x-data-grid/components/columnsManagement/GridColumnsManagement.js","../../node_modules/@mui/x-data-grid/components/toolbar/GridToolbarColumnsButton.js","../../node_modules/@mui/x-data-grid/components/toolbar/GridToolbarDensitySelector.js","../../node_modules/@mui/x-data-grid/components/toolbar/GridToolbarFilterButton.js","../../node_modules/@mui/x-data-grid/components/toolbar/GridToolbarExportContainer.js","../../node_modules/@mui/x-data-grid/components/toolbar/GridToolbarExport.js","../../node_modules/@mui/x-data-grid/components/toolbar/GridToolbarQuickFilter.js","../../node_modules/@mui/x-data-grid/components/toolbar/GridToolbar.js","../../node_modules/@mui/x-data-grid/components/GridSelectedRowCount.js","../../node_modules/@mui/x-data-grid/components/GridFooter.js","../../node_modules/@mui/x-data-grid/internals/utils/getPinnedCellOffset.js","../../node_modules/@mui/x-data-grid/utils/cellBorderUtils.js","../../node_modules/@mui/x-data-grid/components/GridScrollbarFillerCell.js","../../node_modules/@mui/x-data-grid/components/GridSkeletonLoadingOverlay.js","../../node_modules/@mui/x-data-grid/components/GridLoadingOverlay.js","../../node_modules/@mui/x-data-grid/components/GridNoRowsOverlay.js","../../node_modules/@mui/x-data-grid/components/GridPagination.js","../../node_modules/@mui/x-data-grid/components/GridRowCount.js","../../node_modules/@mui/x-data-grid/node_modules/@mui/x-internals/esm/isObjectEmpty/isObjectEmpty.js","../../node_modules/@mui/x-data-grid/utils/composeGridClasses.js","../../node_modules/@mui/x-data-grid/components/GridRow.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridAriaAttributes.js","../../node_modules/@mui/x-data-grid/hooks/features/rows/useGridRowAriaAttributes.js","../../node_modules/@mui/x-data-grid/context/GridContextProvider.js","../../node_modules/@mui/x-data-grid/hooks/core/useGridRefs.js","../../node_modules/@mui/x-data-grid/hooks/core/useGridIsRtl.js","../../node_modules/@mui/x-data-grid/hooks/core/useGridLoggerFactory.js","../../node_modules/@mui/x-data-grid/node_modules/@mui/x-internals/esm/EventManager/EventManager.js","../../node_modules/@mui/x-data-grid/utils/Store.js","../../node_modules/@mui/x-data-grid/hooks/core/useGridApiInitialization.js","../../node_modules/@mui/x-data-grid/hooks/core/useGridLocaleText.js","../../node_modules/@mui/x-data-grid/hooks/core/pipeProcessing/useGridPipeProcessing.js","../../node_modules/@mui/x-data-grid/hooks/core/pipeProcessing/useGridRegisterPipeProcessor.js","../../node_modules/@mui/x-data-grid/hooks/core/pipeProcessing/useGridRegisterPipeApplier.js","../../node_modules/@mui/x-data-grid/hooks/core/strategyProcessing/useGridRegisterStrategyProcessor.js","../../node_modules/@mui/x-data-grid/hooks/core/strategyProcessing/useGridStrategyProcessing.js","../../node_modules/@mui/x-data-grid/hooks/core/useGridStateInitialization.js","../../node_modules/@mui/x-data-grid/hooks/core/useGridProps.js","../../node_modules/@mui/x-data-grid/hooks/core/useGridInitialization.js","../../node_modules/@mui/x-data-grid/hooks/utils/useGridInitializeState.js","../../node_modules/@mui/x-data-grid/hooks/features/export/serializers/csvSerializer.js","../../node_modules/@mui/x-data-grid/hooks/features/clipboard/useGridClipboard.js","../../node_modules/@mui/x-data-grid/hooks/features/columnMenu/useGridColumnMenu.js","../../node_modules/@mui/x-data-grid/hooks/features/columns/useGridColumns.js","../../node_modules/@mui/x-data-grid/hooks/features/density/useGridDensity.js","../../node_modules/@mui/x-data-grid/utils/exportAs.js","../../node_modules/@mui/x-data-grid/hooks/features/export/utils.js","../../node_modules/@mui/x-data-grid/hooks/features/export/useGridCsvExport.js","../../node_modules/@mui/x-data-grid/hooks/features/pagination/useGridPaginationModel.js","../../node_modules/@mui/x-data-grid/hooks/features/export/useGridPrintExport.js","../../node_modules/@mui/x-data-grid/hooks/features/filter/useGridFilter.js","../../node_modules/@mui/x-data-grid/hooks/features/focus/useGridFocus.js","../../node_modules/@mui/x-data-grid/hooks/features/keyboardNavigation/utils.js","../../node_modules/@mui/x-data-grid/hooks/features/keyboardNavigation/useGridKeyboardNavigation.js","../../node_modules/@mui/x-data-grid/hooks/features/pagination/useGridRowCount.js","../../node_modules/@mui/x-data-grid/hooks/features/pagination/useGridPaginationMeta.js","../../node_modules/@mui/x-data-grid/hooks/features/pagination/useGridPagination.js","../../node_modules/@mui/x-data-grid/hooks/features/preferencesPanel/useGridPreferencesPanel.js","../../node_modules/@mui/x-data-grid/hooks/features/editing/utils.js","../../node_modules/@mui/x-data-grid/hooks/features/editing/useGridCellEditing.js","../../node_modules/@mui/x-data-grid/hooks/features/editing/useGridRowEditing.js","../../node_modules/@mui/x-data-grid/hooks/features/editing/useGridEditing.js","../../node_modules/@mui/x-data-grid/hooks/features/rows/useGridRows.js","../../node_modules/@mui/x-data-grid/hooks/features/rows/useGridRowsPreProcessors.js","../../node_modules/@mui/x-data-grid/hooks/features/rows/useGridParamsApi.js","../../node_modules/@mui/x-data-grid/hooks/features/rowSelection/useGridRowSelection.js","../../node_modules/@mui/x-data-grid/hooks/features/rowSelection/useGridRowSelectionPreProcessors.js","../../node_modules/@mui/x-data-grid/hooks/features/sorting/useGridSorting.js","../../node_modules/@mui/x-data-grid/hooks/features/scroll/useGridScroll.js","../../node_modules/@mui/x-data-grid/hooks/features/events/useGridEvents.js","../../node_modules/@mui/x-data-grid/node_modules/@mui/x-internals/esm/throttle/throttle.js","../../node_modules/@mui/x-data-grid/constants/dataGridPropsDefaultValues.js","../../node_modules/@mui/x-data-grid/hooks/features/dimensions/useGridDimensions.js","../../node_modules/@mui/x-data-grid/utils/ResizeObserver.js","../../node_modules/@mui/x-data-grid/hooks/features/rows/useGridRowsMeta.js","../../node_modules/@mui/x-data-grid/hooks/features/statePersistence/useGridStatePersistence.js","../../node_modules/@mui/x-data-grid/hooks/features/columns/useGridColumnSpanning.js","../../node_modules/@mui/x-data-grid/hooks/features/columnGrouping/gridColumnGroupsUtils.js","../../node_modules/@mui/x-data-grid/hooks/features/columnGrouping/useGridColumnGrouping.js","../../node_modules/@mui/x-data-grid/utils/createControllablePromise.js","../../node_modules/@mui/x-data-grid/hooks/features/columnResize/useGridColumnResize.js","../../node_modules/@mui/x-data-grid/hooks/features/rows/gridRowSpanningUtils.js","../../node_modules/@mui/x-data-grid/hooks/features/rows/useGridRowSpanning.js","../../node_modules/@mui/x-data-grid/hooks/features/listView/useGridListView.js","../../node_modules/@mui/x-data-grid/DataGrid/useDataGridComponent.js","../../node_modules/@mui/x-data-grid/components/columnHeaders/GridColumnGroupHeader.js","../../node_modules/@mui/x-data-grid/hooks/features/columnHeaders/useGridColumnHeaders.js","../../node_modules/@mui/x-data-grid/components/columnHeaders/GridBaseColumnHeaders.js","../../node_modules/@mui/x-data-grid/components/GridColumnHeaders.js","../../node_modules/@mui/x-data-grid/components/GridDetailPanels.js","../../node_modules/@mui/x-data-grid/components/GridPinnedRows.js","../../node_modules/@mui/x-data-grid/components/GridNoResultsOverlay.js","../../node_modules/@mui/x-data-grid/material/icons/GridColumnUnsortedIcon.js","../../node_modules/@mui/x-data-grid/material/components/MUISelectOption.js","../../node_modules/@mui/x-data-grid/material/index.js","../../node_modules/@mui/x-data-grid/constants/defaultGridSlotsComponents.js","../../node_modules/@mui/x-data-grid/DataGrid/useDataGridProps.js","../../node_modules/@mui/x-data-grid/DataGrid/DataGrid.js","../../node_modules/@mui/icons-material/Undo.js","../../src/routes/fuelDispensers/FuelDispenserShow/FuelRecords/EmployeeCell.tsx","../../src/routes/fuelDispensers/FuelDispenserShow/FuelRecords/types.ts","../../src/services/Flespi.ts","../../src/routes/fuelDispensers/FuelDispenserShow/FuelRecords/FuelRecordActionsCell.tsx","../../node_modules/@mui/icons-material/Edit.js","../../src/routes/fuelDispensers/FuelDispenserShow/FuelRecords/EditAllocationDialog.tsx","../../src/routes/fuelDispensers/FuelDispenserShow/FuelRecords/FuelRecordAllocationCell.tsx","../../src/routes/fuelDispensers/FuelDispenserShow/FuelRecords/FuelRecordsTable.tsx","../../src/routes/fuelDispensers/FuelDispenserShow/FuelRecords/ManualFuelDispensingRecordModal.tsx","../../src/routes/fuelDispensers/FuelDispenserShow/FuelRecords/TankRefillDialog.tsx","../../src/routes/fuelDispensers/FuelDispenserShow/FuelRecords/index.tsx","../../node_modules/@mui/icons-material/ContentCopy.js","../../src/routes/fuelDispensers/FuelDispenserShow/UnauthorizedButtonPresses/UnauthorizedButtonPressesTable.tsx","../../src/routes/fuelDispensers/FuelDispenserShow/UnauthorizedButtonPresses/index.tsx","../../src/routes/fuelDispensers/TankShapeField.tsx","../../src/routes/fuelDispensers/FuelDispenserShow/index.tsx","../../src/routes/fuelDispensers/index.tsx","../../src/routes/generateReports/index.tsx","../../node_modules/@mui/icons-material/PushPin.js","../../node_modules/@mui/icons-material/Place.js","../../node_modules/react-dom/cjs/react-dom-server-legacy.browser.production.min.js","../../node_modules/react-dom/cjs/react-dom-server.browser.production.min.js","../../node_modules/react-dom/server.browser.js","../../src/components/CustomMap/IconMarker.tsx","../../src/components/CustomMap/PolygonEditMap/LocationMarker.tsx","../../src/components/CustomMap/ZoomBasedLeafletElement.tsx","../../src/components/CustomMap/PolygonEditMap/CoordinateInput.tsx","../../src/routes/pointsOfInterest/PointOfInterestLocationInput.tsx","../../src/routes/pointsOfInterest/PointOfInterestRulesInput.tsx","../../src/routes/pointsOfInterest/utils.ts","../../src/routes/pointsOfInterest/PointOfInterestCreate.tsx","../../src/routes/pointsOfInterest/PointOfInterestList.tsx","../../src/components/react-admin-custom/LocationField.tsx","../../src/routes/pointsOfInterest/PointOfInterestShow.tsx","../../src/routes/pointsOfInterest/PointOfInterrestEdit.tsx","../../src/routes/pointsOfInterest/index.tsx","../../node_modules/@mui/icons-material/Folder.js","../../node_modules/@mui/icons-material/InsertDriveFile.js","../../node_modules/@mui/icons-material/Refresh.js","../../node_modules/@aws-sdk/middleware-expect-continue/node_modules/@smithy/types/dist-es/auth/auth.js","../../node_modules/@aws-sdk/middleware-expect-continue/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js","../../node_modules/@aws-sdk/middleware-expect-continue/node_modules/@smithy/types/dist-es/endpoint.js","../../node_modules/@aws-sdk/middleware-expect-continue/node_modules/@smithy/types/dist-es/extensions/checksum.js","../../node_modules/@aws-sdk/middleware-expect-continue/node_modules/@smithy/types/dist-es/http.js","../../node_modules/@aws-sdk/middleware-expect-continue/node_modules/@smithy/types/dist-es/profile.js","../../node_modules/@aws-sdk/middleware-expect-continue/node_modules/@smithy/types/dist-es/transfer.js","../../node_modules/@aws-sdk/middleware-expect-continue/node_modules/@smithy/protocol-http/dist-es/httpRequest.js","../../node_modules/@aws-sdk/middleware-expect-continue/dist-es/index.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/constants.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/stringUnionSelector.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/types/dist-es/auth/auth.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/types/dist-es/endpoint.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/types/dist-es/extensions/checksum.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/types/dist-es/http.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/types/dist-es/profile.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/types/dist-es/transfer.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/protocol-http/dist-es/httpRequest.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/util-base64/dist-es/constants.browser.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/util-base64/dist-es/toBase64.browser.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/util-stream/dist-es/checksum/ChecksumStream.browser.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/util-stream/dist-es/stream-type-check.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/util-stream/dist-es/checksum/createChecksumStream.browser.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/util-stream/dist-es/ByteArrayCollector.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/util-stream/dist-es/createBufferedReadableStream.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/util-hex-encoding/dist-es/index.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/node_modules/@smithy/is-array-buffer/dist-es/index.js","../../node_modules/strnum/strnum.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/types.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getChecksumAlgorithmForRequest.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getChecksumLocationName.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/hasHeader.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/hasHeaderWithPrefix.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/isStreaming.js","../../node_modules/@aws-crypto/crc32c/build/module/aws_crc32c.js","../../node_modules/@aws-crypto/crc32c/build/module/index.js","../../node_modules/@aws-crypto/crc32/build/module/aws_crc32.js","../../node_modules/@aws-crypto/crc32/build/module/index.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getCrc32ChecksumAlgorithmFunction.browser.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/selectChecksumAlgorithmFunction.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/stringHasher.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/flexibleChecksumsMiddleware.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/flexibleChecksumsInputMiddleware.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getChecksumAlgorithmListForResponse.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/isChecksumWithPartNumber.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getChecksum.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/validateChecksumFromResponse.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/flexibleChecksumsResponseMiddleware.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/getFlexibleChecksumsPlugin.js","../../node_modules/@aws-sdk/middleware-flexible-checksums/dist-es/resolveFlexibleChecksumsConfig.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/protocol-http/dist-es/extensions/httpExtensionConfiguration.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/types/dist-es/auth/auth.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/types/dist-es/endpoint.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/types/dist-es/extensions/checksum.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/types/dist-es/http.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/types/dist-es/middleware.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/types/dist-es/profile.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/types/dist-es/transfer.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/protocol-http/dist-es/httpRequest.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/protocol-http/dist-es/httpResponse.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/middleware-host-header/dist-es/index.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/middleware-logger/dist-es/loggerMiddleware.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/middleware-recursion-detection/dist-es/index.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/types/dist-es/auth/auth.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/types/dist-es/endpoint.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/types/dist-es/extensions/checksum.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/types/dist-es/http.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/types/dist-es/middleware.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/types/dist-es/profile.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/types/dist-es/transfer.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/protocol-http/dist-es/httpRequest.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/protocol-http/dist-es/httpResponse.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/util-base64/dist-es/constants.browser.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/util-stream/dist-es/headStream.browser.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/util-hex-encoding/dist-es/index.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/util-stream/dist-es/splitStream.browser.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/smithy-client/dist-es/parse-utils.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/smithy-client/dist-es/date-utils.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/region-redirect-endpoint-middleware.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/region-redirect-middleware.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-expires-middleware.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/classes/S3ExpressIdentityCache.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/classes/S3ExpressIdentityCacheEntry.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/classes/S3ExpressIdentityProviderImpl.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/signature-v4/dist-es/constants.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/is-array-buffer/dist-es/index.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/signature-v4/dist-es/headerUtil.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/signature-v4/dist-es/utilDate.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/signature-v4/dist-es/SignatureV4.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/util-config-provider/dist-es/types.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/constants.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/classes/SignatureV4S3Express.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js","../../node_modules/@aws-sdk/middleware-sdk-s3/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/functions/s3ExpressMiddleware.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/functions/signS3Express.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3-express/functions/s3ExpressHttpSigningMiddleware.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3Configuration.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/throw-200-exceptions.js","../../node_modules/@aws-sdk/util-arn-parser/dist-es/index.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/bucket-endpoint-middleware.js","../../node_modules/@aws-sdk/middleware-sdk-s3/dist-es/validate-bucket-name.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-middleware/dist-es/getSmithyContext.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-middleware/dist-es/normalizeProvider.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/httpAuthSchemeMiddleware.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemeEndpointRuleSetPlugin.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-serde/dist-es/deserializerMiddleware.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-serde/dist-es/serializerMiddleware.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-serde/dist-es/serdePlugin.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/middleware-http-auth-scheme/getHttpAuthSchemePlugin.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/middleware-http-signing/httpSigningMiddleware.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/middleware-http-signing/getHttpSigningMiddleware.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/normalizeProvider.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-base64/dist-es/constants.browser.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-base64/dist-es/fromBase64.browser.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-utf8/dist-es/fromUtf8.browser.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-utf8/dist-es/toUint8Array.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-utf8/dist-es/toUtf8.browser.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-base64/dist-es/toBase64.browser.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-stream/dist-es/blob/transforms.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-stream/dist-es/blob/Uint8ArrayBlobAdapter.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-stream/dist-es/stream-type-check.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-stream/dist-es/getAwsChunkedEncodingStream.browser.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/querystring-builder/dist-es/index.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/fetch-http-handler/dist-es/create-request.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/fetch-http-handler/dist-es/request-timeout.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/fetch-http-handler/dist-es/fetch-http-handler.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/fetch-http-handler/dist-es/stream-collector.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-hex-encoding/dist-es/index.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-stream/dist-es/sdk-stream-mixin.browser.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/submodules/protocols/collect-stream-body.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/submodules/protocols/extended-encode-uri-component.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/submodules/protocols/resolve-path.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/submodules/protocols/requestBuilder.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/setFeature.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/util-identity-and-auth/DefaultIdentityProviderConfig.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/core/dist-es/util-identity-and-auth/memoizeIdentityProvider.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/middleware-user-agent/dist-es/configurations.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/cache/EndpointCache.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/lib/isIpAddress.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/lib/isValidHostLabel.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/customEndpointFunctions.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/debug/debugId.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/debug/toDebugString.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/types/EndpointError.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/lib/booleanEquals.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/lib/getAttrPathList.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/lib/getAttr.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/lib/isSet.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/lib/not.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/lib/parseURL.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/lib/stringEquals.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/lib/substring.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/lib/uriEncode.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/endpointFunctions.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTemplate.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/getReferenceValue.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateExpression.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/callFunction.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateCondition.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateConditions.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointHeaders.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperty.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointProperties.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/getEndpointUrl.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateEndpointRule.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateErrorRule.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateTreeRule.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/utils/evaluateRules.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-endpoints/dist-es/resolveEndpoint.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/isVirtualHostableS3Bucket.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/parseArn.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/util-endpoints/dist-es/lib/aws/partition.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/util-endpoints/dist-es/aws.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core/dist-es/submodules/client/setCredentialFeature.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core/dist-es/submodules/client/setFeature.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getDateHeader.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getSkewCorrectedDate.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/isClockSkewed.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/utils/getUpdatedSystemClockOffset.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4Signer.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/AwsSdkSigV4ASigner.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/property-provider/dist-es/memoize.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4AConfig.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/signature-v4/dist-es/constants.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/signature-v4/dist-es/credentialDerivation.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/signature-v4/dist-es/getCanonicalHeaders.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/signature-v4/dist-es/getCanonicalQuery.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/is-array-buffer/dist-es/index.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/signature-v4/dist-es/getPayloadHash.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/signature-v4/dist-es/HeaderFormatter.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/signature-v4/dist-es/headerUtil.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/signature-v4/dist-es/moveHeadersToQuery.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/signature-v4/dist-es/prepareRequest.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/signature-v4/dist-es/utilDate.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/signature-v4/dist-es/SignatureV4.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core/dist-es/submodules/httpAuthSchemes/aws_sdk/resolveAwsSdkSigV4Config.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-stack/dist-es/MiddlewareStack.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/client.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/command.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/constants.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/parse-utils.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/date-utils.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/exceptions.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/default-error-handler.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/defaults-mode.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/extensions/checksum.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/extensions/retry.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/extensions/defaultExtensionConfiguration.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/get-array-if-single-item.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/get-value-from-text-node.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/is-serializable-header-value.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/NoOpLogger.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/object-mapping.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/smithy-client/dist-es/quote-header.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core/dist-es/submodules/protocols/common.js","../../node_modules/@aws-sdk/client-s3/node_modules/fast-xml-parser/src/util.js","../../node_modules/@aws-sdk/client-s3/node_modules/fast-xml-parser/src/validator.js","../../node_modules/@aws-sdk/client-s3/node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js","../../node_modules/@aws-sdk/client-s3/node_modules/fast-xml-parser/src/xmlparser/xmlNode.js","../../node_modules/@aws-sdk/client-s3/node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js","../../node_modules/@aws-sdk/client-s3/node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js","../../node_modules/@aws-sdk/client-s3/node_modules/fast-xml-parser/src/xmlparser/node2json.js","../../node_modules/@aws-sdk/client-s3/node_modules/fast-xml-parser/src/xmlparser/XMLParser.js","../../node_modules/@aws-sdk/client-s3/node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js","../../node_modules/@aws-sdk/client-s3/node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js","../../node_modules/@aws-sdk/client-s3/node_modules/fast-xml-parser/src/fxp.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/core/dist-es/submodules/protocols/xml/parseXmlBody.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/middleware-user-agent/dist-es/check-features.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/middleware-user-agent/dist-es/constants.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/middleware-user-agent/dist-es/encode-features.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/middleware-user-agent/dist-es/user-agent-middleware.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-config-provider/dist-es/types.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseDualstackEndpointConfigOptions.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/config-resolver/dist-es/endpointsConfig/NodeUseFipsEndpointConfigOptions.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/config-resolver/dist-es/regionConfig/isFipsRegion.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/config-resolver/dist-es/regionConfig/getRealRegion.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/config-resolver/dist-es/regionConfig/resolveRegionConfig.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-serde-config-resolver/dist-es/EventStreamSerdeConfig.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-content-length/dist-es/index.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.browser.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/querystring-parser/dist-es/index.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/url-parser/dist-es/index.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-endpoint/dist-es/endpointMiddleware.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-endpoint/dist-es/getEndpointPlugin.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-endpoint/dist-es/resolveEndpointConfig.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-retry/dist-es/config.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/service-error-classification/dist-es/constants.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/service-error-classification/dist-es/index.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-retry/dist-es/DefaultRateLimiter.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-retry/dist-es/constants.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-retry/dist-es/defaultRetryBackoffStrategy.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-retry/dist-es/defaultRetryToken.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-retry/dist-es/StandardRetryStrategy.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-retry/dist-es/AdaptiveRetryStrategy.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-retry/dist-es/util.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-retry/dist-es/configurations.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-retry/dist-es/isStreamingPayload/isStreamingPayload.browser.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/middleware-retry/dist-es/retryMiddleware.js","../../node_modules/@aws-sdk/signature-v4-multi-region/dist-es/signature-v4-crt-container.js","../../node_modules/@aws-sdk/signature-v4-multi-region/dist-es/SignatureV4MultiRegion.js","../../node_modules/@aws-sdk/client-s3/dist-es/endpoint/ruleset.js","../../node_modules/@aws-sdk/client-s3/dist-es/endpoint/endpointResolver.js","../../node_modules/@aws-sdk/client-s3/dist-es/auth/httpAuthSchemeProvider.js","../../node_modules/@aws-sdk/client-s3/dist-es/endpoint/EndpointParameters.js","../../node_modules/@aws-sdk/client-s3/dist-es/models/S3ServiceException.js","../../node_modules/@aws-sdk/client-s3/dist-es/models/models_0.js","../../node_modules/@aws-sdk/client-s3/dist-es/models/models_1.js","../../node_modules/@aws-sdk/client-s3/dist-es/protocols/Aws_restXml.js","../../node_modules/@aws-sdk/client-s3/dist-es/commands/CreateSessionCommand.js","../../node_modules/@aws-crypto/sha1-browser/build/module/isEmptyData.js","../../node_modules/@aws-crypto/sha1-browser/build/module/constants.js","../../node_modules/@aws-sdk/util-locate-window/dist-es/index.js","../../node_modules/@aws-crypto/sha1-browser/build/module/webCryptoSha1.js","../../node_modules/@aws-crypto/supports-web-crypto/build/module/supportsWebCrypto.js","../../node_modules/@aws-crypto/sha1-browser/build/module/crossPlatformSha1.js","../../node_modules/@aws-crypto/sha256-browser/build/module/constants.js","../../node_modules/@aws-crypto/sha256-browser/build/module/webCryptoSha256.js","../../node_modules/@aws-crypto/sha256-browser/build/module/crossPlatformSha256.js","../../node_modules/bowser/src/constants.js","../../node_modules/bowser/src/utils.js","../../node_modules/bowser/src/parser-browsers.js","../../node_modules/bowser/src/parser-os.js","../../node_modules/bowser/src/parser-platforms.js","../../node_modules/bowser/src/parser-engines.js","../../node_modules/bowser/src/parser.js","../../node_modules/bowser/src/bowser.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/util-user-agent-browser/dist-es/index.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-codec/dist-es/Int64.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-codec/dist-es/HeaderMarshaller.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-codec/dist-es/splitMessage.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-codec/dist-es/EventStreamCodec.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-codec/dist-es/MessageDecoderStream.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-codec/dist-es/MessageEncoderStream.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageDecoderStream.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageEncoderStream.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-serde-universal/dist-es/getChunkedStream.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-serde-universal/dist-es/getUnmarshalledStream.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-serde-universal/dist-es/EventStreamMarshaller.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-serde-browser/dist-es/utils.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-serde-browser/dist-es/EventStreamMarshaller.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/eventstream-serde-browser/dist-es/provider.js","../../node_modules/@smithy/chunked-blob-reader/dist-es/index.js","../../node_modules/@smithy/hash-blob-browser/dist-es/index.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/invalid-dependency/dist-es/invalidProvider.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/md5-js/dist-es/constants.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/md5-js/dist-es/index.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-body-length-browser/dist-es/calculateBodyLength.js","../../node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.shared.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-defaults-mode-browser/dist-es/constants.js","../../node_modules/@aws-sdk/client-s3/node_modules/@smithy/util-defaults-mode-browser/dist-es/resolveDefaultsModeConfig.js","../../node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.browser.js","../../node_modules/@aws-sdk/client-s3/node_modules/@aws-sdk/region-config-resolver/dist-es/extensions/index.js","../../node_modules/@aws-sdk/client-s3/dist-es/auth/httpAuthExtensionConfiguration.js","../../node_modules/@aws-sdk/client-s3/dist-es/runtimeExtensions.js","../../node_modules/@aws-sdk/client-s3/dist-es/S3Client.js","../../node_modules/@aws-sdk/middleware-ssec/dist-es/index.js","../../node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectCommand.js","../../node_modules/@aws-sdk/client-s3/dist-es/commands/ListObjectsV2Command.js","../../node_modules/@aws-sdk/util-format-url/node_modules/@smithy/util-uri-escape/dist-es/escape-uri.js","../../node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/dist-es/index.js","../../node_modules/@aws-sdk/util-format-url/dist-es/index.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/middleware-endpoint/dist-es/service-customizations/s3.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/createConfigValueProvider.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromConfig.browser.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/querystring-parser/dist-es/index.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/url-parser/dist-es/index.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/toEndpointV1.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/middleware-endpoint/dist-es/adaptors/getEndpointFromInstructions.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/types/dist-es/auth/auth.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/types/dist-es/auth/HttpApiKeyAuth.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/types/dist-es/endpoint.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/types/dist-es/extensions/checksum.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/types/dist-es/http.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/types/dist-es/profile.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/types/dist-es/transfer.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/protocol-http/dist-es/httpRequest.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/util-base64/dist-es/constants.browser.js","../../node_modules/@aws-sdk/s3-request-presigner/node_modules/@smithy/util-hex-encoding/dist-es/index.js","../../node_modules/@aws-sdk/s3-request-presigner/dist-es/constants.js","../../node_modules/@aws-sdk/s3-request-presigner/dist-es/presigner.js","../../node_modules/@aws-sdk/s3-request-presigner/dist-es/getSignedUrl.js","../../src/routes/reports/S3FileExplorer/S3Api.ts","../../src/routes/reports/S3FileExplorer/index.tsx","../../src/routes/reports/index.tsx","../../node_modules/@mui/icons-material/GpsFixed.js","../../src/routes/trackers/TrackerEdit.tsx","../../src/routes/trackers/TrackerList.tsx","../../src/routes/trackers/TrackerShow.tsx","../../src/routes/trackers/index.tsx","../../node_modules/@mui/icons-material/Agriculture.js","../../src/routes/vehicles/VehicleHomeLocationInput.tsx","../../src/routes/vehicles/VehicleCreate.tsx","../../src/routes/vehicles/VehicleEdit.tsx","../../src/routes/vehicles/VehicleList/utils.ts","../../src/routes/vehicles/VehicleList/ListView.tsx","../../src/routes/vehicles/VehicleList/MapView.tsx","../../src/routes/vehicles/VehicleList/index.tsx","../../src/components/FlespiMessageTable/index.tsx","../../src/routes/vehicles/VehicleShow/MessagesTab/index.tsx","../../src/routes/vehicles/VehicleShow/ParametersTab/TelemetryCardGrid.tsx","../../src/routes/vehicles/VehicleShow/ParametersTab/index.tsx","../../src/routes/vehicles/VehicleShow/ServiceTab/index.tsx","../../src/routes/vehicles/VehicleShow/VehicleLogbook/EligiblePieChart.tsx","../../node_modules/@mui/icons-material/LocationOn.js","../../node_modules/polyline-encoded/Polyline.encoded.js","../../src/components/CustomMap/GPolyLineAdvanced.tsx","../../src/routes/vehicles/VehicleShow/VehicleLogbook/VehicleTripsMap.tsx","../../node_modules/@mui/icons-material/Cached.js","../../node_modules/@mui/icons-material/Info.js","../../node_modules/@mui/icons-material/NoteAdd.js","../../src/routes/vehicles/VehicleShow/VehicleLogbook/CropsCell.tsx","../../src/routes/vehicles/VehicleShow/VehicleLogbook/dataUtils.ts","../../src/routes/vehicles/VehicleShow/VehicleLogbook/EditModal.tsx","../../src/routes/vehicles/VehicleShow/VehicleLogbook/ImplementCell.tsx","../../src/routes/vehicles/VehicleShow/VehicleLogbook/ManualRecordModal.tsx","../../src/routes/vehicles/VehicleShow/VehicleLogbook/OperationAreasCell.tsx","../../src/routes/vehicles/VehicleShow/VehicleLogbook/ShowDetailsModal.tsx","../../src/routes/vehicles/VehicleShow/VehicleLogbook/VehicleTripsTable.tsx","../../src/routes/vehicles/VehicleShow/VehicleLogbook/index.tsx","../../src/components/LiveLocationCard.tsx","../../src/routes/vehicles/VehicleShow/index.tsx","../../src/routes/vehicles/index.tsx","../../src/react-admin-amplify/providers/AuthProvider.ts","../../src/react-admin-amplify/providers/DataStoreDataProvider/Filter.ts","../../src/services/AgriFSRest/index.ts","../../src/react-admin-amplify/providers/AdminQueries.ts","../../src/react-admin-amplify/providers/DataStoreDataProvider/DataProvider.ts","../../src/react-admin-amplify/providers/index.ts","../../src/react-admin-amplify/providers/FlespiDataProvider.ts","../../src/routes/Routes.tsx","../../src/App.tsx","../../src/main.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 {\n const originalConsoleMethod = originalConsoleMethods[level] ;\n wrappedFuncs[level] = console[level] ;\n console[level] = originalConsoleMethod;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] ;\n });\n }\n}\n\nfunction makeLogger() {\n let enabled = false;\n const logger = {\n enable: () => {\n enabled = true;\n },\n disable: () => {\n enabled = false;\n },\n isEnabled: () => enabled,\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = (...args) => {\n if (enabled) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);\n });\n }\n };\n });\n } else {\n CONSOLE_LEVELS.forEach(name => {\n logger[name] = () => undefined;\n });\n }\n\n return logger ;\n}\n\n/**\n * This is a logger singleton which either logs things or no-ops if logging is not enabled.\n * The logger is a singleton on the carrier, to ensure that a consistent logger is used throughout the SDK.\n */\nconst logger = getGlobalSingleton('logger', makeLogger);\n\nexport { CONSOLE_LEVELS, consoleSandbox, logger, originalConsoleMethods };\n//# sourceMappingURL=logger.js.map\n","const STACKTRACE_FRAME_LIMIT = 50;\nconst UNKNOWN_FUNCTION = '?';\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nfunction createStackParser(...parsers) {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack, skipFirstLines = 0, framesToPop = 0) => {\n const frames = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirstLines; i < lines.length; i++) {\n const line = lines[i] ;\n // Ignore lines over 1kb as they are unlikely to be stack frames.\n // Many of the regular expressions use backtracking which results in run time that increases exponentially with\n // input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n continue;\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames.slice(framesToPop));\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nfunction stackParserFromStackParserOptions(stackParser) {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nfunction stripSentryFramesAndReverse(stack) {\n if (!stack.length) {\n return [];\n }\n\n const localStack = Array.from(stack);\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (/sentryWrapped/.test(getLastStackFrame(localStack).function || '')) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)\n if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) {\n localStack.pop();\n\n // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n // is produced within the scope itself, making it:\n //\n // Sentry.captureException()\n // scope.captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || getLastStackFrame(localStack).filename,\n function: frame.function || UNKNOWN_FUNCTION,\n }));\n}\n\nfunction getLastStackFrame(arr) {\n return arr[arr.length - 1] || {};\n}\n\nconst defaultFunctionName = '';\n\n/**\n * Safely extract function name from itself\n */\nfunction getFunctionName(fn) {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Get's stack frames from an event without needing to check for undefined properties.\n */\nfunction getFramesFromEvent(event) {\n const exception = event.exception;\n\n if (exception) {\n const frames = [];\n try {\n // @ts-expect-error Object could be undefined\n exception.values.forEach(value => {\n // @ts-expect-error Value could be undefined\n if (value.stacktrace.frames) {\n // @ts-expect-error Value could be undefined\n frames.push(...value.stacktrace.frames);\n }\n });\n return frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n\nexport { UNKNOWN_FUNCTION, createStackParser, getFramesFromEvent, getFunctionName, stackParserFromStackParserOptions, stripSentryFramesAndReverse };\n//# sourceMappingURL=stacktrace.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { logger } from '../logger.js';\nimport { getFunctionName } from '../stacktrace.js';\n\n// We keep the handlers globally\nconst handlers = {};\nconst instrumented = {};\n\n/** Add a handler function. */\nfunction addHandler(type, handler) {\n handlers[type] = handlers[type] || [];\n (handlers[type] ).push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nfunction resetInstrumentationHandlers() {\n Object.keys(handlers).forEach(key => {\n handlers[key ] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nfunction maybeInstrument(type, instrumentFn) {\n if (!instrumented[type]) {\n instrumented[type] = true;\n try {\n instrumentFn();\n } catch (e) {\n DEBUG_BUILD && logger.error(`Error while instrumenting ${type}`, e);\n }\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nfunction triggerHandlers(type, data) {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nexport { addHandler, maybeInstrument, resetInstrumentationHandlers, triggerHandlers };\n//# sourceMappingURL=handlers.js.map\n","import { GLOBAL_OBJ } from '../worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\nlet _oldOnErrorHandler = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addGlobalErrorInstrumentationHandler(handler) {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError() {\n _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n // Note: The reason we are doing window.onerror instead of window.addEventListener('error')\n // is that we are using this handler in the Loader Script, to handle buffered errors consistently\n GLOBAL_OBJ.onerror = function (\n msg,\n url,\n line,\n column,\n error,\n ) {\n const handlerData = {\n column,\n error,\n line,\n msg,\n url,\n };\n triggerHandlers('error', handlerData);\n\n if (_oldOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n\nexport { addGlobalErrorInstrumentationHandler };\n//# sourceMappingURL=globalError.js.map\n","import { GLOBAL_OBJ } from '../worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\nlet _oldOnUnhandledRejectionHandler = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addGlobalUnhandledRejectionInstrumentationHandler(\n handler,\n) {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection() {\n _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n // Note: The reason we are doing window.onunhandledrejection instead of window.addEventListener('unhandledrejection')\n // is that we are using this handler in the Loader Script, to handle buffered rejections consistently\n GLOBAL_OBJ.onunhandledrejection = function (e) {\n const handlerData = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n\nexport { addGlobalUnhandledRejectionInstrumentationHandler };\n//# sourceMappingURL=globalUnhandledRejection.js.map\n","// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isError(wat) {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat, className) {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isErrorEvent(wat) {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isDOMError(wat) {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isDOMException(wat) {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isString(wat) {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isParameterizedString(wat) {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isPrimitive(wat) {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isPlainObject(wat) {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isEvent(wat) {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isElement(wat) {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isRegExp(wat) {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nfunction isThenable(wat) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat?.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isSyntheticEvent(wat) {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\nfunction isInstanceOf(wat, base) {\n try {\n return wat instanceof base;\n } catch (_e) {\n return false;\n }\n}\n\n/**\n * Checks whether given value's type is a Vue ViewModel.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isVueViewModel(wat) {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n return !!(typeof wat === 'object' && wat !== null && ((wat ).__isVue || (wat )._isVue));\n}\n\nexport { isDOMError, isDOMException, isElement, isError, isErrorEvent, isEvent, isInstanceOf, isParameterizedString, isPlainObject, isPrimitive, isRegExp, isString, isSyntheticEvent, isThenable, isVueViewModel };\n//# sourceMappingURL=is.js.map\n","import { isString } from './is.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction htmlTreeAsString(\n elem,\n options = {},\n) {\n if (!elem) {\n return '';\n }\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem ;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch (_oO) {\n return '';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el, keyAttrs) {\n const elem = el\n\n;\n\n const out = [];\n\n if (!elem?.tagName) {\n return '';\n }\n\n // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset) {\n if (elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n if (elem.dataset['sentryElement']) {\n return elem.dataset['sentryElement'];\n }\n }\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs = keyAttrs?.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs?.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n const className = elem.className;\n if (className && isString(className)) {\n const classes = className.split(/\\s+/);\n for (const c of classes) {\n out.push(`.${c}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (const k of allowedAttrs) {\n const attr = elem.getAttribute(k);\n if (attr) {\n out.push(`[${k}=\"${attr}\"]`);\n }\n }\n\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nfunction getLocationHref() {\n try {\n return WINDOW.document.location.href;\n } catch (oO) {\n return '';\n }\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` or `data-sentry-element` attribute with `data-sentry-component` taking\n * precedence. This attribute is added at build-time by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nfunction getComponentName(elem) {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem ;\n const MAX_TRAVERSE_HEIGHT = 5;\n for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {\n if (!currentElem) {\n return null;\n }\n\n if (currentElem instanceof HTMLElement) {\n if (currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n if (currentElem.dataset['sentryElement']) {\n return currentElem.dataset['sentryElement'];\n }\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n\nexport { getComponentName, getLocationHref, htmlTreeAsString };\n//# sourceMappingURL=browser.js.map\n","import { isVueViewModel, isString, isRegExp } from './is.js';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nfunction truncate(str, max = 0) {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nfunction snipLine(line, colno) {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\nfunction safeJoin(input, delimiter) {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push('[VueViewModel]');\n } else {\n output.push(String(value));\n }\n } catch (e) {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nfunction isMatchingPattern(\n value,\n pattern,\n requireExactStringMatch = false,\n) {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nfunction stringMatchesSomePattern(\n testString,\n patterns = [],\n requireExactStringMatch = false,\n) {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n\nexport { isMatchingPattern, safeJoin, snipLine, stringMatchesSomePattern, truncate };\n//# sourceMappingURL=string.js.map\n","import { htmlTreeAsString } from './browser.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { isError, isEvent, isInstanceOf, isElement, isPlainObject, isPrimitive } from './is.js';\nimport { logger } from './logger.js';\nimport { truncate } from './string.js';\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nfunction fill(source, name, replacementFactory) {\n if (!(name in source)) {\n return;\n }\n\n const original = source[name] ;\n const wrapped = replacementFactory(original) ;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n markFunctionWrapped(wrapped, original);\n }\n\n try {\n source[name] = wrapped;\n } catch {\n DEBUG_BUILD && logger.log(`Failed to replace method \"${name}\" in object`, source);\n }\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nfunction addNonEnumerableProperty(obj, name, value) {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch (o_O) {\n DEBUG_BUILD && logger.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nfunction markFunctionWrapped(wrapped, original) {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch (o_O) {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction getOriginalFunction(func) {\n return func.__sentry_original__;\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor\n * an Error.\n */\nfunction convertToPlainObject(value)\n\n {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj\n\n = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target) {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch (_oO) {\n return '';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj) {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj )[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nfunction extractExceptionKeysForMessage(exception, maxLength = 40) {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n const firstKey = keys[0];\n\n if (!firstKey) {\n return '[object has no keys]';\n }\n\n if (firstKey.length >= maxLength) {\n return truncate(firstKey, maxLength);\n }\n\n for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {\n const serialized = keys.slice(0, includedKeys).join(', ');\n if (serialized.length > maxLength) {\n continue;\n }\n if (includedKeys === keys.length) {\n return serialized;\n }\n return truncate(serialized, maxLength);\n }\n\n return '';\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n */\nfunction dropUndefinedKeys(inputValue) {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue, memoizationMap) {\n if (isPojo(inputValue)) {\n // If this node has already been visited due to a circular reference, return the object it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n const returnValue = {};\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n for (const key of Object.getOwnPropertyNames(inputValue)) {\n if (typeof inputValue[key] !== 'undefined') {\n returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);\n }\n }\n\n return returnValue ;\n }\n\n if (Array.isArray(inputValue)) {\n // If this node has already been visited due to a circular reference, return the array it was mapped to in the new object\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n const returnValue = [];\n // Store the mapping of this value in case we visit it again, in case of circular data\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach((item) => {\n returnValue.push(_dropUndefinedKeys(item, memoizationMap));\n });\n\n return returnValue ;\n }\n\n return inputValue;\n}\n\nfunction isPojo(input) {\n if (!isPlainObject(input)) {\n return false;\n }\n\n try {\n const name = (Object.getPrototypeOf(input) ).constructor.name;\n return !name || name === 'Object';\n } catch {\n return true;\n }\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nfunction objectify(wat) {\n let objectified;\n switch (true) {\n // this will catch both undefined and null\n case wat == undefined:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat ).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n\nexport { addNonEnumerableProperty, convertToPlainObject, dropUndefinedKeys, extractExceptionKeysForMessage, fill, getOriginalFunction, markFunctionWrapped, objectify };\n//# sourceMappingURL=object.js.map\n","import { GLOBAL_OBJ } from './worldwide.js';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nfunction dateTimestampInSeconds() {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc() {\n const { performance } = GLOBAL_OBJ ;\n if (!performance?.now) {\n return dateTimestampInSeconds;\n }\n\n // Some browser and environments don't have a timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n const approxStartingTimeOrigin = Date.now() - performance.now();\n const timeOrigin = performance.timeOrigin == undefined ? approxStartingTimeOrigin : performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nconst timestampInSeconds = createUnixTimestampInSecondsFunc();\n\n/**\n * Cached result of getBrowserTimeOrigin.\n */\nlet cachedTimeOrigin;\n\n/**\n * Gets the time origin and the mode used to determine it.\n */\nfunction getBrowserTimeOrigin() {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ ;\n if (!performance?.now) {\n return [undefined, 'none'];\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing?.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n return [performance.timeOrigin, 'timeOrigin'];\n } else {\n return [navigationStart, 'navigationStart'];\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n return [dateNow, 'dateNow'];\n}\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nfunction browserPerformanceTimeOrigin() {\n if (!cachedTimeOrigin) {\n cachedTimeOrigin = getBrowserTimeOrigin();\n }\n\n return cachedTimeOrigin[0];\n}\n\nexport { browserPerformanceTimeOrigin, dateTimestampInSeconds, timestampInSeconds };\n//# sourceMappingURL=time.js.map\n","import { addNonEnumerableProperty } from './object.js';\nimport { snipLine } from './string.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * UUID4 generator\n *\n * @returns string Generated UUID4.\n */\nfunction uuid4() {\n const gbl = GLOBAL_OBJ ;\n const crypto = gbl.crypto || gbl.msCrypto;\n\n let getRandomByte = () => Math.random() * 16;\n try {\n if (crypto?.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto?.getRandomValues) {\n getRandomByte = () => {\n // crypto.getRandomValues might return undefined instead of the typed array\n // in old Chromium versions (e.g. 23.0.1235.0 (151422))\n // However, `typedArray` is still filled in-place.\n // @see https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#typedarray\n const typedArray = new Uint8Array(1);\n crypto.getRandomValues(typedArray);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n return typedArray[0];\n };\n }\n } catch (_) {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n return (([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11).replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event) {\n return event.exception?.values?.[0];\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nfunction getEventDescription(event) {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '';\n }\n return eventId || '';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nfunction addExceptionTypeValue(event, value, type) {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nfunction addExceptionMechanism(event, newMechanism) {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...currentMechanism?.data, ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\n\nfunction _parseInt(input) {\n return parseInt(input || '', 10);\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nfunction parseSemver(input) {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = _parseInt(match[1]);\n const minor = _parseInt(match[2]);\n const patch = _parseInt(match[3]);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nfunction addContextToFrame(lines, frame, linesOfContext = 5) {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line) => snipLine(line, 0));\n\n // We guard here to ensure this is not larger than the existing number of lines\n const lineIndex = Math.min(maxLines - 1, sourceLine);\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n frame.context_line = snipLine(lines[lineIndex], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nfunction checkOrSetAlreadyCaught(exception) {\n if (isAlreadyCaptured(exception)) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception , '__sentry_captured__', true);\n } catch (err) {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\nfunction isAlreadyCaptured(exception) {\n try {\n return (exception ).__sentry_captured__;\n } catch {} // eslint-disable-line no-empty\n}\n\nexport { addContextToFrame, addExceptionMechanism, addExceptionTypeValue, checkOrSetAlreadyCaught, getEventDescription, parseSemver, uuid4 };\n//# sourceMappingURL=misc.js.map\n","import { isThenable } from './is.js';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** SyncPromise internal states */\nvar States; (function (States) {\n /** Pending */\n const PENDING = 0; States[States[\"PENDING\"] = PENDING] = \"PENDING\";\n /** Resolved / OK */\n const RESOLVED = 1; States[States[\"RESOLVED\"] = RESOLVED] = \"RESOLVED\";\n /** Rejected / Error */\n const REJECTED = 2; States[States[\"REJECTED\"] = REJECTED] = \"REJECTED\";\n})(States || (States = {}));\n\n// Overloads so we can call resolvedSyncPromise without arguments and generic argument\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nfunction resolvedSyncPromise(value) {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nfunction rejectedSyncPromise(reason) {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise {\n\n constructor(executor) {\n this._state = States.PENDING;\n this._handlers = [];\n\n this._runExecutor(executor);\n }\n\n /** @inheritdoc */\n then(\n onfulfilled,\n onrejected,\n ) {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result );\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** @inheritdoc */\n catch(\n onrejected,\n ) {\n return this.then(val => val, onrejected);\n }\n\n /** @inheritdoc */\n finally(onfinally) {\n return new SyncPromise((resolve, reject) => {\n let val;\n let isRejected;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val );\n });\n });\n }\n\n /** Excute the resolve/reject handlers. */\n _executeHandlers() {\n if (this._state === States.PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === States.RESOLVED) {\n handler[1](this._value );\n }\n\n if (this._state === States.REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n }\n\n /** Run the executor for the SyncPromise. */\n _runExecutor(executor) {\n const setResult = (state, value) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value ).then(resolve, reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n const resolve = (value) => {\n setResult(States.RESOLVED, value);\n };\n\n const reject = (reason) => {\n setResult(States.REJECTED, reason);\n };\n\n try {\n executor(resolve, reject);\n } catch (e) {\n reject(e);\n }\n }\n}\n\nexport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise };\n//# sourceMappingURL=syncpromise.js.map\n","import './utils-hoist/debug-build.js';\nimport './utils-hoist/logger.js';\nimport { dropUndefinedKeys } from './utils-hoist/object.js';\nimport { timestampInSeconds } from './utils-hoist/time.js';\nimport { uuid4 } from './utils-hoist/misc.js';\nimport './utils-hoist/syncpromise.js';\n\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nfunction makeSession(context) {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see Client.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nfunction updateSession(session, context = {}) {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nfunction closeSession(session, status) {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session) {\n return dropUndefinedKeys({\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n });\n}\n\nexport { closeSession, makeSession, updateSession };\n//# sourceMappingURL=session.js.map\n","import { uuid4 } from './misc.js';\n\n/**\n * Generate a random, valid trace ID.\n */\nfunction generateTraceId() {\n return uuid4();\n}\n\n/**\n * Generate a random, valid span ID.\n */\nfunction generateSpanId() {\n return uuid4().substring(16);\n}\n\nexport { generateSpanId, generateTraceId };\n//# sourceMappingURL=propagationContext.js.map\n","/**\n * Shallow merge two objects.\n * Does not mutate the passed in objects.\n * Undefined/empty values in the merge object will overwrite existing values.\n *\n * By default, this merges 2 levels deep.\n */\nfunction merge(initialObj, mergeObj, levels = 2) {\n // If the merge value is not an object, or we have no merge levels left,\n // we just set the value to the merge value\n if (!mergeObj || typeof mergeObj !== 'object' || levels <= 0) {\n return mergeObj;\n }\n\n // If the merge object is an empty object, and the initial object is not undefined, we return the initial object\n if (initialObj && Object.keys(mergeObj).length === 0) {\n return initialObj;\n }\n\n // Clone object\n const output = { ...initialObj };\n\n // Merge values into output, resursively\n for (const key in mergeObj) {\n if (Object.prototype.hasOwnProperty.call(mergeObj, key)) {\n output[key] = merge(output[key], mergeObj[key], levels - 1);\n }\n }\n\n return output;\n}\n\nexport { merge };\n//# sourceMappingURL=merge.js.map\n","import { addNonEnumerableProperty } from '../utils-hoist/object.js';\n\nconst SCOPE_SPAN_FIELD = '_sentrySpan';\n\n/**\n * Set the active span for a given scope.\n * NOTE: This should NOT be used directly, but is only used internally by the trace methods.\n */\nfunction _setSpanForScope(scope, span) {\n if (span) {\n addNonEnumerableProperty(scope , SCOPE_SPAN_FIELD, span);\n } else {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete (scope )[SCOPE_SPAN_FIELD];\n }\n}\n\n/**\n * Get the active span for a given scope.\n * NOTE: This should NOT be used directly, but is only used internally by the trace methods.\n */\nfunction _getSpanForScope(scope) {\n return scope[SCOPE_SPAN_FIELD];\n}\n\nexport { _getSpanForScope, _setSpanForScope };\n//# sourceMappingURL=spanOnScope.js.map\n","import { updateSession } from './session.js';\nimport { isPlainObject } from './utils-hoist/is.js';\nimport { logger } from './utils-hoist/logger.js';\nimport { uuid4 } from './utils-hoist/misc.js';\nimport { generateTraceId } from './utils-hoist/propagationContext.js';\nimport { dateTimestampInSeconds } from './utils-hoist/time.js';\nimport { merge } from './utils/merge.js';\nimport { _setSpanForScope, _getSpanForScope } from './utils/spanOnScope.js';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * A context to be used for capturing an event.\n * This can either be a Scope, or a partial ScopeContext,\n * or a callback that receives the current scope and returns a new scope to use.\n */\n\n/**\n * Holds additional event information.\n */\nclass Scope {\n /** Flag if notifying is happening. */\n\n /** Callback for client to receive scope changes. */\n\n /** Callback list that will be called during event processing. */\n\n /** Array of breadcrumbs. */\n\n /** User */\n\n /** Tags */\n\n /** Extra */\n\n /** Contexts */\n\n /** Attachments */\n\n /** Propagation Context for distributed tracing */\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n\n /** Fingerprint */\n\n /** Severity */\n\n /**\n * Transaction Name\n *\n * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects.\n * It's purpose is to assign a transaction to the scope that's added to non-transaction events.\n */\n\n /** Session */\n\n /** The client on this scope */\n\n /** Contains the last event id of a captured event. */\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = {\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n };\n }\n\n /**\n * Clone all data from this scope into a new scope.\n */\n clone() {\n const newScope = new Scope();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n if (this._contexts.flags) {\n // We need to copy the `values` array so insertions on a cloned scope\n // won't affect the original array.\n newScope._contexts.flags = {\n values: [...this._contexts.flags.values],\n };\n }\n\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n newScope._lastEventId = this._lastEventId;\n\n _setSpanForScope(newScope, _getSpanForScope(this));\n\n return newScope;\n }\n\n /**\n * Update the client assigned to this scope.\n * Note that not every scope will have a client assigned - isolation scopes & the global scope will generally not have a client,\n * as well as manually created scopes.\n */\n setClient(client) {\n this._client = client;\n }\n\n /**\n * Set the ID of the last captured error event.\n * This is generally only captured on the isolation scope.\n */\n setLastEventId(lastEventId) {\n this._lastEventId = lastEventId;\n }\n\n /**\n * Get the client assigned to this scope.\n */\n getClient() {\n return this._client ;\n }\n\n /**\n * Get the ID of the last captured error event.\n * This is generally only available on the isolation scope.\n */\n lastEventId() {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n addScopeListener(callback) {\n this._scopeListeners.push(callback);\n }\n\n /**\n * Add an event processor that will be called before an event is sent.\n */\n addEventProcessor(callback) {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * Set the user for this scope.\n * Set to `null` to unset the user.\n */\n setUser(user) {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Get the user from this scope.\n */\n getUser() {\n return this._user;\n }\n\n /**\n * Set an object that will be merged into existing tags on the scope,\n * and will be sent as tags data with the event.\n */\n setTags(tags) {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Set a single tag that will be sent as tags data with the event.\n */\n setTag(key, value) {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Set an object that will be merged into existing extra on the scope,\n * and will be sent as extra data with the event.\n */\n setExtras(extras) {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Set a single key:value extra entry that will be sent as extra data with the event.\n */\n setExtra(key, extra) {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the fingerprint on the scope to send with the events.\n * @param {string[]} fingerprint Fingerprint to group events in Sentry.\n */\n setFingerprint(fingerprint) {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the level on the scope for future events.\n */\n setLevel(level) {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the transaction name on the scope so that the name of e.g. taken server route or\n * the page location is attached to future events.\n *\n * IMPORTANT: Calling this function does NOT change the name of the currently active\n * root span. If you want to change the name of the active root span, use\n * `Sentry.updateSpanName(rootSpan, 'new name')` instead.\n *\n * By default, the SDK updates the scope's transaction name automatically on sensible\n * occasions, such as a page navigation or when handling a new request on the server.\n */\n setTransactionName(name) {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets context data with the given name.\n * Data passed as context will be normalized. You can also pass `null` to unset the context.\n * Note that context data will not be merged - calling `setContext` will overwrite an existing context with the same key.\n */\n setContext(key, context) {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Set the session for the scope.\n */\n setSession(session) {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Get the session from the scope.\n */\n getSession() {\n return this._session;\n }\n\n /**\n * Updates the scope with provided data. Can work in three variations:\n * - plain object containing updatable attributes\n * - Scope instance that'll extract the attributes from\n * - callback function that'll receive the current scope as an argument and allow for modifications\n */\n update(captureContext) {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n const scopeInstance =\n scopeToMerge instanceof Scope\n ? scopeToMerge.getScopeData()\n : isPlainObject(scopeToMerge)\n ? (captureContext )\n : undefined;\n\n const { tags, extra, user, contexts, level, fingerprint = [], propagationContext } = scopeInstance || {};\n\n this._tags = { ...this._tags, ...tags };\n this._extra = { ...this._extra, ...extra };\n this._contexts = { ...this._contexts, ...contexts };\n\n if (user && Object.keys(user).length) {\n this._user = user;\n }\n\n if (level) {\n this._level = level;\n }\n\n if (fingerprint.length) {\n this._fingerprint = fingerprint;\n }\n\n if (propagationContext) {\n this._propagationContext = propagationContext;\n }\n\n return this;\n }\n\n /**\n * Clears the current scope and resets its properties.\n * Note: The client will not be cleared.\n */\n clear() {\n // client is not cleared here on purpose!\n this._breadcrumbs = [];\n this._tags = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._session = undefined;\n _setSpanForScope(this, undefined);\n this._attachments = [];\n this.setPropagationContext({ traceId: generateTraceId(), sampleRand: Math.random() });\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Adds a breadcrumb to the scope.\n * By default, the last 100 breadcrumbs are kept.\n */\n addBreadcrumb(breadcrumb, maxBreadcrumbs) {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n };\n\n this._breadcrumbs.push(mergedBreadcrumb);\n if (this._breadcrumbs.length > maxCrumbs) {\n this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs);\n this._client?.recordDroppedEvent('buffer_overflow', 'log_item');\n }\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * Get the last breadcrumb of the scope.\n */\n getLastBreadcrumb() {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * Clear all breadcrumbs from the scope.\n */\n clearBreadcrumbs() {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Add an attachment to the scope.\n */\n addAttachment(attachment) {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * Clear all attachments from the scope.\n */\n clearAttachments() {\n this._attachments = [];\n return this;\n }\n\n /**\n * Get the data of this scope, which should be applied to an event during processing.\n */\n getScopeData() {\n return {\n breadcrumbs: this._breadcrumbs,\n attachments: this._attachments,\n contexts: this._contexts,\n tags: this._tags,\n extra: this._extra,\n user: this._user,\n level: this._level,\n fingerprint: this._fingerprint || [],\n eventProcessors: this._eventProcessors,\n propagationContext: this._propagationContext,\n sdkProcessingMetadata: this._sdkProcessingMetadata,\n transactionName: this._transactionName,\n span: _getSpanForScope(this),\n };\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry.\n */\n setSDKProcessingMetadata(newData) {\n this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2);\n return this;\n }\n\n /**\n * Add propagation context to the scope, used for distributed tracing\n */\n setPropagationContext(context) {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * Get propagation context from the scope, used for distributed tracing\n */\n getPropagationContext() {\n return this._propagationContext;\n }\n\n /**\n * Capture an exception for this scope.\n *\n * @returns {string} The id of the captured Sentry event.\n */\n captureException(exception, hint) {\n const eventId = hint?.event_id || uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a message for this scope.\n *\n * @returns {string} The id of the captured message.\n */\n captureMessage(message, level, hint) {\n const eventId = hint?.event_id || uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a Sentry event for this scope.\n *\n * @returns {string} The id of the captured event.\n */\n captureEvent(event, hint) {\n const eventId = hint?.event_id || uuid4();\n\n if (!this._client) {\n logger.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n _notifyScopeListeners() {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\nexport { Scope };\n//# sourceMappingURL=scope.js.map\n","import { getGlobalSingleton } from './carrier.js';\nimport { Scope } from './scope.js';\n\n/** Get the default current scope. */\nfunction getDefaultCurrentScope() {\n return getGlobalSingleton('defaultCurrentScope', () => new Scope());\n}\n\n/** Get the default isolation scope. */\nfunction getDefaultIsolationScope() {\n return getGlobalSingleton('defaultIsolationScope', () => new Scope());\n}\n\nexport { getDefaultCurrentScope, getDefaultIsolationScope };\n//# sourceMappingURL=defaultScopes.js.map\n","import { getDefaultCurrentScope, getDefaultIsolationScope } from '../defaultScopes.js';\nimport { Scope } from '../scope.js';\nimport { isThenable } from '../utils-hoist/is.js';\nimport { getMainCarrier, getSentryCarrier } from '../carrier.js';\n\n/**\n * This is an object that holds a stack of scopes.\n */\nclass AsyncContextStack {\n\n constructor(scope, isolationScope) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n // scope stack for domains or the process\n this._stack = [{ scope: assignedScope }];\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Fork a scope for the stack.\n */\n withScope(callback) {\n const scope = this._pushScope();\n\n let maybePromiseResult;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n this._popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n this._popScope();\n return res;\n },\n e => {\n this._popScope();\n throw e;\n },\n );\n }\n\n this._popScope();\n return maybePromiseResult;\n }\n\n /**\n * Get the client of the stack.\n */\n getClient() {\n return this.getStackTop().client ;\n }\n\n /**\n * Returns the scope of the top stack.\n */\n getScope() {\n return this.getStackTop().scope;\n }\n\n /**\n * Get the isolation scope for the stack.\n */\n getIsolationScope() {\n return this._isolationScope;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n */\n getStackTop() {\n return this._stack[this._stack.length - 1] ;\n }\n\n /**\n * Push a scope to the stack.\n */\n _pushScope() {\n // We want to clone the content of prev scope\n const scope = this.getScope().clone();\n this._stack.push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * Pop a scope from the stack.\n */\n _popScope() {\n if (this._stack.length <= 1) return false;\n return !!this._stack.pop();\n }\n}\n\n/**\n * Get the global async context stack.\n * This will be removed during the v8 cycle and is only here to make migration easier.\n */\nfunction getAsyncContextStack() {\n const registry = getMainCarrier();\n const sentry = getSentryCarrier(registry);\n\n return (sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope()));\n}\n\nfunction withScope(callback) {\n return getAsyncContextStack().withScope(callback);\n}\n\nfunction withSetScope(scope, callback) {\n const stack = getAsyncContextStack() ;\n return stack.withScope(() => {\n stack.getStackTop().scope = scope;\n return callback(scope);\n });\n}\n\nfunction withIsolationScope(callback) {\n return getAsyncContextStack().withScope(() => {\n return callback(getAsyncContextStack().getIsolationScope());\n });\n}\n\n/**\n * Get the stack-based async context strategy.\n */\nfunction getStackAsyncContextStrategy() {\n return {\n withIsolationScope,\n withScope,\n withSetScope,\n withSetIsolationScope: (_isolationScope, callback) => {\n return withIsolationScope(callback);\n },\n getCurrentScope: () => getAsyncContextStack().getScope(),\n getIsolationScope: () => getAsyncContextStack().getIsolationScope(),\n };\n}\n\nexport { AsyncContextStack, getStackAsyncContextStrategy };\n//# sourceMappingURL=stackStrategy.js.map\n","import { getMainCarrier, getSentryCarrier } from '../carrier.js';\nimport { getStackAsyncContextStrategy } from './stackStrategy.js';\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nfunction setAsyncContextStrategy(strategy) {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n const sentry = getSentryCarrier(registry);\n sentry.acs = strategy;\n}\n\n/**\n * Get the current async context strategy.\n * If none has been setup, the default will be used.\n */\nfunction getAsyncContextStrategy(carrier) {\n const sentry = getSentryCarrier(carrier);\n\n if (sentry.acs) {\n return sentry.acs;\n }\n\n // Otherwise, use the default one (stack)\n return getStackAsyncContextStrategy();\n}\n\nexport { getAsyncContextStrategy, setAsyncContextStrategy };\n//# sourceMappingURL=index.js.map\n","import { getAsyncContextStrategy } from './asyncContext/index.js';\nimport { getMainCarrier, getGlobalSingleton } from './carrier.js';\nimport { Scope } from './scope.js';\nimport './utils-hoist/debug-build.js';\nimport './utils-hoist/logger.js';\nimport { dropUndefinedKeys } from './utils-hoist/object.js';\nimport './utils-hoist/time.js';\nimport './utils-hoist/syncpromise.js';\nimport { generateSpanId } from './utils-hoist/propagationContext.js';\n\n/**\n * Get the currently active scope.\n */\nfunction getCurrentScope() {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n return acs.getCurrentScope();\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current execution context.\n */\nfunction getIsolationScope() {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n return acs.getIsolationScope();\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nfunction getGlobalScope() {\n return getGlobalSingleton('globalScope', () => new Scope());\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n */\n\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nfunction withScope(\n ...rest\n) {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n\n if (!scope) {\n return acs.withScope(callback);\n }\n\n return acs.withSetScope(scope, callback);\n }\n\n return acs.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n */\n\n/**\n * Either creates a new active isolation scope, or sets the given isolation scope as active scope in the given callback.\n */\nfunction withIsolationScope(\n ...rest\n\n) {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [isolationScope, callback] = rest;\n\n if (!isolationScope) {\n return acs.withIsolationScope(callback);\n }\n\n return acs.withSetIsolationScope(isolationScope, callback);\n }\n\n return acs.withIsolationScope(rest[0]);\n}\n\n/**\n * Get the currently active client.\n */\nfunction getClient() {\n return getCurrentScope().getClient();\n}\n\n/**\n * Get a trace context for the given scope.\n */\nfunction getTraceContextFromScope(scope) {\n const propagationContext = scope.getPropagationContext();\n\n const { traceId, parentSpanId, propagationSpanId } = propagationContext;\n\n const traceContext = dropUndefinedKeys({\n trace_id: traceId,\n span_id: propagationSpanId || generateSpanId(),\n parent_span_id: parentSpanId,\n });\n\n return traceContext;\n}\n\nexport { getClient, getCurrentScope, getGlobalScope, getIsolationScope, getTraceContextFromScope, withIsolationScope, withScope };\n//# sourceMappingURL=currentScopes.js.map\n","/**\n * Use this attribute to represent the source of a span.\n * Should be one of: custom, url, route, view, component, task, unknown\n *\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';\n\n/**\n * Attributes that holds the sample rate that was locally applied to a span.\n * If this attribute is not defined, it means that the span inherited a sampling decision.\n *\n * NOTE: Is only defined on root spans.\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';\n\n/**\n * Use this attribute to represent the operation of a span.\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';\n\n/**\n * Use this attribute to represent the origin of a span.\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';\n\n/** The reason why an idle span finished. */\nconst SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = 'sentry.idle_span_finish_reason';\n\n/** The unit of a measurement, which may be stored as a TimedEvent. */\nconst SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = 'sentry.measurement_unit';\n\n/** The value of a measurement, which may be stored as a TimedEvent. */\nconst SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = 'sentry.measurement_value';\n\n/**\n * A custom span name set by users guaranteed to be taken over any automatically\n * inferred name. This attribute is removed before the span is sent.\n *\n * @internal only meant for internal SDK usage\n * @hidden\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = 'sentry.custom_span_name';\n\n/**\n * The id of the profile that this span occurred in.\n */\nconst SEMANTIC_ATTRIBUTE_PROFILE_ID = 'sentry.profile_id';\n\nconst SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = 'sentry.exclusive_time';\n\nconst SEMANTIC_ATTRIBUTE_CACHE_HIT = 'cache.hit';\n\nconst SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key';\n\nconst SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE = 'cache.item_size';\n\n/** TODO: Remove these once we update to latest semantic conventions */\nconst SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD = 'http.request.method';\nconst SEMANTIC_ATTRIBUTE_URL_FULL = 'url.full';\n\nexport { SEMANTIC_ATTRIBUTE_CACHE_HIT, SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, SEMANTIC_ATTRIBUTE_CACHE_KEY, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD, SEMANTIC_ATTRIBUTE_PROFILE_ID, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_URL_FULL };\n//# sourceMappingURL=semanticAttributes.js.map\n","const SPAN_STATUS_UNSET = 0;\nconst SPAN_STATUS_OK = 1;\nconst SPAN_STATUS_ERROR = 2;\n\n/**\n * Converts a HTTP status code into a sentry status with a message.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\n// https://develop.sentry.dev/sdk/event-payloads/span/\nfunction getSpanStatusFromHttpCode(httpStatus) {\n if (httpStatus < 400 && httpStatus >= 100) {\n return { code: SPAN_STATUS_OK };\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return { code: SPAN_STATUS_ERROR, message: 'unauthenticated' };\n case 403:\n return { code: SPAN_STATUS_ERROR, message: 'permission_denied' };\n case 404:\n return { code: SPAN_STATUS_ERROR, message: 'not_found' };\n case 409:\n return { code: SPAN_STATUS_ERROR, message: 'already_exists' };\n case 413:\n return { code: SPAN_STATUS_ERROR, message: 'failed_precondition' };\n case 429:\n return { code: SPAN_STATUS_ERROR, message: 'resource_exhausted' };\n case 499:\n return { code: SPAN_STATUS_ERROR, message: 'cancelled' };\n default:\n return { code: SPAN_STATUS_ERROR, message: 'invalid_argument' };\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return { code: SPAN_STATUS_ERROR, message: 'unimplemented' };\n case 503:\n return { code: SPAN_STATUS_ERROR, message: 'unavailable' };\n case 504:\n return { code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' };\n default:\n return { code: SPAN_STATUS_ERROR, message: 'internal_error' };\n }\n }\n\n return { code: SPAN_STATUS_ERROR, message: 'unknown_error' };\n}\n\n/**\n * Sets the Http status attributes on the current span based on the http code.\n * Additionally, the span's status is updated, depending on the http code.\n */\nfunction setHttpStatus(span, httpStatus) {\n span.setAttribute('http.response.status_code', httpStatus);\n\n const spanStatus = getSpanStatusFromHttpCode(httpStatus);\n if (spanStatus.message !== 'unknown_error') {\n span.setStatus(spanStatus);\n }\n}\n\nexport { SPAN_STATUS_ERROR, SPAN_STATUS_OK, SPAN_STATUS_UNSET, getSpanStatusFromHttpCode, setHttpStatus };\n//# sourceMappingURL=spanstatus.js.map\n","import { addNonEnumerableProperty } from '../utils-hoist/object.js';\n\nconst SCOPE_ON_START_SPAN_FIELD = '_sentryScope';\nconst ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';\n\n/** Store the scope & isolation scope for a span, which can the be used when it is finished. */\nfunction setCapturedScopesOnSpan(span, scope, isolationScope) {\n if (span) {\n addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, isolationScope);\n addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);\n }\n}\n\n/**\n * Grabs the scope and isolation scope off a span that were active when the span was started.\n */\nfunction getCapturedScopesOnSpan(span) {\n return {\n scope: (span )[SCOPE_ON_START_SPAN_FIELD],\n isolationScope: (span )[ISOLATION_SCOPE_ON_START_SPAN_FIELD],\n };\n}\n\nexport { getCapturedScopesOnSpan, setCapturedScopesOnSpan };\n//# sourceMappingURL=utils.js.map\n","/**\n * Parse a sample rate from a given value.\n * This will either return a boolean or number sample rate, if the sample rate is valid (between 0 and 1).\n * If a string is passed, we try to convert it to a number.\n *\n * Any invalid sample rate will return `undefined`.\n */\nfunction parseSampleRate(sampleRate) {\n if (typeof sampleRate === 'boolean') {\n return Number(sampleRate);\n }\n\n const rate = typeof sampleRate === 'string' ? parseFloat(sampleRate) : sampleRate;\n if (typeof rate !== 'number' || isNaN(rate) || rate < 0 || rate > 1) {\n return undefined;\n }\n\n return rate;\n}\n\nexport { parseSampleRate };\n//# sourceMappingURL=parseSampleRate.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { isString } from './is.js';\nimport { logger } from './logger.js';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nconst MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nfunction baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader,\n) {\n const baggageObject = parseBaggageHeader(baggageHeader);\n\n if (!baggageObject) {\n return undefined;\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext ;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nfunction dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext,\n) {\n if (!dynamicSamplingContext) {\n return undefined;\n }\n\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Take a baggage header and parse it into an object.\n */\nfunction parseBaggageHeader(\n baggageHeader,\n) {\n if (!baggageHeader || (!isString(baggageHeader) && !Array.isArray(baggageHeader))) {\n return undefined;\n }\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n return baggageHeader.reduce((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n Object.entries(currBaggageObject).forEach(([key, value]) => {\n acc[key] = value;\n });\n return acc;\n }, {});\n }\n\n return baggageHeaderToObject(baggageHeader);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader) {\n return baggageHeader\n .split(',')\n .map(baggageEntry => baggageEntry.split('=').map(keyOrValue => decodeURIComponent(keyOrValue.trim())))\n .reduce((acc, [key, value]) => {\n if (key && value) {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object) {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n\nexport { MAX_BAGGAGE_STRING_LENGTH, SENTRY_BAGGAGE_KEY_PREFIX, SENTRY_BAGGAGE_KEY_PREFIX_REGEX, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader, objectToBaggageHeader, parseBaggageHeader };\n//# sourceMappingURL=baggage.js.map\n","import { parseSampleRate } from '../utils/parseSampleRate.js';\nimport { baggageHeaderToDynamicSamplingContext } from './baggage.js';\nimport { generateTraceId, generateSpanId } from './propagationContext.js';\n\n// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- RegExp is used for readability here\nconst TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nfunction extractTraceparentData(traceparent) {\n if (!traceparent) {\n return undefined;\n }\n\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n if (!matches) {\n return undefined;\n }\n\n let parentSampled;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n\n/**\n * Create a propagation context from incoming headers or\n * creates a minimal new one if the headers are undefined.\n */\nfunction propagationContextFromHeaders(\n sentryTrace,\n baggage,\n) {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n if (!traceparentData?.traceId) {\n return {\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n };\n }\n\n const sampleRand = getSampleRandFromTraceparentAndDsc(traceparentData, dynamicSamplingContext);\n\n // The sample_rand on the DSC needs to be generated based on traceparent + baggage.\n if (dynamicSamplingContext) {\n dynamicSamplingContext.sample_rand = sampleRand.toString();\n }\n\n const { traceId, parentSpanId, parentSampled } = traceparentData;\n\n return {\n traceId,\n parentSpanId,\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n sampleRand,\n };\n}\n\n/**\n * Create sentry-trace header from span context values.\n */\nfunction generateSentryTraceHeader(\n traceId = generateTraceId(),\n spanId = generateSpanId(),\n sampled,\n) {\n let sampledString = '';\n if (sampled !== undefined) {\n sampledString = sampled ? '-1' : '-0';\n }\n return `${traceId}-${spanId}${sampledString}`;\n}\n\n/**\n * Given any combination of an incoming trace, generate a sample rand based on its defined semantics.\n *\n * Read more: https://develop.sentry.dev/sdk/telemetry/traces/#propagated-random-value\n */\nfunction getSampleRandFromTraceparentAndDsc(\n traceparentData,\n dsc,\n) {\n // When there is an incoming sample rand use it.\n const parsedSampleRand = parseSampleRate(dsc?.sample_rand);\n if (parsedSampleRand !== undefined) {\n return parsedSampleRand;\n }\n\n // Otherwise, if there is an incoming sampling decision + sample rate, generate a sample rand that would lead to the same sampling decision.\n const parsedSampleRate = parseSampleRate(dsc?.sample_rate);\n if (parsedSampleRate && traceparentData?.parentSampled !== undefined) {\n return traceparentData.parentSampled\n ? // Returns a sample rand with positive sampling decision [0, sampleRate)\n Math.random() * parsedSampleRate\n : // Returns a sample rand with negative sampling decision [sampleRate, 1)\n parsedSampleRate + Math.random() * (1 - parsedSampleRate);\n } else {\n // If nothing applies, return a random sample rand.\n return Math.random();\n }\n}\n\nexport { TRACEPARENT_REGEXP, extractTraceparentData, generateSentryTraceHeader, propagationContextFromHeaders };\n//# sourceMappingURL=tracing.js.map\n","import { getAsyncContextStrategy } from '../asyncContext/index.js';\nimport { getMainCarrier } from '../carrier.js';\nimport { getCurrentScope } from '../currentScopes.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME } from '../semanticAttributes.js';\nimport { SPAN_STATUS_UNSET, SPAN_STATUS_OK } from '../tracing/spanstatus.js';\nimport { getCapturedScopesOnSpan } from '../tracing/utils.js';\nimport { consoleSandbox } from '../utils-hoist/logger.js';\nimport { dropUndefinedKeys, addNonEnumerableProperty } from '../utils-hoist/object.js';\nimport { generateSpanId } from '../utils-hoist/propagationContext.js';\nimport { timestampInSeconds } from '../utils-hoist/time.js';\nimport { generateSentryTraceHeader } from '../utils-hoist/tracing.js';\nimport { _getSpanForScope } from './spanOnScope.js';\n\n// These are aligned with OpenTelemetry trace flags\nconst TRACE_FLAG_NONE = 0x0;\nconst TRACE_FLAG_SAMPLED = 0x1;\n\nlet hasShownSpanDropWarning = false;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n * By default, this will only include trace_id, span_id & parent_span_id.\n * If `includeAllData` is true, it will also include data, op, status & origin.\n */\nfunction spanToTransactionTraceContext(span) {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, origin } = spanToJSON(span);\n\n return dropUndefinedKeys({\n parent_span_id,\n span_id,\n trace_id,\n data,\n op,\n status,\n origin,\n });\n}\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in a non-transaction event.\n */\nfunction spanToTraceContext(span) {\n const { spanId, traceId: trace_id, isRemote } = span.spanContext();\n\n // If the span is remote, we use a random/virtual span as span_id to the trace context,\n // and the remote span as parent_span_id\n const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id;\n const scope = getCapturedScopesOnSpan(span).scope;\n\n const span_id = isRemote ? scope?.getPropagationContext().propagationSpanId || generateSpanId() : spanId;\n\n return dropUndefinedKeys({\n parent_span_id,\n span_id,\n trace_id,\n });\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nfunction spanToTraceHeader(span) {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Converts the span links array to a flattened version to be sent within an envelope.\n *\n * If the links array is empty, it returns `undefined` so the empty value can be dropped before it's sent.\n */\nfunction convertSpanLinksForEnvelope(links) {\n if (links && links.length > 0) {\n return links.map(({ context: { spanId, traceId, traceFlags, ...restContext }, attributes }) => ({\n span_id: spanId,\n trace_id: traceId,\n sampled: traceFlags === TRACE_FLAG_SAMPLED,\n attributes,\n ...restContext,\n }));\n } else {\n return undefined;\n }\n}\n\n/**\n * Convert a span time input into a timestamp in seconds.\n */\nfunction spanTimeInputToSeconds(input) {\n if (typeof input === 'number') {\n return ensureTimestampInSeconds(input);\n }\n\n if (Array.isArray(input)) {\n // See {@link HrTime} for the array-based time format\n return input[0] + input[1] / 1e9;\n }\n\n if (input instanceof Date) {\n return ensureTimestampInSeconds(input.getTime());\n }\n\n return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp) {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n */\n// Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n// This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n// And `spanToJSON` needs the Span class from `span.ts` to check here.\nfunction spanToJSON(span) {\n if (spanIsSentrySpan(span)) {\n return span.getSpanJSON();\n }\n\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n\n // Handle a span from @opentelemetry/sdk-base-trace's `Span` class\n if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {\n const { attributes, startTime, name, endTime, parentSpanId, status } = span;\n\n return dropUndefinedKeys({\n span_id,\n trace_id,\n data: attributes,\n description: name,\n parent_span_id: parentSpanId,\n start_timestamp: spanTimeInputToSeconds(startTime),\n // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time\n timestamp: spanTimeInputToSeconds(endTime) || undefined,\n status: getStatusMessage(status),\n op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],\n origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] ,\n });\n }\n\n // Finally, at least we have `spanContext()`....\n // This should not actually happen in reality, but we need to handle it for type safety.\n return {\n span_id,\n trace_id,\n start_timestamp: 0,\n data: {},\n };\n}\n\nfunction spanIsOpenTelemetrySdkTraceBaseSpan(span) {\n const castSpan = span ;\n return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;\n}\n\n/** Exported only for tests. */\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSentrySpan(span) {\n return typeof (span ).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nfunction spanIsSampled(span) {\n // We align our trace flags with the ones OpenTelemetry use\n // So we also check for sampled the same way they do.\n const { traceFlags } = span.spanContext();\n return traceFlags === TRACE_FLAG_SAMPLED;\n}\n\n/** Get the status message to use for a JSON representation of a span. */\nfunction getStatusMessage(status) {\n if (!status || status.code === SPAN_STATUS_UNSET) {\n return undefined;\n }\n\n if (status.code === SPAN_STATUS_OK) {\n return 'ok';\n }\n\n return status.message || 'unknown_error';\n}\n\nconst CHILD_SPANS_FIELD = '_sentryChildSpans';\nconst ROOT_SPAN_FIELD = '_sentryRootSpan';\n\n/**\n * Adds an opaque child span reference to a span.\n */\nfunction addChildSpanToSpan(span, childSpan) {\n // We store the root span reference on the child span\n // We need this for `getRootSpan()` to work\n const rootSpan = span[ROOT_SPAN_FIELD] || span;\n addNonEnumerableProperty(childSpan , ROOT_SPAN_FIELD, rootSpan);\n\n // We store a list of child spans on the parent span\n // We need this for `getSpanDescendants()` to work\n if (span[CHILD_SPANS_FIELD]) {\n span[CHILD_SPANS_FIELD].add(childSpan);\n } else {\n addNonEnumerableProperty(span, CHILD_SPANS_FIELD, new Set([childSpan]));\n }\n}\n\n/** This is only used internally by Idle Spans. */\nfunction removeChildSpanFromSpan(span, childSpan) {\n if (span[CHILD_SPANS_FIELD]) {\n span[CHILD_SPANS_FIELD].delete(childSpan);\n }\n}\n\n/**\n * Returns an array of the given span and all of its descendants.\n */\nfunction getSpanDescendants(span) {\n const resultSet = new Set();\n\n function addSpanChildren(span) {\n // This exit condition is required to not infinitely loop in case of a circular dependency.\n if (resultSet.has(span)) {\n return;\n // We want to ignore unsampled spans (e.g. non recording spans)\n } else if (spanIsSampled(span)) {\n resultSet.add(span);\n const childSpans = span[CHILD_SPANS_FIELD] ? Array.from(span[CHILD_SPANS_FIELD]) : [];\n for (const childSpan of childSpans) {\n addSpanChildren(childSpan);\n }\n }\n }\n\n addSpanChildren(span);\n\n return Array.from(resultSet);\n}\n\n/**\n * Returns the root span of a given span.\n */\nfunction getRootSpan(span) {\n return span[ROOT_SPAN_FIELD] || span;\n}\n\n/**\n * Returns the currently active span.\n */\nfunction getActiveSpan() {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n if (acs.getActiveSpan) {\n return acs.getActiveSpan();\n }\n\n return _getSpanForScope(getCurrentScope());\n}\n\n/**\n * Logs a warning once if `beforeSendSpan` is used to drop spans.\n */\nfunction showSpanDropWarning() {\n if (!hasShownSpanDropWarning) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly.',\n );\n });\n hasShownSpanDropWarning = true;\n }\n}\n\n/**\n * Updates the name of the given span and ensures that the span name is not\n * overwritten by the Sentry SDK.\n *\n * Use this function instead of `span.updateName()` if you want to make sure that\n * your name is kept. For some spans, for example root `http.server` spans the\n * Sentry SDK would otherwise overwrite the span name with a high-quality name\n * it infers when the span ends.\n *\n * Use this function in server code or when your span is started on the server\n * and on the client (browser). If you only update a span name on the client,\n * you can also use `span.updateName()` the SDK does not overwrite the name.\n *\n * @param span - The span to update the name of.\n * @param name - The name to set on the span.\n */\nfunction updateSpanName(span, name) {\n span.updateName(name);\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom',\n [SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]: name,\n });\n}\n\nexport { TRACE_FLAG_NONE, TRACE_FLAG_SAMPLED, addChildSpanToSpan, convertSpanLinksForEnvelope, getActiveSpan, getRootSpan, getSpanDescendants, getStatusMessage, removeChildSpanFromSpan, showSpanDropWarning, spanIsSampled, spanTimeInputToSeconds, spanToJSON, spanToTraceContext, spanToTraceHeader, spanToTransactionTraceContext, updateSpanName };\n//# sourceMappingURL=spanUtils.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { addGlobalErrorInstrumentationHandler } from '../utils-hoist/instrument/globalError.js';\nimport { addGlobalUnhandledRejectionInstrumentationHandler } from '../utils-hoist/instrument/globalUnhandledRejection.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { getActiveSpan, getRootSpan } from '../utils/spanUtils.js';\nimport { SPAN_STATUS_ERROR } from './spanstatus.js';\n\nlet errorsInstrumented = false;\n\n/**\n * Ensure that global errors automatically set the active span status.\n */\nfunction registerSpanErrorInstrumentation() {\n if (errorsInstrumented) {\n return;\n }\n\n errorsInstrumented = true;\n addGlobalErrorInstrumentationHandler(errorCallback);\n addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active root span as failed\n */\nfunction errorCallback() {\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n if (rootSpan) {\n const message = 'internal_error';\n DEBUG_BUILD && logger.log(`[Tracing] Root span: ${message} -> Global error occurred`);\n rootSpan.setStatus({ code: SPAN_STATUS_ERROR, message });\n }\n}\n\n// The function name will be lost when bundling but we need to be able to identify this listener later to maintain the\n// node.js default exit behaviour\nerrorCallback.tag = 'sentry_tracingErrorCallback';\n\nexport { registerSpanErrorInstrumentation };\n//# sourceMappingURL=errors.js.map\n","import { getClient } from '../currentScopes.js';\n\n// Treeshakable guard to remove all code related to tracing\n\n/**\n * Determines if span recording is currently enabled.\n *\n * Spans are recorded when at least one of `tracesSampleRate` and `tracesSampler`\n * is defined in the SDK config. This function does not make any assumption about\n * sampling decisions, it only checks if the SDK is configured to record spans.\n *\n * Important: This function only determines if span recording is enabled. Trace\n * continuation and propagation is separately controlled and not covered by this function.\n * If this function returns `false`, traces can still be propagated (which is what\n * we refer to by \"Tracing without Performance\")\n * @see https://develop.sentry.dev/sdk/telemetry/traces/tracing-without-performance/\n *\n * @param maybeOptions An SDK options object to be passed to this function.\n * If this option is not provided, the function will use the current client's options.\n */\nfunction hasSpansEnabled(\n maybeOptions,\n) {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const options = maybeOptions || getClient()?.getOptions();\n return (\n !!options &&\n // Note: This check is `!= null`, meaning \"nullish\". `0` is not \"nullish\", `undefined` and `null` are. (This comment was brought to you by 15 minutes of questioning life)\n (options.tracesSampleRate != null || !!options.tracesSampler)\n );\n}\n\n/**\n * @see JSDoc of `hasSpansEnabled`\n * @deprecated Use `hasSpansEnabled` instead, which is a more accurately named version of this function.\n * This function will be removed in the next major version of the SDK.\n */\n// TODO(v10): Remove this export\nconst hasTracingEnabled = hasSpansEnabled;\n\nexport { hasSpansEnabled, hasTracingEnabled };\n//# sourceMappingURL=hasSpansEnabled.js.map\n","const DEFAULT_ENVIRONMENT = 'production';\n\nexport { DEFAULT_ENVIRONMENT };\n//# sourceMappingURL=constants.js.map\n","import { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { getClient } from '../currentScopes.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes.js';\nimport { baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader } from '../utils-hoist/baggage.js';\nimport { dropUndefinedKeys, addNonEnumerableProperty } from '../utils-hoist/object.js';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled.js';\nimport { getRootSpan, spanToJSON, spanIsSampled } from '../utils/spanUtils.js';\nimport { getCapturedScopesOnSpan } from './utils.js';\n\n/**\n * If you change this value, also update the terser plugin config to\n * avoid minification of the object property!\n */\nconst FROZEN_DSC_FIELD = '_frozenDsc';\n\n/**\n * Freeze the given DSC on the given span.\n */\nfunction freezeDscOnSpan(span, dsc) {\n const spanWithMaybeDsc = span ;\n addNonEnumerableProperty(spanWithMaybeDsc, FROZEN_DSC_FIELD, dsc);\n}\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nfunction getDynamicSamplingContextFromClient(trace_id, client) {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n public_key,\n trace_id,\n }) ;\n\n client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * Get the dynamic sampling context for the currently active scopes.\n */\nfunction getDynamicSamplingContextFromScope(client, scope) {\n const propagationContext = scope.getPropagationContext();\n return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);\n}\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nfunction getDynamicSamplingContextFromSpan(span) {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n const rootSpan = getRootSpan(span);\n const rootSpanJson = spanToJSON(rootSpan);\n const rootSpanAttributes = rootSpanJson.data;\n const traceState = rootSpan.spanContext().traceState;\n\n // The span sample rate that was locally applied to the root span should also always be applied to the DSC, even if the DSC is frozen.\n // This is so that the downstream traces/services can use parentSampleRate in their `tracesSampler` to make consistent sampling decisions across the entire trace.\n const rootSpanSampleRate =\n traceState?.get('sentry.sample_rate') ?? rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE];\n function applyLocalSampleRateToDsc(dsc) {\n if (typeof rootSpanSampleRate === 'number' || typeof rootSpanSampleRate === 'string') {\n dsc.sample_rate = `${rootSpanSampleRate}`;\n }\n return dsc;\n }\n\n // For core implementation, we freeze the DSC onto the span as a non-enumerable property\n const frozenDsc = (rootSpan )[FROZEN_DSC_FIELD];\n if (frozenDsc) {\n return applyLocalSampleRateToDsc(frozenDsc);\n }\n\n // For OpenTelemetry, we freeze the DSC on the trace state\n const traceStateDsc = traceState?.get('sentry.dsc');\n\n // If the span has a DSC, we want it to take precedence\n const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);\n\n if (dscOnTraceState) {\n return applyLocalSampleRateToDsc(dscOnTraceState);\n }\n\n // Else, we generate it from the span\n const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const source = rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n const name = rootSpanJson.description;\n if (source !== 'url' && name) {\n dsc.transaction = name;\n }\n\n // How can we even land here with hasSpansEnabled() returning false?\n // Otel creates a Non-recording span in Tracing Without Performance mode when handling incoming requests\n // So we end up with an active span that is not sampled (neither positively nor negatively)\n if (hasSpansEnabled()) {\n dsc.sampled = String(spanIsSampled(rootSpan));\n dsc.sample_rand =\n // In OTEL we store the sample rand on the trace state because we cannot access scopes for NonRecordingSpans\n // The Sentry OTEL SpanSampler takes care of writing the sample rand on the root span\n traceState?.get('sentry.sample_rand') ??\n // On all other platforms we can actually get the scopes from a root span (we use this as a fallback)\n getCapturedScopesOnSpan(rootSpan)\n .scope?.getPropagationContext()\n .sampleRand.toString();\n }\n\n applyLocalSampleRateToDsc(dsc);\n\n client.emit('createDsc', dsc, rootSpan);\n\n return dsc;\n}\n\n/**\n * Convert a Span to a baggage header.\n */\nfunction spanToBaggageHeader(span) {\n const dsc = getDynamicSamplingContextFromSpan(span);\n return dynamicSamplingContextToSentryBaggageHeader(dsc);\n}\n\nexport { freezeDscOnSpan, getDynamicSamplingContextFromClient, getDynamicSamplingContextFromScope, getDynamicSamplingContextFromSpan, spanToBaggageHeader };\n//# sourceMappingURL=dynamicSamplingContext.js.map\n","import { generateTraceId, generateSpanId } from '../utils-hoist/propagationContext.js';\nimport { TRACE_FLAG_NONE } from '../utils/spanUtils.js';\n\n/**\n * A Sentry Span that is non-recording, meaning it will not be sent to Sentry.\n */\nclass SentryNonRecordingSpan {\n\n constructor(spanContext = {}) {\n this._traceId = spanContext.traceId || generateTraceId();\n this._spanId = spanContext.spanId || generateSpanId();\n }\n\n /** @inheritdoc */\n spanContext() {\n return {\n spanId: this._spanId,\n traceId: this._traceId,\n traceFlags: TRACE_FLAG_NONE,\n };\n }\n\n /** @inheritdoc */\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n end(_timestamp) {}\n\n /** @inheritdoc */\n setAttribute(_key, _value) {\n return this;\n }\n\n /** @inheritdoc */\n setAttributes(_values) {\n return this;\n }\n\n /** @inheritdoc */\n setStatus(_status) {\n return this;\n }\n\n /** @inheritdoc */\n updateName(_name) {\n return this;\n }\n\n /** @inheritdoc */\n isRecording() {\n return false;\n }\n\n /** @inheritdoc */\n addEvent(\n _name,\n _attributesOrStartTime,\n _startTime,\n ) {\n return this;\n }\n\n /** @inheritDoc */\n addLink(_link) {\n return this;\n }\n\n /** @inheritDoc */\n addLinks(_links) {\n return this;\n }\n\n /**\n * This should generally not be used,\n * but we need it for being compliant with the OTEL Span interface.\n *\n * @hidden\n * @internal\n */\n recordException(_exception, _time) {\n // noop\n }\n}\n\nexport { SentryNonRecordingSpan };\n//# sourceMappingURL=sentryNonRecordingSpan.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { spanToJSON, spanIsSampled, getRootSpan } from '../utils/spanUtils.js';\n\n/**\n * Print a log message for a started span.\n */\nfunction logSpanStart(span) {\n if (!DEBUG_BUILD) return;\n\n const { description = '< unknown name >', op = '< unknown op >', parent_span_id: parentSpanId } = spanToJSON(span);\n const { spanId } = span.spanContext();\n\n const sampled = spanIsSampled(span);\n const rootSpan = getRootSpan(span);\n const isRootSpan = rootSpan === span;\n\n const header = `[Tracing] Starting ${sampled ? 'sampled' : 'unsampled'} ${isRootSpan ? 'root ' : ''}span`;\n\n const infoParts = [`op: ${op}`, `name: ${description}`, `ID: ${spanId}`];\n\n if (parentSpanId) {\n infoParts.push(`parent ID: ${parentSpanId}`);\n }\n\n if (!isRootSpan) {\n const { op, description } = spanToJSON(rootSpan);\n infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`);\n if (op) {\n infoParts.push(`root op: ${op}`);\n }\n if (description) {\n infoParts.push(`root description: ${description}`);\n }\n }\n\n logger.log(`${header}\n ${infoParts.join('\\n ')}`);\n}\n\n/**\n * Print a log message for an ended span.\n */\nfunction logSpanEnd(span) {\n if (!DEBUG_BUILD) return;\n\n const { description = '< unknown name >', op = '< unknown op >' } = spanToJSON(span);\n const { spanId } = span.spanContext();\n const rootSpan = getRootSpan(span);\n const isRootSpan = rootSpan === span;\n\n const msg = `[Tracing] Finishing \"${op}\" ${isRootSpan ? 'root ' : ''}span \"${description}\" with ID ${spanId}`;\n logger.log(msg);\n}\n\nexport { logSpanEnd, logSpanStart };\n//# sourceMappingURL=logSpans.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled.js';\nimport { parseSampleRate } from '../utils/parseSampleRate.js';\n\n/**\n * Makes a sampling decision for the given options.\n *\n * Called every time a root span is created. Only root spans which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n */\nfunction sampleSpan(\n options,\n samplingContext,\n sampleRand,\n) {\n // nothing to do if span recording is not enabled\n if (!hasSpansEnabled(options)) {\n return [false];\n }\n\n let localSampleRateWasApplied = undefined;\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler({\n ...samplingContext,\n inheritOrSampleWith: fallbackSampleRate => {\n // If we have an incoming parent sample rate, we'll just use that one.\n // The sampling decision will be inherited because of the sample_rand that was generated when the trace reached the incoming boundaries of the SDK.\n if (typeof samplingContext.parentSampleRate === 'number') {\n return samplingContext.parentSampleRate;\n }\n\n // Fallback if parent sample rate is not on the incoming trace (e.g. if there is no baggage)\n // This is to provide backwards compatibility if there are incoming traces from older SDKs that don't send a parent sample rate or a sample rand. In these cases we just want to force either a sampling decision on the downstream traces via the sample rate.\n if (typeof samplingContext.parentSampled === 'boolean') {\n return Number(samplingContext.parentSampled);\n }\n\n return fallbackSampleRate;\n },\n });\n localSampleRateWasApplied = true;\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n localSampleRateWasApplied = true;\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get.\n // (The only valid values are booleans or numbers between 0 and 1.)\n const parsedSampleRate = parseSampleRate(sampleRate);\n\n if (parsedSampleRate === undefined) {\n DEBUG_BUILD &&\n logger.warn(\n `[Tracing] Discarding root span because of invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n sampleRate,\n )} of type ${JSON.stringify(typeof sampleRate)}.`,\n );\n return [false];\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!parsedSampleRate) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n return [false, parsedSampleRate, localSampleRateWasApplied];\n }\n\n // We always compare the sample rand for the current execution context against the chosen sample rate.\n // Read more: https://develop.sentry.dev/sdk/telemetry/traces/#propagated-random-value\n const shouldSample = sampleRand < parsedSampleRate;\n\n // if we're not going to keep it, we're done\n if (!shouldSample) {\n DEBUG_BUILD &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n }\n\n return [shouldSample, parsedSampleRate, localSampleRateWasApplied];\n}\n\nexport { sampleSpan };\n//# sourceMappingURL=sampling.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { consoleSandbox, logger } from './logger.js';\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol) {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nfunction dsnToString(dsn, withPassword = false) {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nfunction dsnFromString(str) {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n });\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host = '', port = '', lastPath = ''] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() ;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey });\n}\n\nfunction dsnFromComponents(components) {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn) {\n if (!DEBUG_BUILD) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n logger.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nfunction makeDsn(from) {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n\nexport { dsnFromString, dsnToString, makeDsn };\n//# sourceMappingURL=dsn.js.map\n","import { isVueViewModel, isSyntheticEvent } from './is.js';\nimport { convertToPlainObject } from './object.js';\nimport { getFunctionName } from './stacktrace.js';\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normalized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalize(input, depth = 100, maxProperties = +Infinity) {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nfunction normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object,\n // Default Node.js REPL depth\n depth = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize = 100 * 1024,\n) {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized ;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key,\n value,\n depth = +Infinity,\n maxProperties = +Infinity,\n memo = memoBuilder(),\n) {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n ['boolean', 'string'].includes(typeof value) ||\n (typeof value === 'number' && Number.isFinite(value))\n ) {\n return value ;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value )['__sentry_skip_normalization__']) {\n return value ;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value )['__sentry_override_normalization_depth__'] === 'number'\n ? ((value )['__sentry_override_normalization_depth__'] )\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value ;\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch (err) {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) ;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value );\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value,\n) {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value )._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n if (isVueViewModel(value)) {\n return '[VueViewModel]';\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && !Number.isFinite(value)) {\n return `[${value}]`;\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value) {\n const prototype = Object.getPrototypeOf(value);\n\n return prototype ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value) {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value) {\n return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nfunction normalizeUrlToBase(url, basePath) {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch (_Oo) {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n\n/**\n * Helper to decycle json objects\n */\nfunction memoBuilder() {\n const inner = new WeakSet();\n function memoize(obj) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n\n function unmemoize(obj) {\n inner.delete(obj);\n }\n return [memoize, unmemoize];\n}\n\nexport { normalize, normalizeToSize, normalizeUrlToBase };\n//# sourceMappingURL=normalize.js.map\n","import { getSentryCarrier } from '../carrier.js';\nimport { dsnToString } from './dsn.js';\nimport { normalize } from './normalize.js';\nimport { dropUndefinedKeys } from './object.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction createEnvelope(headers, items = []) {\n return [headers, items] ;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction addItemToEnvelope(envelope, newItem) {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] ;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nfunction forEachEnvelopeItem(\n envelope,\n callback,\n) {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nfunction envelopeContainsItemType(envelope, types) {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8 array.\n */\nfunction encodeUTF8(input) {\n const carrier = getSentryCarrier(GLOBAL_OBJ);\n return carrier.encodePolyfill ? carrier.encodePolyfill(input) : new TextEncoder().encode(input);\n}\n\n/**\n * Decode a UTF8 array to string.\n */\nfunction decodeUTF8(input) {\n const carrier = getSentryCarrier(GLOBAL_OBJ);\n return carrier.decodePolyfill ? carrier.decodePolyfill(input) : new TextDecoder().decode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nfunction serializeEnvelope(envelope) {\n const [envHeaders, items] = envelope;\n\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts = JSON.stringify(envHeaders);\n\n function append(next) {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch (e) {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.stringify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers) {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\n/**\n * Parses an envelope\n */\nfunction parseEnvelope(env) {\n let buffer = typeof env === 'string' ? encodeUTF8(env) : env;\n\n function readBinary(length) {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson() {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(decodeUTF8(readBinary(i))) ;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates envelope item for a single span\n */\nfunction createSpanEnvelopeItem(spanJson) {\n const spanHeaders = {\n type: 'span',\n };\n\n return [spanHeaders, spanJson];\n}\n\n/**\n * Creates attachment envelope items\n */\nfunction createAttachmentEnvelopeItem(attachment) {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data) : attachment.data;\n\n return [\n dropUndefinedKeys({\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n }),\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n profile_chunk: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n raw_security: 'security',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nfunction envelopeItemTypeToDataCategory(type) {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nfunction getSdkMetadataForEnvelopeHeader(metadataOrEvent) {\n if (!metadataOrEvent?.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nfunction createEventEnvelopeHeaders(\n event,\n sdkInfo,\n tunnel,\n dsn,\n) {\n const dynamicSamplingContext = event.sdkProcessingMetadata?.dynamicSamplingContext;\n return {\n event_id: event.event_id ,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dropUndefinedKeys({ ...dynamicSamplingContext }),\n }),\n };\n}\n\nexport { addItemToEnvelope, createAttachmentEnvelopeItem, createEnvelope, createEventEnvelopeHeaders, createSpanEnvelopeItem, envelopeContainsItemType, envelopeItemTypeToDataCategory, forEachEnvelopeItem, getSdkMetadataForEnvelopeHeader, parseEnvelope, serializeEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { getDynamicSamplingContextFromSpan } from './tracing/dynamicSamplingContext.js';\nimport { dsnToString } from './utils-hoist/dsn.js';\nimport { getSdkMetadataForEnvelopeHeader, createEnvelope, createEventEnvelopeHeaders, createSpanEnvelopeItem } from './utils-hoist/envelope.js';\nimport './utils-hoist/debug-build.js';\nimport './utils-hoist/logger.js';\nimport { spanToJSON, showSpanDropWarning } from './utils/spanUtils.js';\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n **/\nfunction enhanceEventWithSdkInfo(event, sdkInfo) {\n if (!sdkInfo) {\n return event;\n }\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || sdkInfo.name;\n event.sdk.version = event.sdk.version || sdkInfo.version;\n event.sdk.integrations = [...(event.sdk.integrations || []), ...(sdkInfo.integrations || [])];\n event.sdk.packages = [...(event.sdk.packages || []), ...(sdkInfo.packages || [])];\n return event;\n}\n\n/** Creates an envelope from a Session */\nfunction createSessionEnvelope(\n session,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n const envelopeHeaders = {\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const envelopeItem =\n 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session.toJSON()];\n\n return createEnvelope(envelopeHeaders, [envelopeItem]);\n}\n\n/**\n * Create an Envelope from an event.\n */\nfunction createEventEnvelope(\n event,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n\n /*\n Note: Due to TS, event.type may be `replay_event`, theoretically.\n In practice, we never call `createEventEnvelope` with `replay_event` type,\n and we'd have to adjust a looot of types to make this work properly.\n We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type)\n So the safe choice is to really guard against the replay_event type here.\n */\n const eventType = event.type && event.type !== 'replay_event' ? event.type : 'event';\n\n enhanceEventWithSdkInfo(event, metadata?.sdk);\n\n const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete event.sdkProcessingMetadata;\n\n const eventItem = [{ type: eventType }, event];\n return createEnvelope(envelopeHeaders, [eventItem]);\n}\n\n/**\n * Create envelope from Span item.\n *\n * Takes an optional client and runs spans through `beforeSendSpan` if available.\n */\nfunction createSpanEnvelope(spans, client) {\n function dscHasRequiredProps(dsc) {\n return !!dsc.trace_id && !!dsc.public_key;\n }\n\n // For the moment we'll obtain the DSC from the first span in the array\n // This might need to be changed if we permit sending multiple spans from\n // different segments in one envelope\n const dsc = getDynamicSamplingContextFromSpan(spans[0]);\n\n const dsn = client?.getDsn();\n const tunnel = client?.getOptions().tunnel;\n\n const headers = {\n sent_at: new Date().toISOString(),\n ...(dscHasRequiredProps(dsc) && { trace: dsc }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const beforeSendSpan = client?.getOptions().beforeSendSpan;\n const convertToSpanJSON = beforeSendSpan\n ? (span) => {\n const spanJson = spanToJSON(span);\n const processedSpan = beforeSendSpan(spanJson);\n\n if (!processedSpan) {\n showSpanDropWarning();\n return spanJson;\n }\n\n return processedSpan;\n }\n : spanToJSON;\n\n const items = [];\n for (const span of spans) {\n const spanJson = convertToSpanJSON(span);\n if (spanJson) {\n items.push(createSpanEnvelopeItem(spanJson));\n }\n }\n\n return createEnvelope(headers, items);\n}\n\nexport { createEventEnvelope, createSessionEnvelope, createSpanEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT } from '../semanticAttributes.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { getRootSpan, getActiveSpan } from '../utils/spanUtils.js';\n\n/**\n * Adds a measurement to the active transaction on the current global scope. You can optionally pass in a different span\n * as the 4th parameter.\n */\nfunction setMeasurement(name, value, unit, activeSpan = getActiveSpan()) {\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n\n if (rootSpan) {\n DEBUG_BUILD && logger.log(`[Measurement] Setting measurement on root span: ${name} = ${value} ${unit}`);\n rootSpan.addEvent(name, {\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: value,\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: unit ,\n });\n }\n}\n\n/**\n * Convert timed events to measurements.\n */\nfunction timedEventsToMeasurements(events) {\n if (!events || events.length === 0) {\n return undefined;\n }\n\n const measurements = {};\n events.forEach(event => {\n const attributes = event.attributes || {};\n const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT] ;\n const value = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE] ;\n\n if (typeof unit === 'string' && typeof value === 'number') {\n measurements[event.name] = { value, unit };\n }\n });\n\n return measurements;\n}\n\nexport { setMeasurement, timedEventsToMeasurements };\n//# sourceMappingURL=measurement.js.map\n","import { getClient, getCurrentScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { createSpanEnvelope } from '../envelope.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_PROFILE_ID, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME } from '../semanticAttributes.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { dropUndefinedKeys } from '../utils-hoist/object.js';\nimport { generateTraceId, generateSpanId } from '../utils-hoist/propagationContext.js';\nimport { timestampInSeconds } from '../utils-hoist/time.js';\nimport { TRACE_FLAG_SAMPLED, TRACE_FLAG_NONE, spanTimeInputToSeconds, getStatusMessage, getRootSpan, spanToJSON, getSpanDescendants, spanToTransactionTraceContext } from '../utils/spanUtils.js';\nimport { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext.js';\nimport { logSpanEnd } from './logSpans.js';\nimport { timedEventsToMeasurements } from './measurement.js';\nimport { getCapturedScopesOnSpan } from './utils.js';\n\nconst MAX_SPAN_COUNT = 1000;\n\n/**\n * Span contains all data about a span\n */\nclass SentrySpan {\n\n /** Epoch timestamp in seconds when the span started. */\n\n /** Epoch timestamp in seconds when the span ended. */\n\n /** Internal keeper of the status */\n\n /** The timed events added to this span. */\n\n /** if true, treat span as a standalone span (not part of a transaction) */\n\n /**\n * You should never call the constructor manually, always use `Sentry.startSpan()`\n * or other span methods.\n * @internal\n * @hideconstructor\n * @hidden\n */\n constructor(spanContext = {}) {\n this._traceId = spanContext.traceId || generateTraceId();\n this._spanId = spanContext.spanId || generateSpanId();\n this._startTime = spanContext.startTimestamp || timestampInSeconds();\n\n this._attributes = {};\n this.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'manual',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,\n ...spanContext.attributes,\n });\n\n this._name = spanContext.name;\n\n if (spanContext.parentSpanId) {\n this._parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this._sampled = spanContext.sampled;\n }\n if (spanContext.endTimestamp) {\n this._endTime = spanContext.endTimestamp;\n }\n\n this._events = [];\n\n this._isStandaloneSpan = spanContext.isStandalone;\n\n // If the span is already ended, ensure we finalize the span immediately\n if (this._endTime) {\n this._onSpanEnded();\n }\n }\n\n /** @inheritDoc */\n addLink(_link) {\n return this;\n }\n\n /** @inheritDoc */\n addLinks(_links) {\n return this;\n }\n\n /**\n * This should generally not be used,\n * but it is needed for being compliant with the OTEL Span interface.\n *\n * @hidden\n * @internal\n */\n recordException(_exception, _time) {\n // noop\n }\n\n /** @inheritdoc */\n spanContext() {\n const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;\n return {\n spanId,\n traceId,\n traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE,\n };\n }\n\n /** @inheritdoc */\n setAttribute(key, value) {\n if (value === undefined) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._attributes[key];\n } else {\n this._attributes[key] = value;\n }\n\n return this;\n }\n\n /** @inheritdoc */\n setAttributes(attributes) {\n Object.keys(attributes).forEach(key => this.setAttribute(key, attributes[key]));\n return this;\n }\n\n /**\n * This should generally not be used,\n * but we need it for browser tracing where we want to adjust the start time afterwards.\n * USE THIS WITH CAUTION!\n *\n * @hidden\n * @internal\n */\n updateStartTime(timeInput) {\n this._startTime = spanTimeInputToSeconds(timeInput);\n }\n\n /**\n * @inheritDoc\n */\n setStatus(value) {\n this._status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n updateName(name) {\n this._name = name;\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'custom');\n return this;\n }\n\n /** @inheritdoc */\n end(endTimestamp) {\n // If already ended, skip\n if (this._endTime) {\n return;\n }\n\n this._endTime = spanTimeInputToSeconds(endTimestamp);\n logSpanEnd(this);\n\n this._onSpanEnded();\n }\n\n /**\n * Get JSON representation of this span.\n *\n * @hidden\n * @internal This method is purely for internal purposes and should not be used outside\n * of SDK code. If you need to get a JSON representation of a span,\n * use `spanToJSON(span)` instead.\n */\n getSpanJSON() {\n return dropUndefinedKeys({\n data: this._attributes,\n description: this._name,\n op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],\n parent_span_id: this._parentSpanId,\n span_id: this._spanId,\n start_timestamp: this._startTime,\n status: getStatusMessage(this._status),\n timestamp: this._endTime,\n trace_id: this._traceId,\n origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] ,\n profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] ,\n exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME] ,\n measurements: timedEventsToMeasurements(this._events),\n is_segment: (this._isStandaloneSpan && getRootSpan(this) === this) || undefined,\n segment_id: this._isStandaloneSpan ? getRootSpan(this).spanContext().spanId : undefined,\n });\n }\n\n /** @inheritdoc */\n isRecording() {\n return !this._endTime && !!this._sampled;\n }\n\n /**\n * @inheritdoc\n */\n addEvent(\n name,\n attributesOrStartTime,\n startTime,\n ) {\n DEBUG_BUILD && logger.log('[Tracing] Adding an event to span:', name);\n\n const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || timestampInSeconds();\n const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {};\n\n const event = {\n name,\n time: spanTimeInputToSeconds(time),\n attributes,\n };\n\n this._events.push(event);\n\n return this;\n }\n\n /**\n * This method should generally not be used,\n * but for now we need a way to publicly check if the `_isStandaloneSpan` flag is set.\n * USE THIS WITH CAUTION!\n * @internal\n * @hidden\n * @experimental\n */\n isStandaloneSpan() {\n return !!this._isStandaloneSpan;\n }\n\n /** Emit `spanEnd` when the span is ended. */\n _onSpanEnded() {\n const client = getClient();\n if (client) {\n client.emit('spanEnd', this);\n }\n\n // A segment span is basically the root span of a local span tree.\n // So for now, this is either what we previously refer to as the root span,\n // or a standalone span.\n const isSegmentSpan = this._isStandaloneSpan || this === getRootSpan(this);\n\n if (!isSegmentSpan) {\n return;\n }\n\n // if this is a standalone span, we send it immediately\n if (this._isStandaloneSpan) {\n if (this._sampled) {\n sendSpanEnvelope(createSpanEnvelope([this], client));\n } else {\n DEBUG_BUILD &&\n logger.log('[Tracing] Discarding standalone span because its trace was not chosen to be sampled.');\n if (client) {\n client.recordDroppedEvent('sample_rate', 'span');\n }\n }\n return;\n }\n\n const transactionEvent = this._convertSpanToTransaction();\n if (transactionEvent) {\n const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope();\n scope.captureEvent(transactionEvent);\n }\n }\n\n /**\n * Finish the transaction & prepare the event to send to Sentry.\n */\n _convertSpanToTransaction() {\n // We can only convert finished spans\n if (!isFullFinishedSpan(spanToJSON(this))) {\n return undefined;\n }\n\n if (!this._name) {\n DEBUG_BUILD && logger.warn('Transaction has no name, falling back to ``.');\n this._name = '';\n }\n\n const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);\n\n if (this._sampled !== true) {\n return undefined;\n }\n\n // The transaction span itself as well as any potential standalone spans should be filtered out\n const finishedSpans = getSpanDescendants(this).filter(span => span !== this && !isStandaloneSpan(span));\n\n const spans = finishedSpans.map(span => spanToJSON(span)).filter(isFullFinishedSpan);\n\n const source = this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] ;\n\n // remove internal root span attributes we don't need to send.\n /* eslint-disable @typescript-eslint/no-dynamic-delete */\n delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];\n spans.forEach(span => {\n delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];\n });\n // eslint-enabled-next-line @typescript-eslint/no-dynamic-delete\n\n const transaction = {\n contexts: {\n trace: spanToTransactionTraceContext(this),\n },\n spans:\n // spans.sort() mutates the array, but `spans` is already a copy so we can safely do this here\n // we do not use spans anymore after this point\n spans.length > MAX_SPAN_COUNT\n ? spans.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT)\n : spans,\n start_timestamp: this._startTime,\n timestamp: this._endTime,\n transaction: this._name,\n type: 'transaction',\n sdkProcessingMetadata: {\n capturedSpanScope,\n capturedSpanIsolationScope,\n ...dropUndefinedKeys({\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),\n }),\n },\n ...(source && {\n transaction_info: {\n source,\n },\n }),\n };\n\n const measurements = timedEventsToMeasurements(this._events);\n const hasMeasurements = measurements && Object.keys(measurements).length;\n\n if (hasMeasurements) {\n DEBUG_BUILD &&\n logger.log(\n '[Measurements] Adding measurements to transaction event',\n JSON.stringify(measurements, undefined, 2),\n );\n transaction.measurements = measurements;\n }\n\n return transaction;\n }\n}\n\nfunction isSpanTimeInput(value) {\n return (value && typeof value === 'number') || value instanceof Date || Array.isArray(value);\n}\n\n// We want to filter out any incomplete SpanJSON objects\nfunction isFullFinishedSpan(input) {\n return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id;\n}\n\n/** `SentrySpan`s can be sent as a standalone span rather than belonging to a transaction */\nfunction isStandaloneSpan(span) {\n return span instanceof SentrySpan && span.isStandaloneSpan();\n}\n\n/**\n * Sends a `SpanEnvelope`.\n *\n * Note: If the envelope's spans are dropped, e.g. via `beforeSendSpan`,\n * the envelope will not be sent either.\n */\nfunction sendSpanEnvelope(envelope) {\n const client = getClient();\n if (!client) {\n return;\n }\n\n const spanItems = envelope[1];\n if (!spanItems || spanItems.length === 0) {\n client.recordDroppedEvent('before_send', 'span');\n return;\n }\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n client.sendEnvelope(envelope);\n}\n\nexport { SentrySpan };\n//# sourceMappingURL=sentrySpan.js.map\n","import { getMainCarrier } from '../carrier.js';\nimport { withScope, getCurrentScope, getIsolationScope, getClient } from '../currentScopes.js';\nimport { getAsyncContextStrategy } from '../asyncContext/index.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE } from '../semanticAttributes.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { generateTraceId } from '../utils-hoist/propagationContext.js';\nimport { propagationContextFromHeaders } from '../utils-hoist/tracing.js';\nimport { handleCallbackErrors } from '../utils/handleCallbackErrors.js';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled.js';\nimport { parseSampleRate } from '../utils/parseSampleRate.js';\nimport { _setSpanForScope, _getSpanForScope } from '../utils/spanOnScope.js';\nimport { spanToJSON, addChildSpanToSpan, spanIsSampled, spanTimeInputToSeconds, getRootSpan } from '../utils/spanUtils.js';\nimport { getDynamicSamplingContextFromSpan, freezeDscOnSpan } from './dynamicSamplingContext.js';\nimport { logSpanStart } from './logSpans.js';\nimport { sampleSpan } from './sampling.js';\nimport { SentryNonRecordingSpan } from './sentryNonRecordingSpan.js';\nimport { SentrySpan } from './sentrySpan.js';\nimport { SPAN_STATUS_ERROR } from './spanstatus.js';\nimport { setCapturedScopesOnSpan } from './utils.js';\n\nconst SUPPRESS_TRACING_KEY = '__SENTRY_SUPPRESS_TRACING__';\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * If you want to create a span that is not set as active, use {@link startInactiveSpan}.\n *\n * You'll always get a span passed to the callback,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nfunction startSpan(options, callback) {\n const acs = getAcs();\n if (acs.startSpan) {\n return acs.startSpan(options, callback);\n }\n\n const spanArguments = parseSentrySpanArguments(options);\n const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;\n\n // We still need to fork a potentially passed scope, as we set the active span on it\n // and we need to ensure that it is cleaned up properly once the span ends.\n const customForkedScope = customScope?.clone();\n\n return withScope(customForkedScope, () => {\n // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n const wrapper = getActiveSpanWrapper(customParentSpan);\n\n return wrapper(() => {\n const scope = getCurrentScope();\n const parentSpan = getParentSpan(scope);\n\n const shouldSkipSpan = options.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? new SentryNonRecordingSpan()\n : createChildOrRootSpan({\n parentSpan,\n spanArguments,\n forceTransaction,\n scope,\n });\n\n _setSpanForScope(scope, activeSpan);\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n () => {\n // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n const { status } = spanToJSON(activeSpan);\n if (activeSpan.isRecording() && (!status || status === 'ok')) {\n activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n },\n () => {\n activeSpan.end();\n },\n );\n });\n });\n}\n\n/**\n * Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span\n * after the function is done automatically. Use `span.end()` to end the span.\n *\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * You'll always get a span passed to the callback,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nfunction startSpanManual(options, callback) {\n const acs = getAcs();\n if (acs.startSpanManual) {\n return acs.startSpanManual(options, callback);\n }\n\n const spanArguments = parseSentrySpanArguments(options);\n const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;\n\n const customForkedScope = customScope?.clone();\n\n return withScope(customForkedScope, () => {\n // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n const wrapper = getActiveSpanWrapper(customParentSpan);\n\n return wrapper(() => {\n const scope = getCurrentScope();\n const parentSpan = getParentSpan(scope);\n\n const shouldSkipSpan = options.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? new SentryNonRecordingSpan()\n : createChildOrRootSpan({\n parentSpan,\n spanArguments,\n forceTransaction,\n scope,\n });\n\n _setSpanForScope(scope, activeSpan);\n\n return handleCallbackErrors(\n // We pass the `finish` function to the callback, so the user can finish the span manually\n // this is mainly here for historic purposes because previously, we instructed users to call\n // `finish` instead of `span.end()` to also clean up the scope. Nowadays, calling `span.end()`\n // or `finish` has the same effect and we simply leave it here to avoid breaking user code.\n () => callback(activeSpan, () => activeSpan.end()),\n () => {\n // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n const { status } = spanToJSON(activeSpan);\n if (activeSpan.isRecording() && (!status || status === 'ok')) {\n activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n },\n );\n });\n });\n}\n\n/**\n * Creates a span. This span is not set as active, so will not get automatic instrumentation spans\n * as children or be able to be accessed via `Sentry.getActiveSpan()`.\n *\n * If you want to create a span that is set as active, use {@link startSpan}.\n *\n * This function will always return a span,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nfunction startInactiveSpan(options) {\n const acs = getAcs();\n if (acs.startInactiveSpan) {\n return acs.startInactiveSpan(options);\n }\n\n const spanArguments = parseSentrySpanArguments(options);\n const { forceTransaction, parentSpan: customParentSpan } = options;\n\n // If `options.scope` is defined, we use this as as a wrapper,\n // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n const wrapper = options.scope\n ? (callback) => withScope(options.scope, callback)\n : customParentSpan !== undefined\n ? (callback) => withActiveSpan(customParentSpan, callback)\n : (callback) => callback();\n\n return wrapper(() => {\n const scope = getCurrentScope();\n const parentSpan = getParentSpan(scope);\n\n const shouldSkipSpan = options.onlyIfParent && !parentSpan;\n\n if (shouldSkipSpan) {\n return new SentryNonRecordingSpan();\n }\n\n return createChildOrRootSpan({\n parentSpan,\n spanArguments,\n forceTransaction,\n scope,\n });\n });\n}\n\n/**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers, or in the browser from ``\n * and `` HTML tags.\n *\n * Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically\n * be attached to the incoming trace.\n */\nconst continueTrace = (\n options\n\n,\n callback,\n) => {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n if (acs.continueTrace) {\n return acs.continueTrace(options, callback);\n }\n\n const { sentryTrace, baggage } = options;\n\n return withScope(scope => {\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n scope.setPropagationContext(propagationContext);\n return callback();\n });\n};\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be\n * passed `null` to start an entirely new span tree.\n *\n * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,\n * spans started within the callback will not be attached to a parent span.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nfunction withActiveSpan(span, callback) {\n const acs = getAcs();\n if (acs.withActiveSpan) {\n return acs.withActiveSpan(span, callback);\n }\n\n return withScope(scope => {\n _setSpanForScope(scope, span || undefined);\n return callback(scope);\n });\n}\n\n/** Suppress tracing in the given callback, ensuring no spans are generated inside of it. */\nfunction suppressTracing(callback) {\n const acs = getAcs();\n\n if (acs.suppressTracing) {\n return acs.suppressTracing(callback);\n }\n\n return withScope(scope => {\n scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true });\n return callback();\n });\n}\n\n/**\n * Starts a new trace for the duration of the provided callback. Spans started within the\n * callback will be part of the new trace instead of a potentially previously started trace.\n *\n * Important: Only use this function if you want to override the default trace lifetime and\n * propagation mechanism of the SDK for the duration and scope of the provided callback.\n * The newly created trace will also be the root of a new distributed trace, for example if\n * you make http requests within the callback.\n * This function might be useful if the operation you want to instrument should not be part\n * of a potentially ongoing trace.\n *\n * Default behavior:\n * - Server-side: A new trace is started for each incoming request.\n * - Browser: A new trace is started for each page our route. Navigating to a new route\n * or page will automatically create a new trace.\n */\nfunction startNewTrace(callback) {\n return withScope(scope => {\n scope.setPropagationContext({\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n });\n DEBUG_BUILD && logger.info(`Starting a new trace with id ${scope.getPropagationContext().traceId}`);\n return withActiveSpan(null, callback);\n });\n}\n\nfunction createChildOrRootSpan({\n parentSpan,\n spanArguments,\n forceTransaction,\n scope,\n}\n\n) {\n if (!hasSpansEnabled()) {\n const span = new SentryNonRecordingSpan();\n\n // If this is a root span, we ensure to freeze a DSC\n // So we can have at least partial data here\n if (forceTransaction || !parentSpan) {\n const dsc = {\n sampled: 'false',\n sample_rate: '0',\n transaction: spanArguments.name,\n ...getDynamicSamplingContextFromSpan(span),\n } ;\n freezeDscOnSpan(span, dsc);\n }\n\n return span;\n }\n\n const isolationScope = getIsolationScope();\n\n let span;\n if (parentSpan && !forceTransaction) {\n span = _startChildSpan(parentSpan, scope, spanArguments);\n addChildSpanToSpan(parentSpan, span);\n } else if (parentSpan) {\n // If we forced a transaction but have a parent span, make sure to continue from the parent span, not the scope\n const dsc = getDynamicSamplingContextFromSpan(parentSpan);\n const { traceId, spanId: parentSpanId } = parentSpan.spanContext();\n const parentSampled = spanIsSampled(parentSpan);\n\n span = _startRootSpan(\n {\n traceId,\n parentSpanId,\n ...spanArguments,\n },\n scope,\n parentSampled,\n );\n\n freezeDscOnSpan(span, dsc);\n } else {\n const {\n traceId,\n dsc,\n parentSpanId,\n sampled: parentSampled,\n } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n span = _startRootSpan(\n {\n traceId,\n parentSpanId,\n ...spanArguments,\n },\n scope,\n parentSampled,\n );\n\n if (dsc) {\n freezeDscOnSpan(span, dsc);\n }\n }\n\n logSpanStart(span);\n\n setCapturedScopesOnSpan(span, scope, isolationScope);\n\n return span;\n}\n\n/**\n * This converts StartSpanOptions to SentrySpanArguments.\n * For the most part (for now) we accept the same options,\n * but some of them need to be transformed.\n */\nfunction parseSentrySpanArguments(options) {\n const exp = options.experimental || {};\n const initialCtx = {\n isStandalone: exp.standalone,\n ...options,\n };\n\n if (options.startTime) {\n const ctx = { ...initialCtx };\n ctx.startTimestamp = spanTimeInputToSeconds(options.startTime);\n delete ctx.startTime;\n return ctx;\n }\n\n return initialCtx;\n}\n\nfunction getAcs() {\n const carrier = getMainCarrier();\n return getAsyncContextStrategy(carrier);\n}\n\nfunction _startRootSpan(spanArguments, scope, parentSampled) {\n const client = getClient();\n const options = client?.getOptions() || {};\n\n const { name = '', attributes } = spanArguments;\n const currentPropagationContext = scope.getPropagationContext();\n const [sampled, sampleRate, localSampleRateWasApplied] = scope.getScopeData().sdkProcessingMetadata[\n SUPPRESS_TRACING_KEY\n ]\n ? [false]\n : sampleSpan(\n options,\n {\n name,\n parentSampled,\n attributes,\n parentSampleRate: parseSampleRate(currentPropagationContext.dsc?.sample_rate),\n },\n currentPropagationContext.sampleRand,\n );\n\n const rootSpan = new SentrySpan({\n ...spanArguments,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom',\n [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]:\n sampleRate !== undefined && localSampleRateWasApplied ? sampleRate : undefined,\n ...spanArguments.attributes,\n },\n sampled,\n });\n\n if (!sampled && client) {\n DEBUG_BUILD && logger.log('[Tracing] Discarding root span because its trace was not chosen to be sampled.');\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n if (client) {\n client.emit('spanStart', rootSpan);\n }\n\n return rootSpan;\n}\n\n/**\n * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.\n * This inherits the sampling decision from the parent span.\n */\nfunction _startChildSpan(parentSpan, scope, spanArguments) {\n const { spanId, traceId } = parentSpan.spanContext();\n const sampled = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? false : spanIsSampled(parentSpan);\n\n const childSpan = sampled\n ? new SentrySpan({\n ...spanArguments,\n parentSpanId: spanId,\n traceId,\n sampled,\n })\n : new SentryNonRecordingSpan({ traceId });\n\n addChildSpanToSpan(parentSpan, childSpan);\n\n const client = getClient();\n if (client) {\n client.emit('spanStart', childSpan);\n // If it has an endTimestamp, it's already ended\n if (spanArguments.endTimestamp) {\n client.emit('spanEnd', childSpan);\n }\n }\n\n return childSpan;\n}\n\nfunction getParentSpan(scope) {\n const span = _getSpanForScope(scope) ;\n\n if (!span) {\n return undefined;\n }\n\n const client = getClient();\n const options = client ? client.getOptions() : {};\n if (options.parentSpanIsAlwaysRootSpan) {\n return getRootSpan(span) ;\n }\n\n return span;\n}\n\nfunction getActiveSpanWrapper(parentSpan) {\n return parentSpan !== undefined\n ? (callback) => {\n return withActiveSpan(parentSpan, callback);\n }\n : (callback) => callback();\n}\n\nexport { continueTrace, startInactiveSpan, startNewTrace, startSpan, startSpanManual, suppressTracing, withActiveSpan };\n//# sourceMappingURL=trace.js.map\n","import { getClient, getCurrentScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON } from '../semanticAttributes.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { timestampInSeconds } from '../utils-hoist/time.js';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled.js';\nimport { _setSpanForScope } from '../utils/spanOnScope.js';\nimport { getActiveSpan, spanTimeInputToSeconds, getSpanDescendants, spanToJSON, removeChildSpanFromSpan } from '../utils/spanUtils.js';\nimport { getDynamicSamplingContextFromSpan, freezeDscOnSpan } from './dynamicSamplingContext.js';\nimport { SentryNonRecordingSpan } from './sentryNonRecordingSpan.js';\nimport { SPAN_STATUS_ERROR } from './spanstatus.js';\nimport { startInactiveSpan } from './trace.js';\n\nconst TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n childSpanTimeout: 15000,\n};\n\nconst FINISH_REASON_HEARTBEAT_FAILED = 'heartbeatFailed';\nconst FINISH_REASON_IDLE_TIMEOUT = 'idleTimeout';\nconst FINISH_REASON_FINAL_TIMEOUT = 'finalTimeout';\nconst FINISH_REASON_EXTERNAL_FINISH = 'externalFinish';\n\n/**\n * An idle span is a span that automatically finishes. It does this by tracking child spans as activities.\n * An idle span is always the active span.\n */\nfunction startIdleSpan(startSpanOptions, options = {}) {\n // Activities store a list of active spans\n const activities = new Map();\n\n // We should not use heartbeat if we finished a span\n let _finished = false;\n\n // Timer that tracks idleTimeout\n let _idleTimeoutID;\n\n // The reason why the span was finished\n let _finishReason = FINISH_REASON_EXTERNAL_FINISH;\n\n let _autoFinishAllowed = !options.disableAutoFinish;\n\n const _cleanupHooks = [];\n\n const {\n idleTimeout = TRACING_DEFAULTS.idleTimeout,\n finalTimeout = TRACING_DEFAULTS.finalTimeout,\n childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout,\n beforeSpanEnd,\n } = options;\n\n const client = getClient();\n\n if (!client || !hasSpansEnabled()) {\n const span = new SentryNonRecordingSpan();\n\n const dsc = {\n sample_rate: '0',\n sampled: 'false',\n ...getDynamicSamplingContextFromSpan(span),\n } ;\n freezeDscOnSpan(span, dsc);\n\n return span;\n }\n\n const scope = getCurrentScope();\n const previousActiveSpan = getActiveSpan();\n const span = _startIdleSpan(startSpanOptions);\n\n // We patch span.end to ensure we can run some things before the span is ended\n // eslint-disable-next-line @typescript-eslint/unbound-method\n span.end = new Proxy(span.end, {\n apply(target, thisArg, args) {\n if (beforeSpanEnd) {\n beforeSpanEnd(span);\n }\n\n // If the span is non-recording, nothing more to do here...\n // This is the case if tracing is enabled but this specific span was not sampled\n if (thisArg instanceof SentryNonRecordingSpan) {\n return;\n }\n\n // Just ensuring that this keeps working, even if we ever have more arguments here\n const [definedEndTimestamp, ...rest] = args;\n const timestamp = definedEndTimestamp || timestampInSeconds();\n const spanEndTimestamp = spanTimeInputToSeconds(timestamp);\n\n // Ensure we end with the last span timestamp, if possible\n const spans = getSpanDescendants(span).filter(child => child !== span);\n\n // If we have no spans, we just end, nothing else to do here\n if (!spans.length) {\n onIdleSpanEnded(spanEndTimestamp);\n return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]);\n }\n\n const childEndTimestamps = spans\n .map(span => spanToJSON(span).timestamp)\n .filter(timestamp => !!timestamp) ;\n const latestSpanEndTimestamp = childEndTimestamps.length ? Math.max(...childEndTimestamps) : undefined;\n\n // In reality this should always exist here, but type-wise it may be undefined...\n const spanStartTimestamp = spanToJSON(span).start_timestamp;\n\n // The final endTimestamp should:\n // * Never be before the span start timestamp\n // * Be the latestSpanEndTimestamp, if there is one, and it is smaller than the passed span end timestamp\n // * Otherwise be the passed end timestamp\n // Final timestamp can never be after finalTimeout\n const endTimestamp = Math.min(\n spanStartTimestamp ? spanStartTimestamp + finalTimeout / 1000 : Infinity,\n Math.max(spanStartTimestamp || -Infinity, Math.min(spanEndTimestamp, latestSpanEndTimestamp || Infinity)),\n );\n\n onIdleSpanEnded(endTimestamp);\n return Reflect.apply(target, thisArg, [endTimestamp, ...rest]);\n },\n });\n\n /**\n * Cancels the existing idle timeout, if there is one.\n */\n function _cancelIdleTimeout() {\n if (_idleTimeoutID) {\n clearTimeout(_idleTimeoutID);\n _idleTimeoutID = undefined;\n }\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n function _restartIdleTimeout(endTimestamp) {\n _cancelIdleTimeout();\n _idleTimeoutID = setTimeout(() => {\n if (!_finished && activities.size === 0 && _autoFinishAllowed) {\n _finishReason = FINISH_REASON_IDLE_TIMEOUT;\n span.end(endTimestamp);\n }\n }, idleTimeout);\n }\n\n /**\n * Restarts child span timeout, if there is none running it will start one.\n */\n function _restartChildSpanTimeout(endTimestamp) {\n _idleTimeoutID = setTimeout(() => {\n if (!_finished && _autoFinishAllowed) {\n _finishReason = FINISH_REASON_HEARTBEAT_FAILED;\n span.end(endTimestamp);\n }\n }, childSpanTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n function _pushActivity(spanId) {\n _cancelIdleTimeout();\n activities.set(spanId, true);\n\n const endTimestamp = timestampInSeconds();\n // We need to add the timeout here to have the real endtimestamp of the idle span\n // Remember timestampInSeconds is in seconds, timeout is in ms\n _restartChildSpanTimeout(endTimestamp + childSpanTimeout / 1000);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n function _popActivity(spanId) {\n if (activities.has(spanId)) {\n activities.delete(spanId);\n }\n\n if (activities.size === 0) {\n const endTimestamp = timestampInSeconds();\n // We need to add the timeout here to have the real endtimestamp of the idle span\n // Remember timestampInSeconds is in seconds, timeout is in ms\n _restartIdleTimeout(endTimestamp + idleTimeout / 1000);\n }\n }\n\n function onIdleSpanEnded(endTimestamp) {\n _finished = true;\n activities.clear();\n\n _cleanupHooks.forEach(cleanup => cleanup());\n\n _setSpanForScope(scope, previousActiveSpan);\n\n const spanJSON = spanToJSON(span);\n\n const { start_timestamp: startTimestamp } = spanJSON;\n // This should never happen, but to make TS happy...\n if (!startTimestamp) {\n return;\n }\n\n const attributes = spanJSON.data;\n if (!attributes[SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason);\n }\n\n logger.log(`[Tracing] Idle span \"${spanJSON.op}\" finished`);\n\n const childSpans = getSpanDescendants(span).filter(child => child !== span);\n\n let discardedSpans = 0;\n childSpans.forEach(childSpan => {\n // We cancel all pending spans with status \"cancelled\" to indicate the idle span was finished early\n if (childSpan.isRecording()) {\n childSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n childSpan.end(endTimestamp);\n DEBUG_BUILD &&\n logger.log('[Tracing] Cancelling span since span ended early', JSON.stringify(childSpan, undefined, 2));\n }\n\n const childSpanJSON = spanToJSON(childSpan);\n const { timestamp: childEndTimestamp = 0, start_timestamp: childStartTimestamp = 0 } = childSpanJSON;\n\n const spanStartedBeforeIdleSpanEnd = childStartTimestamp <= endTimestamp;\n\n // Add a delta with idle timeout so that we prevent false positives\n const timeoutWithMarginOfError = (finalTimeout + idleTimeout) / 1000;\n const spanEndedBeforeFinalTimeout = childEndTimestamp - childStartTimestamp <= timeoutWithMarginOfError;\n\n if (DEBUG_BUILD) {\n const stringifiedSpan = JSON.stringify(childSpan, undefined, 2);\n if (!spanStartedBeforeIdleSpanEnd) {\n logger.log('[Tracing] Discarding span since it happened after idle span was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n logger.log('[Tracing] Discarding span since it finished after idle span final timeout', stringifiedSpan);\n }\n }\n\n if (!spanEndedBeforeFinalTimeout || !spanStartedBeforeIdleSpanEnd) {\n removeChildSpanFromSpan(span, childSpan);\n discardedSpans++;\n }\n });\n\n if (discardedSpans > 0) {\n span.setAttribute('sentry.idle_span_discarded_spans', discardedSpans);\n }\n }\n\n _cleanupHooks.push(\n client.on('spanStart', startedSpan => {\n // If we already finished the idle span,\n // or if this is the idle span itself being started,\n // or if the started span has already been closed,\n // we don't care about it for activity\n if (_finished || startedSpan === span || !!spanToJSON(startedSpan).timestamp) {\n return;\n }\n\n const allSpans = getSpanDescendants(span);\n\n // If the span that was just started is a child of the idle span, we should track it\n if (allSpans.includes(startedSpan)) {\n _pushActivity(startedSpan.spanContext().spanId);\n }\n }),\n );\n\n _cleanupHooks.push(\n client.on('spanEnd', endedSpan => {\n if (_finished) {\n return;\n }\n\n _popActivity(endedSpan.spanContext().spanId);\n }),\n );\n\n _cleanupHooks.push(\n client.on('idleSpanEnableAutoFinish', spanToAllowAutoFinish => {\n if (spanToAllowAutoFinish === span) {\n _autoFinishAllowed = true;\n _restartIdleTimeout();\n\n if (activities.size) {\n _restartChildSpanTimeout();\n }\n }\n }),\n );\n\n // We only start the initial idle timeout if we are not delaying the auto finish\n if (!options.disableAutoFinish) {\n _restartIdleTimeout();\n }\n\n setTimeout(() => {\n if (!_finished) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' });\n _finishReason = FINISH_REASON_FINAL_TIMEOUT;\n span.end();\n }\n }, finalTimeout);\n\n return span;\n}\n\nfunction _startIdleSpan(options) {\n const span = startInactiveSpan(options);\n\n _setSpanForScope(getCurrentScope(), span);\n\n DEBUG_BUILD && logger.log('[Tracing] Started span is an idle span');\n\n return span;\n}\n\nexport { TRACING_DEFAULTS, startIdleSpan };\n//# sourceMappingURL=idleSpan.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { isThenable } from './utils-hoist/is.js';\nimport { logger } from './utils-hoist/logger.js';\nimport { SyncPromise } from './utils-hoist/syncpromise.js';\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nfunction notifyEventProcessors(\n processors,\n event,\n hint,\n index = 0,\n) {\n return new SyncPromise((resolve, reject) => {\n const processor = processors[index];\n if (event === null || typeof processor !== 'function') {\n resolve(event);\n } else {\n const result = processor({ ...event }, hint) ;\n\n DEBUG_BUILD && processor.id && result === null && logger.log(`Event processor \"${processor.id}\" dropped event`);\n\n if (isThenable(result)) {\n void result\n .then(final => notifyEventProcessors(processors, final, hint, index + 1).then(resolve))\n .then(null, reject);\n } else {\n void notifyEventProcessors(processors, result, hint, index + 1)\n .then(resolve)\n .then(null, reject);\n }\n }\n });\n}\n\nexport { notifyEventProcessors };\n//# sourceMappingURL=eventProcessors.js.map\n","import { GLOBAL_OBJ } from './worldwide.js';\n\nlet parsedStackResults;\nlet lastKeysCount;\nlet cachedFilenameDebugIds;\n\n/**\n * Returns a map of filenames to debug identifiers.\n */\nfunction getFilenameToDebugIdMap(stackParser) {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n if (!debugIdMap) {\n return {};\n }\n\n const debugIdKeys = Object.keys(debugIdMap);\n\n // If the count of registered globals hasn't changed since the last call, we\n // can just return the cached result.\n if (cachedFilenameDebugIds && debugIdKeys.length === lastKeysCount) {\n return cachedFilenameDebugIds;\n }\n\n lastKeysCount = debugIdKeys.length;\n\n // Build a map of filename -> debug_id.\n cachedFilenameDebugIds = debugIdKeys.reduce((acc, stackKey) => {\n if (!parsedStackResults) {\n parsedStackResults = {};\n }\n\n const result = parsedStackResults[stackKey];\n\n if (result) {\n acc[result[0]] = result[1];\n } else {\n const parsedStack = stackParser(stackKey);\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n const filename = stackFrame?.filename;\n const debugId = debugIdMap[stackKey];\n\n if (filename && debugId) {\n acc[filename] = debugId;\n parsedStackResults[stackKey] = [filename, debugId];\n break;\n }\n }\n }\n\n return acc;\n }, {});\n\n return cachedFilenameDebugIds;\n}\n\n/**\n * Returns a list of debug images for the given resources.\n */\nfunction getDebugImagesForResources(\n stackParser,\n resource_paths,\n) {\n const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n\n if (!filenameDebugIdMap) {\n return [];\n }\n\n const images = [];\n for (const path of resource_paths) {\n if (path && filenameDebugIdMap[path]) {\n images.push({\n type: 'sourcemap',\n code_file: path,\n debug_id: filenameDebugIdMap[path] ,\n });\n }\n }\n\n return images;\n}\n\nexport { getDebugImagesForResources, getFilenameToDebugIdMap };\n//# sourceMappingURL=debug-ids.js.map\n","import { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext.js';\nimport { dropUndefinedKeys } from '../utils-hoist/object.js';\nimport { merge } from './merge.js';\nimport { spanToTraceContext, getRootSpan, spanToJSON } from './spanUtils.js';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nfunction applyScopeDataToEvent(event, data) {\n const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n // Apply general data\n applyDataToEvent(event, data);\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (span) {\n applySpanToEvent(event, span);\n }\n\n applyFingerprintToEvent(event, fingerprint);\n applyBreadcrumbsToEvent(event, breadcrumbs);\n applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nfunction mergeScopeData(data, mergeData) {\n const {\n extra,\n tags,\n user,\n contexts,\n level,\n sdkProcessingMetadata,\n breadcrumbs,\n fingerprint,\n eventProcessors,\n attachments,\n propagationContext,\n transactionName,\n span,\n } = mergeData;\n\n mergeAndOverwriteScopeData(data, 'extra', extra);\n mergeAndOverwriteScopeData(data, 'tags', tags);\n mergeAndOverwriteScopeData(data, 'user', user);\n mergeAndOverwriteScopeData(data, 'contexts', contexts);\n\n data.sdkProcessingMetadata = merge(data.sdkProcessingMetadata, sdkProcessingMetadata, 2);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\n data.transactionName = transactionName;\n }\n\n if (span) {\n data.span = span;\n }\n\n if (breadcrumbs.length) {\n data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n }\n\n if (fingerprint.length) {\n data.fingerprint = [...data.fingerprint, ...fingerprint];\n }\n\n if (eventProcessors.length) {\n data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n }\n\n if (attachments.length) {\n data.attachments = [...data.attachments, ...attachments];\n }\n\n data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nfunction mergeAndOverwriteScopeData\n\n(data, prop, mergeVal) {\n data[prop] = merge(data[prop], mergeVal, 1);\n}\n\nfunction applyDataToEvent(event, data) {\n const { extra, tags, user, contexts, level, transactionName } = data;\n\n const cleanedExtra = dropUndefinedKeys(extra);\n if (Object.keys(cleanedExtra).length) {\n event.extra = { ...cleanedExtra, ...event.extra };\n }\n\n const cleanedTags = dropUndefinedKeys(tags);\n if (Object.keys(cleanedTags).length) {\n event.tags = { ...cleanedTags, ...event.tags };\n }\n\n const cleanedUser = dropUndefinedKeys(user);\n if (Object.keys(cleanedUser).length) {\n event.user = { ...cleanedUser, ...event.user };\n }\n\n const cleanedContexts = dropUndefinedKeys(contexts);\n if (Object.keys(cleanedContexts).length) {\n event.contexts = { ...cleanedContexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n // transaction events get their `transaction` from the root span name\n if (transactionName && event.type !== 'transaction') {\n event.transaction = transactionName;\n }\n}\n\nfunction applyBreadcrumbsToEvent(event, breadcrumbs) {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event, sdkProcessingMetadata) {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event, span) {\n event.contexts = {\n trace: spanToTraceContext(span),\n ...event.contexts,\n };\n\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n\n const rootSpan = getRootSpan(span);\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName && !event.transaction && event.type === 'transaction') {\n event.transaction = transactionName;\n }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event, fingerprint) {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint\n ? Array.isArray(event.fingerprint)\n ? event.fingerprint\n : [event.fingerprint]\n : [];\n\n // If we have something on the scope, then merge it with event\n if (fingerprint) {\n event.fingerprint = event.fingerprint.concat(fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (!event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n\nexport { applyScopeDataToEvent, mergeAndOverwriteScopeData, mergeScopeData };\n//# sourceMappingURL=applyScopeDataToEvent.js.map\n","import { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { getGlobalScope } from '../currentScopes.js';\nimport { notifyEventProcessors } from '../eventProcessors.js';\nimport { Scope } from '../scope.js';\nimport { getFilenameToDebugIdMap } from '../utils-hoist/debug-ids.js';\nimport { uuid4, addExceptionMechanism } from '../utils-hoist/misc.js';\nimport { normalize } from '../utils-hoist/normalize.js';\nimport { truncate } from '../utils-hoist/string.js';\nimport { dateTimestampInSeconds } from '../utils-hoist/time.js';\nimport { mergeScopeData, applyScopeDataToEvent } from './applyScopeDataToEvent.js';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nfunction prepareEvent(\n options,\n event,\n hint,\n scope,\n client,\n isolationScope,\n) {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = options;\n const prepared = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n if (client) {\n client.emit('applyFrameMetadata', event);\n }\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n const finalScope = getFinalScope(scope, hint.captureContext);\n\n if (hint.mechanism) {\n addExceptionMechanism(prepared, hint.mechanism);\n }\n\n const clientEventProcessors = client ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Scope.addEventProcessor} gets the finished prepared event.\n // Merge scope data together\n const data = getGlobalScope().getScopeData();\n\n if (isolationScope) {\n const isolationData = isolationScope.getScopeData();\n mergeScopeData(data, isolationData);\n }\n\n if (finalScope) {\n const finalScopeData = finalScope.getScopeData();\n mergeScopeData(data, finalScopeData);\n }\n\n const attachments = [...(hint.attachments || []), ...data.attachments];\n if (attachments.length) {\n hint.attachments = attachments;\n }\n\n applyScopeDataToEvent(prepared, data);\n\n const eventProcessors = [\n ...clientEventProcessors,\n // Run scope event processors _after_ all other processors\n ...data.eventProcessors,\n ];\n\n const result = notifyEventProcessors(eventProcessors, prepared, hint);\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n *\n * Only exported for tests.\n *\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event, options) {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n // empty strings do not make sense for environment, release, and dist\n // so we handle them the same as if they were not provided\n event.environment = event.environment || environment || DEFAULT_ENVIRONMENT;\n\n if (!event.release && release) {\n event.release = release;\n }\n\n if (!event.dist && dist) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception?.values?.[0];\n if (exception?.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request?.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nfunction applyDebugIds(event, stackParser) {\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n\n event.exception?.values?.forEach(exception => {\n exception.stacktrace?.frames?.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nfunction applyDebugMeta(event) {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap = {};\n event.exception?.values?.forEach(exception => {\n exception.stacktrace?.frames?.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id,\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event, integrationNames) {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event, depth, maxBreadth) {\n if (!event) {\n return null;\n }\n\n const normalized = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts?.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n return {\n ...span,\n ...(span.data && {\n data: normalize(span.data, depth, maxBreadth),\n }),\n };\n });\n }\n\n // event.contexts.flags (FeatureFlagContext) stores context for our feature\n // flag integrations. It has a greater nesting depth than our other typed\n // Contexts, so we re-normalize with a fixed depth of 3 here. We do not want\n // to skip this in case of conflicting, user-provided context.\n if (event.contexts?.flags && normalized.contexts) {\n normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth);\n }\n\n return normalized;\n}\n\nfunction getFinalScope(scope, captureContext) {\n if (!captureContext) {\n return scope;\n }\n\n const finalScope = scope ? scope.clone() : new Scope();\n finalScope.update(captureContext);\n return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nfunction parseEventHintOrCaptureContext(\n hint,\n) {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(hint) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\nconst captureContextKeys = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'propagationContext',\n] ;\n\nfunction hintIsScopeContext(hint) {\n return Object.keys(hint).some(key => captureContextKeys.includes(key ));\n}\n\nexport { applyClientOptions, applyDebugIds, applyDebugMeta, parseEventHintOrCaptureContext, prepareEvent };\n//# sourceMappingURL=prepareEvent.js.map\n","import { getCurrentScope, getIsolationScope, getClient, withIsolationScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { makeSession, updateSession, closeSession } from './session.js';\nimport { isThenable } from './utils-hoist/is.js';\nimport { logger } from './utils-hoist/logger.js';\nimport { uuid4 } from './utils-hoist/misc.js';\nimport { timestampInSeconds } from './utils-hoist/time.js';\nimport { GLOBAL_OBJ } from './utils-hoist/worldwide.js';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent.js';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nfunction captureException(exception, hint) {\n return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nfunction captureMessage(message, captureContext) {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const context = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return getCurrentScope().captureMessage(message, level, context);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nfunction captureEvent(event, hint) {\n return getCurrentScope().captureEvent(event, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\nfunction setContext(name, context) {\n getIsolationScope().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nfunction setExtras(extras) {\n getIsolationScope().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nfunction setExtra(key, extra) {\n getIsolationScope().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nfunction setTags(tags) {\n getIsolationScope().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nfunction setTag(key, value) {\n getIsolationScope().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nfunction setUser(user) {\n getIsolationScope().setUser(user);\n}\n\n/**\n * The last error event id of the isolation scope.\n *\n * Warning: This function really returns the last recorded error event id on the current\n * isolation scope. If you call this function after handling a certain error and another error\n * is captured in between, the last one is returned instead of the one you might expect.\n * Also, ids of events that were never sent to Sentry (for example because\n * they were dropped in `beforeSend`) could be returned.\n *\n * @returns The last event id of the isolation scope.\n */\nfunction lastEventId() {\n return getIsolationScope().lastEventId();\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nfunction captureCheckIn(checkIn, upsertMonitorConfig) {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && logger.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nfunction withMonitor(\n monitorSlug,\n callback,\n upsertMonitorConfig,\n) {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status) {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n\n return withIsolationScope(() => {\n let maybePromiseResult;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n Promise.resolve(maybePromiseResult).then(\n () => {\n finishCheckIn('ok');\n },\n e => {\n finishCheckIn('error');\n throw e;\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\n });\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nasync function flush(timeout) {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nasync function close(timeout) {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nfunction isInitialized() {\n return !!getClient();\n}\n\n/** If the SDK is initialized & enabled. */\nfunction isEnabled() {\n const client = getClient();\n return client?.getOptions().enabled !== false && !!client?.getTransport();\n}\n\n/**\n * Add an event processor.\n * This will be added to the current isolation scope, ensuring any event that is processed in the current execution\n * context will have the processor applied.\n */\nfunction addEventProcessor(callback) {\n getIsolationScope().addEventProcessor(callback);\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nfunction startSession(context) {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession?.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nfunction endSession() {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate() {\n const isolationScope = getIsolationScope();\n const client = getClient();\n const session = isolationScope.getSession();\n if (session && client) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nfunction captureSession(end = false) {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n\nexport { addEventProcessor, captureCheckIn, captureEvent, captureException, captureMessage, captureSession, close, endSession, flush, isEnabled, isInitialized, lastEventId, setContext, setExtra, setExtras, setTag, setTags, setUser, startSession, withMonitor };\n//# sourceMappingURL=exports.js.map\n","import { makeDsn, dsnToString } from './utils-hoist/dsn.js';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn) {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn) {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn, sdkInfo) {\n const params = {\n sentry_version: SENTRY_API_VERSION,\n };\n\n if (dsn.publicKey) {\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n params.sentry_key = dsn.publicKey;\n }\n\n if (sdkInfo) {\n params.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`;\n }\n\n return new URLSearchParams(params).toString();\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nfunction getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) {\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nfunction getReportDialogEndpoint(dsnLike, dialogOptions) {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'onClose') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n\nexport { getEnvelopeEndpointWithUrlEncodedAuth, getReportDialogEndpoint };\n//# sourceMappingURL=api.js.map\n","import { getClient } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { logger } from './utils-hoist/logger.js';\n\nconst installedIntegrations = [];\n\n/** Map of integrations assigned to a client */\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preserve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations) {\n const integrationsByName = {};\n\n integrations.forEach((currentInstance) => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.values(integrationsByName);\n}\n\n/** Gets integrations to install */\nfunction getIntegrationsToSetup(options) {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach((integration) => {\n integration.isDefaultInstance = true;\n });\n\n let integrations;\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n const resolvedUserIntegrations = userIntegrations(defaultIntegrations);\n integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations];\n } else {\n integrations = defaultIntegrations;\n }\n\n return filterDuplicates(integrations);\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nfunction setupIntegrations(client, integrations) {\n const integrationIndex = {};\n\n integrations.forEach((integration) => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(client, integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nfunction afterSetupIntegrations(client, integrations) {\n for (const integration of integrations) {\n // guard against empty provided integrations\n if (integration?.afterAllSetup) {\n integration.afterAllSetup(client);\n }\n }\n}\n\n/** Setup a single integration. */\nfunction setupIntegration(client, integration, integrationIndex) {\n if (integrationIndex[integration.name]) {\n DEBUG_BUILD && logger.log(`Integration skipped because it was already installed: ${integration.name}`);\n return;\n }\n integrationIndex[integration.name] = integration;\n\n // `setupOnce` is only called the first time\n if (installedIntegrations.indexOf(integration.name) === -1 && typeof integration.setupOnce === 'function') {\n integration.setupOnce();\n installedIntegrations.push(integration.name);\n }\n\n // `setup` is run for each client\n if (integration.setup && typeof integration.setup === 'function') {\n integration.setup(client);\n }\n\n if (typeof integration.preprocessEvent === 'function') {\n const callback = integration.preprocessEvent.bind(integration) ;\n client.on('preprocessEvent', (event, hint) => callback(event, hint, client));\n }\n\n if (typeof integration.processEvent === 'function') {\n const callback = integration.processEvent.bind(integration) ;\n\n const processor = Object.assign((event, hint) => callback(event, hint, client), {\n id: integration.name,\n });\n\n client.addEventProcessor(processor);\n }\n\n DEBUG_BUILD && logger.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current scope's client. */\nfunction addIntegration(integration) {\n const client = getClient();\n\n if (!client) {\n DEBUG_BUILD && logger.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n/**\n * Define an integration function that can be used to create an integration instance.\n * Note that this by design hides the implementation details of the integration, as they are considered internal.\n */\nfunction defineIntegration(fn) {\n return fn;\n}\n\nexport { addIntegration, afterSetupIntegrations, defineIntegration, getIntegrationsToSetup, installedIntegrations, setupIntegration, setupIntegrations };\n//# sourceMappingURL=integration.js.map\n","import { createEnvelope } from './envelope.js';\nimport { dateTimestampInSeconds } from './time.js';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nfunction createClientReportEnvelope(\n discarded_events,\n dsn,\n timestamp,\n) {\n const clientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n\nexport { createClientReportEnvelope };\n//# sourceMappingURL=clientreport.js.map\n","/** An error emitted by Sentry SDKs and related utilities. */\nclass SentryError extends Error {\n\n constructor(\n message,\n logLevel = 'warn',\n ) {\n super(message);this.message = message;\n this.logLevel = logLevel;\n }\n}\n\nexport { SentryError };\n//# sourceMappingURL=error.js.map\n","/**\n * Get a list of possible event messages from a Sentry event.\n */\nfunction getPossibleEventMessages(event) {\n const possibleMessages = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n try {\n // @ts-expect-error Try catching to save bundle size\n const lastException = event.exception.values[event.exception.values.length - 1];\n if (lastException?.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n } catch (e) {\n // ignore errors here\n }\n\n return possibleMessages;\n}\n\nexport { getPossibleEventMessages };\n//# sourceMappingURL=eventUtils.js.map\n","import { SEMANTIC_ATTRIBUTE_PROFILE_ID, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME } from '../semanticAttributes.js';\nimport '../utils-hoist/debug-build.js';\nimport '../utils-hoist/logger.js';\nimport { dropUndefinedKeys } from '../utils-hoist/object.js';\nimport '../utils-hoist/time.js';\nimport '../utils-hoist/syncpromise.js';\n\n/**\n * Converts a transaction event to a span JSON object.\n */\nfunction convertTransactionEventToSpanJson(event) {\n const { trace_id, parent_span_id, span_id, status, origin, data, op } = event.contexts?.trace ?? {};\n\n return dropUndefinedKeys({\n data: data ?? {},\n description: event.transaction,\n op,\n parent_span_id,\n span_id: span_id ?? '',\n start_timestamp: event.start_timestamp ?? 0,\n status,\n timestamp: event.timestamp,\n trace_id: trace_id ?? '',\n origin,\n profile_id: data?.[SEMANTIC_ATTRIBUTE_PROFILE_ID] ,\n exclusive_time: data?.[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME] ,\n measurements: event.measurements,\n is_segment: true,\n });\n}\n\n/**\n * Converts a span JSON object to a transaction event.\n */\nfunction convertSpanJsonToTransactionEvent(span) {\n const event = {\n type: 'transaction',\n timestamp: span.timestamp,\n start_timestamp: span.start_timestamp,\n transaction: span.description,\n contexts: {\n trace: {\n trace_id: span.trace_id,\n span_id: span.span_id,\n parent_span_id: span.parent_span_id,\n op: span.op,\n status: span.status,\n origin: span.origin,\n data: {\n ...span.data,\n ...(span.profile_id && { [SEMANTIC_ATTRIBUTE_PROFILE_ID]: span.profile_id }),\n ...(span.exclusive_time && { [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: span.exclusive_time }),\n },\n },\n },\n measurements: span.measurements,\n };\n\n return dropUndefinedKeys(event);\n}\n\nexport { convertSpanJsonToTransactionEvent, convertTransactionEventToSpanJson };\n//# sourceMappingURL=transactionEvent.js.map\n","import { getEnvelopeEndpointWithUrlEncodedAuth } from './api.js';\nimport { DEFAULT_ENVIRONMENT } from './constants.js';\nimport { getTraceContextFromScope, getCurrentScope, getIsolationScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope.js';\nimport { setupIntegration, afterSetupIntegrations, setupIntegrations } from './integration.js';\nimport { updateSession } from './session.js';\nimport { getDynamicSamplingContextFromScope } from './tracing/dynamicSamplingContext.js';\nimport { createClientReportEnvelope } from './utils-hoist/clientreport.js';\nimport { makeDsn, dsnToString } from './utils-hoist/dsn.js';\nimport { addItemToEnvelope, createAttachmentEnvelopeItem } from './utils-hoist/envelope.js';\nimport { SentryError } from './utils-hoist/error.js';\nimport { isPrimitive, isThenable, isPlainObject, isParameterizedString } from './utils-hoist/is.js';\nimport { logger } from './utils-hoist/logger.js';\nimport { uuid4, checkOrSetAlreadyCaught } from './utils-hoist/misc.js';\nimport { resolvedSyncPromise, SyncPromise, rejectedSyncPromise } from './utils-hoist/syncpromise.js';\nimport { getPossibleEventMessages } from './utils/eventUtils.js';\nimport { merge } from './utils/merge.js';\nimport { parseSampleRate } from './utils/parseSampleRate.js';\nimport { prepareEvent } from './utils/prepareEvent.js';\nimport { showSpanDropWarning } from './utils/spanUtils.js';\nimport { convertTransactionEventToSpanJson, convertSpanJsonToTransactionEvent } from './utils/transactionEvent.js';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\nconst MISSING_RELEASE_FOR_SESSION_ERROR = 'Discarded session because of missing or non-string release';\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link Client._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends Client {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nclass Client {\n /** Options passed to the SDK. */\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n\n /** Array of set up integrations. */\n\n /** Number of calls being processed */\n\n /** Holds flushable */\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n constructor(options) {\n this._options = options;\n this._integrations = {};\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && logger.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(\n this._dsn,\n options.tunnel,\n options._metadata ? options._metadata.sdk : undefined,\n );\n this._transport = options.transport({\n tunnel: this._options.tunnel,\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * Captures an exception event and sends it to Sentry.\n *\n * Unlike `captureException` exported from every SDK, this method requires that you pass it the current scope.\n */\n captureException(exception, hint, scope) {\n const eventId = uuid4();\n\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return eventId;\n }\n\n const hintWithEventId = {\n event_id: eventId,\n ...hint,\n };\n\n this._process(\n this.eventFromException(exception, hintWithEventId).then(event =>\n this._captureEvent(event, hintWithEventId, scope),\n ),\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * Captures a message event and sends it to Sentry.\n *\n * Unlike `captureMessage` exported from every SDK, this method requires that you pass it the current scope.\n */\n captureMessage(\n message,\n level,\n hint,\n currentScope,\n ) {\n const hintWithEventId = {\n event_id: uuid4(),\n ...hint,\n };\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(eventMessage, level, hintWithEventId)\n : this.eventFromException(message, hintWithEventId);\n\n this._process(promisedEvent.then(event => this._captureEvent(event, hintWithEventId, currentScope)));\n\n return hintWithEventId.event_id;\n }\n\n /**\n * Captures a manually created event and sends it to Sentry.\n *\n * Unlike `captureEvent` exported from every SDK, this method requires that you pass it the current scope.\n */\n captureEvent(event, hint, currentScope) {\n const eventId = uuid4();\n\n // ensure we haven't captured this very object before\n if (hint?.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n DEBUG_BUILD && logger.log(ALREADY_SEEN_ERROR);\n return eventId;\n }\n\n const hintWithEventId = {\n event_id: eventId,\n ...hint,\n };\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope;\n const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope;\n\n this._process(\n this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope, capturedSpanIsolationScope),\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * Captures a session.\n */\n captureSession(session) {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n\n /**\n * Create a cron monitor check in and send it to Sentry. This method is not available on all clients.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n * @param scope An optional scope containing event metadata.\n * @returns A string representing the id of the check in.\n */\n\n /**\n * Get the current Dsn.\n */\n getDsn() {\n return this._dsn;\n }\n\n /**\n * Get the current options.\n */\n getOptions() {\n return this._options;\n }\n\n /**\n * Get the SDK metadata.\n * @see SdkMetadata\n */\n getSdkMetadata() {\n return this._options._metadata;\n }\n\n /**\n * Returns the transport that is used by the client.\n * Please note that the transport gets lazy initialized so it will only be there once the first event has been sent.\n */\n getTransport() {\n return this._transport;\n }\n\n /**\n * Wait for all events to be sent or the timeout to expire, whichever comes first.\n *\n * @param timeout Maximum time in ms the client should wait for events to be flushed. Omitting this parameter will\n * cause the client to wait until all events are sent before resolving the promise.\n * @returns A promise that will resolve with `true` if all events are sent before the timeout, or `false` if there are\n * still events in the queue when the timeout is reached.\n */\n flush(timeout) {\n const transport = this._transport;\n if (transport) {\n this.emit('flush');\n return this._isClientDoneProcessing(timeout).then(clientFinished => {\n return transport.flush(timeout).then(transportFlushed => clientFinished && transportFlushed);\n });\n } else {\n return resolvedSyncPromise(true);\n }\n }\n\n /**\n * Flush the event queue and set the client to `enabled = false`. See {@link Client.flush}.\n *\n * @param {number} timeout Maximum time in ms the client should wait before shutting down. Omitting this parameter will cause\n * the client to wait until all events are sent before disabling itself.\n * @returns {Promise} A promise which resolves to `true` if the flush completes successfully before the timeout, or `false` if\n * it doesn't.\n */\n close(timeout) {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n this.emit('close');\n return result;\n });\n }\n\n /**\n * Get all installed event processors.\n */\n getEventProcessors() {\n return this._eventProcessors;\n }\n\n /**\n * Adds an event processor that applies to any event processed by this client.\n */\n addEventProcessor(eventProcessor) {\n this._eventProcessors.push(eventProcessor);\n }\n\n /**\n * Initialize this client.\n * Call this after the client was set on a scope.\n */\n init() {\n if (\n this._isEnabled() ||\n // Force integrations to be setup even if no DSN was set when we have\n // Spotlight enabled. This is particularly important for browser as we\n // don't support the `spotlight` option there and rely on the users\n // adding the `spotlightBrowserIntegration()` to their integrations which\n // wouldn't get initialized with the check below when there's no DSN set.\n this._options.integrations.some(({ name }) => name.startsWith('Spotlight'))\n ) {\n this._setupIntegrations();\n }\n }\n\n /**\n * Gets an installed integration by its name.\n *\n * @returns {Integration|undefined} The installed integration or `undefined` if no integration with that `name` was installed.\n */\n getIntegrationByName(integrationName) {\n return this._integrations[integrationName] ;\n }\n\n /**\n * Add an integration to the client.\n * This can be used to e.g. lazy load integrations.\n * In most cases, this should not be necessary,\n * and you're better off just passing the integrations via `integrations: []` at initialization time.\n * However, if you find the need to conditionally load & add an integration, you can use `addIntegration` to do so.\n */\n addIntegration(integration) {\n const isAlreadyInstalled = this._integrations[integration.name];\n\n // This hook takes care of only installing if not already installed\n setupIntegration(this, integration, this._integrations);\n // Here we need to check manually to make sure to not run this multiple times\n if (!isAlreadyInstalled) {\n afterSetupIntegrations(this, [integration]);\n }\n }\n\n /**\n * Send a fully prepared event to Sentry.\n */\n sendEvent(event, hint = {}) {\n this.emit('beforeSendEvent', event, hint);\n\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment));\n }\n\n const promise = this.sendEnvelope(env);\n if (promise) {\n promise.then(sendResponse => this.emit('afterSendEvent', event, sendResponse), null);\n }\n }\n\n /**\n * Send a session or session aggregrates to Sentry.\n */\n sendSession(session) {\n // Backfill release and environment on session\n const { release: clientReleaseOption, environment: clientEnvironmentOption = DEFAULT_ENVIRONMENT } = this._options;\n if ('aggregates' in session) {\n const sessionAttrs = session.attrs || {};\n if (!sessionAttrs.release && !clientReleaseOption) {\n DEBUG_BUILD && logger.warn(MISSING_RELEASE_FOR_SESSION_ERROR);\n return;\n }\n sessionAttrs.release = sessionAttrs.release || clientReleaseOption;\n sessionAttrs.environment = sessionAttrs.environment || clientEnvironmentOption;\n session.attrs = sessionAttrs;\n } else {\n if (!session.release && !clientReleaseOption) {\n DEBUG_BUILD && logger.warn(MISSING_RELEASE_FOR_SESSION_ERROR);\n return;\n }\n session.release = session.release || clientReleaseOption;\n session.environment = session.environment || clientEnvironmentOption;\n }\n\n this.emit('beforeSendSession', session);\n\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(env);\n }\n\n /**\n * Record on the client that an event got dropped (ie, an event that will not be sent to Sentry).\n */\n recordDroppedEvent(reason, category, count = 1) {\n if (this._options.sendClientReports) {\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n DEBUG_BUILD && logger.log(`Recording outcome: \"${key}\"${count > 1 ? ` (${count} times)` : ''}`);\n this._outcomes[key] = (this._outcomes[key] || 0) + count;\n }\n }\n\n /* eslint-disable @typescript-eslint/unified-signatures */\n /**\n * Register a callback for whenever a span is started.\n * Receives the span as argument.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n\n /**\n * Register a hook oin this client.\n */\n on(hook, callback) {\n const hooks = (this._hooks[hook] = this._hooks[hook] || []);\n\n // @ts-expect-error We assume the types are correct\n hooks.push(callback);\n\n // This function returns a callback execution handler that, when invoked,\n // deregisters a callback. This is crucial for managing instances where callbacks\n // need to be unregistered to prevent self-referencing in callback closures,\n // ensuring proper garbage collection.\n return () => {\n // @ts-expect-error We assume the types are correct\n const cbIndex = hooks.indexOf(callback);\n if (cbIndex > -1) {\n hooks.splice(cbIndex, 1);\n }\n };\n }\n\n /** Fire a hook whenever a span starts. */\n\n /**\n * Emit a hook that was previously registered via `on()`.\n */\n emit(hook, ...rest) {\n const callbacks = this._hooks[hook];\n if (callbacks) {\n callbacks.forEach(callback => callback(...rest));\n }\n }\n\n /**\n * Send an envelope to Sentry.\n */\n sendEnvelope(envelope) {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n return this._transport.send(envelope).then(null, reason => {\n DEBUG_BUILD && logger.error('Error while sending envelope:', reason);\n return reason;\n });\n }\n\n DEBUG_BUILD && logger.error('Transport disabled');\n\n return resolvedSyncPromise({});\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Setup integrations for this client. */\n _setupIntegrations() {\n const { integrations } = this._options;\n this._integrations = setupIntegrations(this, integrations);\n afterSetupIntegrations(this, integrations);\n }\n\n /** Updates existing session based on the provided event */\n _updateSessionFromEvent(session, event) {\n let crashed = event.level === 'fatal';\n let errored = false;\n const exceptions = event.exception?.values;\n\n if (exceptions) {\n errored = true;\n\n for (const ex of exceptions) {\n const mechanism = ex.mechanism;\n if (mechanism?.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n _isClientDoneProcessing(timeout) {\n return new SyncPromise(resolve => {\n let ticked = 0;\n const tick = 1;\n\n const interval = setInterval(() => {\n if (this._numProcessing == 0) {\n clearInterval(interval);\n resolve(true);\n } else {\n ticked += tick;\n if (timeout && ticked >= timeout) {\n clearInterval(interval);\n resolve(false);\n }\n }\n }, tick);\n });\n }\n\n /** Determines whether this SDK is enabled and a transport is present. */\n _isEnabled() {\n return this.getOptions().enabled !== false && this._transport !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param currentScope A scope containing event metadata.\n * @returns A new event with more information.\n */\n _prepareEvent(\n event,\n hint,\n currentScope,\n isolationScope,\n ) {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations?.length) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n if (!event.type) {\n isolationScope.setLastEventId(event.event_id || hint.event_id);\n }\n\n return prepareEvent(options, event, hint, currentScope, this, isolationScope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n this.emit('postprocessEvent', evt, hint);\n\n evt.contexts = {\n trace: getTraceContextFromScope(currentScope),\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = getDynamicSamplingContextFromScope(this, currentScope);\n\n evt.sdkProcessingMetadata = {\n dynamicSamplingContext,\n ...evt.sdkProcessingMetadata,\n };\n\n return evt;\n });\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n _captureEvent(\n event,\n hint = {},\n currentScope = getCurrentScope(),\n isolationScope = getIsolationScope(),\n ) {\n if (DEBUG_BUILD && isErrorEvent(event)) {\n logger.log(`Captured error event \\`${getPossibleEventMessages(event)[0] || ''}\\``);\n }\n\n return this._processEvent(event, hint, currentScope, isolationScope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (DEBUG_BUILD) {\n // If something's gone wrong, log the error as a warning. If it's just us having used a `SentryError` for\n // control flow, log just the message (no stack) as a log-level log.\n if (reason instanceof SentryError && reason.logLevel === 'log') {\n logger.log(reason.message);\n } else {\n logger.warn(reason);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param currentScope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n _processEvent(\n event,\n hint,\n currentScope,\n isolationScope,\n ) {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n const parsedSampleRate = typeof sampleRate === 'undefined' ? undefined : parseSampleRate(sampleRate);\n if (isError && typeof parsedSampleRate === 'number' && Math.random() > parsedSampleRate) {\n this.recordDroppedEvent('sample_rate', 'error');\n return rejectedSyncPromise(\n new SentryError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n 'log',\n ),\n );\n }\n\n const dataCategory = (eventType === 'replay_event' ? 'replay' : eventType) ;\n\n return this._prepareEvent(event, hint, currentScope, isolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory);\n throw new SentryError('An event processor returned `null`, will not send event.', 'log');\n }\n\n const isInternalException = hint.data && (hint.data ).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(this, options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory);\n if (isTransaction) {\n const spans = event.spans || [];\n // the transaction itself counts as one span, plus all the child spans that are added\n const spanCount = 1 + spans.length;\n this.recordDroppedEvent('before_send', 'span', spanCount);\n }\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (isError && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n if (isTransaction) {\n const spanCountBefore = processedEvent.sdkProcessingMetadata?.spanCountBeforeProcessing || 0;\n const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;\n\n const droppedSpanCount = spanCountBefore - spanCountAfter;\n if (droppedSpanCount > 0) {\n this.recordDroppedEvent('before_send', 'span', droppedSpanCount);\n }\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (reason instanceof SentryError) {\n throw reason;\n }\n\n this.captureException(reason, {\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw new SentryError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n _process(promise) {\n this._numProcessing++;\n void promise.then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n return reason;\n },\n );\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n _clearOutcomes() {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.entries(outcomes).map(([key, quantity]) => {\n const [reason, category] = key.split(':') ;\n return {\n reason,\n category,\n quantity,\n };\n });\n }\n\n /**\n * Sends client reports as an envelope.\n */\n _flushOutcomes() {\n DEBUG_BUILD && logger.log('Flushing outcomes...');\n\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n DEBUG_BUILD && logger.log('No outcomes to send');\n return;\n }\n\n // This is really the only place where we want to check for a DSN and only send outcomes then\n if (!this._dsn) {\n DEBUG_BUILD && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n DEBUG_BUILD && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(envelope);\n }\n\n /**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n */\n\n}\n\n/**\n * @deprecated Use `Client` instead. This alias may be removed in a future major version.\n */\n// TODO(v10): Remove\n\n/**\n * @deprecated Use `Client` instead. This alias may be removed in a future major version.\n */\n// TODO(v10): Remove\nconst BaseClient = Client;\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult,\n beforeSendLabel,\n) {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw new SentryError(invalidValueError);\n }\n return event;\n },\n e => {\n throw new SentryError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw new SentryError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n client,\n options,\n event,\n hint,\n) {\n const { beforeSend, beforeSendTransaction, beforeSendSpan } = options;\n let processedEvent = event;\n\n if (isErrorEvent(processedEvent) && beforeSend) {\n return beforeSend(processedEvent, hint);\n }\n\n if (isTransactionEvent(processedEvent)) {\n if (beforeSendSpan) {\n // process root span\n const processedRootSpanJson = beforeSendSpan(convertTransactionEventToSpanJson(processedEvent));\n if (!processedRootSpanJson) {\n showSpanDropWarning();\n } else {\n // update event with processed root span values\n processedEvent = merge(event, convertSpanJsonToTransactionEvent(processedRootSpanJson));\n }\n\n // process child spans\n if (processedEvent.spans) {\n const processedSpans = [];\n for (const span of processedEvent.spans) {\n const processedSpan = beforeSendSpan(span);\n if (!processedSpan) {\n showSpanDropWarning();\n processedSpans.push(span);\n } else {\n processedSpans.push(processedSpan);\n }\n }\n processedEvent.spans = processedSpans;\n }\n }\n\n if (beforeSendTransaction) {\n if (processedEvent.spans) {\n // We store the # of spans before processing in SDK metadata,\n // so we can compare it afterwards to determine how many spans were dropped\n const spanCountBefore = processedEvent.spans.length;\n processedEvent.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n spanCountBeforeProcessing: spanCountBefore,\n };\n }\n return beforeSendTransaction(processedEvent , hint);\n }\n }\n\n return processedEvent;\n}\n\nfunction isErrorEvent(event) {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\nexport { BaseClient, Client };\n//# sourceMappingURL=client.js.map\n","import { getCurrentScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { logger, consoleSandbox } from './utils-hoist/logger.js';\n\n/** A class object that can instantiate Client objects. */\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nfunction initAndBind(\n clientClass,\n options,\n) {\n if (options.debug === true) {\n if (DEBUG_BUILD) {\n logger.enable();\n } else {\n // use `console.warn` rather than `logger.warn` since by non-debug bundles have all `logger.x` statements stripped\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n });\n }\n }\n const scope = getCurrentScope();\n scope.update(options.initialScope);\n\n const client = new clientClass(options);\n setCurrentClient(client);\n client.init();\n return client;\n}\n\n/**\n * Make the given client the current client.\n */\nfunction setCurrentClient(client) {\n getCurrentScope().setClient(client);\n}\n\nexport { initAndBind, setCurrentClient };\n//# sourceMappingURL=sdk.js.map\n","import { SentryError } from './error.js';\nimport { rejectedSyncPromise, SyncPromise, resolvedSyncPromise } from './syncpromise.js';\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nfunction makePromiseBuffer(limit) {\n const buffer = [];\n\n function isReady() {\n return limit === undefined || buffer.length < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike\n * @returns Removed promise.\n */\n function remove(task) {\n return buffer.splice(buffer.indexOf(task), 1)[0] || Promise.resolve(undefined);\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task:\n * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer) {\n if (!isReady()) {\n return rejectedSyncPromise(new SentryError('Not adding Promise because buffer limit was reached.'));\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n if (buffer.indexOf(task) === -1) {\n buffer.push(task);\n }\n void task\n .then(() => remove(task))\n // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike`\n // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't\n // have promises, so TS has to polyfill when down-compiling.)\n .then(null, () =>\n remove(task).then(null, () => {\n // We have to add another catch here because `remove()` starts a new promise chain.\n }),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout) {\n return new SyncPromise((resolve, reject) => {\n let counter = buffer.length;\n\n if (!counter) {\n return resolve(true);\n }\n\n // wait for `timeout` ms and then resolve to `false` (if not cancelled first)\n const capturedSetTimeout = setTimeout(() => {\n if (timeout && timeout > 0) {\n resolve(false);\n }\n }, timeout);\n\n // if all promises resolve in time, cancel the timer and resolve to `true`\n buffer.forEach(item => {\n void resolvedSyncPromise(item).then(() => {\n if (!--counter) {\n clearTimeout(capturedSetTimeout);\n resolve(true);\n }\n }, reject);\n });\n });\n }\n\n return {\n $: buffer,\n add,\n drain,\n };\n}\n\nexport { makePromiseBuffer };\n//# sourceMappingURL=promisebuffer.js.map\n","// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\n\nconst DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nfunction parseRetryAfterHeader(header, now = Date.now()) {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nfunction disabledUntil(limits, dataCategory) {\n return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nfunction isRateLimited(limits, dataCategory, now = Date.now()) {\n return disabledUntil(limits, dataCategory) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nfunction updateRateLimits(\n limits,\n { statusCode, headers },\n now = Date.now(),\n) {\n const updatedRateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers?.['x-sentry-rate-limits'];\n const retryAfterHeader = headers?.['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n *
,
,..\n * where each
is of the form\n * : : : : \n * where\n * is a delay in seconds\n * is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * ;;...\n * is what's being limited (org, project, or key) - ignored by SDK\n * is an arbitrary string like \"org_quota\" - ignored by SDK\n * Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n * Only present if rate limit applies to the metric_bucket data category.\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories, , , namespaces] = limit.split(':', 5) ;\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n if (category === 'metric_bucket') {\n // namespaces will be present when category === 'metric_bucket'\n if (!namespaces || namespaces.split(';').includes('custom')) {\n updatedRateLimits[category] = now + delay;\n }\n } else {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n\nexport { DEFAULT_RETRY_AFTER, disabledUntil, isRateLimited, parseRetryAfterHeader, updateRateLimits };\n//# sourceMappingURL=ratelimit.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { forEachEnvelopeItem, envelopeItemTypeToDataCategory, createEnvelope, serializeEnvelope } from '../utils-hoist/envelope.js';\nimport { SentryError } from '../utils-hoist/error.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { makePromiseBuffer } from '../utils-hoist/promisebuffer.js';\nimport { isRateLimited, updateRateLimits } from '../utils-hoist/ratelimit.js';\nimport { resolvedSyncPromise } from '../utils-hoist/syncpromise.js';\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 64;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nfunction createTransport(\n options,\n makeRequest,\n buffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n) {\n let rateLimits = {};\n const flush = (timeout) => buffer.drain(timeout);\n\n function send(envelope) {\n const filteredEnvelopeItems = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const dataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, dataCategory)) {\n options.recordDroppedEvent('ratelimit_backoff', dataCategory);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return resolvedSyncPromise({});\n }\n\n const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems );\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason) => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type));\n });\n };\n\n const requestTask = () =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n DEBUG_BUILD && logger.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error instanceof SentryError) {\n DEBUG_BUILD && logger.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return resolvedSyncPromise({});\n } else {\n throw error;\n }\n },\n );\n }\n\n return {\n send,\n flush,\n };\n}\n\nexport { DEFAULT_TRANSPORT_BUFFER_SIZE, createTransport };\n//# sourceMappingURL=base.js.map\n","/**\n * Checks whether given url points to Sentry server\n *\n * @param url url to verify\n */\nfunction isSentryRequestUrl(url, client) {\n const dsn = client?.getDsn();\n const tunnel = client?.getOptions().tunnel;\n return checkDsn(url, dsn) || checkTunnel(url, tunnel);\n}\n\nfunction checkTunnel(url, tunnel) {\n if (!tunnel) {\n return false;\n }\n\n return removeTrailingSlash(url) === removeTrailingSlash(tunnel);\n}\n\nfunction checkDsn(url, dsn) {\n return dsn ? url.includes(dsn.host) : false;\n}\n\nfunction removeTrailingSlash(str) {\n return str[str.length - 1] === '/' ? str.slice(0, -1) : str;\n}\n\nexport { isSentryRequestUrl };\n//# sourceMappingURL=isSentryRequestUrl.js.map\n","// By default, we want to infer the IP address, unless this is explicitly set to `null`\n// We do this after all other processing is done\n// If `ip_address` is explicitly set to `null` or a value, we leave it as is\n\n/**\n * @internal\n */\nfunction addAutoIpAddressToUser(objWithMaybeUser) {\n if (objWithMaybeUser.user?.ip_address === undefined) {\n objWithMaybeUser.user = {\n ...objWithMaybeUser.user,\n ip_address: '{{auto}}',\n };\n }\n}\n\n/**\n * @internal\n */\nfunction addAutoIpAddressToSession(session) {\n if ('aggregates' in session) {\n if (session.attrs?.['ip_address'] === undefined) {\n session.attrs = {\n ...session.attrs,\n ip_address: '{{auto}}',\n };\n }\n } else {\n if (session.ipAddress === undefined) {\n session.ipAddress = '{{auto}}';\n }\n }\n}\n\nexport { addAutoIpAddressToSession, addAutoIpAddressToUser };\n//# sourceMappingURL=ipAddress.js.map\n","import { SDK_VERSION } from '../utils-hoist/version.js';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n *\n * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.\n * We don't extract it for bundle size reasons.\n * @see https://github.com/getsentry/sentry-javascript/pull/7404\n * @see https://github.com/getsentry/sentry-javascript/pull/4196\n *\n * If you make changes to this function consider updating the others as well.\n *\n * @param options SDK options object that gets mutated\n * @param names list of package names\n */\nfunction applySdkMetadata(options, name, names = [name], source = 'npm') {\n const metadata = options._metadata || {};\n\n if (!metadata.sdk) {\n metadata.sdk = {\n name: `sentry.javascript.${name}`,\n packages: names.map(name => ({\n name: `${source}:@sentry/${name}`,\n version: SDK_VERSION,\n })),\n version: SDK_VERSION,\n };\n }\n\n options._metadata = metadata;\n}\n\nexport { applySdkMetadata };\n//# sourceMappingURL=sdkMetadata.js.map\n","import { getAsyncContextStrategy } from '../asyncContext/index.js';\nimport { getMainCarrier } from '../carrier.js';\nimport { getClient, getCurrentScope } from '../currentScopes.js';\nimport { isEnabled } from '../exports.js';\nimport '../tracing/errors.js';\nimport '../utils-hoist/debug-build.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport '../debug-build.js';\nimport '../utils-hoist/time.js';\nimport { getActiveSpan, spanToTraceHeader } from './spanUtils.js';\nimport { getDynamicSamplingContextFromSpan, getDynamicSamplingContextFromScope } from '../tracing/dynamicSamplingContext.js';\nimport { TRACEPARENT_REGEXP, generateSentryTraceHeader } from '../utils-hoist/tracing.js';\nimport { dynamicSamplingContextToSentryBaggageHeader } from '../utils-hoist/baggage.js';\n\n/**\n * Extracts trace propagation data from the current span or from the client's scope (via transaction or propagation\n * context) and serializes it to `sentry-trace` and `baggage` values to strings. These values can be used to propagate\n * a trace via our tracing Http headers or Html `` tags.\n *\n * This function also applies some validation to the generated sentry-trace and baggage values to ensure that\n * only valid strings are returned.\n *\n * @returns an object with the tracing data values. The object keys are the name of the tracing key to be used as header\n * or meta tag name.\n */\nfunction getTraceData(options = {}) {\n const client = getClient();\n if (!isEnabled() || !client) {\n return {};\n }\n\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n if (acs.getTraceData) {\n return acs.getTraceData(options);\n }\n\n const scope = getCurrentScope();\n const span = options.span || getActiveSpan();\n const sentryTrace = span ? spanToTraceHeader(span) : scopeToTraceHeader(scope);\n const dsc = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope);\n const baggage = dynamicSamplingContextToSentryBaggageHeader(dsc);\n\n const isValidSentryTraceHeader = TRACEPARENT_REGEXP.test(sentryTrace);\n if (!isValidSentryTraceHeader) {\n logger.warn('Invalid sentry-trace data. Cannot generate trace data');\n return {};\n }\n\n return {\n 'sentry-trace': sentryTrace,\n baggage,\n };\n}\n\n/**\n * Get a sentry-trace header value for the given scope.\n */\nfunction scopeToTraceHeader(scope) {\n const { traceId, sampled, propagationSpanId } = scope.getPropagationContext();\n return generateSentryTraceHeader(traceId, propagationSpanId, sampled);\n}\n\nexport { getTraceData };\n//# sourceMappingURL=traceData.js.map\n","import { getClient, getIsolationScope } from './currentScopes.js';\nimport { consoleSandbox } from './utils-hoist/logger.js';\nimport { dateTimestampInSeconds } from './utils-hoist/time.js';\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n */\nfunction addBreadcrumb(breadcrumb, hint) {\n const client = getClient();\n const isolationScope = getIsolationScope();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions();\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? (consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint)) )\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n}\n\nexport { addBreadcrumb };\n//# sourceMappingURL=breadcrumbs.js.map\n","import { getClient } from '../currentScopes.js';\nimport { defineIntegration } from '../integration.js';\nimport { getOriginalFunction } from '../utils-hoist/object.js';\n\nlet originalFunctionToString;\n\nconst INTEGRATION_NAME = 'FunctionToString';\n\nconst SETUP_CLIENTS = new WeakMap();\n\nconst _functionToStringIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n Function.prototype.toString = function ( ...args) {\n const originalFunction = getOriginalFunction(this);\n const context =\n SETUP_CLIENTS.has(getClient() ) && originalFunction !== undefined ? originalFunction : this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n },\n setup(client) {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) ;\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * ```js\n * Sentry.init({\n * integrations: [\n * functionToStringIntegration(),\n * ],\n * });\n * ```\n */\nconst functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n\nexport { functionToStringIntegration };\n//# sourceMappingURL=functiontostring.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { defineIntegration } from '../integration.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { getEventDescription } from '../utils-hoist/misc.js';\nimport { stringMatchesSomePattern } from '../utils-hoist/string.js';\nimport { getPossibleEventMessages } from '../utils/eventUtils.js';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [\n /^Script error\\.?$/,\n /^Javascript error: Script error\\.? on line 0$/,\n /^ResizeObserver loop completed with undelivered notifications.$/, // The browser logs this when a ResizeObserver handler takes a bit longer. Usually this is not an actual issue though. It indicates slowness.\n /^Cannot redefine property: googletag$/, // This is thrown when google tag manager is used in combination with an ad blocker\n \"undefined is not an object (evaluating 'a.L')\", // Random error that happens but not actionable or noticeable to end-users.\n 'can\\'t redefine non-configurable property \"solana\"', // Probably a browser extension or custom browser (Brave) throwing this error\n \"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)\", // Error thrown by GTM, seemingly not affecting end-users\n \"Can't find variable: _AutofillCallbackHandler\", // Unactionable error in instagram webview https://developers.facebook.com/community/threads/320013549791141/\n /^Non-Error promise rejection captured with value: Object Not Found Matching Id:\\d+, MethodName:simulateEvent, ParamCount:\\d+$/, // unactionable error from CEFSharp, a .NET library that embeds chromium in .NET apps\n];\n\n/** Options for the InboundFilters integration */\n\nconst INTEGRATION_NAME = 'InboundFilters';\nconst _inboundFiltersIntegration = ((options = {}) => {\n return {\n name: INTEGRATION_NAME,\n processEvent(event, _hint, client) {\n const clientOptions = client.getOptions();\n const mergedOptions = _mergeOptions(options, clientOptions);\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n}) ;\n\nconst inboundFiltersIntegration = defineIntegration(_inboundFiltersIntegration);\n\nfunction _mergeOptions(\n internalOptions = {},\n clientOptions = {},\n) {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [...(internalOptions.ignoreTransactions || []), ...(clientOptions.ignoreTransactions || [])],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\nfunction _shouldDropEvent(event, options) {\n if (options.ignoreInternal && _isSentryError(event)) {\n DEBUG_BUILD &&\n logger.warn(`Event dropped due to being internal Sentry Error.\\nEvent: ${getEventDescription(event)}`);\n return true;\n }\n if (_isIgnoredError(event, options.ignoreErrors)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isUselessError(event)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to not having an error message, error type or stacktrace.\\nEvent: ${getEventDescription(\n event,\n )}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n DEBUG_BUILD &&\n logger.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n return false;\n}\n\nfunction _isIgnoredError(event, ignoreErrors) {\n // If event.type, this is not an error\n if (event.type || !ignoreErrors || !ignoreErrors.length) {\n return false;\n }\n\n return getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event, ignoreTransactions) {\n if (event.type !== 'transaction' || !ignoreTransactions || !ignoreTransactions.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event, denyUrls) {\n if (!denyUrls?.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event, allowUrls) {\n if (!allowUrls?.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _isSentryError(event) {\n try {\n // @ts-expect-error can't be a sentry error if undefined\n return event.exception.values[0].type === 'SentryError';\n } catch (e) {\n // ignore\n }\n return false;\n}\n\nfunction _getLastValidUrl(frames = []) {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event) {\n try {\n let frames;\n try {\n // @ts-expect-error we only care about frames if the whole thing here is defined\n frames = event.exception.values[0].stacktrace.frames;\n } catch (e) {\n // ignore\n }\n return frames ? _getLastValidUrl(frames) : null;\n } catch (oO) {\n DEBUG_BUILD && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n\nfunction _isUselessError(event) {\n if (event.type) {\n // event is not an error\n return false;\n }\n\n // We only want to consider events for dropping that actually have recorded exception values.\n if (!event.exception?.values?.length) {\n return false;\n }\n\n return (\n // No top-level message\n !event.message &&\n // There are no exception values that have a stacktrace, a non-generic-Error type or value\n !event.exception.values.some(value => value.stacktrace || (value.type && value.type !== 'Error') || value.value)\n );\n}\n\nexport { inboundFiltersIntegration };\n//# sourceMappingURL=inboundfilters.js.map\n","import { isInstanceOf } from './is.js';\nimport { truncate } from './string.js';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nfunction applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation,\n parser,\n maxValueLimit = 250,\n key,\n limit,\n event,\n hint,\n) {\n if (!event.exception?.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = truncateAggregateExceptions(\n aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException ,\n key,\n event.exception.values,\n originalException,\n 0,\n ),\n maxValueLimit,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error,\n key,\n prevExceptions,\n exception,\n exceptionId,\n) {\n if (prevExceptions.length >= limit + 1) {\n return prevExceptions;\n }\n\n let newExceptions = [...prevExceptions];\n\n // Recursively call this function in order to walk down a chain of errors\n if (isInstanceOf(error[key], Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, error[key]);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error[key],\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n\n // This will create exception grouping for AggregateErrors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n if (Array.isArray(error.errors)) {\n error.errors.forEach((childError, i) => {\n if (isInstanceOf(childError, Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, childError);\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n childError,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n });\n }\n\n return newExceptions;\n}\n\nfunction applyExceptionGroupFieldsForParentException(exception, exceptionId) {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n ...(exception.type === 'AggregateError' && { is_exception_group: true }),\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception,\n source,\n exceptionId,\n parentId,\n) {\n // Don't know if this default makes sense. The protocol requires us to set these values so we pick *some* default.\n exception.mechanism = exception.mechanism || { type: 'generic', handled: true };\n\n exception.mechanism = {\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\n/**\n * Truncate the message (exception.value) of all exceptions in the event.\n * Because this event processor is ran after `applyClientOptions`,\n * we need to truncate the message of the added exceptions here.\n */\nfunction truncateAggregateExceptions(exceptions, maxValueLength) {\n return exceptions.map(exception => {\n if (exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n return exception;\n });\n}\n\nexport { applyAggregateErrorsToEvent };\n//# sourceMappingURL=aggregate-errors.js.map\n","import { CONSOLE_LEVELS, originalConsoleMethods } from '../logger.js';\nimport { fill } from '../object.js';\nimport { GLOBAL_OBJ } from '../worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addConsoleInstrumentationHandler(handler) {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole() {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level) {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod) {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args) {\n const handlerData = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log?.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n\nexport { addConsoleInstrumentationHandler };\n//# sourceMappingURL=console.js.map\n","/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nfunction severityLevelFromString(level) {\n return (\n level === 'warn' ? 'warning' : ['fatal', 'error', 'warning', 'log', 'info', 'debug'].includes(level) ? level : 'log'\n ) ;\n}\n\nexport { severityLevelFromString };\n//# sourceMappingURL=severity.js.map\n","import { defineIntegration } from '../integration.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { logger } from '../utils-hoist/logger.js';\nimport { getFramesFromEvent } from '../utils-hoist/stacktrace.js';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent;\n\n return {\n name: INTEGRATION_NAME,\n processEvent(currentEvent) {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, previousEvent)) {\n DEBUG_BUILD && logger.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch (_oO) {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) ;\n\n/**\n * Deduplication filter.\n */\nconst dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/** only exported for tests. */\nfunction _shouldDropEvent(currentEvent, previousEvent) {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\nfunction _isSameMessageEvent(currentEvent, previousEvent) {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameExceptionEvent(currentEvent, previousEvent) {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameStacktrace(currentEvent, previousEvent) {\n let currentFrames = getFramesFromEvent(currentEvent);\n let previousFrames = getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames ;\n previousFrames = previousFrames ;\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const frameA = previousFrames[i];\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction _isSameFingerprint(currentEvent, previousEvent) {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint ;\n previousFingerprint = previousFingerprint ;\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch (_oO) {\n return false;\n }\n}\n\nfunction _getExceptionFromEvent(event) {\n return event.exception?.values && event.exception.values[0];\n}\n\nexport { _shouldDropEvent, dedupeIntegration };\n//# sourceMappingURL=dedupe.js.map\n","/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nfunction parseUrl(url) {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nfunction stripUrlQueryAndFragment(urlPath) {\n return (urlPath.split(/[?#]/, 1) )[0];\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span name\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nfunction getSanitizedUrlString(url) {\n const { protocol, host, path } = url;\n\n const filteredHost =\n host\n // Always filter out authority\n ?.replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n // TODO: Use new URL global if it exists\n .replace(/(:80)$/, '')\n .replace(/(:443)$/, '') || '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n\nexport { getSanitizedUrlString, parseUrl, stripUrlQueryAndFragment };\n//# sourceMappingURL=url.js.map\n","import { getClient } from './currentScopes.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP } from './semanticAttributes.js';\nimport './tracing/errors.js';\nimport { isInstanceOf } from './utils-hoist/is.js';\nimport './utils-hoist/debug-build.js';\nimport './utils-hoist/logger.js';\nimport './debug-build.js';\nimport './utils-hoist/time.js';\nimport { hasSpansEnabled } from './utils/hasSpansEnabled.js';\nimport { getActiveSpan } from './utils/spanUtils.js';\nimport { SENTRY_BAGGAGE_KEY_PREFIX } from './utils-hoist/baggage.js';\nimport { SentryNonRecordingSpan } from './tracing/sentryNonRecordingSpan.js';\nimport { setHttpStatus, SPAN_STATUS_ERROR } from './tracing/spanstatus.js';\nimport { startInactiveSpan } from './tracing/trace.js';\nimport { parseUrl } from './utils-hoist/url.js';\nimport { getTraceData } from './utils/traceData.js';\n\n/**\n * Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`.\n *\n * @returns Span if a span was created, otherwise void.\n */\nfunction instrumentFetchRequest(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n spanOrigin = 'auto.http.browser',\n) {\n if (!handlerData.fetchData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = hasSpansEnabled() && shouldCreateSpan(handlerData.fetchData.url);\n\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n endSpan(span, handlerData);\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const { method, url } = handlerData.fetchData;\n\n const fullUrl = getFullURL(url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const hasParent = !!getActiveSpan();\n\n const span =\n shouldCreateSpanResult && hasParent\n ? startInactiveSpan({\n name: `${method} ${url}`,\n attributes: {\n url,\n type: 'fetch',\n 'http.method': method,\n 'http.url': fullUrl,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.client',\n },\n })\n : new SentryNonRecordingSpan();\n\n handlerData.fetchData.__span = span.spanContext().spanId;\n spans[span.spanContext().spanId] = span;\n\n if (shouldAttachHeaders(handlerData.fetchData.url)) {\n const request = handlerData.args[0];\n\n const options = handlerData.args[1] || {};\n\n const headers = _addTracingHeadersToFetchRequest(\n request,\n options,\n // If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction),\n // we do not want to use the span as base for the trace headers,\n // which means that the headers will be generated from the scope and the sampling decision is deferred\n hasSpansEnabled() && hasParent ? span : undefined,\n );\n if (headers) {\n // Ensure this is actually set, if no options have been passed previously\n handlerData.args[1] = options;\n options.headers = headers;\n }\n }\n\n const client = getClient();\n\n if (client) {\n const fetchHint = {\n input: handlerData.args,\n response: handlerData.response,\n startTimestamp: handlerData.startTimestamp,\n endTimestamp: handlerData.endTimestamp,\n } ;\n\n client.emit('beforeOutgoingRequestSpan', span, fetchHint);\n }\n\n return span;\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers.\n */\nfunction _addTracingHeadersToFetchRequest(\n request,\n fetchOptionsObj\n\n,\n span,\n) {\n const traceHeaders = getTraceData({ span });\n const sentryTrace = traceHeaders['sentry-trace'];\n const baggage = traceHeaders.baggage;\n\n // Nothing to do, when we return undefined here, the original headers will be used\n if (!sentryTrace) {\n return undefined;\n }\n\n const headers = fetchOptionsObj.headers || (isRequest(request) ? request.headers : undefined);\n\n if (!headers) {\n return { ...traceHeaders };\n } else if (isHeaders(headers)) {\n const newHeaders = new Headers(headers);\n newHeaders.set('sentry-trace', sentryTrace);\n\n if (baggage) {\n const prevBaggageHeader = newHeaders.get('baggage');\n if (prevBaggageHeader) {\n const prevHeaderStrippedFromSentryBaggage = stripBaggageHeaderOfSentryBaggageValues(prevBaggageHeader);\n newHeaders.set(\n 'baggage',\n // If there are non-sentry entries (i.e. if the stripped string is non-empty/truthy) combine the stripped header and sentry baggage header\n // otherwise just set the sentry baggage header\n prevHeaderStrippedFromSentryBaggage ? `${prevHeaderStrippedFromSentryBaggage},${baggage}` : baggage,\n );\n } else {\n newHeaders.set('baggage', baggage);\n }\n }\n\n return newHeaders;\n } else if (Array.isArray(headers)) {\n const newHeaders = [\n ...headers\n // Remove any existing sentry-trace headers\n .filter(header => {\n return !(Array.isArray(header) && header[0] === 'sentry-trace');\n })\n // Get rid of previous sentry baggage values in baggage header\n .map(header => {\n if (Array.isArray(header) && header[0] === 'baggage' && typeof header[1] === 'string') {\n const [headerName, headerValue, ...rest] = header;\n return [headerName, stripBaggageHeaderOfSentryBaggageValues(headerValue), ...rest];\n } else {\n return header;\n }\n }),\n // Attach the new sentry-trace header\n ['sentry-trace', sentryTrace],\n ];\n\n if (baggage) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push(['baggage', baggage]);\n }\n\n return newHeaders ;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n let newBaggageHeaders = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders = existingBaggageHeader\n .map(headerItem =>\n typeof headerItem === 'string' ? stripBaggageHeaderOfSentryBaggageValues(headerItem) : headerItem,\n )\n .filter(headerItem => headerItem === '');\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(stripBaggageHeaderOfSentryBaggageValues(existingBaggageHeader));\n }\n\n if (baggage) {\n newBaggageHeaders.push(baggage);\n }\n\n return {\n ...(headers ),\n 'sentry-trace': sentryTrace,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\nfunction getFullURL(url) {\n try {\n const parsed = new URL(url);\n return parsed.href;\n } catch {\n return undefined;\n }\n}\n\nfunction endSpan(span, handlerData) {\n if (handlerData.response) {\n setHttpStatus(span, handlerData.response.status);\n\n const contentLength = handlerData.response?.headers && handlerData.response.headers.get('content-length');\n\n if (contentLength) {\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setAttribute('http.response_content_length', contentLengthNum);\n }\n }\n } else if (handlerData.error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n span.end();\n}\n\nfunction stripBaggageHeaderOfSentryBaggageValues(baggageHeader) {\n return (\n baggageHeader\n .split(',')\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n .filter(baggageEntry => !baggageEntry.split('=')[0].startsWith(SENTRY_BAGGAGE_KEY_PREFIX))\n .join(',')\n );\n}\n\nfunction isRequest(request) {\n return typeof Request !== 'undefined' && isInstanceOf(request, Request);\n}\n\nfunction isHeaders(headers) {\n return typeof Headers !== 'undefined' && isInstanceOf(headers, Headers);\n}\n\nexport { instrumentFetchRequest };\n//# sourceMappingURL=fetch.js.map\n","/**\n * Determine a breadcrumb's log level (only `warning` or `error`) based on an HTTP status code.\n */\nfunction getBreadcrumbLogLevelFromHttpStatusCode(statusCode) {\n // NOTE: undefined defaults to 'info' in Sentry\n if (statusCode === undefined) {\n return undefined;\n } else if (statusCode >= 400 && statusCode < 500) {\n return 'warning';\n } else if (statusCode >= 500) {\n return 'error';\n } else {\n return undefined;\n }\n}\n\nexport { getBreadcrumbLogLevelFromHttpStatusCode };\n//# sourceMappingURL=breadcrumb-log-level.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { logger } from './logger.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nconst WINDOW = GLOBAL_OBJ ;\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsErrorEvent() {\n try {\n new ErrorEvent('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMError() {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-expect-error It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMException() {\n try {\n new DOMException('');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsHistory() {\n return 'history' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsFetch() {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n new Request('http://www.example.com');\n new Response();\n return true;\n } catch (e) {\n return false;\n }\n}\n\n/**\n * isNative checks if the given function is a native implementation\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isNativeFunction(func) {\n return func && /^function\\s+\\w+\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nfunction supportsNativeFetch() {\n if (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!supportsFetch()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFunction(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement ) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow?.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFunction(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReportingObserver() {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReferrerPolicy() {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!supportsFetch()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' ,\n });\n return true;\n } catch (e) {\n return false;\n }\n}\n\nexport { isNativeFunction, supportsDOMError, supportsDOMException, supportsErrorEvent, supportsFetch, supportsHistory, supportsNativeFetch, supportsReferrerPolicy, supportsReportingObserver };\n//# sourceMappingURL=supports.js.map\n","import { isError } from '../is.js';\nimport { fill, addNonEnumerableProperty } from '../object.js';\nimport { supportsNativeFetch } from '../supports.js';\nimport { timestampInSeconds } from '../time.js';\nimport { GLOBAL_OBJ } from '../worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addFetchInstrumentationHandler(\n handler,\n skipNativeFetchCheck,\n) {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, () => instrumentFetch(undefined, skipNativeFetchCheck));\n}\n\n/**\n * Add an instrumentation handler for long-lived fetch requests, like consuming server-sent events (SSE) via fetch.\n * The handler will resolve the request body and emit the actual `endTimestamp`, so that the\n * span can be updated accordingly.\n *\n * Only used internally\n * @hidden\n */\nfunction addFetchEndInstrumentationHandler(handler) {\n const type = 'fetch-body-resolved';\n addHandler(type, handler);\n maybeInstrument(type, () => instrumentFetch(streamHandler));\n}\n\nfunction instrumentFetch(onFetchResolved, skipNativeFetchCheck = false) {\n if (skipNativeFetchCheck && !supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch) {\n return function (...args) {\n // We capture the error right here and not in the Promise error callback because Safari (and probably other\n // browsers too) will wipe the stack trace up to this point, only leaving us with this file which is useless.\n\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your fetch call did not\n // have a stack trace, so the SDK backfilled the stack trace so\n // you can see which fetch call failed.\n const virtualError = new Error();\n\n const { method, url } = parseFetchArgs(args);\n const handlerData = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: timestampInSeconds() * 1000,\n // // Adding the error to be able to fingerprint the failed fetch event in HttpClient instrumentation\n virtualError,\n };\n\n // if there is no callback, fetch is instrumented directly\n if (!onFetchResolved) {\n triggerHandlers('fetch', {\n ...handlerData,\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n async (response) => {\n if (onFetchResolved) {\n onFetchResolved(response);\n } else {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: timestampInSeconds() * 1000,\n response,\n });\n }\n\n return response;\n },\n (error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: timestampInSeconds() * 1000,\n error,\n });\n\n if (isError(error) && error.stack === undefined) {\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your fetch call did not\n // have a stack trace, so the SDK backfilled the stack trace so\n // you can see which fetch call failed.\n error.stack = virtualError.stack;\n addNonEnumerableProperty(error, 'framesToPop', 1);\n }\n\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nasync function resolveResponse(res, onFinishedResolving) {\n if (res?.body) {\n const body = res.body;\n const responseReader = body.getReader();\n\n // Define a maximum duration after which we just cancel\n const maxFetchDurationTimeout = setTimeout(\n () => {\n body.cancel().then(null, () => {\n // noop\n });\n },\n 90 * 1000, // 90s\n );\n\n let readingActive = true;\n while (readingActive) {\n let chunkTimeout;\n try {\n // abort reading if read op takes more than 5s\n chunkTimeout = setTimeout(() => {\n body.cancel().then(null, () => {\n // noop on error\n });\n }, 5000);\n\n // This .read() call will reject/throw when we abort due to timeouts through `body.cancel()`\n const { done } = await responseReader.read();\n\n clearTimeout(chunkTimeout);\n\n if (done) {\n onFinishedResolving();\n readingActive = false;\n }\n } catch (error) {\n readingActive = false;\n } finally {\n clearTimeout(chunkTimeout);\n }\n }\n\n clearTimeout(maxFetchDurationTimeout);\n\n responseReader.releaseLock();\n body.cancel().then(null, () => {\n // noop on error\n });\n }\n}\n\nfunction streamHandler(response) {\n // clone response for awaiting stream\n let clonedResponseForResolving;\n try {\n clonedResponseForResolving = response.clone();\n } catch {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n resolveResponse(clonedResponseForResolving, () => {\n triggerHandlers('fetch-body-resolved', {\n endTimestamp: timestampInSeconds() * 1000,\n response,\n });\n });\n}\n\nfunction hasProp(obj, prop) {\n return !!obj && typeof obj === 'object' && !!(obj )[prop];\n}\n\nfunction getUrlFromResource(resource) {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nfunction parseFetchArgs(fetchArgs) {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [url, options] = fetchArgs ;\n\n return {\n url: getUrlFromResource(url),\n method: hasProp(options, 'method') ? String(options.method).toUpperCase() : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg ),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n\nexport { addFetchEndInstrumentationHandler, addFetchInstrumentationHandler, parseFetchArgs };\n//# sourceMappingURL=fetch.js.map\n","/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `logger` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nfunction isBrowserBundle() {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nfunction getSDKSource() {\n // This comment is used to identify this line in the CDN bundle build step and replace this with \"return 'cdn';\"\n /* __SENTRY_SDK_SOURCE__ */ return 'npm';\n}\n\nexport { getSDKSource, isBrowserBundle };\n//# sourceMappingURL=env.js.map\n","import { isBrowserBundle } from './env.js';\n\n/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the logger, or b) put your function elsewhere.\n */\n\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nfunction isNodeEnv() {\n // explicitly check for browser bundles as those can be optimized statically\n // by terser/rollup.\n return (\n !isBrowserBundle() &&\n Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction dynamicRequire(mod, request) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @param existingModule module to use for requiring\n * @returns possibly required module\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction loadModule(moduleName, existingModule = module) {\n let mod;\n\n try {\n mod = dynamicRequire(existingModule, moduleName);\n } catch (e) {\n // no-empty\n }\n\n if (!mod) {\n try {\n const { cwd } = dynamicRequire(existingModule, 'process');\n mod = dynamicRequire(existingModule, `${cwd()}/node_modules/${moduleName}`) ;\n } catch (e) {\n // no-empty\n }\n }\n\n return mod;\n}\n\nexport { isNodeEnv, loadModule };\n//# sourceMappingURL=node.js.map\n","import { isNodeEnv } from './node.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * Returns true if we are in the browser.\n */\nfunction isBrowser() {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer() {\n const process = (GLOBAL_OBJ ).process;\n return process?.type === 'renderer';\n}\n\nexport { isBrowser };\n//# sourceMappingURL=isBrowser.js.map\n","import { GLOBAL_OBJ, getOriginalFunction, markFunctionWrapped, addNonEnumerableProperty, withScope, addExceptionTypeValue, addExceptionMechanism, captureException } from '@sentry/core';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nlet ignoreOnError = 0;\n\n/**\n * @hidden\n */\nfunction shouldIgnoreOnError() {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nfunction ignoreNextOnError() {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\n\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nfunction wrap(\n fn,\n options\n\n = {},\n) {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n function isFunction(fn) {\n return typeof fn === 'function';\n }\n\n if (!isFunction(fn)) {\n return fn;\n }\n\n try {\n // if we're dealing with a function that was previously wrapped, return\n // the original wrapper.\n const wrapper = (fn ).__sentry_wrapped__;\n if (wrapper) {\n if (typeof wrapper === 'function') {\n return wrapper;\n } else {\n // If we find that the `__sentry_wrapped__` function is not a function at the time of accessing it, it means\n // that something messed with it. In that case we want to return the originally passed function.\n return fn;\n }\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch (e) {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n // Wrap the function itself\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped = function ( ...args) {\n try {\n // Also wrap arguments that are themselves functions\n const wrappedArguments = args.map(arg => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n captureException(ex);\n });\n\n throw ex;\n }\n } ;\n\n // Wrap the wrapped function in a proxy, to ensure any other properties of the original function remain available\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property ] = fn[property ];\n }\n }\n } catch {\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n }\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name');\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get() {\n return fn.name;\n },\n });\n }\n } catch {\n // This may throw if e.g. the descriptor does not exist, or a browser does not allow redefining `name`.\n // to save some bytes we simply try-catch this\n }\n\n return sentryWrapped;\n}\n\nexport { WINDOW, ignoreNextOnError, shouldIgnoreOnError, wrap };\n//# sourceMappingURL=helpers.js.map\n","import { addExceptionMechanism, resolvedSyncPromise, isErrorEvent, isDOMError, isDOMException, addExceptionTypeValue, isError, isPlainObject, isEvent, isParameterizedString, getClient, normalizeToSize, extractExceptionKeysForMessage } from '@sentry/core';\n\n/**\n * This function creates an exception from a JavaScript Error\n */\nfunction exceptionFromError(stackParser, ex) {\n // Get the frames first since Opera can lose the stack if we touch anything else first\n const frames = parseStackFrames(stackParser, ex);\n\n const exception = {\n type: extractType(ex),\n value: extractMessage(ex),\n };\n\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n if (exception.type === undefined && exception.value === '') {\n exception.value = 'Unrecoverable error caught';\n }\n\n return exception;\n}\n\nfunction eventFromPlainObject(\n stackParser,\n exception,\n syntheticException,\n isUnhandledRejection,\n) {\n const client = getClient();\n const normalizeDepth = client?.getOptions().normalizeDepth;\n\n // If we can, we extract an exception from the object properties\n const errorFromProp = getErrorPropertyFromObject(exception);\n\n const extra = {\n __serialized__: normalizeToSize(exception, normalizeDepth),\n };\n\n if (errorFromProp) {\n return {\n exception: {\n values: [exceptionFromError(stackParser, errorFromProp)],\n },\n extra,\n };\n }\n\n const event = {\n exception: {\n values: [\n {\n type: isEvent(exception) ? exception.constructor.name : isUnhandledRejection ? 'UnhandledRejection' : 'Error',\n value: getNonErrorObjectExceptionValue(exception, { isUnhandledRejection }),\n } ,\n ],\n },\n extra,\n } ;\n\n if (syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n // event.exception.values[0] has been set above\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception.values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\nfunction eventFromError(stackParser, ex) {\n return {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n}\n\n/** Parses stack frames from an error */\nfunction parseStackFrames(\n stackParser,\n ex,\n) {\n // Access and store the stacktrace property before doing ANYTHING\n // else to it because Opera is not very good at providing it\n // reliably in other circumstances.\n const stacktrace = ex.stacktrace || ex.stack || '';\n\n const skipLines = getSkipFirstStackStringLines(ex);\n const framesToPop = getPopFirstTopFrames(ex);\n\n try {\n return stackParser(stacktrace, skipLines, framesToPop);\n } catch (e) {\n // no-empty\n }\n\n return [];\n}\n\n// Based on our own mapping pattern - https://github.com/getsentry/sentry/blob/9f08305e09866c8bd6d0c24f5b0aabdd7dd6c59c/src/sentry/lang/javascript/errormapping.py#L83-L108\nconst reactMinifiedRegexp = /Minified React error #\\d+;/i;\n\n/**\n * Certain known React errors contain links that would be falsely\n * parsed as frames. This function check for these errors and\n * returns number of the stack string lines to skip.\n */\nfunction getSkipFirstStackStringLines(ex) {\n if (ex && reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n\n return 0;\n}\n\n/**\n * If error has `framesToPop` property, it means that the\n * creator tells us the first x frames will be useless\n * and should be discarded. Typically error from wrapper function\n * which don't point to the actual location in the developer's code.\n *\n * Example: https://github.com/zertosh/invariant/blob/master/invariant.js#L46\n */\nfunction getPopFirstTopFrames(ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n return 0;\n}\n\n// https://developer.mozilla.org/en-US/docs/WebAssembly/JavaScript_interface/Exception\n// @ts-expect-error - WebAssembly.Exception is a valid class\nfunction isWebAssemblyException(exception) {\n // Check for support\n // @ts-expect-error - WebAssembly.Exception is a valid class\n if (typeof WebAssembly !== 'undefined' && typeof WebAssembly.Exception !== 'undefined') {\n // @ts-expect-error - WebAssembly.Exception is a valid class\n return exception instanceof WebAssembly.Exception;\n } else {\n return false;\n }\n}\n\n/**\n * Extracts from errors what we use as the exception `type` in error events.\n *\n * Usually, this is the `name` property on Error objects but WASM errors need to be treated differently.\n */\nfunction extractType(ex) {\n const name = ex?.name;\n\n // The name for WebAssembly.Exception Errors needs to be extracted differently.\n // Context: https://github.com/getsentry/sentry-javascript/issues/13787\n if (!name && isWebAssemblyException(ex)) {\n // Emscripten sets array[type, message] to the \"message\" property on the WebAssembly.Exception object\n const hasTypeInMessage = ex.message && Array.isArray(ex.message) && ex.message.length == 2;\n return hasTypeInMessage ? ex.message[0] : 'WebAssembly.Exception';\n }\n\n return name;\n}\n\n/**\n * There are cases where stacktrace.message is an Event object\n * https://github.com/getsentry/sentry-javascript/issues/1949\n * In this specific case we try to extract stacktrace.message.error.message\n */\nfunction extractMessage(ex) {\n const message = ex?.message;\n\n if (isWebAssemblyException(ex)) {\n // For Node 18, Emscripten sets array[type, message] to the \"message\" property on the WebAssembly.Exception object\n if (Array.isArray(ex.message) && ex.message.length == 2) {\n return ex.message[1];\n }\n return 'wasm exception';\n }\n\n if (!message) {\n return 'No error message';\n }\n\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\n }\n\n return message;\n}\n\n/**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n * @hidden\n */\nfunction eventFromException(\n stackParser,\n exception,\n hint,\n attachStacktrace,\n) {\n const syntheticException = hint?.syntheticException || undefined;\n const event = eventFromUnknownInput(stackParser, exception, syntheticException, attachStacktrace);\n addExceptionMechanism(event); // defaults to { type: 'generic', handled: true }\n event.level = 'error';\n if (hint?.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nfunction eventFromMessage(\n stackParser,\n message,\n level = 'info',\n hint,\n attachStacktrace,\n) {\n const syntheticException = hint?.syntheticException || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint?.event_id) {\n event.event_id = hint.event_id;\n }\n return resolvedSyncPromise(event);\n}\n\n/**\n * @hidden\n */\nfunction eventFromUnknownInput(\n stackParser,\n exception,\n syntheticException,\n attachStacktrace,\n isUnhandledRejection,\n) {\n let event;\n\n if (isErrorEvent(exception ) && (exception ).error) {\n // If it is an ErrorEvent with `error` property, extract it to get actual Error\n const errorEvent = exception ;\n return eventFromError(stackParser, errorEvent.error );\n }\n\n // If it is a `DOMError` (which is a legacy API, but still supported in some browsers) then we just extract the name\n // and message, as it doesn't provide anything else. According to the spec, all `DOMExceptions` should also be\n // `Error`s, but that's not the case in IE11, so in that case we treat it the same as we do a `DOMError`.\n //\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMError\n // https://developer.mozilla.org/en-US/docs/Web/API/DOMException\n // https://webidl.spec.whatwg.org/#es-DOMException-specialness\n if (isDOMError(exception) || isDOMException(exception )) {\n const domException = exception ;\n\n if ('stack' in (exception )) {\n event = eventFromError(stackParser, exception );\n } else {\n const name = domException.name || (isDOMError(domException) ? 'DOMError' : 'DOMException');\n const message = domException.message ? `${name}: ${domException.message}` : name;\n event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n addExceptionTypeValue(event, message);\n }\n if ('code' in domException) {\n // eslint-disable-next-line deprecation/deprecation\n event.tags = { ...event.tags, 'DOMException.code': `${domException.code}` };\n }\n\n return event;\n }\n if (isError(exception)) {\n // we have a real Error object, do nothing\n return eventFromError(stackParser, exception);\n }\n if (isPlainObject(exception) || isEvent(exception)) {\n // If it's a plain object or an instance of `Event` (the built-in JS kind, not this SDK's `Event` type), serialize\n // it manually. This will allow us to group events based on top-level keys which is much better than creating a new\n // group on any key/value change.\n const objectException = exception ;\n event = eventFromPlainObject(stackParser, objectException, syntheticException, isUnhandledRejection);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n return event;\n }\n\n // If none of previous checks were valid, then it means that it's not:\n // - an instance of DOMError\n // - an instance of DOMException\n // - an instance of Event\n // - an instance of Error\n // - a valid ErrorEvent (one with an error property)\n // - a plain Object\n //\n // So bail out and capture it as a simple message:\n event = eventFromString(stackParser, exception , syntheticException, attachStacktrace);\n addExceptionTypeValue(event, `${exception}`, undefined);\n addExceptionMechanism(event, {\n synthetic: true,\n });\n\n return event;\n}\n\nfunction eventFromString(\n stackParser,\n message,\n syntheticException,\n attachStacktrace,\n) {\n const event = {};\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: message, stacktrace: { frames } }],\n };\n }\n addExceptionMechanism(event, { synthetic: true });\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n\nfunction getNonErrorObjectExceptionValue(\n exception,\n { isUnhandledRejection },\n) {\n const keys = extractExceptionKeysForMessage(exception);\n const captureType = isUnhandledRejection ? 'promise rejection' : 'exception';\n\n // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n // We still want to try to get a decent message for these cases\n if (isErrorEvent(exception)) {\n return `Event \\`ErrorEvent\\` captured as ${captureType} with message \\`${exception.message}\\``;\n }\n\n if (isEvent(exception)) {\n const className = getObjectClassName(exception);\n return `Event \\`${className}\\` (type=${exception.type}) captured as ${captureType}`;\n }\n\n return `Object captured as ${captureType} with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj) {\n try {\n const prototype = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch (e) {\n // ignore errors here\n }\n}\n\n/** If a plain object has a property that is an `Error`, return this error. */\nfunction getErrorPropertyFromObject(obj) {\n for (const prop in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n const value = obj[prop];\n if (value instanceof Error) {\n return value;\n }\n }\n }\n\n return undefined;\n}\n\nexport { eventFromException, eventFromMessage, eventFromUnknownInput, exceptionFromError, extractMessage, extractType };\n//# sourceMappingURL=eventbuilder.js.map\n","import { Client, getSDKSource, applySdkMetadata, addAutoIpAddressToUser, addAutoIpAddressToSession } from '@sentry/core';\nimport { eventFromException, eventFromMessage } from './eventbuilder.js';\nimport { WINDOW } from './helpers.js';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/core Options for more information.\n */\n\n/**\n * The Sentry Browser SDK Client.\n *\n * @see BrowserOptions for documentation on configuration options.\n * @see SentryClient for usage documentation.\n */\nclass BrowserClient extends Client {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n constructor(options) {\n const opts = {\n // We default this to true, as it is the safer scenario\n parentSpanIsAlwaysRootSpan: true,\n ...options,\n };\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n applySdkMetadata(opts, 'browser', ['browser'], sdkSource);\n\n super(opts);\n\n if (opts.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\n }\n\n if (this._options.sendDefaultPii) {\n this.on('postprocessEvent', addAutoIpAddressToUser);\n this.on('beforeSendSession', addAutoIpAddressToSession);\n }\n }\n\n /**\n * @inheritDoc\n */\n eventFromException(exception, hint) {\n return eventFromException(this._options.stackParser, exception, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n eventFromMessage(\n message,\n level = 'info',\n hint,\n ) {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * @inheritDoc\n */\n _prepareEvent(\n event,\n hint,\n currentScope,\n isolationScope,\n ) {\n event.platform = event.platform || 'javascript';\n\n return super._prepareEvent(event, hint, currentScope, isolationScope);\n }\n}\n\nexport { BrowserClient };\n//# sourceMappingURL=client.js.map\n","/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","const getRating = (value, thresholds) => {\n if (value > thresholds[1]) {\n return 'poor';\n }\n if (value > thresholds[0]) {\n return 'needs-improvement';\n }\n return 'good';\n};\n\nconst bindReporter = (\n callback,\n metric,\n thresholds,\n reportAllChanges,\n) => {\n let prevValue;\n let delta;\n return (forceReport) => {\n if (metric.value >= 0) {\n if (forceReport || reportAllChanges) {\n delta = metric.value - (prevValue || 0);\n\n // Report the metric if there's a non-zero delta or if no previous\n // value exists (which can happen in the case of the document becoming\n // hidden when the metric value is 0).\n // See: https://github.com/GoogleChrome/web-vitals/issues/14\n if (delta || prevValue === undefined) {\n prevValue = metric.value;\n metric.delta = delta;\n metric.rating = getRating(metric.value, thresholds);\n callback(metric);\n }\n }\n }\n };\n};\n\nexport { bindReporter };\n//# sourceMappingURL=bindReporter.js.map\n","import { GLOBAL_OBJ } from '@sentry/core';\n\nconst WINDOW = GLOBAL_OBJ\n\n;\n\nexport { WINDOW };\n//# sourceMappingURL=types.js.map\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Performantly generate a unique, 30-char string by combining a version\n * number, the current timestamp with a 13-digit number integer.\n * @return {string}\n */\nconst generateUniqueID = () => {\n return `v4-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n\nexport { generateUniqueID };\n//# sourceMappingURL=generateUniqueID.js.map\n","import { WINDOW } from '../../../types.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n// sentry-specific change:\n// add optional param to not check for responseStart (see comment below)\nconst getNavigationEntry = (checkResponseStart = true) => {\n const navigationEntry = WINDOW.performance?.getEntriesByType?.('navigation')[0];\n // Check to ensure the `responseStart` property is present and valid.\n // In some cases no value is reported by the browser (for\n // privacy/security reasons), and in other cases (bugs) the value is\n // negative or is larger than the current page time. Ignore these cases:\n // https://github.com/GoogleChrome/web-vitals/issues/137\n // https://github.com/GoogleChrome/web-vitals/issues/162\n // https://github.com/GoogleChrome/web-vitals/issues/275\n if (\n // sentry-specific change:\n // We don't want to check for responseStart for our own use of `getNavigationEntry`\n !checkResponseStart ||\n (navigationEntry && navigationEntry.responseStart > 0 && navigationEntry.responseStart < performance.now())\n ) {\n return navigationEntry;\n }\n};\n\nexport { getNavigationEntry };\n//# sourceMappingURL=getNavigationEntry.js.map\n","import { getNavigationEntry } from './getNavigationEntry.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nconst getActivationStart = () => {\n const navEntry = getNavigationEntry();\n return navEntry?.activationStart || 0;\n};\n\nexport { getActivationStart };\n//# sourceMappingURL=getActivationStart.js.map\n","import { WINDOW } from '../../../types.js';\nimport { generateUniqueID } from './generateUniqueID.js';\nimport { getActivationStart } from './getActivationStart.js';\nimport { getNavigationEntry } from './getNavigationEntry.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nconst initMetric = (name, value) => {\n const navEntry = getNavigationEntry();\n let navigationType = 'navigate';\n\n if (navEntry) {\n if (WINDOW.document?.prerendering || getActivationStart() > 0) {\n navigationType = 'prerender';\n } else if (WINDOW.document?.wasDiscarded) {\n navigationType = 'restore';\n } else if (navEntry.type) {\n navigationType = navEntry.type.replace(/_/g, '-') ;\n }\n }\n\n // Use `entries` type specific for the metric.\n const entries = [];\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good' , // If needed, will be updated when reported. `const` to keep the type from widening to `string`.\n delta: 0,\n entries,\n id: generateUniqueID(),\n navigationType,\n };\n};\n\nexport { initMetric };\n//# sourceMappingURL=initMetric.js.map\n","/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Takes a performance entry type and a callback function, and creates a\n * `PerformanceObserver` instance that will observe the specified entry type\n * with buffering enabled and call the callback _for each entry_.\n *\n * This function also feature-detects entry support and wraps the logic in a\n * try/catch to avoid errors in unsupporting browsers.\n */\nconst observe = (\n type,\n callback,\n opts,\n) => {\n try {\n if (PerformanceObserver.supportedEntryTypes.includes(type)) {\n const po = new PerformanceObserver(list => {\n // Delay by a microtask to workaround a bug in Safari where the\n // callback is invoked immediately, rather than in a separate task.\n // See: https://github.com/GoogleChrome/web-vitals/issues/277\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.resolve().then(() => {\n callback(list.getEntries() );\n });\n });\n po.observe(\n Object.assign(\n {\n type,\n buffered: true,\n },\n opts || {},\n ) ,\n );\n return po;\n }\n } catch (e) {\n // Do nothing.\n }\n return;\n};\n\nexport { observe };\n//# sourceMappingURL=observe.js.map\n","import { WINDOW } from '../../../types.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n// Sentry-specific change:\n// This function's logic was NOT updated to web-vitals 4.2.4 but we continue\n// to use the web-vitals 3.5.2 due to us having stricter browser support.\n// PR with context that made the changes: https://github.com/GoogleChrome/web-vitals/pull/442/files#r1530492402\n// The PR removed listening to the `pagehide` event, in favour of only listening to `visibilitychange` event.\n// This is \"more correct\" but some browsers we still support (Safari 12.1-14.0) don't fully support `visibilitychange`\n// or have known bugs w.r.t the `visibilitychange` event.\n// TODO (v9): If we decide to drop support for Safari 12.1-14.0, we can use the logic from web-vitals 4.2.4\n// In this case, we also need to update the integration tests that currently trigger the `pagehide` event to\n// simulate the page being hidden.\nconst onHidden = (cb) => {\n const onHiddenOrPageHide = (event) => {\n if (event.type === 'pagehide' || WINDOW.document?.visibilityState === 'hidden') {\n cb(event);\n }\n };\n\n if (WINDOW.document) {\n addEventListener('visibilitychange', onHiddenOrPageHide, true);\n // Some browsers have buggy implementations of visibilitychange,\n // so we use pagehide in addition, just to be safe.\n addEventListener('pagehide', onHiddenOrPageHide, true);\n }\n};\n\nexport { onHidden };\n//# sourceMappingURL=onHidden.js.map\n","/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst runOnce = (cb) => {\n let called = false;\n return () => {\n if (!called) {\n cb();\n called = true;\n }\n };\n};\n\nexport { runOnce };\n//# sourceMappingURL=runOnce.js.map\n","import { WINDOW } from '../../../types.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = () => {\n // If the document is hidden when this code runs, assume it was always\n // hidden and the page was loaded in the background, with the one exception\n // that visibility state is always 'hidden' during prerendering, so we have\n // to ignore that case until prerendering finishes (see: `prerenderingchange`\n // event logic below).\n return WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n};\n\nconst onVisibilityUpdate = (event) => {\n // If the document is 'hidden' and no previous hidden timestamp has been\n // set, update it based on the current event data.\n if (WINDOW.document.visibilityState === 'hidden' && firstHiddenTime > -1) {\n // If the event is a 'visibilitychange' event, it means the page was\n // visible prior to this change, so the event timestamp is the first\n // hidden time.\n // However, if the event is not a 'visibilitychange' event, then it must\n // be a 'prerenderingchange' event, and the fact that the document is\n // still 'hidden' from the above check means the tab was activated\n // in a background state and so has always been hidden.\n firstHiddenTime = event.type === 'visibilitychange' ? event.timeStamp : 0;\n\n // Remove all listeners now that a `firstHiddenTime` value has been set.\n removeChangeListeners();\n }\n};\n\nconst addChangeListeners = () => {\n addEventListener('visibilitychange', onVisibilityUpdate, true);\n // IMPORTANT: when a page is prerendering, its `visibilityState` is\n // 'hidden', so in order to account for cases where this module checks for\n // visibility during prerendering, an additional check after prerendering\n // completes is also required.\n addEventListener('prerenderingchange', onVisibilityUpdate, true);\n};\n\nconst removeChangeListeners = () => {\n removeEventListener('visibilitychange', onVisibilityUpdate, true);\n removeEventListener('prerenderingchange', onVisibilityUpdate, true);\n};\n\nconst getVisibilityWatcher = () => {\n if (WINDOW.document && firstHiddenTime < 0) {\n // If the document is hidden when this code runs, assume it was hidden\n // since navigation start. This isn't a perfect heuristic, but it's the\n // best we can do until an API is available to support querying past\n // visibilityState.\n firstHiddenTime = initHiddenTime();\n addChangeListeners();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n\nexport { getVisibilityWatcher };\n//# sourceMappingURL=getVisibilityWatcher.js.map\n","import { WINDOW } from '../../../types.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nconst whenActivated = (callback) => {\n if (WINDOW.document?.prerendering) {\n addEventListener('prerenderingchange', () => callback(), true);\n } else {\n callback();\n }\n};\n\nexport { whenActivated };\n//# sourceMappingURL=whenActivated.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getActivationStart } from './lib/getActivationStart.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { whenActivated } from './lib/whenActivated.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/** Thresholds for FCP. See https://web.dev/articles/fcp#what_is_a_good_fcp_score */\nconst FCPThresholds = [1800, 3000];\n\n/**\n * Calculates the [FCP](https://web.dev/articles/fcp) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `paint` performance entry used to determine the value. The reported\n * value is a `DOMHighResTimeStamp`.\n */\nconst onFCP = (onReport, opts = {}) => {\n whenActivated(() => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FCP');\n let report;\n\n const handleEntries = (entries) => {\n entries.forEach(entry => {\n if (entry.name === 'first-contentful-paint') {\n po.disconnect();\n\n // Only report if the page wasn't hidden prior to the first paint.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n // The activationStart reference is used because FCP should be\n // relative to page activation rather than navigation start if the\n // page was prerendered. But in cases where `activationStart` occurs\n // after the FCP, this time should be clamped at 0.\n metric.value = Math.max(entry.startTime - getActivationStart(), 0);\n metric.entries.push(entry);\n report(true);\n }\n }\n });\n };\n\n const po = observe('paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric, FCPThresholds, opts.reportAllChanges);\n }\n });\n};\n\nexport { FCPThresholds, onFCP };\n//# sourceMappingURL=onFCP.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\nimport { runOnce } from './lib/runOnce.js';\nimport { onFCP } from './onFCP.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/** Thresholds for CLS. See https://web.dev/articles/cls#what_is_a_good_cls_score */\nconst CLSThresholds = [0.1, 0.25];\n\n/**\n * Calculates the [CLS](https://web.dev/articles/cls) value for the current page and\n * calls the `callback` function once the value is ready to be reported, along\n * with all `layout-shift` performance entries that were used in the metric\n * value calculation. The reported value is a `double` (corresponding to a\n * [layout shift score](https://web.dev/articles/cls#layout_shift_score)).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** CLS should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nconst onCLS = (onReport, opts = {}) => {\n // Start monitoring FCP so we can only report CLS if FCP is also reported.\n // Note: this is done to match the current behavior of CrUX.\n onFCP(\n runOnce(() => {\n const metric = initMetric('CLS', 0);\n let report;\n\n let sessionValue = 0;\n let sessionEntries = [];\n\n const handleEntries = (entries) => {\n entries.forEach(entry => {\n // Only count layout shifts without recent user input.\n if (!entry.hadRecentInput) {\n const firstSessionEntry = sessionEntries[0];\n const lastSessionEntry = sessionEntries[sessionEntries.length - 1];\n\n // If the entry occurred less than 1 second after the previous entry\n // and less than 5 seconds after the first entry in the session,\n // include the entry in the current session. Otherwise, start a new\n // session.\n if (\n sessionValue &&\n firstSessionEntry &&\n lastSessionEntry &&\n entry.startTime - lastSessionEntry.startTime < 1000 &&\n entry.startTime - firstSessionEntry.startTime < 5000\n ) {\n sessionValue += entry.value;\n sessionEntries.push(entry);\n } else {\n sessionValue = entry.value;\n sessionEntries = [entry];\n }\n }\n });\n\n // If the current session value is larger than the current CLS value,\n // update CLS and the entries contributing to it.\n if (sessionValue > metric.value) {\n metric.value = sessionValue;\n metric.entries = sessionEntries;\n report();\n }\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric, CLSThresholds, opts.reportAllChanges);\n\n onHidden(() => {\n handleEntries(po.takeRecords() );\n report(true);\n });\n\n // Queue a task to report (if nothing else triggers a report first).\n // This allows CLS to be reported as soon as FCP fires when\n // `reportAllChanges` is true.\n setTimeout(report, 0);\n }\n }),\n );\n};\n\nexport { CLSThresholds, onCLS };\n//# sourceMappingURL=getCLS.js.map\n","import { bindReporter } from './lib/bindReporter.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\nimport { runOnce } from './lib/runOnce.js';\nimport { whenActivated } from './lib/whenActivated.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/** Thresholds for FID. See https://web.dev/articles/fid#what_is_a_good_fid_score */\nconst FIDThresholds = [100, 300];\n\n/**\n * Calculates the [FID](https://web.dev/articles/fid) value for the current page and\n * calls the `callback` function once the value is ready, along with the\n * relevant `first-input` performance entry used to determine the value. The\n * reported value is a `DOMHighResTimeStamp`.\n *\n * _**Important:** since FID is only reported after the user interacts with the\n * page, it's possible that it will not be reported for some page loads._\n */\nconst onFID = (onReport, opts = {}) => {\n whenActivated(() => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('FID');\n // eslint-disable-next-line prefer-const\n let report;\n\n const handleEntry = (entry) => {\n // Only report if the page wasn't hidden prior to the first input.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n metric.value = entry.processingStart - entry.startTime;\n metric.entries.push(entry);\n report(true);\n }\n };\n\n const handleEntries = (entries) => {\n (entries ).forEach(handleEntry);\n };\n\n const po = observe('first-input', handleEntries);\n\n report = bindReporter(onReport, metric, FIDThresholds, opts.reportAllChanges);\n\n if (po) {\n onHidden(\n runOnce(() => {\n handleEntries(po.takeRecords() );\n po.disconnect();\n }),\n );\n }\n });\n};\n\nexport { FIDThresholds, onFID };\n//# sourceMappingURL=getFID.js.map\n","import { observe } from '../observe.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\nlet interactionCountEstimate = 0;\nlet minKnownInteractionId = Infinity;\nlet maxKnownInteractionId = 0;\n\nconst updateEstimate = (entries) => {\n entries.forEach(e => {\n if (e.interactionId) {\n minKnownInteractionId = Math.min(minKnownInteractionId, e.interactionId);\n maxKnownInteractionId = Math.max(maxKnownInteractionId, e.interactionId);\n\n interactionCountEstimate = maxKnownInteractionId ? (maxKnownInteractionId - minKnownInteractionId) / 7 + 1 : 0;\n }\n });\n};\n\nlet po;\n\n/**\n * Returns the `interactionCount` value using the native API (if available)\n * or the polyfill estimate in this module.\n */\nconst getInteractionCount = () => {\n return po ? interactionCountEstimate : performance.interactionCount || 0;\n};\n\n/**\n * Feature detects native support or initializes the polyfill if needed.\n */\nconst initInteractionCountPolyfill = () => {\n if ('interactionCount' in performance || po) return;\n\n po = observe('event', updateEstimate, {\n type: 'event',\n buffered: true,\n durationThreshold: 0,\n } );\n};\n\nexport { getInteractionCount, initInteractionCountPolyfill };\n//# sourceMappingURL=interactionCountPolyfill.js.map\n","import { getInteractionCount } from './polyfills/interactionCountPolyfill.js';\n\n/*\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n// A list of longest interactions on the page (by latency) sorted so the\n// longest one is first. The list is at most MAX_INTERACTIONS_TO_CONSIDER long.\nconst longestInteractionList = [];\n\n// A mapping of longest interactions by their interaction ID.\n// This is used for faster lookup.\nconst longestInteractionMap = new Map();\n\n// The default `durationThreshold` used across this library for observing\n// `event` entries via PerformanceObserver.\nconst DEFAULT_DURATION_THRESHOLD = 40;\n\n// Used to store the interaction count after a bfcache restore, since p98\n// interaction latencies should only consider the current navigation.\nlet prevInteractionCount = 0;\n\n/**\n * Returns the interaction count since the last bfcache restore (or for the\n * full page lifecycle if there were no bfcache restores).\n */\nconst getInteractionCountForNavigation = () => {\n return getInteractionCount() - prevInteractionCount;\n};\n\n/**\n * Returns the estimated p98 longest interaction based on the stored\n * interaction candidates and the interaction count for the current page.\n */\nconst estimateP98LongestInteraction = () => {\n const candidateInteractionIndex = Math.min(\n longestInteractionList.length - 1,\n Math.floor(getInteractionCountForNavigation() / 50),\n );\n\n return longestInteractionList[candidateInteractionIndex];\n};\n\n// To prevent unnecessary memory usage on pages with lots of interactions,\n// store at most 10 of the longest interactions to consider as INP candidates.\nconst MAX_INTERACTIONS_TO_CONSIDER = 10;\n\n/**\n * A list of callback functions to run before each entry is processed.\n * Exposing this list allows the attribution build to hook into the\n * entry processing pipeline.\n */\nconst entryPreProcessingCallbacks = [];\n\n/**\n * Takes a performance entry and adds it to the list of worst interactions\n * if its duration is long enough to make it among the worst. If the\n * entry is part of an existing interaction, it is merged and the latency\n * and entries list is updated as needed.\n */\nconst processInteractionEntry = (entry) => {\n entryPreProcessingCallbacks.forEach(cb => cb(entry));\n\n // Skip further processing for entries that cannot be INP candidates.\n if (!(entry.interactionId || entry.entryType === 'first-input')) return;\n\n // The least-long of the 10 longest interactions.\n const minLongestInteraction = longestInteractionList[longestInteractionList.length - 1];\n\n const existingInteraction = longestInteractionMap.get(entry.interactionId);\n\n // Only process the entry if it's possibly one of the ten longest,\n // or if it's part of an existing interaction.\n if (\n existingInteraction ||\n longestInteractionList.length < MAX_INTERACTIONS_TO_CONSIDER ||\n (minLongestInteraction && entry.duration > minLongestInteraction.latency)\n ) {\n // If the interaction already exists, update it. Otherwise create one.\n if (existingInteraction) {\n // If the new entry has a longer duration, replace the old entries,\n // otherwise add to the array.\n if (entry.duration > existingInteraction.latency) {\n existingInteraction.entries = [entry];\n existingInteraction.latency = entry.duration;\n } else if (\n entry.duration === existingInteraction.latency &&\n entry.startTime === existingInteraction.entries[0]?.startTime\n ) {\n existingInteraction.entries.push(entry);\n }\n } else {\n const interaction = {\n id: entry.interactionId,\n latency: entry.duration,\n entries: [entry],\n };\n longestInteractionMap.set(interaction.id, interaction);\n longestInteractionList.push(interaction);\n }\n\n // Sort the entries by latency (descending) and keep only the top ten.\n longestInteractionList.sort((a, b) => b.latency - a.latency);\n if (longestInteractionList.length > MAX_INTERACTIONS_TO_CONSIDER) {\n longestInteractionList.splice(MAX_INTERACTIONS_TO_CONSIDER).forEach(i => longestInteractionMap.delete(i.id));\n }\n }\n};\n\nexport { DEFAULT_DURATION_THRESHOLD, entryPreProcessingCallbacks, estimateP98LongestInteraction, longestInteractionList, longestInteractionMap, processInteractionEntry };\n//# sourceMappingURL=interactions.js.map\n","import { WINDOW } from '../../../types.js';\nimport { onHidden } from './onHidden.js';\nimport { runOnce } from './runOnce.js';\n\n/*\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/**\n * Runs the passed callback during the next idle period, or immediately\n * if the browser's visibility state is (or becomes) hidden.\n */\nconst whenIdle = (cb) => {\n const rIC = WINDOW.requestIdleCallback || WINDOW.setTimeout;\n\n let handle = -1;\n // eslint-disable-next-line no-param-reassign\n cb = runOnce(cb) ;\n // If the document is hidden, run the callback immediately, otherwise\n // race an idle callback with the next `visibilitychange` event.\n if (WINDOW.document?.visibilityState === 'hidden') {\n cb();\n } else {\n handle = rIC(cb);\n onHidden(cb);\n }\n return handle;\n};\n\nexport { whenIdle };\n//# sourceMappingURL=whenIdle.js.map\n","import { WINDOW } from '../../types.js';\nimport { bindReporter } from './lib/bindReporter.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { DEFAULT_DURATION_THRESHOLD, processInteractionEntry, estimateP98LongestInteraction } from './lib/interactions.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\nimport { initInteractionCountPolyfill } from './lib/polyfills/interactionCountPolyfill.js';\nimport { whenActivated } from './lib/whenActivated.js';\nimport { whenIdle } from './lib/whenIdle.js';\n\n/*\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/** Thresholds for INP. See https://web.dev/articles/inp#what_is_a_good_inp_score */\nconst INPThresholds = [200, 500];\n\n/**\n * Calculates the [INP](https://web.dev/articles/inp) value for the current\n * page and calls the `callback` function once the value is ready, along with\n * the `event` performance entries reported for that interaction. The reported\n * value is a `DOMHighResTimeStamp`.\n *\n * A custom `durationThreshold` configuration option can optionally be passed to\n * control what `event-timing` entries are considered for INP reporting. The\n * default threshold is `40`, which means INP scores of less than 40 are\n * reported as 0. Note that this will not affect your 75th percentile INP value\n * unless that value is also less than 40 (well below the recommended\n * [good](https://web.dev/articles/inp#what_is_a_good_inp_score) threshold).\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called as soon as the value is initially\n * determined as well as any time the value changes throughout the page\n * lifespan.\n *\n * _**Important:** INP should be continually monitored for changes throughout\n * the entire lifespan of a page—including if the user returns to the page after\n * it's been hidden/backgrounded. However, since browsers often [will not fire\n * additional callbacks once the user has backgrounded a\n * page](https://developer.chrome.com/blog/page-lifecycle-api/#advice-hidden),\n * `callback` is always called when the page's visibility state changes to\n * hidden. As a result, the `callback` function might be called multiple times\n * during the same page load._\n */\nconst onINP = (onReport, opts = {}) => {\n // Return if the browser doesn't support all APIs needed to measure INP.\n if (!('PerformanceEventTiming' in WINDOW && 'interactionId' in PerformanceEventTiming.prototype)) {\n return;\n }\n\n whenActivated(() => {\n // TODO(philipwalton): remove once the polyfill is no longer needed.\n initInteractionCountPolyfill();\n\n const metric = initMetric('INP');\n // eslint-disable-next-line prefer-const\n let report;\n\n const handleEntries = (entries) => {\n // Queue the `handleEntries()` callback in the next idle task.\n // This is needed to increase the chances that all event entries that\n // occurred between the user interaction and the next paint\n // have been dispatched. Note: there is currently an experiment\n // running in Chrome (EventTimingKeypressAndCompositionInteractionId)\n // 123+ that if rolled out fully may make this no longer necessary.\n whenIdle(() => {\n entries.forEach(processInteractionEntry);\n\n const inp = estimateP98LongestInteraction();\n\n if (inp && inp.latency !== metric.value) {\n metric.value = inp.latency;\n metric.entries = inp.entries;\n report();\n }\n });\n };\n\n const po = observe('event', handleEntries, {\n // Event Timing entries have their durations rounded to the nearest 8ms,\n // so a duration of 40ms would be any event that spans 2.5 or more frames\n // at 60Hz. This threshold is chosen to strike a balance between usefulness\n // and performance. Running this callback for any interaction that spans\n // just one or two frames is likely not worth the insight that could be\n // gained.\n durationThreshold: opts.durationThreshold != null ? opts.durationThreshold : DEFAULT_DURATION_THRESHOLD,\n });\n\n report = bindReporter(onReport, metric, INPThresholds, opts.reportAllChanges);\n\n if (po) {\n // Also observe entries of type `first-input`. This is useful in cases\n // where the first interaction is less than the `durationThreshold`.\n po.observe({ type: 'first-input', buffered: true });\n\n onHidden(() => {\n handleEntries(po.takeRecords() );\n report(true);\n });\n }\n });\n};\n\nexport { INPThresholds, onINP };\n//# sourceMappingURL=getINP.js.map\n","import { WINDOW } from '../../types.js';\nimport { bindReporter } from './lib/bindReporter.js';\nimport { getActivationStart } from './lib/getActivationStart.js';\nimport { getVisibilityWatcher } from './lib/getVisibilityWatcher.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { observe } from './lib/observe.js';\nimport { onHidden } from './lib/onHidden.js';\nimport { runOnce } from './lib/runOnce.js';\nimport { whenActivated } from './lib/whenActivated.js';\nimport { whenIdle } from './lib/whenIdle.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/** Thresholds for LCP. See https://web.dev/articles/lcp#what_is_a_good_lcp_score */\nconst LCPThresholds = [2500, 4000];\n\nconst reportedMetricIDs = {};\n\n/**\n * Calculates the [LCP](https://web.dev/articles/lcp) value for the current page and\n * calls the `callback` function once the value is ready (along with the\n * relevant `largest-contentful-paint` performance entry used to determine the\n * value). The reported value is a `DOMHighResTimeStamp`.\n *\n * If the `reportAllChanges` configuration option is set to `true`, the\n * `callback` function will be called any time a new `largest-contentful-paint`\n * performance entry is dispatched, or once the final value of the metric has\n * been determined.\n */\nconst onLCP = (onReport, opts = {}) => {\n whenActivated(() => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report;\n\n const handleEntries = (entries) => {\n // If reportAllChanges is set then call this function for each entry,\n // otherwise only consider the last one.\n if (!opts.reportAllChanges) {\n // eslint-disable-next-line no-param-reassign\n entries = entries.slice(-1);\n }\n\n entries.forEach(entry => {\n // Only report if the page wasn't hidden prior to LCP.\n if (entry.startTime < visibilityWatcher.firstHiddenTime) {\n // The startTime attribute returns the value of the renderTime if it is\n // not 0, and the value of the loadTime otherwise. The activationStart\n // reference is used because LCP should be relative to page activation\n // rather than navigation start if the page was pre-rendered. But in cases\n // where `activationStart` occurs after the LCP, this time should be\n // clamped at 0.\n metric.value = Math.max(entry.startTime - getActivationStart(), 0);\n metric.entries = [entry];\n report();\n }\n });\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric, LCPThresholds, opts.reportAllChanges);\n\n const stopListening = runOnce(() => {\n if (!reportedMetricIDs[metric.id]) {\n handleEntries(po.takeRecords() );\n po.disconnect();\n reportedMetricIDs[metric.id] = true;\n report(true);\n }\n });\n\n // Stop listening after input. Note: while scrolling is an input that\n // stops LCP observation, it's unreliable since it can be programmatically\n // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75\n ['keydown', 'click'].forEach(type => {\n // Wrap in a setTimeout so the callback is run in a separate task\n // to avoid extending the keyboard/click handler to reduce INP impact\n // https://github.com/GoogleChrome/web-vitals/issues/383\n if (WINDOW.document) {\n addEventListener(type, () => whenIdle(stopListening ), {\n once: true,\n capture: true,\n });\n }\n });\n\n onHidden(stopListening);\n }\n });\n};\n\nexport { LCPThresholds, onLCP };\n//# sourceMappingURL=getLCP.js.map\n","import { WINDOW } from '../../types.js';\nimport { bindReporter } from './lib/bindReporter.js';\nimport { getActivationStart } from './lib/getActivationStart.js';\nimport { getNavigationEntry } from './lib/getNavigationEntry.js';\nimport { initMetric } from './lib/initMetric.js';\nimport { whenActivated } from './lib/whenActivated.js';\n\n/*\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n\n/** Thresholds for TTFB. See https://web.dev/articles/ttfb#what_is_a_good_ttfb_score */\nconst TTFBThresholds = [800, 1800];\n\n/**\n * Runs in the next task after the page is done loading and/or prerendering.\n * @param callback\n */\nconst whenReady = (callback) => {\n if (WINDOW.document?.prerendering) {\n whenActivated(() => whenReady(callback));\n } else if (WINDOW.document?.readyState !== 'complete') {\n addEventListener('load', () => whenReady(callback), true);\n } else {\n // Queue a task so the callback runs after `loadEventEnd`.\n setTimeout(callback, 0);\n }\n};\n\n/**\n * Calculates the [TTFB](https://web.dev/articles/ttfb) value for the\n * current page and calls the `callback` function once the page has loaded,\n * along with the relevant `navigation` performance entry used to determine the\n * value. The reported value is a `DOMHighResTimeStamp`.\n *\n * Note, this function waits until after the page is loaded to call `callback`\n * in order to ensure all properties of the `navigation` entry are populated.\n * This is useful if you want to report on other metrics exposed by the\n * [Navigation Timing API](https://w3c.github.io/navigation-timing/). For\n * example, the TTFB metric starts from the page's [time\n * origin](https://www.w3.org/TR/hr-time-2/#sec-time-origin), which means it\n * includes time spent on DNS lookup, connection negotiation, network latency,\n * and server processing time.\n */\nconst onTTFB = (onReport, opts = {}) => {\n const metric = initMetric('TTFB');\n const report = bindReporter(onReport, metric, TTFBThresholds, opts.reportAllChanges);\n\n whenReady(() => {\n const navigationEntry = getNavigationEntry();\n\n if (navigationEntry) {\n // The activationStart reference is used because TTFB should be\n // relative to page activation rather than navigation start if the\n // page was prerendered. But in cases where `activationStart` occurs\n // after the first byte is received, this time should be clamped at 0.\n metric.value = Math.max(navigationEntry.responseStart - getActivationStart(), 0);\n\n metric.entries = [navigationEntry];\n report(true);\n }\n });\n};\n\nexport { TTFBThresholds, onTTFB };\n//# sourceMappingURL=onTTFB.js.map\n","import { logger, getFunctionName } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { onCLS } from './web-vitals/getCLS.js';\nimport { onFID } from './web-vitals/getFID.js';\nimport { onINP } from './web-vitals/getINP.js';\nimport { onLCP } from './web-vitals/getLCP.js';\nimport { observe } from './web-vitals/lib/observe.js';\nimport { onTTFB } from './web-vitals/onTTFB.js';\n\nconst handlers = {};\nconst instrumented = {};\n\nlet _previousCls;\nlet _previousFid;\nlet _previousLcp;\nlet _previousTtfb;\nlet _previousInp;\n\n/**\n * Add a callback that will be triggered when a CLS metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for CLS when the cleanup callback is called.\n * This will lead to the CLS being finalized and frozen.\n */\nfunction addClsInstrumentationHandler(\n callback,\n stopOnCallback = false,\n) {\n return addMetricObserver('cls', callback, instrumentCls, _previousCls, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a LCP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n *\n * Pass `stopOnCallback = true` to stop listening for LCP when the cleanup callback is called.\n * This will lead to the LCP being finalized and frozen.\n */\nfunction addLcpInstrumentationHandler(\n callback,\n stopOnCallback = false,\n) {\n return addMetricObserver('lcp', callback, instrumentLcp, _previousLcp, stopOnCallback);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nfunction addFidInstrumentationHandler(callback) {\n return addMetricObserver('fid', callback, instrumentFid, _previousFid);\n}\n\n/**\n * Add a callback that will be triggered when a FID metric is available.\n */\nfunction addTtfbInstrumentationHandler(callback) {\n return addMetricObserver('ttfb', callback, instrumentTtfb, _previousTtfb);\n}\n\n/**\n * Add a callback that will be triggered when a INP metric is available.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nfunction addInpInstrumentationHandler(\n callback,\n) {\n return addMetricObserver('inp', callback, instrumentInp, _previousInp);\n}\n\n/**\n * Add a callback that will be triggered when a performance observer is triggered,\n * and receives the entries of the observer.\n * Returns a cleanup callback which can be called to remove the instrumentation handler.\n */\nfunction addPerformanceInstrumentationHandler(\n type,\n callback,\n) {\n addHandler(type, callback);\n\n if (!instrumented[type]) {\n instrumentPerformanceObserver(type);\n instrumented[type] = true;\n }\n\n return getCleanupCallback(type, callback);\n}\n\n/** Trigger all handlers of a given type. */\nfunction triggerHandlers(type, data) {\n const typeHandlers = handlers[type];\n\n if (!typeHandlers?.length) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nfunction instrumentCls() {\n return onCLS(\n metric => {\n triggerHandlers('cls', {\n metric,\n });\n _previousCls = metric;\n },\n // We want the callback to be called whenever the CLS value updates.\n // By default, the callback is only called when the tab goes to the background.\n { reportAllChanges: true },\n );\n}\n\nfunction instrumentFid() {\n return onFID(metric => {\n triggerHandlers('fid', {\n metric,\n });\n _previousFid = metric;\n });\n}\n\nfunction instrumentLcp() {\n return onLCP(\n metric => {\n triggerHandlers('lcp', {\n metric,\n });\n _previousLcp = metric;\n },\n // We want the callback to be called whenever the LCP value updates.\n // By default, the callback is only called when the tab goes to the background.\n { reportAllChanges: true },\n );\n}\n\nfunction instrumentTtfb() {\n return onTTFB(metric => {\n triggerHandlers('ttfb', {\n metric,\n });\n _previousTtfb = metric;\n });\n}\n\nfunction instrumentInp() {\n return onINP(metric => {\n triggerHandlers('inp', {\n metric,\n });\n _previousInp = metric;\n });\n}\n\nfunction addMetricObserver(\n type,\n callback,\n instrumentFn,\n previousValue,\n stopOnCallback = false,\n) {\n addHandler(type, callback);\n\n let stopListening;\n\n if (!instrumented[type]) {\n stopListening = instrumentFn();\n instrumented[type] = true;\n }\n\n if (previousValue) {\n callback({ metric: previousValue });\n }\n\n return getCleanupCallback(type, callback, stopOnCallback ? stopListening : undefined);\n}\n\nfunction instrumentPerformanceObserver(type) {\n const options = {};\n\n // Special per-type options we want to use\n if (type === 'event') {\n options.durationThreshold = 0;\n }\n\n observe(\n type,\n entries => {\n triggerHandlers(type, { entries });\n },\n options,\n );\n}\n\nfunction addHandler(type, handler) {\n handlers[type] = handlers[type] || [];\n (handlers[type] ).push(handler);\n}\n\n// Get a callback which can be called to remove the instrumentation handler\nfunction getCleanupCallback(\n type,\n callback,\n stopListening,\n) {\n return () => {\n if (stopListening) {\n stopListening();\n }\n\n const typeHandlers = handlers[type];\n\n if (!typeHandlers) {\n return;\n }\n\n const index = typeHandlers.indexOf(callback);\n if (index !== -1) {\n typeHandlers.splice(index, 1);\n }\n };\n}\n\n/**\n * Check if a PerformanceEntry is a PerformanceEventTiming by checking for the `duration` property.\n */\nfunction isPerformanceEventTiming(entry) {\n return 'duration' in entry;\n}\n\nexport { addClsInstrumentationHandler, addFidInstrumentationHandler, addInpInstrumentationHandler, addLcpInstrumentationHandler, addPerformanceInstrumentationHandler, addTtfbInstrumentationHandler, isPerformanceEventTiming };\n//# sourceMappingURL=instrument.js.map\n","import { spanToJSON, withActiveSpan, startInactiveSpan, getClient, getCurrentScope } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\n/**\n * Checks if a given value is a valid measurement value.\n */\nfunction isMeasurementValue(value) {\n return typeof value === 'number' && isFinite(value);\n}\n\n/**\n * Helper function to start child on transactions. This function will make sure that the transaction will\n * use the start timestamp of the created child span if it is earlier than the transactions actual\n * start timestamp.\n */\nfunction startAndEndSpan(\n parentSpan,\n startTimeInSeconds,\n endTime,\n { ...ctx },\n) {\n const parentStartTime = spanToJSON(parentSpan).start_timestamp;\n if (parentStartTime && parentStartTime > startTimeInSeconds) {\n // We can only do this for SentrySpans...\n if (typeof (parentSpan ).updateStartTime === 'function') {\n (parentSpan ).updateStartTime(startTimeInSeconds);\n }\n }\n\n // The return value only exists for tests\n return withActiveSpan(parentSpan, () => {\n const span = startInactiveSpan({\n startTime: startTimeInSeconds,\n ...ctx,\n });\n\n if (span) {\n span.end(endTime);\n }\n\n return span;\n });\n}\n\n/**\n * Starts an inactive, standalone span used to send web vital values to Sentry.\n * DO NOT use this for arbitrary spans, as these spans require special handling\n * during ingestion to extract metrics.\n *\n * This function adds a bunch of attributes and data to the span that's shared\n * by all web vital standalone spans. However, you need to take care of adding\n * the actual web vital value as an event to the span. Also, you need to assign\n * a transaction name and some other values that are specific to the web vital.\n *\n * Ultimately, you also need to take care of ending the span to send it off.\n *\n * @param options\n *\n * @returns an inactive, standalone and NOT YET ended span\n */\nfunction startStandaloneWebVitalSpan(options) {\n const client = getClient();\n if (!client) {\n return;\n }\n\n const { name, transaction, attributes: passedAttributes, startTime } = options;\n\n const { release, environment, sendDefaultPii } = client.getOptions();\n // We need to get the replay, user, and activeTransaction from the current scope\n // so that we can associate replay id, profile id, and a user display to the span\n const replay = client.getIntegrationByName('Replay');\n const replayId = replay?.getReplayId();\n\n const scope = getCurrentScope();\n\n const user = scope.getUser();\n const userDisplay = user !== undefined ? user.email || user.id || user.ip_address : undefined;\n\n let profileId;\n try {\n // @ts-expect-error skip optional chaining to save bundle size with try catch\n profileId = scope.getScopeData().contexts.profile.profile_id;\n } catch {\n // do nothing\n }\n\n const attributes = {\n release,\n environment,\n\n user: userDisplay || undefined,\n profile_id: profileId || undefined,\n replay_id: replayId || undefined,\n\n transaction,\n\n // Web vital score calculation relies on the user agent to account for different\n // browsers setting different thresholds for what is considered a good/meh/bad value.\n // For example: Chrome vs. Chrome Mobile\n 'user_agent.original': WINDOW.navigator?.userAgent,\n\n // This tells Sentry to infer the IP address from the request\n 'client.address': sendDefaultPii ? '{{auto}}' : undefined,\n\n ...passedAttributes,\n };\n\n return startInactiveSpan({\n name,\n attributes,\n startTime,\n experimental: {\n standalone: true,\n },\n });\n}\n\n/** Get the browser performance API. */\nfunction getBrowserPerformanceAPI() {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n return WINDOW.addEventListener && WINDOW.performance;\n}\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time) {\n return time / 1000;\n}\n\n/**\n * Converts ALPN protocol ids to name and version.\n *\n * (https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids)\n * @param nextHopProtocol PerformanceResourceTiming.nextHopProtocol\n */\nfunction extractNetworkProtocol(nextHopProtocol) {\n let name = 'unknown';\n let version = 'unknown';\n let _name = '';\n for (const char of nextHopProtocol) {\n // http/1.1 etc.\n if (char === '/') {\n [name, version] = nextHopProtocol.split('/') ;\n break;\n }\n // h2, h3 etc.\n if (!isNaN(Number(char))) {\n name = _name === 'h' ? 'http' : _name;\n version = nextHopProtocol.split(_name)[1] ;\n break;\n }\n _name += char;\n }\n if (_name === nextHopProtocol) {\n // webrtc, ftp, etc.\n name = _name;\n }\n return { name, version };\n}\n\nexport { extractNetworkProtocol, getBrowserPerformanceAPI, isMeasurementValue, msToSec, startAndEndSpan, startStandaloneWebVitalSpan };\n//# sourceMappingURL=utils.js.map\n","import { getClient, getActiveSpan, getRootSpan, spanToJSON, logger, browserPerformanceTimeOrigin, getCurrentScope, htmlTreeAsString, dropUndefinedKeys, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { addClsInstrumentationHandler } from './instrument.js';\nimport { msToSec, startStandaloneWebVitalSpan } from './utils.js';\nimport { onHidden } from './web-vitals/lib/onHidden.js';\n\n/**\n * Starts tracking the Cumulative Layout Shift on the current page and collects the value once\n *\n * - the page visibility is hidden\n * - a navigation span is started (to stop CLS measurement for SPA soft navigations)\n *\n * Once either of these events triggers, the CLS value is sent as a standalone span and we stop\n * measuring CLS.\n */\nfunction trackClsAsStandaloneSpan() {\n let standaloneCLsValue = 0;\n let standaloneClsEntry;\n let pageloadSpanId;\n\n if (!supportsLayoutShift()) {\n return;\n }\n\n let sentSpan = false;\n function _collectClsOnce() {\n if (sentSpan) {\n return;\n }\n sentSpan = true;\n if (pageloadSpanId) {\n sendStandaloneClsSpan(standaloneCLsValue, standaloneClsEntry, pageloadSpanId);\n }\n cleanupClsHandler();\n }\n\n const cleanupClsHandler = addClsInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1] ;\n if (!entry) {\n return;\n }\n standaloneCLsValue = metric.value;\n standaloneClsEntry = entry;\n }, true);\n\n // use pagehide event from web-vitals\n onHidden(() => {\n _collectClsOnce();\n });\n\n // Since the call chain of this function is synchronous and evaluates before the SDK client is created,\n // we need to wait with subscribing to a client hook until the client is created. Therefore, we defer\n // to the next tick after the SDK setup.\n setTimeout(() => {\n const client = getClient();\n\n if (!client) {\n return;\n }\n\n const unsubscribeStartNavigation = client.on('startNavigationSpan', () => {\n _collectClsOnce();\n unsubscribeStartNavigation?.();\n });\n\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n const rootSpan = getRootSpan(activeSpan);\n const spanJSON = spanToJSON(rootSpan);\n if (spanJSON.op === 'pageload') {\n pageloadSpanId = rootSpan.spanContext().spanId;\n }\n }\n }, 0);\n}\n\nfunction sendStandaloneClsSpan(clsValue, entry, pageloadSpanId) {\n DEBUG_BUILD && logger.log(`Sending CLS span (${clsValue})`);\n\n const startTime = msToSec((browserPerformanceTimeOrigin() || 0) + (entry?.startTime || 0));\n const routeName = getCurrentScope().getScopeData().transactionName;\n\n const name = entry ? htmlTreeAsString(entry.sources[0]?.node) : 'Layout shift';\n\n const attributes = dropUndefinedKeys({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser.cls',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'ui.webvital.cls',\n [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: entry?.duration || 0,\n // attach the pageload span id to the CLS span so that we can link them in the UI\n 'sentry.pageload.span_id': pageloadSpanId,\n });\n\n const span = startStandaloneWebVitalSpan({\n name,\n transaction: routeName,\n attributes,\n startTime,\n });\n\n if (span) {\n span.addEvent('cls', {\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: '',\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: clsValue,\n });\n\n // LayoutShift performance entries always have a duration of 0, so we don't need to add `entry.duration` here\n // see: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry/duration\n span.end(startTime);\n }\n}\n\nfunction supportsLayoutShift() {\n try {\n return PerformanceObserver.supportedEntryTypes.includes('layout-shift');\n } catch {\n return false;\n }\n}\n\nexport { trackClsAsStandaloneSpan };\n//# sourceMappingURL=cls.js.map\n","import { browserPerformanceTimeOrigin, getActiveSpan, spanToJSON, setMeasurement, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, parseUrl, htmlTreeAsString, getComponentName } from '@sentry/core';\nimport { WINDOW } from '../types.js';\nimport { trackClsAsStandaloneSpan } from './cls.js';\nimport { addPerformanceInstrumentationHandler, addClsInstrumentationHandler, addLcpInstrumentationHandler, addFidInstrumentationHandler, addTtfbInstrumentationHandler } from './instrument.js';\nimport { getBrowserPerformanceAPI, msToSec, startAndEndSpan, extractNetworkProtocol, isMeasurementValue } from './utils.js';\nimport { getActivationStart } from './web-vitals/lib/getActivationStart.js';\nimport { getNavigationEntry } from './web-vitals/lib/getNavigationEntry.js';\nimport { getVisibilityWatcher } from './web-vitals/lib/getVisibilityWatcher.js';\n\nconst MAX_INT_AS_BYTES = 2147483647;\n\nlet _performanceCursor = 0;\n\nlet _measurements = {};\nlet _lcpEntry;\nlet _clsEntry;\n\n/**\n * Start tracking web vitals.\n * The callback returned by this function can be used to stop tracking & ensure all measurements are final & captured.\n *\n * @returns A function that forces web vitals collection\n */\nfunction startTrackingWebVitals({ recordClsStandaloneSpans }) {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin()) {\n // @ts-expect-error we want to make sure all of these are available, even if TS is sure they are\n if (performance.mark) {\n WINDOW.performance.mark('sentry-tracing-init');\n }\n const fidCleanupCallback = _trackFID();\n const lcpCleanupCallback = _trackLCP();\n const ttfbCleanupCallback = _trackTtfb();\n const clsCleanupCallback = recordClsStandaloneSpans ? trackClsAsStandaloneSpan() : _trackCLS();\n\n return () => {\n fidCleanupCallback();\n lcpCleanupCallback();\n ttfbCleanupCallback();\n clsCleanupCallback?.();\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nfunction startTrackingLongTasks() {\n addPerformanceInstrumentationHandler('longtask', ({ entries }) => {\n const parent = getActiveSpan();\n if (!parent) {\n return;\n }\n\n const { op: parentOp, start_timestamp: parentStartTimestamp } = spanToJSON(parent);\n\n for (const entry of entries) {\n const startTime = msToSec((browserPerformanceTimeOrigin() ) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n if (parentOp === 'navigation' && parentStartTimestamp && startTime < parentStartTimestamp) {\n // Skip adding a span if the long task started before the navigation started.\n // `startAndEndSpan` will otherwise adjust the parent's start time to the span's start\n // time, potentially skewing the duration of the actual navigation as reported via our\n // routing instrumentations\n continue;\n }\n\n startAndEndSpan(parent, startTime, startTime + duration, {\n name: 'Main UI thread blocked',\n op: 'ui.long-task',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n },\n });\n }\n });\n}\n\n/**\n * Start tracking long animation frames.\n */\nfunction startTrackingLongAnimationFrames() {\n // NOTE: the current web-vitals version (3.5.2) does not support long-animation-frame, so\n // we directly observe `long-animation-frame` events instead of through the web-vitals\n // `observe` helper function.\n const observer = new PerformanceObserver(list => {\n const parent = getActiveSpan();\n if (!parent) {\n return;\n }\n for (const entry of list.getEntries() ) {\n if (!entry.scripts[0]) {\n continue;\n }\n\n const startTime = msToSec((browserPerformanceTimeOrigin() ) + entry.startTime);\n\n const { start_timestamp: parentStartTimestamp, op: parentOp } = spanToJSON(parent);\n\n if (parentOp === 'navigation' && parentStartTimestamp && startTime < parentStartTimestamp) {\n // Skip adding the span if the long animation frame started before the navigation started.\n // `startAndEndSpan` will otherwise adjust the parent's start time to the span's start\n // time, potentially skewing the duration of the actual navigation as reported via our\n // routing instrumentations\n continue;\n }\n const duration = msToSec(entry.duration);\n\n const attributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n };\n\n const initialScript = entry.scripts[0];\n const { invoker, invokerType, sourceURL, sourceFunctionName, sourceCharPosition } = initialScript;\n attributes['browser.script.invoker'] = invoker;\n attributes['browser.script.invoker_type'] = invokerType;\n if (sourceURL) {\n attributes['code.filepath'] = sourceURL;\n }\n if (sourceFunctionName) {\n attributes['code.function'] = sourceFunctionName;\n }\n if (sourceCharPosition !== -1) {\n attributes['browser.script.source_char_position'] = sourceCharPosition;\n }\n\n startAndEndSpan(parent, startTime, startTime + duration, {\n name: 'Main UI thread blocked',\n op: 'ui.long-animation-frame',\n attributes,\n });\n }\n });\n\n observer.observe({ type: 'long-animation-frame', buffered: true });\n}\n\n/**\n * Start tracking interaction events.\n */\nfunction startTrackingInteractions() {\n addPerformanceInstrumentationHandler('event', ({ entries }) => {\n const parent = getActiveSpan();\n if (!parent) {\n return;\n }\n for (const entry of entries) {\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin() ) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n const spanOptions = {\n name: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n startTime: startTime,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n },\n };\n\n const componentName = getComponentName(entry.target);\n if (componentName) {\n spanOptions.attributes['ui.component_name'] = componentName;\n }\n\n startAndEndSpan(parent, startTime, startTime + duration, spanOptions);\n }\n }\n });\n}\n\n/**\n * Starts tracking the Cumulative Layout Shift on the current page and collects the value and last entry\n * to the `_measurements` object which ultimately is applied to the pageload span's measurements.\n */\nfunction _trackCLS() {\n return addClsInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1] ;\n if (!entry) {\n return;\n }\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry;\n }, true);\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP() {\n return addLcpInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry ;\n }, true);\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID() {\n return addFidInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin() );\n const startTime = msToSec(entry.startTime);\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\nfunction _trackTtfb() {\n return addTtfbInstrumentationHandler(({ metric }) => {\n const entry = metric.entries[metric.entries.length - 1];\n if (!entry) {\n return;\n }\n\n _measurements['ttfb'] = { value: metric.value, unit: 'millisecond' };\n });\n}\n\n/** Add performance related spans to a transaction */\nfunction addPerformanceEntries(span, options) {\n const performance = getBrowserPerformanceAPI();\n const origin = browserPerformanceTimeOrigin();\n if (!performance?.getEntries || !origin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n const timeOrigin = msToSec(origin);\n\n const performanceEntries = performance.getEntries();\n\n const { op, start_timestamp: transactionStartTime } = spanToJSON(span);\n\n performanceEntries.slice(_performanceCursor).forEach(entry => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(\n // Inexplicably, Chrome sometimes emits a negative duration. We need to work around this.\n // There is a SO post attempting to explain this, but it leaves one with open questions: https://stackoverflow.com/questions/23191918/peformance-getentries-and-negative-duration-display\n // The way we clamp the value is probably not accurate, since we have observed this happen for things that may take a while to load, like for example the replay worker.\n // TODO: Investigate why this happens and how to properly mitigate. For now, this is a workaround to prevent transactions being dropped due to negative duration spans.\n Math.max(0, entry.duration),\n );\n\n if (op === 'navigation' && transactionStartTime && timeOrigin + startTime < transactionStartTime) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(span, entry , timeOrigin);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(span, entry, startTime, duration, timeOrigin);\n\n // capture web vitals\n const firstHidden = getVisibilityWatcher();\n // Only report if the page wasn't hidden prior to the web vital.\n const shouldRecord = entry.startTime < firstHidden.firstHiddenTime;\n\n if (entry.name === 'first-paint' && shouldRecord) {\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n _addResourceSpans(span, entry , entry.name, startTime, duration, timeOrigin);\n break;\n }\n // Ignore other entry types.\n }\n });\n\n _performanceCursor = Math.max(performanceEntries.length - 1, 0);\n\n _trackNavigator(span);\n\n // Measurements are only available for pageload transactions\n if (op === 'pageload') {\n _addTtfbRequestTimeToMeasurements(_measurements);\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n startAndEndSpan(span, fidMark.value, fidMark.value + msToSec(_measurements['fid'].value), {\n name: 'first input delay',\n op: 'ui.action',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n },\n });\n\n // Delete mark.fid as we don't want it to be part of final payload\n delete _measurements['mark.fid'];\n }\n\n // If FCP is not recorded we should not record the cls value\n // according to the new definition of CLS.\n // TODO: Check if the first condition is still necessary: `onCLS` already only fires once `onFCP` was called.\n if (!('fcp' in _measurements) || !options.recordClsOnPageloadSpan) {\n delete _measurements.cls;\n }\n\n Object.entries(_measurements).forEach(([measurementName, measurement]) => {\n setMeasurement(measurementName, measurement.value, measurement.unit);\n });\n\n // Set timeOrigin which denotes the timestamp which to base the LCP/FCP/FP/TTFB measurements on\n span.setAttribute('performance.timeOrigin', timeOrigin);\n\n // In prerendering scenarios, where a page might be prefetched and pre-rendered before the user clicks the link,\n // the navigation starts earlier than when the user clicks it. Web Vitals should always be based on the\n // user-perceived time, so they are not reported from the actual start of the navigation, but rather from the\n // time where the user actively started the navigation, for example by clicking a link.\n // This is user action is called \"activation\" and the time between navigation and activation is stored in\n // the `activationStart` attribute of the \"navigation\" PerformanceEntry.\n span.setAttribute('performance.activationStart', getActivationStart());\n\n _setWebVitalAttributes(span);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/**\n * Create measure related spans.\n * Exported only for tests.\n */\nfunction _addMeasureSpans(\n span,\n entry,\n startTime,\n duration,\n timeOrigin,\n) {\n const navEntry = getNavigationEntry(false);\n const requestTime = msToSec(navEntry ? navEntry.requestStart : 0);\n // Because performance.measure accepts arbitrary timestamps it can produce\n // spans that happen before the browser even makes a request for the page.\n //\n // An example of this is the automatically generated Next.js-before-hydration\n // spans created by the Next.js framework.\n //\n // To prevent this we will pin the start timestamp to the request start time\n // This does make duration inaccurate, so if this does happen, we will add\n // an attribute to the span\n const measureStartTimestamp = timeOrigin + Math.max(startTime, requestTime);\n const startTimeStamp = timeOrigin + startTime;\n const measureEndTimestamp = startTimeStamp + duration;\n\n const attributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.resource.browser.metrics',\n };\n\n if (measureStartTimestamp !== startTimeStamp) {\n attributes['sentry.browser.measure_happened_before_request'] = true;\n attributes['sentry.browser.measure_start_time'] = measureStartTimestamp;\n }\n\n startAndEndSpan(span, measureStartTimestamp, measureEndTimestamp, {\n name: entry.name ,\n op: entry.entryType ,\n attributes,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\nfunction _addNavigationSpans(span, entry, timeOrigin) {\n (['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'] ).forEach(event => {\n _addPerformanceNavigationTiming(span, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(span, entry, 'secureConnection', timeOrigin, 'TLS/SSL');\n _addPerformanceNavigationTiming(span, entry, 'fetch', timeOrigin, 'cache');\n _addPerformanceNavigationTiming(span, entry, 'domainLookup', timeOrigin, 'DNS');\n\n _addRequest(span, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n span,\n entry,\n event,\n timeOrigin,\n name = event,\n) {\n const eventEnd = _getEndPropertyNameForNavigationTiming(event) ;\n const end = entry[eventEnd];\n const start = entry[`${event}Start`];\n if (!start || !end) {\n return;\n }\n startAndEndSpan(span, timeOrigin + msToSec(start), timeOrigin + msToSec(end), {\n op: `browser.${name}`,\n name: entry.name,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n },\n });\n}\n\nfunction _getEndPropertyNameForNavigationTiming(event) {\n if (event === 'secureConnection') {\n return 'connectEnd';\n }\n if (event === 'fetch') {\n return 'domainLookupStart';\n }\n return `${event}End`;\n}\n\n/** Create request and response related spans */\nfunction _addRequest(span, entry, timeOrigin) {\n const requestStartTimestamp = timeOrigin + msToSec(entry.requestStart );\n const responseEndTimestamp = timeOrigin + msToSec(entry.responseEnd );\n const responseStartTimestamp = timeOrigin + msToSec(entry.responseStart );\n if (entry.responseEnd) {\n // It is possible that we are collecting these metrics when the page hasn't finished loading yet, for example when the HTML slowly streams in.\n // In this case, ie. when the document request hasn't finished yet, `entry.responseEnd` will be 0.\n // In order not to produce faulty spans, where the end timestamp is before the start timestamp, we will only collect\n // these spans when the responseEnd value is available. The backend (Relay) would drop the entire span if it contained faulty spans.\n startAndEndSpan(span, requestStartTimestamp, responseEndTimestamp, {\n op: 'browser.request',\n name: entry.name,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n },\n });\n\n startAndEndSpan(span, responseStartTimestamp, responseEndTimestamp, {\n op: 'browser.response',\n name: entry.name,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ui.browser.metrics',\n },\n });\n }\n}\n\n/**\n * Create resource-related spans.\n * Exported only for tests.\n */\nfunction _addResourceSpans(\n span,\n entry,\n resourceUrl,\n startTime,\n duration,\n timeOrigin,\n) {\n // we already instrument based on fetch and xhr, so we don't need to\n // duplicate spans here.\n if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') {\n return;\n }\n\n const parsedUrl = parseUrl(resourceUrl);\n\n const attributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.resource.browser.metrics',\n };\n setResourceEntrySizeData(attributes, entry, 'transferSize', 'http.response_transfer_size');\n setResourceEntrySizeData(attributes, entry, 'encodedBodySize', 'http.response_content_length');\n setResourceEntrySizeData(attributes, entry, 'decodedBodySize', 'http.decoded_response_content_length');\n\n // `deliveryType` is experimental and does not exist everywhere\n const deliveryType = (entry ).deliveryType;\n if (deliveryType != null) {\n attributes['http.response_delivery_type'] = deliveryType;\n }\n\n // Types do not reflect this property yet\n const renderBlockingStatus = (entry )\n .renderBlockingStatus;\n if (renderBlockingStatus) {\n attributes['resource.render_blocking_status'] = renderBlockingStatus;\n }\n\n if (parsedUrl.protocol) {\n attributes['url.scheme'] = parsedUrl.protocol.split(':').pop(); // the protocol returned by parseUrl includes a :, but OTEL spec does not, so we remove it.\n }\n\n if (parsedUrl.host) {\n attributes['server.address'] = parsedUrl.host;\n }\n\n attributes['url.same_origin'] = resourceUrl.includes(WINDOW.location.origin);\n\n const { name, version } = extractNetworkProtocol(entry.nextHopProtocol);\n attributes['network.protocol.name'] = name;\n attributes['network.protocol.version'] = version;\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n startAndEndSpan(span, startTimestamp, endTimestamp, {\n name: resourceUrl.replace(WINDOW.location.origin, ''),\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n attributes,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(span) {\n const navigator = WINDOW.navigator ;\n if (!navigator) {\n return;\n }\n\n // track network connectivity\n const connection = navigator.connection;\n if (connection) {\n if (connection.effectiveType) {\n span.setAttribute('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n span.setAttribute('connectionType', connection.type);\n }\n\n if (isMeasurementValue(connection.rtt)) {\n _measurements['connection.rtt'] = { value: connection.rtt, unit: 'millisecond' };\n }\n }\n\n if (isMeasurementValue(navigator.deviceMemory)) {\n span.setAttribute('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n span.setAttribute('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to span to allow debugging */\nfunction _setWebVitalAttributes(span) {\n if (_lcpEntry) {\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n span.setAttribute('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n span.setAttribute('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n span.setAttribute('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n if (_lcpEntry.loadTime != null) {\n // loadTime is the time of LCP that's related to receiving the LCP element response..\n span.setAttribute('lcp.loadTime', _lcpEntry.loadTime);\n }\n\n if (_lcpEntry.renderTime != null) {\n // renderTime is loadTime + rendering time\n // it's 0 if the LCP element is loaded from a 3rd party origin that doesn't send the\n // `Timing-Allow-Origin` header.\n span.setAttribute('lcp.renderTime', _lcpEntry.renderTime);\n }\n\n span.setAttribute('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry?.sources) {\n _clsEntry.sources.forEach((source, index) =>\n span.setAttribute(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n\nfunction setResourceEntrySizeData(\n attributes,\n entry,\n key,\n dataKey,\n) {\n const entryVal = entry[key];\n if (entryVal != null && entryVal < MAX_INT_AS_BYTES) {\n attributes[dataKey] = entryVal;\n }\n}\n\n/**\n * Add ttfb request time information to measurements.\n *\n * ttfb information is added via vendored web vitals library.\n */\nfunction _addTtfbRequestTimeToMeasurements(_measurements) {\n const navEntry = getNavigationEntry(false);\n if (!navEntry) {\n return;\n }\n\n const { responseStart, requestStart } = navEntry;\n\n if (requestStart <= responseStart) {\n _measurements['ttfb.requestTime'] = {\n value: responseStart - requestStart,\n unit: 'millisecond',\n };\n }\n}\n\nexport { _addMeasureSpans, _addResourceSpans, addPerformanceEntries, startTrackingInteractions, startTrackingLongAnimationFrames, startTrackingLongTasks, startTrackingWebVitals };\n//# sourceMappingURL=browserMetrics.js.map\n","import { addHandler, maybeInstrument, triggerHandlers, fill, addNonEnumerableProperty, uuid4 } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\nconst DEBOUNCE_DURATION = 1000;\n\nlet debounceTimerID;\nlet lastCapturedEventType;\nlet lastCapturedEventTargetId;\n\n/**\n * Add an instrumentation handler for when a click or a keypress happens.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addClickKeypressInstrumentationHandler(handler) {\n const type = 'dom';\n addHandler(type, handler);\n maybeInstrument(type, instrumentDOM);\n}\n\n/** Exported for tests only. */\nfunction instrumentDOM() {\n if (!WINDOW.document) {\n return;\n }\n\n // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom\n // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before\n // we instrument `addEventListener` so that we don't end up attaching this handler twice.\n const triggerDOMHandler = triggerHandlers.bind(null, 'dom');\n const globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true);\n WINDOW.document.addEventListener('click', globalDOMEventHandler, false);\n WINDOW.document.addEventListener('keypress', globalDOMEventHandler, false);\n\n // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled\n // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That\n // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler\n // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still\n // guaranteed to fire at least once.)\n ['EventTarget', 'Node'].forEach((target) => {\n const globalObject = WINDOW ;\n const proto = globalObject[target]?.prototype;\n\n // eslint-disable-next-line no-prototype-builtins\n if (!proto?.hasOwnProperty?.('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener) {\n return function ( type, listener, options) {\n if (type === 'click' || type == 'keypress') {\n try {\n const handlers = (this.__sentry_instrumentation_handlers__ =\n this.__sentry_instrumentation_handlers__ || {});\n const handlerForType = (handlers[type] = handlers[type] || { refCount: 0 });\n\n if (!handlerForType.handler) {\n const handler = makeDOMEventHandler(triggerDOMHandler);\n handlerForType.handler = handler;\n originalAddEventListener.call(this, type, handler, options);\n }\n\n handlerForType.refCount++;\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListeners` calls with no proper `this` context.\n }\n }\n\n return originalAddEventListener.call(this, type, listener, options);\n };\n });\n\n fill(\n proto,\n 'removeEventListener',\n function (originalRemoveEventListener) {\n return function ( type, listener, options) {\n if (type === 'click' || type == 'keypress') {\n try {\n const handlers = this.__sentry_instrumentation_handlers__ || {};\n const handlerForType = handlers[type];\n\n if (handlerForType) {\n handlerForType.refCount--;\n // If there are no longer any custom handlers of the current type on this element, we can remove ours, too.\n if (handlerForType.refCount <= 0) {\n originalRemoveEventListener.call(this, type, handlerForType.handler, options);\n handlerForType.handler = undefined;\n delete handlers[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete\n }\n\n // If there are no longer any custom handlers of any type on this element, cleanup everything.\n if (Object.keys(handlers).length === 0) {\n delete this.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListeners` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\n/**\n * Check whether the event is similar to the last captured one. For example, two click events on the same button.\n */\nfunction isSimilarToLastCapturedEvent(event) {\n // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress.\n if (event.type !== lastCapturedEventType) {\n return false;\n }\n\n try {\n // If both events have the same type, it's still possible that actions were performed on different targets.\n // e.g. 2 clicks on different buttons.\n if (!event.target || (event.target )._sentryId !== lastCapturedEventTargetId) {\n return false;\n }\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n }\n\n // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_\n // to which an event listener was attached), we treat them as the same action, as we want to capture\n // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box.\n return true;\n}\n\n/**\n * Decide whether an event should be captured.\n * @param event event to be captured\n */\nfunction shouldSkipDOMEvent(eventType, target) {\n // We are only interested in filtering `keypress` events for now.\n if (eventType !== 'keypress') {\n return false;\n }\n\n if (!target?.tagName) {\n return true;\n }\n\n // Only consider keypress events on actual input elements. This will disregard keypresses targeting body\n // e.g.tabbing through elements, hotkeys, etc.\n if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n */\nfunction makeDOMEventHandler(\n handler,\n globalListener = false,\n) {\n return (event) => {\n // It's possible this handler might trigger multiple times for the same\n // event (e.g. event propagation through node ancestors).\n // Ignore if we've already captured that event.\n if (!event || event['_sentryCaptured']) {\n return;\n }\n\n const target = getEventTarget(event);\n\n // We always want to skip _some_ events.\n if (shouldSkipDOMEvent(event.type, target)) {\n return;\n }\n\n // Mark event as \"seen\"\n addNonEnumerableProperty(event, '_sentryCaptured', true);\n\n if (target && !target._sentryId) {\n // Add UUID to event target so we can identify if\n addNonEnumerableProperty(target, '_sentryId', uuid4());\n }\n\n const name = event.type === 'keypress' ? 'input' : event.type;\n\n // If there is no last captured event, it means that we can safely capture the new event and store it for future comparisons.\n // If there is a last captured event, see if the new event is different enough to treat it as a unique one.\n // If that's the case, emit the previous event and store locally the newly-captured DOM event.\n if (!isSimilarToLastCapturedEvent(event)) {\n const handlerData = { event, name, global: globalListener };\n handler(handlerData);\n lastCapturedEventType = event.type;\n lastCapturedEventTargetId = target ? target._sentryId : undefined;\n }\n\n // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together.\n clearTimeout(debounceTimerID);\n debounceTimerID = WINDOW.setTimeout(() => {\n lastCapturedEventTargetId = undefined;\n lastCapturedEventType = undefined;\n }, DEBOUNCE_DURATION);\n };\n}\n\nfunction getEventTarget(event) {\n try {\n return event.target ;\n } catch (e) {\n // just accessing `target` property can throw an exception in some rare circumstances\n // see: https://github.com/getsentry/sentry-javascript/issues/838\n return null;\n }\n}\n\nexport { addClickKeypressInstrumentationHandler, instrumentDOM };\n//# sourceMappingURL=dom.js.map\n","import { addHandler, maybeInstrument, triggerHandlers, supportsHistory, fill } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\nlet lastHref;\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addHistoryInstrumentationHandler(handler) {\n const type = 'history';\n addHandler(type, handler);\n maybeInstrument(type, instrumentHistory);\n}\n\nfunction instrumentHistory() {\n // The `popstate` event may also be triggered on `pushState`, but it may not always reliably be emitted by the browser\n // Which is why we also monkey-patch methods below, in addition to this\n WINDOW.addEventListener('popstate', () => {\n const to = WINDOW.location.href;\n // keep track of the current URL state, as we always receive only the updated state\n const from = lastHref;\n lastHref = to;\n\n if (from === to) {\n return;\n }\n\n const handlerData = { from, to } ;\n triggerHandlers('history', handlerData);\n });\n\n // Just guard against this not being available, in weird environments\n if (!supportsHistory()) {\n return;\n }\n\n function historyReplacementFunction(originalHistoryFunction) {\n return function ( ...args) {\n const url = args.length > 2 ? args[2] : undefined;\n if (url) {\n // coerce to string (this is what pushState does)\n const from = lastHref;\n const to = String(url);\n // keep track of the current URL state, as we always receive only the updated state\n lastHref = to;\n\n if (from === to) {\n return;\n }\n\n const handlerData = { from, to } ;\n triggerHandlers('history', handlerData);\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nexport { addHistoryInstrumentationHandler };\n//# sourceMappingURL=history.js.map\n","import { isNativeFunction, logger } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { WINDOW } from './types.js';\n\n/**\n * We generally want to use window.fetch / window.setTimeout.\n * However, in some cases this may be wrapped (e.g. by Zone.js for Angular),\n * so we try to get an unpatched version of this from a sandboxed iframe.\n */\n\nconst cachedImplementations = {};\n\n/**\n * Get the native implementation of a browser function.\n *\n * This can be used to ensure we get an unwrapped version of a function, in cases where a wrapped function can lead to problems.\n *\n * The following methods can be retrieved:\n * - `setTimeout`: This can be wrapped by e.g. Angular, causing change detection to be triggered.\n * - `fetch`: This can be wrapped by e.g. ad-blockers, causing an infinite loop when a request is blocked.\n */\nfunction getNativeImplementation(\n name,\n) {\n const cached = cachedImplementations[name];\n if (cached) {\n return cached;\n }\n\n let impl = WINDOW[name] ;\n\n // Fast path to avoid DOM I/O\n if (isNativeFunction(impl)) {\n return (cachedImplementations[name] = impl.bind(WINDOW) );\n }\n\n const document = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow?.[name]) {\n impl = contentWindow[name] ;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n // Could not create sandbox iframe, just use window.xxx\n DEBUG_BUILD && logger.warn(`Could not create sandbox iframe for ${name} check, bailing to window.${name}: `, e);\n }\n }\n\n // Sanity check: This _should_ not happen, but if it does, we just skip caching...\n // This can happen e.g. in tests where fetch may not be available in the env, or similar.\n if (!impl) {\n return impl;\n }\n\n return (cachedImplementations[name] = impl.bind(WINDOW) );\n}\n\n/** Clear a cached implementation. */\nfunction clearCachedImplementation(name) {\n cachedImplementations[name] = undefined;\n}\n\n/**\n * A special usecase for incorrectly wrapped Fetch APIs in conjunction with ad-blockers.\n * Whenever someone wraps the Fetch API and returns the wrong promise chain,\n * this chain becomes orphaned and there is no possible way to capture it's rejections\n * other than allowing it bubble up to this very handler. eg.\n *\n * const f = window.fetch;\n * window.fetch = function () {\n * const p = f.apply(this, arguments);\n *\n * p.then(function() {\n * console.log('hi.');\n * });\n *\n * return p;\n * }\n *\n * `p.then(function () { ... })` is producing a completely separate promise chain,\n * however, what's returned is `p` - the result of original `fetch` call.\n *\n * This mean, that whenever we use the Fetch API to send our own requests, _and_\n * some ad-blocker blocks it, this orphaned chain will _always_ reject,\n * effectively causing another event to be captured.\n * This makes a whole process become an infinite loop, which we need to somehow\n * deal with, and break it in one way or another.\n *\n * To deal with this issue, we are making sure that we _always_ use the real\n * browser Fetch API, instead of relying on what `window.fetch` exposes.\n * The only downside to this would be missing our own requests as breadcrumbs,\n * but because we are already not doing this, it should be just fine.\n *\n * Possible failed fetch error messages per-browser:\n *\n * Chrome: Failed to fetch\n * Edge: Failed to Fetch\n * Firefox: NetworkError when attempting to fetch resource\n * Safari: resource blocked by content blocker\n */\nfunction fetch(...rest) {\n return getNativeImplementation('fetch')(...rest);\n}\n\n/**\n * Get an unwrapped `setTimeout` method.\n * This ensures that even if e.g. Angular wraps `setTimeout`, we get the native implementation,\n * avoiding triggering change detection.\n */\nfunction setTimeout(...rest) {\n return getNativeImplementation('setTimeout')(...rest);\n}\n\nexport { clearCachedImplementation, fetch, getNativeImplementation, setTimeout };\n//# sourceMappingURL=getNativeImplementation.js.map\n","import { addHandler, maybeInstrument, timestampInSeconds, isString, triggerHandlers } from '@sentry/core';\nimport { WINDOW } from '../types.js';\n\nconst SENTRY_XHR_DATA_KEY = '__sentry_xhr_v3__';\n\n/**\n * Add an instrumentation handler for when an XHR request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addXhrInstrumentationHandler(handler) {\n const type = 'xhr';\n addHandler(type, handler);\n maybeInstrument(type, instrumentXHR);\n}\n\n/** Exported only for tests. */\nfunction instrumentXHR() {\n if (!(WINDOW ).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n xhrproto.open = new Proxy(xhrproto.open, {\n apply(originalOpen, xhrOpenThisArg, xhrOpenArgArray) {\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your XHR call did not\n // have a stack trace. If you are using HttpClient integration,\n // this is the expected behavior, as we are using this virtual error to capture\n // the location of your XHR call, and group your HttpClient events accordingly.\n const virtualError = new Error();\n\n const startTimestamp = timestampInSeconds() * 1000;\n\n // open() should always be called with two or more arguments\n // But to be on the safe side, we actually validate this and bail out if we don't have a method & url\n const method = isString(xhrOpenArgArray[0]) ? xhrOpenArgArray[0].toUpperCase() : undefined;\n const url = parseUrl(xhrOpenArgArray[1]);\n\n if (!method || !url) {\n return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray);\n }\n\n xhrOpenThisArg[SENTRY_XHR_DATA_KEY] = {\n method,\n url,\n request_headers: {},\n };\n\n // if Sentry key appears in URL, don't capture it as a request\n if (method === 'POST' && url.match(/sentry_key/)) {\n xhrOpenThisArg.__sentry_own_request__ = true;\n }\n\n const onreadystatechangeHandler = () => {\n // For whatever reason, this is not the same instance here as from the outer method\n const xhrInfo = xhrOpenThisArg[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (xhrOpenThisArg.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = xhrOpenThisArg.status;\n } catch (e) {\n /* do nothing */\n }\n\n const handlerData = {\n endTimestamp: timestampInSeconds() * 1000,\n startTimestamp,\n xhr: xhrOpenThisArg,\n virtualError,\n };\n triggerHandlers('xhr', handlerData);\n }\n };\n\n if ('onreadystatechange' in xhrOpenThisArg && typeof xhrOpenThisArg.onreadystatechange === 'function') {\n xhrOpenThisArg.onreadystatechange = new Proxy(xhrOpenThisArg.onreadystatechange, {\n apply(originalOnreadystatechange, onreadystatechangeThisArg, onreadystatechangeArgArray) {\n onreadystatechangeHandler();\n return originalOnreadystatechange.apply(onreadystatechangeThisArg, onreadystatechangeArgArray);\n },\n });\n } else {\n xhrOpenThisArg.addEventListener('readystatechange', onreadystatechangeHandler);\n }\n\n // Intercepting `setRequestHeader` to access the request headers of XHR instance.\n // This will only work for user/library defined headers, not for the default/browser-assigned headers.\n // Request cookies are also unavailable for XHR, as `Cookie` header can't be defined by `setRequestHeader`.\n xhrOpenThisArg.setRequestHeader = new Proxy(xhrOpenThisArg.setRequestHeader, {\n apply(\n originalSetRequestHeader,\n setRequestHeaderThisArg,\n setRequestHeaderArgArray,\n ) {\n const [header, value] = setRequestHeaderArgArray;\n\n const xhrInfo = setRequestHeaderThisArg[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo && isString(header) && isString(value)) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return originalSetRequestHeader.apply(setRequestHeaderThisArg, setRequestHeaderArgArray);\n },\n });\n\n return originalOpen.apply(xhrOpenThisArg, xhrOpenArgArray);\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n xhrproto.send = new Proxy(xhrproto.send, {\n apply(originalSend, sendThisArg, sendArgArray) {\n const sentryXhrData = sendThisArg[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return originalSend.apply(sendThisArg, sendArgArray);\n }\n\n if (sendArgArray[0] !== undefined) {\n sentryXhrData.body = sendArgArray[0];\n }\n\n const handlerData = {\n startTimestamp: timestampInSeconds() * 1000,\n xhr: sendThisArg,\n };\n triggerHandlers('xhr', handlerData);\n\n return originalSend.apply(sendThisArg, sendArgArray);\n },\n });\n}\n\nfunction parseUrl(url) {\n if (isString(url)) {\n return url;\n }\n\n try {\n // url can be a string or URL\n // but since URL is not available in IE11, we do not check for it,\n // but simply assume it is an URL and return `toString()` from it (which returns the full URL)\n // If that fails, we just return undefined\n return (url ).toString();\n } catch {} // eslint-disable-line no-empty\n\n return undefined;\n}\n\nexport { SENTRY_XHR_DATA_KEY, addXhrInstrumentationHandler, instrumentXHR };\n//# sourceMappingURL=xhr.js.map\n","import { logger } from '@sentry/core';\nimport { DEBUG_BUILD } from './debug-build.js';\n\n/**\n * Serializes FormData.\n *\n * This is a bit simplified, but gives us a decent estimate.\n * This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'.\n *\n */\nfunction serializeFormData(formData) {\n // @ts-expect-error passing FormData to URLSearchParams actually works\n return new URLSearchParams(formData).toString();\n}\n\n/** Get the string representation of a body. */\nfunction getBodyString(body, _logger = logger) {\n try {\n if (typeof body === 'string') {\n return [body];\n }\n\n if (body instanceof URLSearchParams) {\n return [body.toString()];\n }\n\n if (body instanceof FormData) {\n return [serializeFormData(body)];\n }\n\n if (!body) {\n return [undefined];\n }\n } catch (error) {\n DEBUG_BUILD && _logger.error(error, 'Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && _logger.info('Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\n/**\n * Parses the fetch arguments to extract the request payload.\n *\n * We only support getting the body from the fetch options.\n */\nfunction getFetchRequestArgBody(fetchArgs = []) {\n if (fetchArgs.length !== 2 || typeof fetchArgs[1] !== 'object') {\n return undefined;\n }\n\n return (fetchArgs[1] ).body;\n}\n\nexport { getBodyString, getFetchRequestArgBody, serializeFormData };\n//# sourceMappingURL=networkUtils.js.map\n","import { browserPerformanceTimeOrigin, getActiveSpan, getRootSpan, spanToJSON, getCurrentScope, htmlTreeAsString, dropUndefinedKeys, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE } from '@sentry/core';\nimport { addInpInstrumentationHandler, addPerformanceInstrumentationHandler, isPerformanceEventTiming } from './instrument.js';\nimport { getBrowserPerformanceAPI, msToSec, startStandaloneWebVitalSpan } from './utils.js';\n\nconst LAST_INTERACTIONS = [];\nconst INTERACTIONS_SPAN_MAP = new Map();\n\n/**\n * Start tracking INP webvital events.\n */\nfunction startTrackingINP() {\n const performance = getBrowserPerformanceAPI();\n if (performance && browserPerformanceTimeOrigin()) {\n const inpCallback = _trackINP();\n\n return () => {\n inpCallback();\n };\n }\n\n return () => undefined;\n}\n\nconst INP_ENTRY_MAP = {\n click: 'click',\n pointerdown: 'click',\n pointerup: 'click',\n mousedown: 'click',\n mouseup: 'click',\n touchstart: 'click',\n touchend: 'click',\n mouseover: 'hover',\n mouseout: 'hover',\n mouseenter: 'hover',\n mouseleave: 'hover',\n pointerover: 'hover',\n pointerout: 'hover',\n pointerenter: 'hover',\n pointerleave: 'hover',\n dragstart: 'drag',\n dragend: 'drag',\n drag: 'drag',\n dragenter: 'drag',\n dragleave: 'drag',\n dragover: 'drag',\n drop: 'drag',\n keydown: 'press',\n keyup: 'press',\n keypress: 'press',\n input: 'press',\n};\n\n/** Starts tracking the Interaction to Next Paint on the current page. */\nfunction _trackINP() {\n return addInpInstrumentationHandler(({ metric }) => {\n if (metric.value == undefined) {\n return;\n }\n\n const entry = metric.entries.find(entry => entry.duration === metric.value && INP_ENTRY_MAP[entry.name]);\n\n if (!entry) {\n return;\n }\n\n const { interactionId } = entry;\n const interactionType = INP_ENTRY_MAP[entry.name];\n\n /** Build the INP span, create an envelope from the span, and then send the envelope */\n const startTime = msToSec((browserPerformanceTimeOrigin() ) + entry.startTime);\n const duration = msToSec(metric.value);\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan ? getRootSpan(activeSpan) : undefined;\n\n // We first try to lookup the span from our INTERACTIONS_SPAN_MAP,\n // where we cache the route per interactionId\n const cachedSpan = interactionId != null ? INTERACTIONS_SPAN_MAP.get(interactionId) : undefined;\n\n const spanToUse = cachedSpan || rootSpan;\n\n // Else, we try to use the active span.\n // Finally, we fall back to look at the transactionName on the scope\n const routeName = spanToUse ? spanToJSON(spanToUse).description : getCurrentScope().getScopeData().transactionName;\n\n const name = htmlTreeAsString(entry.target);\n const attributes = dropUndefinedKeys({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser.inp',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: `ui.interaction.${interactionType}`,\n [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: entry.duration,\n });\n\n const span = startStandaloneWebVitalSpan({\n name,\n transaction: routeName,\n attributes,\n startTime,\n });\n\n if (span) {\n span.addEvent('inp', {\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: 'millisecond',\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: metric.value,\n });\n\n span.end(startTime + duration);\n }\n });\n}\n\n/**\n * Register a listener to cache route information for INP interactions.\n */\nfunction registerInpInteractionListener() {\n const handleEntries = ({ entries }) => {\n const activeSpan = getActiveSpan();\n const activeRootSpan = activeSpan && getRootSpan(activeSpan);\n\n entries.forEach(entry => {\n if (!isPerformanceEventTiming(entry) || !activeRootSpan) {\n return;\n }\n\n const interactionId = entry.interactionId;\n if (interactionId == null) {\n return;\n }\n\n // If the interaction was already recorded before, nothing more to do\n if (INTERACTIONS_SPAN_MAP.has(interactionId)) {\n return;\n }\n\n // We keep max. 10 interactions in the list, then remove the oldest one & clean up\n if (LAST_INTERACTIONS.length > 10) {\n const last = LAST_INTERACTIONS.shift() ;\n INTERACTIONS_SPAN_MAP.delete(last);\n }\n\n // We add the interaction to the list of recorded interactions\n // and store the span for this interaction\n LAST_INTERACTIONS.push(interactionId);\n INTERACTIONS_SPAN_MAP.set(interactionId, activeRootSpan);\n });\n };\n\n addPerformanceInstrumentationHandler('event', handleEntries);\n addPerformanceInstrumentationHandler('first-input', handleEntries);\n}\n\nexport { registerInpInteractionListener, startTrackingINP };\n//# sourceMappingURL=inp.js.map\n","import { getNativeImplementation, clearCachedImplementation } from '@sentry-internal/browser-utils';\nimport { createTransport, rejectedSyncPromise } from '@sentry/core';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nfunction makeFetchTransport(\n options,\n nativeFetch = getNativeImplementation('fetch'),\n) {\n let pendingBodySize = 0;\n let pendingCount = 0;\n\n function makeRequest(request) {\n const requestSize = request.body.length;\n pendingBodySize += requestSize;\n pendingCount++;\n\n const requestOptions = {\n body: request.body,\n method: 'POST',\n referrerPolicy: 'strict-origin',\n headers: options.headers,\n // Outgoing requests are usually cancelled when navigating to a different page, causing a \"TypeError: Failed to\n // fetch\" error and sending a \"network_error\" client-outcome - in Chrome, the request status shows \"(cancelled)\".\n // The `keepalive` flag keeps outgoing requests alive, even when switching pages. We want this since we're\n // frequently sending events right before the user is switching pages (eg. when finishing navigation transactions).\n // Gotchas:\n // - `keepalive` isn't supported by Firefox\n // - As per spec (https://fetch.spec.whatwg.org/#http-network-or-cache-fetch):\n // If the sum of contentLength and inflightKeepaliveBytes is greater than 64 kibibytes, then return a network error.\n // We will therefore only activate the flag when we're below that limit.\n // There is also a limit of requests that can be open at the same time, so we also limit this to 15\n // See https://github.com/getsentry/sentry-javascript/pull/7553 for details\n keepalive: pendingBodySize <= 60000 && pendingCount < 15,\n ...options.fetchOptions,\n };\n\n if (!nativeFetch) {\n clearCachedImplementation('fetch');\n return rejectedSyncPromise('No fetch implementation available');\n }\n\n try {\n // TODO: This may need a `suppressTracing` call in the future when we switch the browser SDK to OTEL\n return nativeFetch(options.url, requestOptions).then(response => {\n pendingBodySize -= requestSize;\n pendingCount--;\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n } catch (e) {\n clearCachedImplementation('fetch');\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n\nexport { makeFetchTransport };\n//# sourceMappingURL=fetch.js.map\n","import { createStackParser, UNKNOWN_FUNCTION } from '@sentry/core';\n\n// This was originally forked from https://github.com/csnover/TraceKit, and was largely\n// re - written as part of raven - js.\n//\n// This code was later copied to the JavaScript mono - repo and further modified and\n// refactored over the years.\n\n\nconst OPERA10_PRIORITY = 10;\nconst OPERA11_PRIORITY = 20;\nconst CHROME_PRIORITY = 30;\nconst WINJS_PRIORITY = 40;\nconst GECKO_PRIORITY = 50;\n\nfunction createFrame(filename, func, lineno, colno) {\n const frame = {\n filename,\n function: func === '' ? UNKNOWN_FUNCTION : func,\n in_app: true, // All browser frames are considered in_app\n };\n\n if (lineno !== undefined) {\n frame.lineno = lineno;\n }\n\n if (colno !== undefined) {\n frame.colno = colno;\n }\n\n return frame;\n}\n\n// This regex matches frames that have no function name (ie. are at the top level of a module).\n// For example \"at http://localhost:5000//script.js:1:126\"\n// Frames _with_ function names usually look as follows: \"at commitLayoutEffects (react-dom.development.js:23426:1)\"\nconst chromeRegexNoFnName = /^\\s*at (\\S+?)(?::(\\d+))(?::(\\d+))\\s*$/i;\n\n// This regex matches all the frames that have a function name.\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\n\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\n// Chromium based browsers: Chrome, Brave, new Opera, new Edge\n// We cannot call this variable `chrome` because it can conflict with global `chrome` variable in certain environments\n// See: https://github.com/getsentry/sentry-javascript/issues/6880\nconst chromeStackParserFn = line => {\n // If the stack line has no function name, we need to parse it differently\n const noFnParts = chromeRegexNoFnName.exec(line) ;\n\n if (noFnParts) {\n const [, filename, line, col] = noFnParts;\n return createFrame(filename, UNKNOWN_FUNCTION, +line, +col);\n }\n\n const parts = chromeRegex.exec(line) ;\n\n if (parts) {\n const isEval = parts[2] && parts[2].indexOf('eval') === 0; // start of line\n\n if (isEval) {\n const subMatch = chromeEvalRegex.exec(parts[2]) ;\n\n if (subMatch) {\n // throw out eval line/column and use top-most line/column number\n parts[2] = subMatch[1]; // url\n parts[3] = subMatch[2]; // line\n parts[4] = subMatch[3]; // column\n }\n }\n\n // Kamil: One more hack won't hurt us right? Understanding and adding more rules on top of these regexps right now\n // would be way too time consuming. (TODO: Rewrite whole RegExp to be more readable)\n const [func, filename] = extractSafariExtensionDetails(parts[1] || UNKNOWN_FUNCTION, parts[2]);\n\n return createFrame(filename, func, parts[3] ? +parts[3] : undefined, parts[4] ? +parts[4] : undefined);\n }\n\n return;\n};\n\nconst chromeStackLineParser = [CHROME_PRIORITY, chromeStackParserFn];\n\n// gecko regex: `(?:bundle|\\d+\\.js)`: `bundle` is for react native, `\\d+\\.js` also but specifically for ram bundles because it\n// generates filenames without a prefix like `file://` the filenames in the stacktrace are just 42.js\n// We need this specific case for now because we want no other regex to match.\nconst geckoREgex =\n /^\\s*(.*?)(?:\\((.*?)\\))?(?:^|@)?((?:[-a-z]+)?:\\/.*?|\\[native code\\]|[^@]*(?:bundle|\\d+\\.js)|\\/[\\w\\-. /=]+)(?::(\\d+))?(?::(\\d+))?\\s*$/i;\nconst geckoEvalRegex = /(\\S+) line (\\d+)(?: > eval line \\d+)* > eval/i;\n\nconst gecko = line => {\n const parts = geckoREgex.exec(line) ;\n\n if (parts) {\n const isEval = parts[3] && parts[3].indexOf(' > eval') > -1;\n if (isEval) {\n const subMatch = geckoEvalRegex.exec(parts[3]) ;\n\n if (subMatch) {\n // throw out eval line/column and use top-most line number\n parts[1] = parts[1] || 'eval';\n parts[3] = subMatch[1];\n parts[4] = subMatch[2];\n parts[5] = ''; // no column when eval\n }\n }\n\n let filename = parts[3];\n let func = parts[1] || UNKNOWN_FUNCTION;\n [func, filename] = extractSafariExtensionDetails(func, filename);\n\n return createFrame(filename, func, parts[4] ? +parts[4] : undefined, parts[5] ? +parts[5] : undefined);\n }\n\n return;\n};\n\nconst geckoStackLineParser = [GECKO_PRIORITY, gecko];\n\nconst winjsRegex = /^\\s*at (?:((?:\\[object object\\])?.+) )?\\(?((?:[-a-z]+):.*?):(\\d+)(?::(\\d+))?\\)?\\s*$/i;\n\nconst winjs = line => {\n const parts = winjsRegex.exec(line) ;\n\n return parts\n ? createFrame(parts[2], parts[1] || UNKNOWN_FUNCTION, +parts[3], parts[4] ? +parts[4] : undefined)\n : undefined;\n};\n\nconst winjsStackLineParser = [WINJS_PRIORITY, winjs];\n\nconst opera10Regex = / line (\\d+).*script (?:in )?(\\S+)(?:: in function (\\S+))?$/i;\n\nconst opera10 = line => {\n const parts = opera10Regex.exec(line) ;\n return parts ? createFrame(parts[2], parts[3] || UNKNOWN_FUNCTION, +parts[1]) : undefined;\n};\n\nconst opera10StackLineParser = [OPERA10_PRIORITY, opera10];\n\nconst opera11Regex =\n / line (\\d+), column (\\d+)\\s*(?:in (?:]+)>|([^)]+))\\(.*\\))? in (.*):\\s*$/i;\n\nconst opera11 = line => {\n const parts = opera11Regex.exec(line) ;\n return parts ? createFrame(parts[5], parts[3] || parts[4] || UNKNOWN_FUNCTION, +parts[1], +parts[2]) : undefined;\n};\n\nconst opera11StackLineParser = [OPERA11_PRIORITY, opera11];\n\nconst defaultStackLineParsers = [chromeStackLineParser, geckoStackLineParser];\n\nconst defaultStackParser = createStackParser(...defaultStackLineParsers);\n\n/**\n * Safari web extensions, starting version unknown, can produce \"frames-only\" stacktraces.\n * What it means, is that instead of format like:\n *\n * Error: wat\n * at function@url:row:col\n * at function@url:row:col\n * at function@url:row:col\n *\n * it produces something like:\n *\n * function@url:row:col\n * function@url:row:col\n * function@url:row:col\n *\n * Because of that, it won't be captured by `chrome` RegExp and will fall into `Gecko` branch.\n * This function is extracted so that we can use it in both places without duplicating the logic.\n * Unfortunately \"just\" changing RegExp is too complicated now and making it pass all tests\n * and fix this case seems like an impossible, or at least way too time-consuming task.\n */\nconst extractSafariExtensionDetails = (func, filename) => {\n const isSafariExtension = func.indexOf('safari-extension') !== -1;\n const isSafariWebExtension = func.indexOf('safari-web-extension') !== -1;\n\n return isSafariExtension || isSafariWebExtension\n ? [\n func.indexOf('@') !== -1 ? (func.split('@')[0] ) : UNKNOWN_FUNCTION,\n isSafariExtension ? `safari-extension:${filename}` : `safari-web-extension:${filename}`,\n ]\n : [func, filename];\n};\n\nexport { chromeStackLineParser, defaultStackLineParsers, defaultStackParser, geckoStackLineParser, opera10StackLineParser, opera11StackLineParser, winjsStackLineParser };\n//# sourceMappingURL=stack-parsers.js.map\n","/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","import { addClickKeypressInstrumentationHandler, addXhrInstrumentationHandler, addHistoryInstrumentationHandler, SENTRY_XHR_DATA_KEY } from '@sentry-internal/browser-utils';\nimport { defineIntegration, addConsoleInstrumentationHandler, addFetchInstrumentationHandler, getClient, addBreadcrumb, getEventDescription, logger, htmlTreeAsString, getComponentName, severityLevelFromString, safeJoin, getBreadcrumbLogLevelFromHttpStatusCode, parseUrl } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\n\n/* eslint-disable max-lines */\n\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\nconst INTEGRATION_NAME = 'Breadcrumbs';\n\nconst _breadcrumbsIntegration = ((options = {}) => {\n const _options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n if (_options.console) {\n addConsoleInstrumentationHandler(_getConsoleBreadcrumbHandler(client));\n }\n if (_options.dom) {\n addClickKeypressInstrumentationHandler(_getDomBreadcrumbHandler(client, _options.dom));\n }\n if (_options.xhr) {\n addXhrInstrumentationHandler(_getXhrBreadcrumbHandler(client));\n }\n if (_options.fetch) {\n addFetchInstrumentationHandler(_getFetchBreadcrumbHandler(client));\n }\n if (_options.history) {\n addHistoryInstrumentationHandler(_getHistoryBreadcrumbHandler(client));\n }\n if (_options.sentry) {\n client.on('beforeSendEvent', _getSentryBreadcrumbHandler(client));\n }\n },\n };\n}) ;\n\nconst breadcrumbsIntegration = defineIntegration(_breadcrumbsIntegration);\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction _getSentryBreadcrumbHandler(client) {\n return function addSentryBreadcrumb(event) {\n if (getClient() !== client) {\n return;\n }\n\n addBreadcrumb(\n {\n category: `sentry.${event.type === 'transaction' ? 'transaction' : 'event'}`,\n event_id: event.event_id,\n level: event.level,\n message: getEventDescription(event),\n },\n {\n event,\n },\n );\n };\n}\n\n/**\n * A HOC that creates a function that creates breadcrumbs from DOM API calls.\n * This is a HOC so that we get access to dom options in the closure.\n */\nfunction _getDomBreadcrumbHandler(\n client,\n dom,\n) {\n return function _innerDomBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n let target;\n let componentName;\n let keyAttrs = typeof dom === 'object' ? dom.serializeAttribute : undefined;\n\n let maxStringLength =\n typeof dom === 'object' && typeof dom.maxStringLength === 'number' ? dom.maxStringLength : undefined;\n if (maxStringLength && maxStringLength > MAX_ALLOWED_STRING_LENGTH) {\n DEBUG_BUILD &&\n logger.warn(\n `\\`dom.maxStringLength\\` cannot exceed ${MAX_ALLOWED_STRING_LENGTH}, but a value of ${maxStringLength} was configured. Sentry will use ${MAX_ALLOWED_STRING_LENGTH} instead.`,\n );\n maxStringLength = MAX_ALLOWED_STRING_LENGTH;\n }\n\n if (typeof keyAttrs === 'string') {\n keyAttrs = [keyAttrs];\n }\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n const event = handlerData.event ;\n const element = _isEvent(event) ? event.target : event;\n\n target = htmlTreeAsString(element, { keyAttrs, maxStringLength });\n componentName = getComponentName(element);\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n const breadcrumb = {\n category: `ui.${handlerData.name}`,\n message: target,\n };\n\n if (componentName) {\n breadcrumb.data = { 'ui.component_name': componentName };\n }\n\n addBreadcrumb(breadcrumb, {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _getConsoleBreadcrumbHandler(client) {\n return function _consoleBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: handlerData.args,\n logger: 'console',\n },\n level: severityLevelFromString(handlerData.level),\n message: safeJoin(handlerData.args, ' '),\n };\n\n if (handlerData.level === 'assert') {\n if (handlerData.args[0] === false) {\n breadcrumb.message = `Assertion failed: ${safeJoin(handlerData.args.slice(1), ' ') || 'console.assert'}`;\n breadcrumb.data.arguments = handlerData.args.slice(1);\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n };\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _getXhrBreadcrumbHandler(client) {\n return function _xhrBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n const sentryXhrData = handlerData.xhr[SENTRY_XHR_DATA_KEY];\n\n // We only capture complete, non-sentry requests\n if (!startTimestamp || !endTimestamp || !sentryXhrData) {\n return;\n }\n\n const { method, url, status_code, body } = sentryXhrData;\n\n const data = {\n method,\n url,\n status_code,\n };\n\n const hint = {\n xhr: handlerData.xhr,\n input: body,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'xhr',\n data,\n type: 'http',\n level: getBreadcrumbLogLevelFromHttpStatusCode(status_code),\n };\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint );\n\n addBreadcrumb(breadcrumb, hint);\n };\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _getFetchBreadcrumbHandler(client) {\n return function _fetchBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n const { startTimestamp, endTimestamp } = handlerData;\n\n // We only capture complete fetch requests\n if (!endTimestamp) {\n return;\n }\n\n if (handlerData.fetchData.url.match(/sentry_key/) && handlerData.fetchData.method === 'POST') {\n // We will not create breadcrumbs for fetch requests that contain `sentry_key` (internal sentry requests)\n return;\n }\n\n ({\n method: handlerData.fetchData.method,\n url: handlerData.fetchData.url,\n });\n\n if (handlerData.error) {\n const data = handlerData.fetchData;\n const hint = {\n data: handlerData.error,\n input: handlerData.args,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n } ;\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint );\n\n addBreadcrumb(breadcrumb, hint);\n } else {\n const response = handlerData.response ;\n const data = {\n ...handlerData.fetchData,\n status_code: response?.status,\n };\n\n handlerData.fetchData.request_body_size;\n handlerData.fetchData.response_body_size;\n response?.status;\n\n const hint = {\n input: handlerData.args,\n response,\n startTimestamp,\n endTimestamp,\n };\n\n const breadcrumb = {\n category: 'fetch',\n data,\n type: 'http',\n level: getBreadcrumbLogLevelFromHttpStatusCode(data.status_code),\n };\n\n client.emit('beforeOutgoingRequestBreadcrumb', breadcrumb, hint );\n\n addBreadcrumb(breadcrumb, hint);\n }\n };\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _getHistoryBreadcrumbHandler(client) {\n return function _historyBreadcrumb(handlerData) {\n if (getClient() !== client) {\n return;\n }\n\n let from = handlerData.from;\n let to = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = from ? parseUrl(from) : undefined;\n const parsedTo = parseUrl(to);\n\n // Initial pushState doesn't provide `from` information\n if (!parsedFrom?.path) {\n parsedFrom = parsedLoc;\n }\n\n // Use only the path component of the URL if the URL matches the current\n // document (almost all the time when using pushState)\n if (parsedLoc.protocol === parsedTo.protocol && parsedLoc.host === parsedTo.host) {\n to = parsedTo.relative;\n }\n if (parsedLoc.protocol === parsedFrom.protocol && parsedLoc.host === parsedFrom.host) {\n from = parsedFrom.relative;\n }\n\n addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n };\n}\n\nfunction _isEvent(event) {\n return !!event && !!(event ).target;\n}\n\nexport { breadcrumbsIntegration };\n//# sourceMappingURL=breadcrumbs.js.map\n","import { defineIntegration, fill, getFunctionName, getOriginalFunction } from '@sentry/core';\nimport { WINDOW, wrap } from '../helpers.js';\n\nconst DEFAULT_EVENT_TARGET = [\n 'EventTarget',\n 'Window',\n 'Node',\n 'ApplicationCache',\n 'AudioTrackList',\n 'BroadcastChannel',\n 'ChannelMergerNode',\n 'CryptoOperation',\n 'EventSource',\n 'FileReader',\n 'HTMLUnknownElement',\n 'IDBDatabase',\n 'IDBRequest',\n 'IDBTransaction',\n 'KeyOperation',\n 'MediaController',\n 'MessagePort',\n 'ModalWindow',\n 'Notification',\n 'SVGElementInstance',\n 'Screen',\n 'SharedWorker',\n 'TextTrack',\n 'TextTrackCue',\n 'TextTrackList',\n 'WebSocket',\n 'WebSocketWorker',\n 'Worker',\n 'XMLHttpRequest',\n 'XMLHttpRequestEventTarget',\n 'XMLHttpRequestUpload',\n];\n\nconst INTEGRATION_NAME = 'BrowserApiErrors';\n\nconst _browserApiErrorsIntegration = ((options = {}) => {\n const _options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n // TODO: This currently only works for the first client this is setup\n // We may want to adjust this to check for client etc.\n setupOnce() {\n if (_options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (_options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (_options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (_options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = _options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n },\n };\n}) ;\n\n/**\n * Wrap timer functions and event targets to catch errors and provide better meta data.\n */\nconst browserApiErrorsIntegration = defineIntegration(_browserApiErrorsIntegration);\n\nfunction _wrapTimeFunction(original) {\n return function ( ...args) {\n const originalCallback = args[0];\n args[0] = wrap(originalCallback, {\n mechanism: {\n data: { function: getFunctionName(original) },\n handled: false,\n type: 'instrument',\n },\n });\n return original.apply(this, args);\n };\n}\n\nfunction _wrapRAF(original) {\n return function ( callback) {\n return original.apply(this, [\n wrap(callback, {\n mechanism: {\n data: {\n function: 'requestAnimationFrame',\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n }),\n ]);\n };\n}\n\nfunction _wrapXHR(originalSend) {\n return function ( ...args) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const xhr = this;\n const xmlHttpRequestProps = ['onload', 'onerror', 'onprogress', 'onreadystatechange'];\n\n xmlHttpRequestProps.forEach(prop => {\n if (prop in xhr && typeof xhr[prop] === 'function') {\n fill(xhr, prop, function (original) {\n const wrapOptions = {\n mechanism: {\n data: {\n function: prop,\n handler: getFunctionName(original),\n },\n handled: false,\n type: 'instrument',\n },\n };\n\n // If Instrument integration has been called before BrowserApiErrors, get the name of original function\n const originalFunction = getOriginalFunction(original);\n if (originalFunction) {\n wrapOptions.mechanism.data.handler = getFunctionName(originalFunction);\n }\n\n // Otherwise wrap directly\n return wrap(original, wrapOptions);\n });\n }\n });\n\n return originalSend.apply(this, args);\n };\n}\n\nfunction _wrapEventTarget(target) {\n const globalObject = WINDOW ;\n const proto = globalObject[target]?.prototype;\n\n // eslint-disable-next-line no-prototype-builtins\n if (!proto?.hasOwnProperty?.('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original)\n\n {\n return function ( eventName, fn, options) {\n try {\n if (isEventListenerObject(fn)) {\n // ESlint disable explanation:\n // First, it is generally safe to call `wrap` with an unbound function. Furthermore, using `.bind()` would\n // introduce a bug here, because bind returns a new function that doesn't have our\n // flags(like __sentry_original__) attached. `wrap` checks for those flags to avoid unnecessary wrapping.\n // Without those flags, every call to addEventListener wraps the function again, causing a memory leak.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n fn.handleEvent = wrap(fn.handleEvent, {\n mechanism: {\n data: {\n function: 'handleEvent',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n });\n }\n } catch {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n wrap(fn, {\n mechanism: {\n data: {\n function: 'addEventListener',\n handler: getFunctionName(fn),\n target,\n },\n handled: false,\n type: 'instrument',\n },\n }),\n options,\n ]);\n };\n });\n\n fill(proto, 'removeEventListener', function (originalRemoveEventListener)\n\n {\n return function ( eventName, fn, options) {\n /**\n * There are 2 possible scenarios here:\n *\n * 1. Someone passes a callback, which was attached prior to Sentry initialization, or by using unmodified\n * method, eg. `document.addEventListener.call(el, name, handler). In this case, we treat this function\n * as a pass-through, and call original `removeEventListener` with it.\n *\n * 2. Someone passes a callback, which was attached after Sentry was initialized, which means that it was using\n * our wrapped version of `addEventListener`, which internally calls `wrap` helper.\n * This helper \"wraps\" whole callback inside a try/catch statement, and attached appropriate metadata to it,\n * in order for us to make a distinction between wrapped/non-wrapped functions possible.\n * If a function was wrapped, it has additional property of `__sentry_wrapped__`, holding the handler.\n *\n * When someone adds a handler prior to initialization, and then do it again, but after,\n * then we have to detach both of them. Otherwise, if we'd detach only wrapped one, it'd be impossible\n * to get rid of the initial handler and it'd stick there forever.\n */\n try {\n const originalEventHandler = (fn ).__sentry_wrapped__;\n if (originalEventHandler) {\n originalRemoveEventListener.call(this, eventName, originalEventHandler, options);\n }\n } catch (e) {\n // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments\n }\n return originalRemoveEventListener.call(this, eventName, fn, options);\n };\n });\n}\n\nfunction isEventListenerObject(obj) {\n return typeof (obj ).handleEvent === 'function';\n}\n\nexport { browserApiErrorsIntegration };\n//# sourceMappingURL=browserapierrors.js.map\n","import { addHistoryInstrumentationHandler } from '@sentry-internal/browser-utils';\nimport { defineIntegration, logger, startSession, captureSession } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\n\n/**\n * When added, automatically creates sessions which allow you to track adoption and crashes (crash free rate) in your Releases in Sentry.\n * More information: https://docs.sentry.io/product/releases/health/\n *\n * Note: In order for session tracking to work, you need to set up Releases: https://docs.sentry.io/product/releases/\n */\nconst browserSessionIntegration = defineIntegration(() => {\n return {\n name: 'BrowserSession',\n setupOnce() {\n if (typeof WINDOW.document === 'undefined') {\n DEBUG_BUILD &&\n logger.warn('Using the `browserSessionIntegration` in non-browser environments is not supported.');\n return;\n }\n\n // The session duration for browser sessions does not track a meaningful\n // concept that can be used as a metric.\n // Automatically captured sessions are akin to page views, and thus we\n // discard their duration.\n startSession({ ignoreDuration: true });\n captureSession();\n\n // We want to create a session for every navigation as well\n addHistoryInstrumentationHandler(({ from, to }) => {\n // Don't create an additional session for the initial route or if the location did not change\n if (from !== undefined && from !== to) {\n startSession({ ignoreDuration: true });\n captureSession();\n }\n });\n },\n };\n});\n\nexport { browserSessionIntegration };\n//# sourceMappingURL=browsersession.js.map\n","import { defineIntegration, addGlobalErrorInstrumentationHandler, getClient, captureEvent, addGlobalUnhandledRejectionInstrumentationHandler, isPrimitive, isString, getLocationHref, UNKNOWN_FUNCTION, logger } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { eventFromUnknownInput } from '../eventbuilder.js';\nimport { shouldIgnoreOnError } from '../helpers.js';\n\nconst INTEGRATION_NAME = 'GlobalHandlers';\n\nconst _globalHandlersIntegration = ((options = {}) => {\n const _options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n Error.stackTraceLimit = 50;\n },\n setup(client) {\n if (_options.onerror) {\n _installGlobalOnErrorHandler(client);\n globalHandlerLog('onerror');\n }\n if (_options.onunhandledrejection) {\n _installGlobalOnUnhandledRejectionHandler(client);\n globalHandlerLog('onunhandledrejection');\n }\n },\n };\n}) ;\n\nconst globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);\n\nfunction _installGlobalOnErrorHandler(client) {\n addGlobalErrorInstrumentationHandler(data => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const { msg, url, line, column, error } = data;\n\n const event = _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onerror',\n },\n });\n });\n}\n\nfunction _installGlobalOnUnhandledRejectionHandler(client) {\n addGlobalUnhandledRejectionInstrumentationHandler(e => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const error = _getUnhandledRejectionError(e );\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'onunhandledrejection',\n },\n });\n });\n}\n\nfunction _getUnhandledRejectionError(error) {\n if (isPrimitive(error)) {\n return error;\n }\n\n // dig the object of the rejection out of known event types\n try {\n\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in (error )) {\n return (error ).reason;\n }\n\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n if ('detail' in (error ) && 'reason' in (error ).detail) {\n return (error ).detail.reason;\n }\n } catch {} // eslint-disable-line no-empty\n\n return error;\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nfunction _eventFromRejectionWithPrimitive(reason) {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\nfunction _enhanceEventWithInitialFrame(\n event,\n url,\n line,\n column,\n) {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n const colno = column;\n const lineno = line;\n const filename = isString(url) && url.length > 0 ? url : getLocationHref();\n\n // event.exception.values[0].stacktrace.frames\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n filename,\n function: UNKNOWN_FUNCTION,\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type) {\n DEBUG_BUILD && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions() {\n const client = getClient();\n const options = client?.getOptions() || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n\nexport { globalHandlersIntegration };\n//# sourceMappingURL=globalhandlers.js.map\n","import { defineIntegration, getLocationHref } from '@sentry/core';\nimport { WINDOW } from '../helpers.js';\n\n/**\n * Collects information about HTTP request headers and\n * attaches them to the event.\n */\nconst httpContextIntegration = defineIntegration(() => {\n return {\n name: 'HttpContext',\n preprocessEvent(event) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n // grab as much info as exists and add it to the event\n const url = event.request?.url || getLocationHref();\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...event.request?.headers,\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = {\n ...event.request,\n ...(url && { url }),\n headers,\n };\n\n event.request = request;\n },\n };\n});\n\nexport { httpContextIntegration };\n//# sourceMappingURL=httpcontext.js.map\n","import { defineIntegration, applyAggregateErrorsToEvent } from '@sentry/core';\nimport { exceptionFromError } from '../eventbuilder.js';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options = {}) => {\n const limit = options.limit || DEFAULT_LIMIT;\n const key = options.key || DEFAULT_KEY;\n\n return {\n name: INTEGRATION_NAME,\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(\n // This differs from the LinkedErrors integration in core by using a different exceptionFromError function\n exceptionFromError,\n options.stackParser,\n options.maxValueLength,\n key,\n limit,\n event,\n hint,\n );\n },\n };\n}) ;\n\n/**\n * Aggregrate linked errors in an event.\n */\nconst linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\nexport { linkedErrorsIntegration };\n//# sourceMappingURL=linkederrors.js.map\n","import { inboundFiltersIntegration, functionToStringIntegration, dedupeIntegration, consoleSandbox, supportsFetch, logger, stackParserFromStackParserOptions, getIntegrationsToSetup, initAndBind, getCurrentScope, lastEventId, getReportDialogEndpoint, getLocationHref } from '@sentry/core';\nimport { BrowserClient } from './client.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { WINDOW } from './helpers.js';\nimport { breadcrumbsIntegration } from './integrations/breadcrumbs.js';\nimport { browserApiErrorsIntegration } from './integrations/browserapierrors.js';\nimport { browserSessionIntegration } from './integrations/browsersession.js';\nimport { globalHandlersIntegration } from './integrations/globalhandlers.js';\nimport { httpContextIntegration } from './integrations/httpcontext.js';\nimport { linkedErrorsIntegration } from './integrations/linkederrors.js';\nimport { defaultStackParser } from './stack-parsers.js';\nimport { makeFetchTransport } from './transports/fetch.js';\n\n/** Get the default integrations for the browser SDK. */\nfunction getDefaultIntegrations(_options) {\n /**\n * Note: Please make sure this stays in sync with Angular SDK, which re-exports\n * `getDefaultIntegrations` but with an adjusted set of integrations.\n */\n return [\n inboundFiltersIntegration(),\n functionToStringIntegration(),\n browserApiErrorsIntegration(),\n breadcrumbsIntegration(),\n globalHandlersIntegration(),\n linkedErrorsIntegration(),\n dedupeIntegration(),\n httpContextIntegration(),\n browserSessionIntegration(),\n ];\n}\n\n/** Exported only for tests. */\nfunction applyDefaultOptions(optionsArg = {}) {\n const defaultOptions = {\n defaultIntegrations: getDefaultIntegrations(),\n release:\n typeof __SENTRY_RELEASE__ === 'string' // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n ? __SENTRY_RELEASE__\n : WINDOW.SENTRY_RELEASE?.id, // This supports the variable that sentry-webpack-plugin injects\n sendClientReports: true,\n };\n\n return {\n ...defaultOptions,\n ...dropTopLevelUndefinedKeys(optionsArg),\n };\n}\n\n/**\n * In contrast to the regular `dropUndefinedKeys` method,\n * this one does not deep-drop keys, but only on the top level.\n */\nfunction dropTopLevelUndefinedKeys(obj) {\n const mutatetedObj = {};\n\n for (const k of Object.getOwnPropertyNames(obj)) {\n const key = k ;\n if (obj[key] !== undefined) {\n mutatetedObj[key] = obj[key];\n }\n }\n\n return mutatetedObj;\n}\n\nfunction shouldShowBrowserExtensionError() {\n const windowWithMaybeExtension =\n typeof WINDOW.window !== 'undefined' && (WINDOW );\n if (!windowWithMaybeExtension) {\n // No need to show the error if we're not in a browser window environment (e.g. service workers)\n return false;\n }\n\n const extensionKey = windowWithMaybeExtension.chrome ? 'chrome' : 'browser';\n const extensionObject = windowWithMaybeExtension[extensionKey];\n\n const runtimeId = extensionObject?.runtime?.id;\n const href = getLocationHref() || '';\n\n const extensionProtocols = ['chrome-extension:', 'moz-extension:', 'ms-browser-extension:', 'safari-web-extension:'];\n\n // Running the SDK in a dedicated extension page and calling Sentry.init is fine; no risk of data leakage\n const isDedicatedExtensionPage =\n !!runtimeId && WINDOW === WINDOW.top && extensionProtocols.some(protocol => href.startsWith(`${protocol}//`));\n\n // Running the SDK in NW.js, which appears like a browser extension but isn't, is also fine\n // see: https://github.com/getsentry/sentry-javascript/issues/12668\n const isNWjs = typeof windowWithMaybeExtension.nw !== 'undefined';\n\n return !!runtimeId && !isDedicatedExtensionPage && !isNWjs;\n}\n\n/**\n * A magic string that build tooling can leverage in order to inject a release value into the SDK.\n */\n\n/**\n * The Sentry Browser SDK Client.\n *\n * To use this SDK, call the {@link init} function as early as possible when\n * loading the web page. To set context information or send manual events, use\n * the provided methods.\n *\n * @example\n *\n * ```\n *\n * import { init } from '@sentry/browser';\n *\n * init({\n * dsn: '__DSN__',\n * // ...\n * });\n * ```\n *\n * @example\n * ```\n *\n * import { addBreadcrumb } from '@sentry/browser';\n * addBreadcrumb({\n * message: 'My Breadcrumb',\n * // ...\n * });\n * ```\n *\n * @example\n *\n * ```\n *\n * import * as Sentry from '@sentry/browser';\n * Sentry.captureMessage('Hello, world!');\n * Sentry.captureException(new Error('Good bye'));\n * Sentry.captureEvent({\n * message: 'Manual',\n * stacktrace: [\n * // ...\n * ],\n * });\n * ```\n *\n * @see {@link BrowserOptions} for documentation on configuration options.\n */\nfunction init(browserOptions = {}) {\n const options = applyDefaultOptions(browserOptions);\n\n if (!options.skipBrowserExtensionCheck && shouldShowBrowserExtensionError()) {\n if (DEBUG_BUILD) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(\n '[Sentry] You cannot run Sentry this way in a browser extension, check: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/',\n );\n });\n }\n return;\n }\n\n if (DEBUG_BUILD && !supportsFetch()) {\n logger.warn(\n 'No Fetch API detected. The Sentry SDK requires a Fetch API compatible environment to send events. Please add a Fetch API polyfill.',\n );\n }\n const clientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || makeFetchTransport,\n };\n\n return initAndBind(BrowserClient, clientOptions);\n}\n\n/**\n * Present the user with a report dialog.\n *\n * @param options Everything is optional, we try to fetch all info need from the global scope.\n */\nfunction showReportDialog(options = {}) {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n DEBUG_BUILD && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n const scope = getCurrentScope();\n const client = scope.getClient();\n const dsn = client?.getDsn();\n\n if (!dsn) {\n DEBUG_BUILD && logger.error('DSN not configured for showReportDialog call');\n return;\n }\n\n if (scope) {\n options.user = {\n ...scope.getUser(),\n ...options.user,\n };\n }\n\n if (!options.eventId) {\n const eventId = lastEventId();\n if (eventId) {\n options.eventId = eventId;\n }\n }\n\n const script = WINDOW.document.createElement('script');\n script.async = true;\n script.crossOrigin = 'anonymous';\n script.src = getReportDialogEndpoint(dsn, options);\n\n if (options.onLoad) {\n script.onload = options.onLoad;\n }\n\n const { onClose } = options;\n if (onClose) {\n const reportDialogClosedMessageHandler = (event) => {\n if (event.data === '__sentry_reportdialog_closed__') {\n try {\n onClose();\n } finally {\n WINDOW.removeEventListener('message', reportDialogClosedMessageHandler);\n }\n }\n };\n WINDOW.addEventListener('message', reportDialogClosedMessageHandler);\n }\n\n const injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n DEBUG_BUILD && logger.error('Not injecting report dialog. No injection point found in HTML');\n }\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nfunction forceLoad() {\n // Noop\n}\n\n/**\n * This function is here to be API compatible with the loader.\n * @hidden\n */\nfunction onLoad(callback) {\n callback();\n}\n\nexport { applyDefaultOptions, forceLoad, getDefaultIntegrations, init, onLoad, showReportDialog };\n//# sourceMappingURL=sdk.js.map\n","import { GLOBAL_OBJ, normalize, fill, htmlTreeAsString, browserPerformanceTimeOrigin, logger as logger$1, severityLevelFromString, captureException, addBreadcrumb, uuid4, getClient, getLocationHref, getCurrentScope, getActiveSpan, getDynamicSamplingContextFromSpan, isSentryRequestUrl, dropUndefinedKeys, stringMatchesSomePattern, addEventProcessor, createEnvelope, createEventEnvelopeHeaders, getSdkMetadataForEnvelopeHeader, prepareEvent, getIsolationScope, resolvedSyncPromise, updateRateLimits, isRateLimited, setContext, getRootSpan, spanToJSON, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, isBrowser, parseSampleRate, consoleSandbox } from '@sentry/core';\nimport { setTimeout as setTimeout$3, addPerformanceInstrumentationHandler, addLcpInstrumentationHandler, addClsInstrumentationHandler, addFidInstrumentationHandler, addInpInstrumentationHandler, serializeFormData, getFetchRequestArgBody, getBodyString, SENTRY_XHR_DATA_KEY, addClickKeypressInstrumentationHandler, addHistoryInstrumentationHandler } from '@sentry-internal/browser-utils';\n\n// exporting a separate copy of `WINDOW` rather than exporting the one from `@sentry/browser`\n// prevents the browser package from being bundled in the CDN bundle, and avoids a\n// circular dependency between the browser and replay packages should `@sentry/browser` import\n// from `@sentry/replay` in the future\nconst WINDOW = GLOBAL_OBJ ;\n\nconst REPLAY_SESSION_KEY = 'sentryReplaySession';\nconst REPLAY_EVENT_NAME = 'replay_event';\nconst UNABLE_TO_SEND_REPLAY = 'Unable to send Replay';\n\n// The idle limit for a session after which recording is paused.\nconst SESSION_IDLE_PAUSE_DURATION = 300000; // 5 minutes in ms\n\n// The idle limit for a session after which the session expires.\nconst SESSION_IDLE_EXPIRE_DURATION = 900000; // 15 minutes in ms\n\n/** Default flush delays */\nconst DEFAULT_FLUSH_MIN_DELAY = 5000;\n// XXX: Temp fix for our debounce logic where `maxWait` would never occur if it\n// was the same as `wait`\nconst DEFAULT_FLUSH_MAX_DELAY = 5500;\n\n/* How long to wait for error checkouts */\nconst BUFFER_CHECKOUT_TIME = 60000;\n\nconst RETRY_BASE_INTERVAL = 5000;\nconst RETRY_MAX_COUNT = 3;\n\n/* The max (uncompressed) size in bytes of a network body. Any body larger than this will be truncated. */\nconst NETWORK_BODY_MAX_SIZE = 150000;\n\n/* The max size of a single console arg that is captured. Any arg larger than this will be truncated. */\nconst CONSOLE_ARG_MAX_SIZE = 5000;\n\n/* Min. time to wait before we consider something a slow click. */\nconst SLOW_CLICK_THRESHOLD = 3000;\n/* For scroll actions after a click, we only look for a very short time period to detect programmatic scrolling. */\nconst SLOW_CLICK_SCROLL_TIMEOUT = 300;\n\n/** When encountering a total segment size exceeding this size, stop the replay (as we cannot properly ingest it). */\nconst REPLAY_MAX_EVENT_BUFFER_SIZE = 20000000; // ~20MB\n\n/** Replays must be min. 5s long before we send them. */\nconst MIN_REPLAY_DURATION = 4999;\n/* The max. allowed value that the minReplayDuration can be set to. */\nconst MIN_REPLAY_DURATION_LIMIT = 15000;\n\n/** The max. length of a replay. */\nconst MAX_REPLAY_DURATION = 3600000; // 60 minutes in ms;\n\nvar NodeType$3;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType$3 || (NodeType$3 = {}));\n\nfunction isElement$1(n) {\n return n.nodeType === n.ELEMENT_NODE;\n}\nfunction isShadowRoot(n) {\n const host = n?.host;\n return Boolean(host?.shadowRoot === n);\n}\nfunction isNativeShadowDom(shadowRoot) {\n return Object.prototype.toString.call(shadowRoot) === '[object ShadowRoot]';\n}\nfunction fixBrowserCompatibilityIssuesInCSS(cssText) {\n if (cssText.includes(' background-clip: text;') &&\n !cssText.includes(' -webkit-background-clip: text;')) {\n cssText = cssText.replace(/\\sbackground-clip:\\s*text;/g, ' -webkit-background-clip: text; background-clip: text;');\n }\n return cssText;\n}\nfunction escapeImportStatement(rule) {\n const { cssText } = rule;\n if (cssText.split('\"').length < 3)\n return cssText;\n const statement = ['@import', `url(${JSON.stringify(rule.href)})`];\n if (rule.layerName === '') {\n statement.push(`layer`);\n }\n else if (rule.layerName) {\n statement.push(`layer(${rule.layerName})`);\n }\n if (rule.supportsText) {\n statement.push(`supports(${rule.supportsText})`);\n }\n if (rule.media.length) {\n statement.push(rule.media.mediaText);\n }\n return statement.join(' ') + ';';\n}\nfunction stringifyStylesheet(s) {\n try {\n const rules = s.rules || s.cssRules;\n return rules\n ? fixBrowserCompatibilityIssuesInCSS(Array.from(rules, stringifyRule).join(''))\n : null;\n }\n catch (error) {\n return null;\n }\n}\nfunction fixAllCssProperty(rule) {\n let styles = '';\n for (let i = 0; i < rule.style.length; i++) {\n const styleDeclaration = rule.style;\n const attribute = styleDeclaration[i];\n const isImportant = styleDeclaration.getPropertyPriority(attribute);\n styles += `${attribute}:${styleDeclaration.getPropertyValue(attribute)}${isImportant ? ` !important` : ''};`;\n }\n return `${rule.selectorText} { ${styles} }`;\n}\nfunction stringifyRule(rule) {\n let importStringified;\n if (isCSSImportRule(rule)) {\n try {\n importStringified =\n stringifyStylesheet(rule.styleSheet) ||\n escapeImportStatement(rule);\n }\n catch (error) {\n }\n }\n else if (isCSSStyleRule(rule)) {\n let cssText = rule.cssText;\n const needsSafariColonFix = rule.selectorText.includes(':');\n const needsAllFix = typeof rule.style['all'] === 'string' && rule.style['all'];\n if (needsAllFix) {\n cssText = fixAllCssProperty(rule);\n }\n if (needsSafariColonFix) {\n cssText = fixSafariColons(cssText);\n }\n if (needsSafariColonFix || needsAllFix) {\n return cssText;\n }\n }\n return importStringified || rule.cssText;\n}\nfunction fixSafariColons(cssStringified) {\n const regex = /(\\[(?:[\\w-]+)[^\\\\])(:(?:[\\w-]+)\\])/gm;\n return cssStringified.replace(regex, '$1\\\\$2');\n}\nfunction isCSSImportRule(rule) {\n return 'styleSheet' in rule;\n}\nfunction isCSSStyleRule(rule) {\n return 'selectorText' in rule;\n}\nclass Mirror {\n constructor() {\n this.idNodeMap = new Map();\n this.nodeMetaMap = new WeakMap();\n }\n getId(n) {\n if (!n)\n return -1;\n const id = this.getMeta(n)?.id;\n return id ?? -1;\n }\n getNode(id) {\n return this.idNodeMap.get(id) || null;\n }\n getIds() {\n return Array.from(this.idNodeMap.keys());\n }\n getMeta(n) {\n return this.nodeMetaMap.get(n) || null;\n }\n removeNodeFromMap(n) {\n const id = this.getId(n);\n this.idNodeMap.delete(id);\n if (n.childNodes) {\n n.childNodes.forEach((childNode) => this.removeNodeFromMap(childNode));\n }\n }\n has(id) {\n return this.idNodeMap.has(id);\n }\n hasNode(node) {\n return this.nodeMetaMap.has(node);\n }\n add(n, meta) {\n const id = meta.id;\n this.idNodeMap.set(id, n);\n this.nodeMetaMap.set(n, meta);\n }\n replace(id, n) {\n const oldNode = this.getNode(id);\n if (oldNode) {\n const meta = this.nodeMetaMap.get(oldNode);\n if (meta)\n this.nodeMetaMap.set(n, meta);\n }\n this.idNodeMap.set(id, n);\n }\n reset() {\n this.idNodeMap = new Map();\n this.nodeMetaMap = new WeakMap();\n }\n}\nfunction createMirror() {\n return new Mirror();\n}\nfunction shouldMaskInput({ maskInputOptions, tagName, type, }) {\n if (tagName === 'OPTION') {\n tagName = 'SELECT';\n }\n return Boolean(maskInputOptions[tagName.toLowerCase()] ||\n (type && maskInputOptions[type]) ||\n type === 'password' ||\n (tagName === 'INPUT' && !type && maskInputOptions['text']));\n}\nfunction maskInputValue({ isMasked, element, value, maskInputFn, }) {\n let text = value || '';\n if (!isMasked) {\n return text;\n }\n if (maskInputFn) {\n text = maskInputFn(text, element);\n }\n return '*'.repeat(text.length);\n}\nfunction toLowerCase(str) {\n return str.toLowerCase();\n}\nfunction toUpperCase(str) {\n return str.toUpperCase();\n}\nconst ORIGINAL_ATTRIBUTE_NAME = '__rrweb_original__';\nfunction is2DCanvasBlank(canvas) {\n const ctx = canvas.getContext('2d');\n if (!ctx)\n return true;\n const chunkSize = 50;\n for (let x = 0; x < canvas.width; x += chunkSize) {\n for (let y = 0; y < canvas.height; y += chunkSize) {\n const getImageData = ctx.getImageData;\n const originalGetImageData = ORIGINAL_ATTRIBUTE_NAME in getImageData\n ? getImageData[ORIGINAL_ATTRIBUTE_NAME]\n : getImageData;\n const pixelBuffer = new Uint32Array(originalGetImageData.call(ctx, x, y, Math.min(chunkSize, canvas.width - x), Math.min(chunkSize, canvas.height - y)).data.buffer);\n if (pixelBuffer.some((pixel) => pixel !== 0))\n return false;\n }\n }\n return true;\n}\nfunction getInputType(element) {\n const type = element.type;\n return element.hasAttribute('data-rr-is-password')\n ? 'password'\n : type\n ?\n toLowerCase(type)\n : null;\n}\nfunction getInputValue(el, tagName, type) {\n if (tagName === 'INPUT' && (type === 'radio' || type === 'checkbox')) {\n return el.getAttribute('value') || '';\n }\n return el.value;\n}\nfunction extractFileExtension(path, baseURL) {\n let url;\n try {\n url = new URL(path, baseURL ?? window.location.href);\n }\n catch (err) {\n return null;\n }\n const regex = /\\.([0-9a-z]+)(?:$)/i;\n const match = url.pathname.match(regex);\n return match?.[1] ?? null;\n}\nconst cachedImplementations$1 = {};\nfunction getImplementation$1(name) {\n const cached = cachedImplementations$1[name];\n if (cached) {\n return cached;\n }\n const document = window.document;\n let impl = window[name];\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow[name]) {\n impl =\n contentWindow[name];\n }\n document.head.removeChild(sandbox);\n }\n catch (e) {\n }\n }\n return (cachedImplementations$1[name] = impl.bind(window));\n}\nfunction setTimeout$2(...rest) {\n return getImplementation$1('setTimeout')(...rest);\n}\nfunction clearTimeout$2(...rest) {\n return getImplementation$1('clearTimeout')(...rest);\n}\nfunction getIframeContentDocument(iframe) {\n try {\n return iframe.contentDocument;\n }\n catch (e) {\n }\n}\n\nlet _id = 1;\nconst tagNameRegex = new RegExp('[^a-z0-9-_:]');\nconst IGNORED_NODE = -2;\nfunction genId() {\n return _id++;\n}\nfunction getValidTagName(element) {\n if (element instanceof HTMLFormElement) {\n return 'form';\n }\n const processedTagName = toLowerCase(element.tagName);\n if (tagNameRegex.test(processedTagName)) {\n return 'div';\n }\n return processedTagName;\n}\nfunction extractOrigin(url) {\n let origin = '';\n if (url.indexOf('//') > -1) {\n origin = url.split('/').slice(0, 3).join('/');\n }\n else {\n origin = url.split('/')[0];\n }\n origin = origin.split('?')[0];\n return origin;\n}\nlet canvasService;\nlet canvasCtx;\nconst URL_IN_CSS_REF = /url\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\)/gm;\nconst URL_PROTOCOL_MATCH = /^(?:[a-z+]+:)?\\/\\//i;\nconst URL_WWW_MATCH = /^www\\..*/i;\nconst DATA_URI = /^(data:)([^,]*),(.*)/i;\nfunction absoluteToStylesheet(cssText, href) {\n return (cssText || '').replace(URL_IN_CSS_REF, (origin, quote1, path1, quote2, path2, path3) => {\n const filePath = path1 || path2 || path3;\n const maybeQuote = quote1 || quote2 || '';\n if (!filePath) {\n return origin;\n }\n if (URL_PROTOCOL_MATCH.test(filePath) || URL_WWW_MATCH.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (DATA_URI.test(filePath)) {\n return `url(${maybeQuote}${filePath}${maybeQuote})`;\n }\n if (filePath[0] === '/') {\n return `url(${maybeQuote}${extractOrigin(href) + filePath}${maybeQuote})`;\n }\n const stack = href.split('/');\n const parts = filePath.split('/');\n stack.pop();\n for (const part of parts) {\n if (part === '.') {\n continue;\n }\n else if (part === '..') {\n stack.pop();\n }\n else {\n stack.push(part);\n }\n }\n return `url(${maybeQuote}${stack.join('/')}${maybeQuote})`;\n });\n}\nconst SRCSET_NOT_SPACES = /^[^ \\t\\n\\r\\u000c]+/;\nconst SRCSET_COMMAS_OR_SPACES = /^[, \\t\\n\\r\\u000c]+/;\nfunction getAbsoluteSrcsetString(doc, attributeValue) {\n if (attributeValue.trim() === '') {\n return attributeValue;\n }\n let pos = 0;\n function collectCharacters(regEx) {\n let chars;\n const match = regEx.exec(attributeValue.substring(pos));\n if (match) {\n chars = match[0];\n pos += chars.length;\n return chars;\n }\n return '';\n }\n const output = [];\n while (true) {\n collectCharacters(SRCSET_COMMAS_OR_SPACES);\n if (pos >= attributeValue.length) {\n break;\n }\n let url = collectCharacters(SRCSET_NOT_SPACES);\n if (url.slice(-1) === ',') {\n url = absoluteToDoc(doc, url.substring(0, url.length - 1));\n output.push(url);\n }\n else {\n let descriptorsStr = '';\n url = absoluteToDoc(doc, url);\n let inParens = false;\n while (true) {\n const c = attributeValue.charAt(pos);\n if (c === '') {\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (!inParens) {\n if (c === ',') {\n pos += 1;\n output.push((url + descriptorsStr).trim());\n break;\n }\n else if (c === '(') {\n inParens = true;\n }\n }\n else {\n if (c === ')') {\n inParens = false;\n }\n }\n descriptorsStr += c;\n pos += 1;\n }\n }\n }\n return output.join(', ');\n}\nconst cachedDocument = new WeakMap();\nfunction absoluteToDoc(doc, attributeValue) {\n if (!attributeValue || attributeValue.trim() === '') {\n return attributeValue;\n }\n return getHref(doc, attributeValue);\n}\nfunction isSVGElement(el) {\n return Boolean(el.tagName === 'svg' || el.ownerSVGElement);\n}\nfunction getHref(doc, customHref) {\n let a = cachedDocument.get(doc);\n if (!a) {\n a = doc.createElement('a');\n cachedDocument.set(doc, a);\n }\n if (!customHref) {\n customHref = '';\n }\n else if (customHref.startsWith('blob:') || customHref.startsWith('data:')) {\n return customHref;\n }\n a.setAttribute('href', customHref);\n return a.href;\n}\nfunction transformAttribute(doc, tagName, name, value, element, maskAttributeFn) {\n if (!value) {\n return value;\n }\n if (name === 'src' ||\n (name === 'href' && !(tagName === 'use' && value[0] === '#'))) {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'xlink:href' && value[0] !== '#') {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'background' &&\n (tagName === 'table' || tagName === 'td' || tagName === 'th')) {\n return absoluteToDoc(doc, value);\n }\n else if (name === 'srcset') {\n return getAbsoluteSrcsetString(doc, value);\n }\n else if (name === 'style') {\n return absoluteToStylesheet(value, getHref(doc));\n }\n else if (tagName === 'object' && name === 'data') {\n return absoluteToDoc(doc, value);\n }\n if (typeof maskAttributeFn === 'function') {\n return maskAttributeFn(name, value, element);\n }\n return value;\n}\nfunction ignoreAttribute(tagName, name, _value) {\n return (tagName === 'video' || tagName === 'audio') && name === 'autoplay';\n}\nfunction _isBlockedElement(element, blockClass, blockSelector, unblockSelector) {\n try {\n if (unblockSelector && element.matches(unblockSelector)) {\n return false;\n }\n if (typeof blockClass === 'string') {\n if (element.classList.contains(blockClass)) {\n return true;\n }\n }\n else {\n for (let eIndex = element.classList.length; eIndex--;) {\n const className = element.classList[eIndex];\n if (blockClass.test(className)) {\n return true;\n }\n }\n }\n if (blockSelector) {\n return element.matches(blockSelector);\n }\n }\n catch (e) {\n }\n return false;\n}\nfunction elementClassMatchesRegex(el, regex) {\n for (let eIndex = el.classList.length; eIndex--;) {\n const className = el.classList[eIndex];\n if (regex.test(className)) {\n return true;\n }\n }\n return false;\n}\nfunction distanceToMatch(node, matchPredicate, limit = Infinity, distance = 0) {\n if (!node)\n return -1;\n if (node.nodeType !== node.ELEMENT_NODE)\n return -1;\n if (distance > limit)\n return -1;\n if (matchPredicate(node))\n return distance;\n return distanceToMatch(node.parentNode, matchPredicate, limit, distance + 1);\n}\nfunction createMatchPredicate(className, selector) {\n return (node) => {\n const el = node;\n if (el === null)\n return false;\n try {\n if (className) {\n if (typeof className === 'string') {\n if (el.matches(`.${className}`))\n return true;\n }\n else if (elementClassMatchesRegex(el, className)) {\n return true;\n }\n }\n if (selector && el.matches(selector))\n return true;\n return false;\n }\n catch {\n return false;\n }\n };\n}\nfunction needMaskingText(node, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText) {\n try {\n const el = node.nodeType === node.ELEMENT_NODE\n ? node\n : node.parentElement;\n if (el === null)\n return false;\n if (el.tagName === 'INPUT') {\n const autocomplete = el.getAttribute('autocomplete');\n const disallowedAutocompleteValues = [\n 'current-password',\n 'new-password',\n 'cc-number',\n 'cc-exp',\n 'cc-exp-month',\n 'cc-exp-year',\n 'cc-csc',\n ];\n if (disallowedAutocompleteValues.includes(autocomplete)) {\n return true;\n }\n }\n let maskDistance = -1;\n let unmaskDistance = -1;\n if (maskAllText) {\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector));\n if (unmaskDistance < 0) {\n return true;\n }\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector), unmaskDistance >= 0 ? unmaskDistance : Infinity);\n }\n else {\n maskDistance = distanceToMatch(el, createMatchPredicate(maskTextClass, maskTextSelector));\n if (maskDistance < 0) {\n return false;\n }\n unmaskDistance = distanceToMatch(el, createMatchPredicate(unmaskTextClass, unmaskTextSelector), maskDistance >= 0 ? maskDistance : Infinity);\n }\n return maskDistance >= 0\n ? unmaskDistance >= 0\n ? maskDistance <= unmaskDistance\n : true\n : unmaskDistance >= 0\n ? false\n : !!maskAllText;\n }\n catch (e) {\n }\n return !!maskAllText;\n}\nfunction onceIframeLoaded(iframeEl, listener, iframeLoadTimeout) {\n const win = iframeEl.contentWindow;\n if (!win) {\n return;\n }\n let fired = false;\n let readyState;\n try {\n readyState = win.document.readyState;\n }\n catch (error) {\n return;\n }\n if (readyState !== 'complete') {\n const timer = setTimeout$2(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, iframeLoadTimeout);\n iframeEl.addEventListener('load', () => {\n clearTimeout$2(timer);\n fired = true;\n listener();\n });\n return;\n }\n const blankUrl = 'about:blank';\n if (win.location.href !== blankUrl ||\n iframeEl.src === blankUrl ||\n iframeEl.src === '') {\n setTimeout$2(listener, 0);\n return iframeEl.addEventListener('load', listener);\n }\n iframeEl.addEventListener('load', listener);\n}\nfunction onceStylesheetLoaded(link, listener, styleSheetLoadTimeout) {\n let fired = false;\n let styleSheetLoaded;\n try {\n styleSheetLoaded = link.sheet;\n }\n catch (error) {\n return;\n }\n if (styleSheetLoaded)\n return;\n const timer = setTimeout$2(() => {\n if (!fired) {\n listener();\n fired = true;\n }\n }, styleSheetLoadTimeout);\n link.addEventListener('load', () => {\n clearTimeout$2(timer);\n fired = true;\n listener();\n });\n}\nfunction serializeNode(n, options) {\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskAttributeFn, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, inlineStylesheet, maskInputOptions = {}, maskTextFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, } = options;\n const rootId = getRootId(doc, mirror);\n switch (n.nodeType) {\n case n.DOCUMENT_NODE:\n if (n.compatMode !== 'CSS1Compat') {\n return {\n type: NodeType$3.Document,\n childNodes: [],\n compatMode: n.compatMode,\n };\n }\n else {\n return {\n type: NodeType$3.Document,\n childNodes: [],\n };\n }\n case n.DOCUMENT_TYPE_NODE:\n return {\n type: NodeType$3.DocumentType,\n name: n.name,\n publicId: n.publicId,\n systemId: n.systemId,\n rootId,\n };\n case n.ELEMENT_NODE:\n return serializeElementNode(n, {\n doc,\n blockClass,\n blockSelector,\n unblockSelector,\n inlineStylesheet,\n maskAttributeFn,\n maskInputOptions,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement,\n rootId,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n });\n case n.TEXT_NODE:\n return serializeTextNode(n, {\n doc,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskTextFn,\n maskInputOptions,\n maskInputFn,\n rootId,\n });\n case n.CDATA_SECTION_NODE:\n return {\n type: NodeType$3.CDATA,\n textContent: '',\n rootId,\n };\n case n.COMMENT_NODE:\n return {\n type: NodeType$3.Comment,\n textContent: n.textContent || '',\n rootId,\n };\n default:\n return false;\n }\n}\nfunction getRootId(doc, mirror) {\n if (!mirror.hasNode(doc))\n return undefined;\n const docId = mirror.getId(doc);\n return docId === 1 ? undefined : docId;\n}\nfunction serializeTextNode(n, options) {\n const { maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, maskTextFn, maskInputOptions, maskInputFn, rootId, } = options;\n const parentTagName = n.parentNode && n.parentNode.tagName;\n let textContent = n.textContent;\n const isStyle = parentTagName === 'STYLE' ? true : undefined;\n const isScript = parentTagName === 'SCRIPT' ? true : undefined;\n const isTextarea = parentTagName === 'TEXTAREA' ? true : undefined;\n if (isStyle && textContent) {\n try {\n if (n.nextSibling || n.previousSibling) {\n }\n else if (n.parentNode.sheet?.cssRules) {\n textContent = stringifyStylesheet(n.parentNode.sheet);\n }\n }\n catch (err) {\n console.warn(`Cannot get CSS styles from text's parentNode. Error: ${err}`, n);\n }\n textContent = absoluteToStylesheet(textContent, getHref(options.doc));\n }\n if (isScript) {\n textContent = 'SCRIPT_PLACEHOLDER';\n }\n const forceMask = needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, maskAllText);\n if (!isStyle && !isScript && !isTextarea && textContent && forceMask) {\n textContent = maskTextFn\n ? maskTextFn(textContent, n.parentElement)\n : textContent.replace(/[\\S]/g, '*');\n }\n if (isTextarea && textContent && (maskInputOptions.textarea || forceMask)) {\n textContent = maskInputFn\n ? maskInputFn(textContent, n.parentNode)\n : textContent.replace(/[\\S]/g, '*');\n }\n if (parentTagName === 'OPTION' && textContent) {\n const isInputMasked = shouldMaskInput({\n type: null,\n tagName: parentTagName,\n maskInputOptions,\n });\n textContent = maskInputValue({\n isMasked: needMaskingText(n, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked),\n element: n,\n value: textContent,\n maskInputFn,\n });\n }\n return {\n type: NodeType$3.Text,\n textContent: textContent || '',\n isStyle,\n rootId,\n };\n}\nfunction serializeElementNode(n, options) {\n const { doc, blockClass, blockSelector, unblockSelector, inlineStylesheet, maskInputOptions = {}, maskAttributeFn, maskInputFn, dataURLOptions = {}, inlineImages, recordCanvas, keepIframeSrcFn, newlyAddedElement = false, rootId, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, } = options;\n const needBlock = _isBlockedElement(n, blockClass, blockSelector, unblockSelector);\n const tagName = getValidTagName(n);\n let attributes = {};\n const len = n.attributes.length;\n for (let i = 0; i < len; i++) {\n const attr = n.attributes[i];\n if (attr.name && !ignoreAttribute(tagName, attr.name, attr.value)) {\n attributes[attr.name] = transformAttribute(doc, tagName, toLowerCase(attr.name), attr.value, n, maskAttributeFn);\n }\n }\n if (tagName === 'link' && inlineStylesheet) {\n const stylesheet = Array.from(doc.styleSheets).find((s) => {\n return s.href === n.href;\n });\n let cssText = null;\n if (stylesheet) {\n cssText = stringifyStylesheet(stylesheet);\n }\n if (cssText) {\n attributes.rel = null;\n attributes.href = null;\n attributes.crossorigin = null;\n attributes._cssText = absoluteToStylesheet(cssText, stylesheet.href);\n }\n }\n if (tagName === 'style' &&\n n.sheet &&\n !(n.innerText || n.textContent || '').trim().length) {\n const cssText = stringifyStylesheet(n.sheet);\n if (cssText) {\n attributes._cssText = absoluteToStylesheet(cssText, getHref(doc));\n }\n }\n if (tagName === 'input' ||\n tagName === 'textarea' ||\n tagName === 'select' ||\n tagName === 'option') {\n const el = n;\n const type = getInputType(el);\n const value = getInputValue(el, toUpperCase(tagName), type);\n const checked = el.checked;\n if (type !== 'submit' && type !== 'button' && value) {\n const forceMask = needMaskingText(el, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, shouldMaskInput({\n type,\n tagName: toUpperCase(tagName),\n maskInputOptions,\n }));\n attributes.value = maskInputValue({\n isMasked: forceMask,\n element: el,\n value,\n maskInputFn,\n });\n }\n if (checked) {\n attributes.checked = checked;\n }\n }\n if (tagName === 'option') {\n if (n.selected && !maskInputOptions['select']) {\n attributes.selected = true;\n }\n else {\n delete attributes.selected;\n }\n }\n if (tagName === 'canvas' && recordCanvas) {\n if (n.__context === '2d') {\n if (!is2DCanvasBlank(n)) {\n attributes.rr_dataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n }\n else if (!('__context' in n)) {\n const canvasDataURL = n.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n const blankCanvas = doc.createElement('canvas');\n blankCanvas.width = n.width;\n blankCanvas.height = n.height;\n const blankCanvasDataURL = blankCanvas.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n if (canvasDataURL !== blankCanvasDataURL) {\n attributes.rr_dataURL = canvasDataURL;\n }\n }\n }\n if (tagName === 'img' && inlineImages) {\n if (!canvasService) {\n canvasService = doc.createElement('canvas');\n canvasCtx = canvasService.getContext('2d');\n }\n const image = n;\n const imageSrc = image.currentSrc || image.getAttribute('src') || '';\n const priorCrossOrigin = image.crossOrigin;\n const recordInlineImage = () => {\n image.removeEventListener('load', recordInlineImage);\n try {\n canvasService.width = image.naturalWidth;\n canvasService.height = image.naturalHeight;\n canvasCtx.drawImage(image, 0, 0);\n attributes.rr_dataURL = canvasService.toDataURL(dataURLOptions.type, dataURLOptions.quality);\n }\n catch (err) {\n if (image.crossOrigin !== 'anonymous') {\n image.crossOrigin = 'anonymous';\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else\n image.addEventListener('load', recordInlineImage);\n return;\n }\n else {\n console.warn(`Cannot inline img src=${imageSrc}! Error: ${err}`);\n }\n }\n if (image.crossOrigin === 'anonymous') {\n priorCrossOrigin\n ? (attributes.crossOrigin = priorCrossOrigin)\n : image.removeAttribute('crossorigin');\n }\n };\n if (image.complete && image.naturalWidth !== 0)\n recordInlineImage();\n else\n image.addEventListener('load', recordInlineImage);\n }\n if (tagName === 'audio' || tagName === 'video') {\n attributes.rr_mediaState = n.paused\n ? 'paused'\n : 'played';\n attributes.rr_mediaCurrentTime = n.currentTime;\n }\n if (!newlyAddedElement) {\n if (n.scrollLeft) {\n attributes.rr_scrollLeft = n.scrollLeft;\n }\n if (n.scrollTop) {\n attributes.rr_scrollTop = n.scrollTop;\n }\n }\n if (needBlock) {\n const { width, height } = n.getBoundingClientRect();\n attributes = {\n class: attributes.class,\n rr_width: `${width}px`,\n rr_height: `${height}px`,\n };\n }\n if (tagName === 'iframe' && !keepIframeSrcFn(attributes.src)) {\n if (!needBlock && !getIframeContentDocument(n)) {\n attributes.rr_src = attributes.src;\n }\n delete attributes.src;\n }\n let isCustomElement;\n try {\n if (customElements.get(tagName))\n isCustomElement = true;\n }\n catch (e) {\n }\n return {\n type: NodeType$3.Element,\n tagName,\n attributes,\n childNodes: [],\n isSVG: isSVGElement(n) || undefined,\n needBlock,\n rootId,\n isCustom: isCustomElement,\n };\n}\nfunction lowerIfExists(maybeAttr) {\n if (maybeAttr === undefined || maybeAttr === null) {\n return '';\n }\n else {\n return maybeAttr.toLowerCase();\n }\n}\nfunction slimDOMExcluded(sn, slimDOMOptions) {\n if (slimDOMOptions.comment && sn.type === NodeType$3.Comment) {\n return true;\n }\n else if (sn.type === NodeType$3.Element) {\n if (slimDOMOptions.script &&\n (sn.tagName === 'script' ||\n (sn.tagName === 'link' &&\n (sn.attributes.rel === 'preload' ||\n sn.attributes.rel === 'modulepreload')) ||\n (sn.tagName === 'link' &&\n sn.attributes.rel === 'prefetch' &&\n typeof sn.attributes.href === 'string' &&\n extractFileExtension(sn.attributes.href) === 'js'))) {\n return true;\n }\n else if (slimDOMOptions.headFavicon &&\n ((sn.tagName === 'link' && sn.attributes.rel === 'shortcut icon') ||\n (sn.tagName === 'meta' &&\n (lowerIfExists(sn.attributes.name).match(/^msapplication-tile(image|color)$/) ||\n lowerIfExists(sn.attributes.name) === 'application-name' ||\n lowerIfExists(sn.attributes.rel) === 'icon' ||\n lowerIfExists(sn.attributes.rel) === 'apple-touch-icon' ||\n lowerIfExists(sn.attributes.rel) === 'shortcut icon')))) {\n return true;\n }\n else if (sn.tagName === 'meta') {\n if (slimDOMOptions.headMetaDescKeywords &&\n lowerIfExists(sn.attributes.name).match(/^description|keywords$/)) {\n return true;\n }\n else if (slimDOMOptions.headMetaSocial &&\n (lowerIfExists(sn.attributes.property).match(/^(og|twitter|fb):/) ||\n lowerIfExists(sn.attributes.name).match(/^(og|twitter):/) ||\n lowerIfExists(sn.attributes.name) === 'pinterest')) {\n return true;\n }\n else if (slimDOMOptions.headMetaRobots &&\n (lowerIfExists(sn.attributes.name) === 'robots' ||\n lowerIfExists(sn.attributes.name) === 'googlebot' ||\n lowerIfExists(sn.attributes.name) === 'bingbot')) {\n return true;\n }\n else if (slimDOMOptions.headMetaHttpEquiv &&\n sn.attributes['http-equiv'] !== undefined) {\n return true;\n }\n else if (slimDOMOptions.headMetaAuthorship &&\n (lowerIfExists(sn.attributes.name) === 'author' ||\n lowerIfExists(sn.attributes.name) === 'generator' ||\n lowerIfExists(sn.attributes.name) === 'framework' ||\n lowerIfExists(sn.attributes.name) === 'publisher' ||\n lowerIfExists(sn.attributes.name) === 'progid' ||\n lowerIfExists(sn.attributes.property).match(/^article:/) ||\n lowerIfExists(sn.attributes.property).match(/^product:/))) {\n return true;\n }\n else if (slimDOMOptions.headMetaVerification &&\n (lowerIfExists(sn.attributes.name) === 'google-site-verification' ||\n lowerIfExists(sn.attributes.name) === 'yandex-verification' ||\n lowerIfExists(sn.attributes.name) === 'csrf-token' ||\n lowerIfExists(sn.attributes.name) === 'p:domain_verify' ||\n lowerIfExists(sn.attributes.name) === 'verify-v1' ||\n lowerIfExists(sn.attributes.name) === 'verification' ||\n lowerIfExists(sn.attributes.name) === 'shopify-checkout-api-token')) {\n return true;\n }\n }\n }\n return false;\n}\nfunction serializeNodeWithId(n, options) {\n const { doc, mirror, blockClass, blockSelector, unblockSelector, maskAllText, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, skipChild = false, inlineStylesheet = true, maskInputOptions = {}, maskAttributeFn, maskTextFn, maskInputFn, slimDOMOptions, dataURLOptions = {}, inlineImages = false, recordCanvas = false, onSerialize, onIframeLoad, iframeLoadTimeout = 5000, onStylesheetLoad, stylesheetLoadTimeout = 5000, keepIframeSrcFn = () => false, newlyAddedElement = false, } = options;\n let { preserveWhiteSpace = true } = options;\n const _serializedNode = serializeNode(n, {\n doc,\n mirror,\n blockClass,\n blockSelector,\n maskAllText,\n unblockSelector,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n keepIframeSrcFn,\n newlyAddedElement,\n });\n if (!_serializedNode) {\n console.warn(n, 'not serialized');\n return null;\n }\n let id;\n if (mirror.hasNode(n)) {\n id = mirror.getId(n);\n }\n else if (slimDOMExcluded(_serializedNode, slimDOMOptions) ||\n (!preserveWhiteSpace &&\n _serializedNode.type === NodeType$3.Text &&\n !_serializedNode.isStyle &&\n !_serializedNode.textContent.replace(/^\\s+|\\s+$/gm, '').length)) {\n id = IGNORED_NODE;\n }\n else {\n id = genId();\n }\n const serializedNode = Object.assign(_serializedNode, { id });\n mirror.add(n, serializedNode);\n if (id === IGNORED_NODE) {\n return null;\n }\n if (onSerialize) {\n onSerialize(n);\n }\n let recordChild = !skipChild;\n if (serializedNode.type === NodeType$3.Element) {\n recordChild = recordChild && !serializedNode.needBlock;\n delete serializedNode.needBlock;\n const shadowRoot = n.shadowRoot;\n if (shadowRoot && isNativeShadowDom(shadowRoot))\n serializedNode.isShadowHost = true;\n }\n if ((serializedNode.type === NodeType$3.Document ||\n serializedNode.type === NodeType$3.Element) &&\n recordChild) {\n if (slimDOMOptions.headWhitespace &&\n serializedNode.type === NodeType$3.Element &&\n serializedNode.tagName === 'head') {\n preserveWhiteSpace = false;\n }\n const bypassOptions = {\n doc,\n mirror,\n blockClass,\n blockSelector,\n maskAllText,\n unblockSelector,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n };\n for (const childN of Array.from(n.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n if (isElement$1(n) && n.shadowRoot) {\n for (const childN of Array.from(n.shadowRoot.childNodes)) {\n const serializedChildNode = serializeNodeWithId(childN, bypassOptions);\n if (serializedChildNode) {\n isNativeShadowDom(n.shadowRoot) &&\n (serializedChildNode.isShadow = true);\n serializedNode.childNodes.push(serializedChildNode);\n }\n }\n }\n }\n if (n.parentNode &&\n isShadowRoot(n.parentNode) &&\n isNativeShadowDom(n.parentNode)) {\n serializedNode.isShadow = true;\n }\n if (serializedNode.type === NodeType$3.Element &&\n serializedNode.tagName === 'iframe') {\n onceIframeLoaded(n, () => {\n const iframeDoc = getIframeContentDocument(n);\n if (iframeDoc && onIframeLoad) {\n const serializedIframeNode = serializeNodeWithId(iframeDoc, {\n doc: iframeDoc,\n mirror,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n });\n if (serializedIframeNode) {\n onIframeLoad(n, serializedIframeNode);\n }\n }\n }, iframeLoadTimeout);\n }\n if (serializedNode.type === NodeType$3.Element &&\n serializedNode.tagName === 'link' &&\n typeof serializedNode.attributes.rel === 'string' &&\n (serializedNode.attributes.rel === 'stylesheet' ||\n (serializedNode.attributes.rel === 'preload' &&\n typeof serializedNode.attributes.href === 'string' &&\n extractFileExtension(serializedNode.attributes.href) === 'css'))) {\n onceStylesheetLoaded(n, () => {\n if (onStylesheetLoad) {\n const serializedLinkNode = serializeNodeWithId(n, {\n doc,\n mirror,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n });\n if (serializedLinkNode) {\n onStylesheetLoad(n, serializedLinkNode);\n }\n }\n }, stylesheetLoadTimeout);\n }\n return serializedNode;\n}\nfunction snapshot(n, options) {\n const { mirror = new Mirror(), blockClass = 'rr-block', blockSelector = null, unblockSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, inlineImages = false, recordCanvas = false, maskAllInputs = false, maskAttributeFn, maskTextFn, maskInputFn, slimDOM = false, dataURLOptions, preserveWhiteSpace, onSerialize, onIframeLoad, iframeLoadTimeout, onStylesheetLoad, stylesheetLoadTimeout, keepIframeSrcFn = () => false, } = options;\n const maskInputOptions = maskAllInputs === true\n ? {\n color: true,\n date: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n }\n : maskAllInputs === false\n ? {}\n : maskAllInputs;\n const slimDOMOptions = slimDOM === true || slimDOM === 'all'\n ?\n {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaDescKeywords: slimDOM === 'all',\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaAuthorship: true,\n headMetaVerification: true,\n }\n : slimDOM === false\n ? {}\n : slimDOM;\n return serializeNodeWithId(n, {\n doc: n,\n mirror,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n skipChild: false,\n inlineStylesheet,\n maskInputOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n slimDOMOptions,\n dataURLOptions,\n inlineImages,\n recordCanvas,\n preserveWhiteSpace,\n onSerialize,\n onIframeLoad,\n iframeLoadTimeout,\n onStylesheetLoad,\n stylesheetLoadTimeout,\n keepIframeSrcFn,\n newlyAddedElement: false,\n });\n}\n\nfunction on(type, fn, target = document) {\n const options = { capture: true, passive: true };\n target.addEventListener(type, fn, options);\n return () => target.removeEventListener(type, fn, options);\n}\nconst DEPARTED_MIRROR_ACCESS_WARNING = 'Please stop import mirror directly. Instead of that,' +\n '\\r\\n' +\n 'now you can use replayer.getMirror() to access the mirror instance of a replayer,' +\n '\\r\\n' +\n 'or you can use record.mirror to access the mirror instance during recording.';\nlet _mirror = {\n map: {},\n getId() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return -1;\n },\n getNode() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return null;\n },\n removeNodeFromMap() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n has() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n return false;\n },\n reset() {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n },\n};\nif (typeof window !== 'undefined' && window.Proxy && window.Reflect) {\n _mirror = new Proxy(_mirror, {\n get(target, prop, receiver) {\n if (prop === 'map') {\n console.error(DEPARTED_MIRROR_ACCESS_WARNING);\n }\n return Reflect.get(target, prop, receiver);\n },\n });\n}\nfunction throttle$1(func, wait, options = {}) {\n let timeout = null;\n let previous = 0;\n return function (...args) {\n const now = Date.now();\n if (!previous && options.leading === false) {\n previous = now;\n }\n const remaining = wait - (now - previous);\n const context = this;\n if (remaining <= 0 || remaining > wait) {\n if (timeout) {\n clearTimeout$1(timeout);\n timeout = null;\n }\n previous = now;\n func.apply(context, args);\n }\n else if (!timeout && options.trailing !== false) {\n timeout = setTimeout$1(() => {\n previous = options.leading === false ? 0 : Date.now();\n timeout = null;\n func.apply(context, args);\n }, remaining);\n }\n };\n}\nfunction hookSetter(target, key, d, isRevoked, win = window) {\n const original = win.Object.getOwnPropertyDescriptor(target, key);\n win.Object.defineProperty(target, key, isRevoked\n ? d\n : {\n set(value) {\n setTimeout$1(() => {\n d.set.call(this, value);\n }, 0);\n if (original && original.set) {\n original.set.call(this, value);\n }\n },\n });\n return () => hookSetter(target, key, original || {}, true);\n}\nfunction patch(source, name, replacement) {\n try {\n if (!(name in source)) {\n return () => {\n };\n }\n const original = source[name];\n const wrapped = replacement(original);\n if (typeof wrapped === 'function') {\n wrapped.prototype = wrapped.prototype || {};\n Object.defineProperties(wrapped, {\n __rrweb_original__: {\n enumerable: false,\n value: original,\n },\n });\n }\n source[name] = wrapped;\n return () => {\n source[name] = original;\n };\n }\n catch {\n return () => {\n };\n }\n}\nlet nowTimestamp = Date.now;\nif (!(/[1-9][0-9]{12}/.test(Date.now().toString()))) {\n nowTimestamp = () => new Date().getTime();\n}\nfunction getWindowScroll(win) {\n const doc = win.document;\n return {\n left: doc.scrollingElement\n ? doc.scrollingElement.scrollLeft\n : win.pageXOffset !== undefined\n ? win.pageXOffset\n : doc?.documentElement.scrollLeft ||\n doc?.body?.parentElement?.scrollLeft ||\n doc?.body?.scrollLeft ||\n 0,\n top: doc.scrollingElement\n ? doc.scrollingElement.scrollTop\n : win.pageYOffset !== undefined\n ? win.pageYOffset\n : doc?.documentElement.scrollTop ||\n doc?.body?.parentElement?.scrollTop ||\n doc?.body?.scrollTop ||\n 0,\n };\n}\nfunction getWindowHeight() {\n return (window.innerHeight ||\n (document.documentElement && document.documentElement.clientHeight) ||\n (document.body && document.body.clientHeight));\n}\nfunction getWindowWidth() {\n return (window.innerWidth ||\n (document.documentElement && document.documentElement.clientWidth) ||\n (document.body && document.body.clientWidth));\n}\nfunction closestElementOfNode(node) {\n if (!node) {\n return null;\n }\n const el = node.nodeType === node.ELEMENT_NODE\n ? node\n : node.parentElement;\n return el;\n}\nfunction isBlocked(node, blockClass, blockSelector, unblockSelector, checkAncestors) {\n if (!node) {\n return false;\n }\n const el = closestElementOfNode(node);\n if (!el) {\n return false;\n }\n const blockedPredicate = createMatchPredicate(blockClass, blockSelector);\n if (!checkAncestors) {\n const isUnblocked = unblockSelector && el.matches(unblockSelector);\n return blockedPredicate(el) && !isUnblocked;\n }\n const blockDistance = distanceToMatch(el, blockedPredicate);\n let unblockDistance = -1;\n if (blockDistance < 0) {\n return false;\n }\n if (unblockSelector) {\n unblockDistance = distanceToMatch(el, createMatchPredicate(null, unblockSelector));\n }\n if (blockDistance > -1 && unblockDistance < 0) {\n return true;\n }\n return blockDistance < unblockDistance;\n}\nfunction isSerialized(n, mirror) {\n return mirror.getId(n) !== -1;\n}\nfunction isIgnored(n, mirror) {\n return mirror.getId(n) === IGNORED_NODE;\n}\nfunction isAncestorRemoved(target, mirror) {\n if (isShadowRoot(target)) {\n return false;\n }\n const id = mirror.getId(target);\n if (!mirror.has(id)) {\n return true;\n }\n if (target.parentNode &&\n target.parentNode.nodeType === target.DOCUMENT_NODE) {\n return false;\n }\n if (!target.parentNode) {\n return true;\n }\n return isAncestorRemoved(target.parentNode, mirror);\n}\nfunction legacy_isTouchEvent(event) {\n return Boolean(event.changedTouches);\n}\nfunction polyfill(win = window) {\n if ('NodeList' in win && !win.NodeList.prototype.forEach) {\n win.NodeList.prototype.forEach = Array.prototype\n .forEach;\n }\n if ('DOMTokenList' in win && !win.DOMTokenList.prototype.forEach) {\n win.DOMTokenList.prototype.forEach = Array.prototype\n .forEach;\n }\n if (!Node.prototype.contains) {\n Node.prototype.contains = (...args) => {\n let node = args[0];\n if (!(0 in args)) {\n throw new TypeError('1 argument is required');\n }\n do {\n if (this === node) {\n return true;\n }\n } while ((node = node && node.parentNode));\n return false;\n };\n }\n}\nfunction isSerializedIframe(n, mirror) {\n return Boolean(n.nodeName === 'IFRAME' && mirror.getMeta(n));\n}\nfunction isSerializedStylesheet(n, mirror) {\n return Boolean(n.nodeName === 'LINK' &&\n n.nodeType === n.ELEMENT_NODE &&\n n.getAttribute &&\n n.getAttribute('rel') === 'stylesheet' &&\n mirror.getMeta(n));\n}\nfunction hasShadowRoot(n) {\n return Boolean(n?.shadowRoot);\n}\nclass StyleSheetMirror {\n constructor() {\n this.id = 1;\n this.styleIDMap = new WeakMap();\n this.idStyleMap = new Map();\n }\n getId(stylesheet) {\n return this.styleIDMap.get(stylesheet) ?? -1;\n }\n has(stylesheet) {\n return this.styleIDMap.has(stylesheet);\n }\n add(stylesheet, id) {\n if (this.has(stylesheet))\n return this.getId(stylesheet);\n let newId;\n if (id === undefined) {\n newId = this.id++;\n }\n else\n newId = id;\n this.styleIDMap.set(stylesheet, newId);\n this.idStyleMap.set(newId, stylesheet);\n return newId;\n }\n getStyle(id) {\n return this.idStyleMap.get(id) || null;\n }\n reset() {\n this.styleIDMap = new WeakMap();\n this.idStyleMap = new Map();\n this.id = 1;\n }\n generateId() {\n return this.id++;\n }\n}\nfunction getShadowHost(n) {\n let shadowHost = null;\n if (n.getRootNode?.()?.nodeType === Node.DOCUMENT_FRAGMENT_NODE &&\n n.getRootNode().host)\n shadowHost = n.getRootNode().host;\n return shadowHost;\n}\nfunction getRootShadowHost(n) {\n let rootShadowHost = n;\n let shadowHost;\n while ((shadowHost = getShadowHost(rootShadowHost)))\n rootShadowHost = shadowHost;\n return rootShadowHost;\n}\nfunction shadowHostInDom(n) {\n const doc = n.ownerDocument;\n if (!doc)\n return false;\n const shadowHost = getRootShadowHost(n);\n return doc.contains(shadowHost);\n}\nfunction inDom(n) {\n const doc = n.ownerDocument;\n if (!doc)\n return false;\n return doc.contains(n) || shadowHostInDom(n);\n}\nconst cachedImplementations = {};\nfunction getImplementation(name) {\n const cached = cachedImplementations[name];\n if (cached) {\n return cached;\n }\n const document = window.document;\n let impl = window[name];\n if (document && typeof document.createElement === 'function') {\n try {\n const sandbox = document.createElement('iframe');\n sandbox.hidden = true;\n document.head.appendChild(sandbox);\n const contentWindow = sandbox.contentWindow;\n if (contentWindow && contentWindow[name]) {\n impl =\n contentWindow[name];\n }\n document.head.removeChild(sandbox);\n }\n catch (e) {\n }\n }\n return (cachedImplementations[name] = impl.bind(window));\n}\nfunction onRequestAnimationFrame(...rest) {\n return getImplementation('requestAnimationFrame')(...rest);\n}\nfunction setTimeout$1(...rest) {\n return getImplementation('setTimeout')(...rest);\n}\nfunction clearTimeout$1(...rest) {\n return getImplementation('clearTimeout')(...rest);\n}\n\nvar EventType = /* @__PURE__ */ ((EventType2) => {\n EventType2[EventType2[\"DomContentLoaded\"] = 0] = \"DomContentLoaded\";\n EventType2[EventType2[\"Load\"] = 1] = \"Load\";\n EventType2[EventType2[\"FullSnapshot\"] = 2] = \"FullSnapshot\";\n EventType2[EventType2[\"IncrementalSnapshot\"] = 3] = \"IncrementalSnapshot\";\n EventType2[EventType2[\"Meta\"] = 4] = \"Meta\";\n EventType2[EventType2[\"Custom\"] = 5] = \"Custom\";\n EventType2[EventType2[\"Plugin\"] = 6] = \"Plugin\";\n return EventType2;\n})(EventType || {});\nvar IncrementalSource = /* @__PURE__ */ ((IncrementalSource2) => {\n IncrementalSource2[IncrementalSource2[\"Mutation\"] = 0] = \"Mutation\";\n IncrementalSource2[IncrementalSource2[\"MouseMove\"] = 1] = \"MouseMove\";\n IncrementalSource2[IncrementalSource2[\"MouseInteraction\"] = 2] = \"MouseInteraction\";\n IncrementalSource2[IncrementalSource2[\"Scroll\"] = 3] = \"Scroll\";\n IncrementalSource2[IncrementalSource2[\"ViewportResize\"] = 4] = \"ViewportResize\";\n IncrementalSource2[IncrementalSource2[\"Input\"] = 5] = \"Input\";\n IncrementalSource2[IncrementalSource2[\"TouchMove\"] = 6] = \"TouchMove\";\n IncrementalSource2[IncrementalSource2[\"MediaInteraction\"] = 7] = \"MediaInteraction\";\n IncrementalSource2[IncrementalSource2[\"StyleSheetRule\"] = 8] = \"StyleSheetRule\";\n IncrementalSource2[IncrementalSource2[\"CanvasMutation\"] = 9] = \"CanvasMutation\";\n IncrementalSource2[IncrementalSource2[\"Font\"] = 10] = \"Font\";\n IncrementalSource2[IncrementalSource2[\"Log\"] = 11] = \"Log\";\n IncrementalSource2[IncrementalSource2[\"Drag\"] = 12] = \"Drag\";\n IncrementalSource2[IncrementalSource2[\"StyleDeclaration\"] = 13] = \"StyleDeclaration\";\n IncrementalSource2[IncrementalSource2[\"Selection\"] = 14] = \"Selection\";\n IncrementalSource2[IncrementalSource2[\"AdoptedStyleSheet\"] = 15] = \"AdoptedStyleSheet\";\n IncrementalSource2[IncrementalSource2[\"CustomElement\"] = 16] = \"CustomElement\";\n return IncrementalSource2;\n})(IncrementalSource || {});\nvar MouseInteractions = /* @__PURE__ */ ((MouseInteractions2) => {\n MouseInteractions2[MouseInteractions2[\"MouseUp\"] = 0] = \"MouseUp\";\n MouseInteractions2[MouseInteractions2[\"MouseDown\"] = 1] = \"MouseDown\";\n MouseInteractions2[MouseInteractions2[\"Click\"] = 2] = \"Click\";\n MouseInteractions2[MouseInteractions2[\"ContextMenu\"] = 3] = \"ContextMenu\";\n MouseInteractions2[MouseInteractions2[\"DblClick\"] = 4] = \"DblClick\";\n MouseInteractions2[MouseInteractions2[\"Focus\"] = 5] = \"Focus\";\n MouseInteractions2[MouseInteractions2[\"Blur\"] = 6] = \"Blur\";\n MouseInteractions2[MouseInteractions2[\"TouchStart\"] = 7] = \"TouchStart\";\n MouseInteractions2[MouseInteractions2[\"TouchMove_Departed\"] = 8] = \"TouchMove_Departed\";\n MouseInteractions2[MouseInteractions2[\"TouchEnd\"] = 9] = \"TouchEnd\";\n MouseInteractions2[MouseInteractions2[\"TouchCancel\"] = 10] = \"TouchCancel\";\n return MouseInteractions2;\n})(MouseInteractions || {});\nvar PointerTypes = /* @__PURE__ */ ((PointerTypes2) => {\n PointerTypes2[PointerTypes2[\"Mouse\"] = 0] = \"Mouse\";\n PointerTypes2[PointerTypes2[\"Pen\"] = 1] = \"Pen\";\n PointerTypes2[PointerTypes2[\"Touch\"] = 2] = \"Touch\";\n return PointerTypes2;\n})(PointerTypes || {});\n\nvar NodeType$1;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType$1 || (NodeType$1 = {}));\nvar NodeType$2;\n(function (NodeType) {\n NodeType[NodeType[\"PLACEHOLDER\"] = 0] = \"PLACEHOLDER\";\n NodeType[NodeType[\"ELEMENT_NODE\"] = 1] = \"ELEMENT_NODE\";\n NodeType[NodeType[\"ATTRIBUTE_NODE\"] = 2] = \"ATTRIBUTE_NODE\";\n NodeType[NodeType[\"TEXT_NODE\"] = 3] = \"TEXT_NODE\";\n NodeType[NodeType[\"CDATA_SECTION_NODE\"] = 4] = \"CDATA_SECTION_NODE\";\n NodeType[NodeType[\"ENTITY_REFERENCE_NODE\"] = 5] = \"ENTITY_REFERENCE_NODE\";\n NodeType[NodeType[\"ENTITY_NODE\"] = 6] = \"ENTITY_NODE\";\n NodeType[NodeType[\"PROCESSING_INSTRUCTION_NODE\"] = 7] = \"PROCESSING_INSTRUCTION_NODE\";\n NodeType[NodeType[\"COMMENT_NODE\"] = 8] = \"COMMENT_NODE\";\n NodeType[NodeType[\"DOCUMENT_NODE\"] = 9] = \"DOCUMENT_NODE\";\n NodeType[NodeType[\"DOCUMENT_TYPE_NODE\"] = 10] = \"DOCUMENT_TYPE_NODE\";\n NodeType[NodeType[\"DOCUMENT_FRAGMENT_NODE\"] = 11] = \"DOCUMENT_FRAGMENT_NODE\";\n})(NodeType$2 || (NodeType$2 = {}));\n\nfunction getIFrameContentDocument(iframe) {\n try {\n return iframe.contentDocument;\n }\n catch (e) {\n }\n}\nfunction getIFrameContentWindow(iframe) {\n try {\n return iframe.contentWindow;\n }\n catch (e) {\n }\n}\n\nfunction isNodeInLinkedList(n) {\n return '__ln' in n;\n}\nclass DoubleLinkedList {\n constructor() {\n this.length = 0;\n this.head = null;\n this.tail = null;\n }\n get(position) {\n if (position >= this.length) {\n throw new Error('Position outside of list range');\n }\n let current = this.head;\n for (let index = 0; index < position; index++) {\n current = current?.next || null;\n }\n return current;\n }\n addNode(n) {\n const node = {\n value: n,\n previous: null,\n next: null,\n };\n n.__ln = node;\n if (n.previousSibling && isNodeInLinkedList(n.previousSibling)) {\n const current = n.previousSibling.__ln.next;\n node.next = current;\n node.previous = n.previousSibling.__ln;\n n.previousSibling.__ln.next = node;\n if (current) {\n current.previous = node;\n }\n }\n else if (n.nextSibling &&\n isNodeInLinkedList(n.nextSibling) &&\n n.nextSibling.__ln.previous) {\n const current = n.nextSibling.__ln.previous;\n node.previous = current;\n node.next = n.nextSibling.__ln;\n n.nextSibling.__ln.previous = node;\n if (current) {\n current.next = node;\n }\n }\n else {\n if (this.head) {\n this.head.previous = node;\n }\n node.next = this.head;\n this.head = node;\n }\n if (node.next === null) {\n this.tail = node;\n }\n this.length++;\n }\n removeNode(n) {\n const current = n.__ln;\n if (!this.head) {\n return;\n }\n if (!current.previous) {\n this.head = current.next;\n if (this.head) {\n this.head.previous = null;\n }\n else {\n this.tail = null;\n }\n }\n else {\n current.previous.next = current.next;\n if (current.next) {\n current.next.previous = current.previous;\n }\n else {\n this.tail = current.previous;\n }\n }\n if (n.__ln) {\n delete n.__ln;\n }\n this.length--;\n }\n}\nconst moveKey = (id, parentId) => `${id}@${parentId}`;\nclass MutationBuffer {\n constructor() {\n this.frozen = false;\n this.locked = false;\n this.texts = [];\n this.attributes = [];\n this.attributeMap = new WeakMap();\n this.removes = [];\n this.mapRemoves = [];\n this.movedMap = {};\n this.addedSet = new Set();\n this.movedSet = new Set();\n this.droppedSet = new Set();\n this.processMutations = (mutations) => {\n mutations.forEach(this.processMutation);\n this.emit();\n };\n this.emit = () => {\n if (this.frozen || this.locked) {\n return;\n }\n const adds = [];\n const addedIds = new Set();\n const addList = new DoubleLinkedList();\n const getNextId = (n) => {\n let ns = n;\n let nextId = IGNORED_NODE;\n while (nextId === IGNORED_NODE) {\n ns = ns && ns.nextSibling;\n nextId = ns && this.mirror.getId(ns);\n }\n return nextId;\n };\n const pushAdd = (n) => {\n if (!n.parentNode || !inDom(n)) {\n return;\n }\n const parentId = isShadowRoot(n.parentNode)\n ? this.mirror.getId(getShadowHost(n))\n : this.mirror.getId(n.parentNode);\n const nextId = getNextId(n);\n if (parentId === -1 || nextId === -1) {\n return addList.addNode(n);\n }\n const sn = serializeNodeWithId(n, {\n doc: this.doc,\n mirror: this.mirror,\n blockClass: this.blockClass,\n blockSelector: this.blockSelector,\n maskAllText: this.maskAllText,\n unblockSelector: this.unblockSelector,\n maskTextClass: this.maskTextClass,\n unmaskTextClass: this.unmaskTextClass,\n maskTextSelector: this.maskTextSelector,\n unmaskTextSelector: this.unmaskTextSelector,\n skipChild: true,\n newlyAddedElement: true,\n inlineStylesheet: this.inlineStylesheet,\n maskInputOptions: this.maskInputOptions,\n maskAttributeFn: this.maskAttributeFn,\n maskTextFn: this.maskTextFn,\n maskInputFn: this.maskInputFn,\n slimDOMOptions: this.slimDOMOptions,\n dataURLOptions: this.dataURLOptions,\n recordCanvas: this.recordCanvas,\n inlineImages: this.inlineImages,\n onSerialize: (currentN) => {\n if (isSerializedIframe(currentN, this.mirror) &&\n !isBlocked(currentN, this.blockClass, this.blockSelector, this.unblockSelector, false)) {\n this.iframeManager.addIframe(currentN);\n }\n if (isSerializedStylesheet(currentN, this.mirror)) {\n this.stylesheetManager.trackLinkElement(currentN);\n }\n if (hasShadowRoot(n)) {\n this.shadowDomManager.addShadowRoot(n.shadowRoot, this.doc);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n if (isBlocked(iframe, this.blockClass, this.blockSelector, this.unblockSelector, false)) {\n return;\n }\n this.iframeManager.attachIframe(iframe, childSn);\n if (iframe.contentWindow) {\n this.canvasManager.addWindow(iframe.contentWindow);\n }\n this.shadowDomManager.observeAttachShadow(iframe);\n },\n onStylesheetLoad: (link, childSn) => {\n this.stylesheetManager.attachLinkElement(link, childSn);\n },\n });\n if (sn) {\n adds.push({\n parentId,\n nextId,\n node: sn,\n });\n addedIds.add(sn.id);\n }\n };\n while (this.mapRemoves.length) {\n this.mirror.removeNodeFromMap(this.mapRemoves.shift());\n }\n for (const n of this.movedSet) {\n if (isParentRemoved(this.removes, n, this.mirror) &&\n !this.movedSet.has(n.parentNode)) {\n continue;\n }\n pushAdd(n);\n }\n for (const n of this.addedSet) {\n if (!isAncestorInSet(this.droppedSet, n) &&\n !isParentRemoved(this.removes, n, this.mirror)) {\n pushAdd(n);\n }\n else if (isAncestorInSet(this.movedSet, n)) {\n pushAdd(n);\n }\n else {\n this.droppedSet.add(n);\n }\n }\n let candidate = null;\n while (addList.length) {\n let node = null;\n if (candidate) {\n const parentId = this.mirror.getId(candidate.value.parentNode);\n const nextId = getNextId(candidate.value);\n if (parentId !== -1 && nextId !== -1) {\n node = candidate;\n }\n }\n if (!node) {\n let tailNode = addList.tail;\n while (tailNode) {\n const _node = tailNode;\n tailNode = tailNode.previous;\n if (_node) {\n const parentId = this.mirror.getId(_node.value.parentNode);\n const nextId = getNextId(_node.value);\n if (nextId === -1)\n continue;\n else if (parentId !== -1) {\n node = _node;\n break;\n }\n else {\n const unhandledNode = _node.value;\n if (unhandledNode.parentNode &&\n unhandledNode.parentNode.nodeType ===\n Node.DOCUMENT_FRAGMENT_NODE) {\n const shadowHost = unhandledNode.parentNode\n .host;\n const parentId = this.mirror.getId(shadowHost);\n if (parentId !== -1) {\n node = _node;\n break;\n }\n }\n }\n }\n }\n }\n if (!node) {\n while (addList.head) {\n addList.removeNode(addList.head.value);\n }\n break;\n }\n candidate = node.previous;\n addList.removeNode(node.value);\n pushAdd(node.value);\n }\n const payload = {\n texts: this.texts\n .map((text) => ({\n id: this.mirror.getId(text.node),\n value: text.value,\n }))\n .filter((text) => !addedIds.has(text.id))\n .filter((text) => this.mirror.has(text.id)),\n attributes: this.attributes\n .map((attribute) => {\n const { attributes } = attribute;\n if (typeof attributes.style === 'string') {\n const diffAsStr = JSON.stringify(attribute.styleDiff);\n const unchangedAsStr = JSON.stringify(attribute._unchangedStyles);\n if (diffAsStr.length < attributes.style.length) {\n if ((diffAsStr + unchangedAsStr).split('var(').length ===\n attributes.style.split('var(').length) {\n attributes.style = attribute.styleDiff;\n }\n }\n }\n return {\n id: this.mirror.getId(attribute.node),\n attributes: attributes,\n };\n })\n .filter((attribute) => !addedIds.has(attribute.id))\n .filter((attribute) => this.mirror.has(attribute.id)),\n removes: this.removes,\n adds,\n };\n if (!payload.texts.length &&\n !payload.attributes.length &&\n !payload.removes.length &&\n !payload.adds.length) {\n return;\n }\n this.texts = [];\n this.attributes = [];\n this.attributeMap = new WeakMap();\n this.removes = [];\n this.addedSet = new Set();\n this.movedSet = new Set();\n this.droppedSet = new Set();\n this.movedMap = {};\n this.mutationCb(payload);\n };\n this.processMutation = (m) => {\n if (isIgnored(m.target, this.mirror)) {\n return;\n }\n switch (m.type) {\n case 'characterData': {\n const value = m.target.textContent;\n if (!isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) &&\n value !== m.oldValue) {\n this.texts.push({\n value: needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, this.maskAllText) && value\n ? this.maskTextFn\n ? this.maskTextFn(value, closestElementOfNode(m.target))\n : value.replace(/[\\S]/g, '*')\n : value,\n node: m.target,\n });\n }\n break;\n }\n case 'attributes': {\n const target = m.target;\n let attributeName = m.attributeName;\n let value = m.target.getAttribute(attributeName);\n if (attributeName === 'value') {\n const type = getInputType(target);\n const tagName = target.tagName;\n value = getInputValue(target, tagName, type);\n const isInputMasked = shouldMaskInput({\n maskInputOptions: this.maskInputOptions,\n tagName,\n type,\n });\n const forceMask = needMaskingText(m.target, this.maskTextClass, this.maskTextSelector, this.unmaskTextClass, this.unmaskTextSelector, isInputMasked);\n value = maskInputValue({\n isMasked: forceMask,\n element: target,\n value,\n maskInputFn: this.maskInputFn,\n });\n }\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) ||\n value === m.oldValue) {\n return;\n }\n let item = this.attributeMap.get(m.target);\n if (target.tagName === 'IFRAME' &&\n attributeName === 'src' &&\n !this.keepIframeSrcFn(value)) {\n const iframeDoc = getIFrameContentDocument(target);\n if (!iframeDoc) {\n attributeName = 'rr_src';\n }\n else {\n return;\n }\n }\n if (!item) {\n item = {\n node: m.target,\n attributes: {},\n styleDiff: {},\n _unchangedStyles: {},\n };\n this.attributes.push(item);\n this.attributeMap.set(m.target, item);\n }\n if (attributeName === 'type' &&\n target.tagName === 'INPUT' &&\n (m.oldValue || '').toLowerCase() === 'password') {\n target.setAttribute('data-rr-is-password', 'true');\n }\n if (!ignoreAttribute(target.tagName, attributeName)) {\n item.attributes[attributeName] = transformAttribute(this.doc, toLowerCase(target.tagName), toLowerCase(attributeName), value, target, this.maskAttributeFn);\n if (attributeName === 'style') {\n if (!this.unattachedDoc) {\n try {\n this.unattachedDoc =\n document.implementation.createHTMLDocument();\n }\n catch (e) {\n this.unattachedDoc = this.doc;\n }\n }\n const old = this.unattachedDoc.createElement('span');\n if (m.oldValue) {\n old.setAttribute('style', m.oldValue);\n }\n for (const pname of Array.from(target.style)) {\n const newValue = target.style.getPropertyValue(pname);\n const newPriority = target.style.getPropertyPriority(pname);\n if (newValue !== old.style.getPropertyValue(pname) ||\n newPriority !== old.style.getPropertyPriority(pname)) {\n if (newPriority === '') {\n item.styleDiff[pname] = newValue;\n }\n else {\n item.styleDiff[pname] = [newValue, newPriority];\n }\n }\n else {\n item._unchangedStyles[pname] = [newValue, newPriority];\n }\n }\n for (const pname of Array.from(old.style)) {\n if (target.style.getPropertyValue(pname) === '') {\n item.styleDiff[pname] = false;\n }\n }\n }\n }\n break;\n }\n case 'childList': {\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, true)) {\n return;\n }\n m.addedNodes.forEach((n) => this.genAdds(n, m.target));\n m.removedNodes.forEach((n) => {\n const nodeId = this.mirror.getId(n);\n const parentId = isShadowRoot(m.target)\n ? this.mirror.getId(m.target.host)\n : this.mirror.getId(m.target);\n if (isBlocked(m.target, this.blockClass, this.blockSelector, this.unblockSelector, false) ||\n isIgnored(n, this.mirror) ||\n !isSerialized(n, this.mirror)) {\n return;\n }\n if (this.addedSet.has(n)) {\n deepDelete(this.addedSet, n);\n this.droppedSet.add(n);\n }\n else if (this.addedSet.has(m.target) && nodeId === -1) ;\n else if (isAncestorRemoved(m.target, this.mirror)) ;\n else if (this.movedSet.has(n) &&\n this.movedMap[moveKey(nodeId, parentId)]) {\n deepDelete(this.movedSet, n);\n }\n else {\n this.removes.push({\n parentId,\n id: nodeId,\n isShadow: isShadowRoot(m.target) && isNativeShadowDom(m.target)\n ? true\n : undefined,\n });\n }\n this.mapRemoves.push(n);\n });\n break;\n }\n }\n };\n this.genAdds = (n, target) => {\n if (this.processedNodeManager.inOtherBuffer(n, this))\n return;\n if (this.addedSet.has(n) || this.movedSet.has(n))\n return;\n if (this.mirror.hasNode(n)) {\n if (isIgnored(n, this.mirror)) {\n return;\n }\n this.movedSet.add(n);\n let targetId = null;\n if (target && this.mirror.hasNode(target)) {\n targetId = this.mirror.getId(target);\n }\n if (targetId && targetId !== -1) {\n this.movedMap[moveKey(this.mirror.getId(n), targetId)] = true;\n }\n }\n else {\n this.addedSet.add(n);\n this.droppedSet.delete(n);\n }\n if (!isBlocked(n, this.blockClass, this.blockSelector, this.unblockSelector, false)) {\n n.childNodes.forEach((childN) => this.genAdds(childN));\n if (hasShadowRoot(n)) {\n n.shadowRoot.childNodes.forEach((childN) => {\n this.processedNodeManager.add(childN, this);\n this.genAdds(childN, n);\n });\n }\n }\n };\n }\n init(options) {\n [\n 'mutationCb',\n 'blockClass',\n 'blockSelector',\n 'unblockSelector',\n 'maskAllText',\n 'maskTextClass',\n 'unmaskTextClass',\n 'maskTextSelector',\n 'unmaskTextSelector',\n 'inlineStylesheet',\n 'maskInputOptions',\n 'maskAttributeFn',\n 'maskTextFn',\n 'maskInputFn',\n 'keepIframeSrcFn',\n 'recordCanvas',\n 'inlineImages',\n 'slimDOMOptions',\n 'dataURLOptions',\n 'doc',\n 'mirror',\n 'iframeManager',\n 'stylesheetManager',\n 'shadowDomManager',\n 'canvasManager',\n 'processedNodeManager',\n ].forEach((key) => {\n this[key] = options[key];\n });\n }\n freeze() {\n this.frozen = true;\n this.canvasManager.freeze();\n }\n unfreeze() {\n this.frozen = false;\n this.canvasManager.unfreeze();\n this.emit();\n }\n isFrozen() {\n return this.frozen;\n }\n lock() {\n this.locked = true;\n this.canvasManager.lock();\n }\n unlock() {\n this.locked = false;\n this.canvasManager.unlock();\n this.emit();\n }\n reset() {\n this.shadowDomManager.reset();\n this.canvasManager.reset();\n }\n}\nfunction deepDelete(addsSet, n) {\n addsSet.delete(n);\n n.childNodes.forEach((childN) => deepDelete(addsSet, childN));\n}\nfunction isParentRemoved(removes, n, mirror) {\n if (removes.length === 0)\n return false;\n return _isParentRemoved(removes, n, mirror);\n}\nfunction _isParentRemoved(removes, n, mirror) {\n let node = n.parentNode;\n while (node) {\n const parentId = mirror.getId(node);\n if (removes.some((r) => r.id === parentId)) {\n return true;\n }\n node = node.parentNode;\n }\n return false;\n}\nfunction isAncestorInSet(set, n) {\n if (set.size === 0)\n return false;\n return _isAncestorInSet(set, n);\n}\nfunction _isAncestorInSet(set, n) {\n const { parentNode } = n;\n if (!parentNode) {\n return false;\n }\n if (set.has(parentNode)) {\n return true;\n }\n return _isAncestorInSet(set, parentNode);\n}\n\nlet errorHandler;\nfunction registerErrorHandler(handler) {\n errorHandler = handler;\n}\nfunction unregisterErrorHandler() {\n errorHandler = undefined;\n}\nconst callbackWrapper = (cb) => {\n if (!errorHandler) {\n return cb;\n }\n const rrwebWrapped = ((...rest) => {\n try {\n return cb(...rest);\n }\n catch (error) {\n if (errorHandler && errorHandler(error) === true) {\n return () => {\n };\n }\n throw error;\n }\n });\n return rrwebWrapped;\n};\n\nconst mutationBuffers = [];\nfunction getEventTarget(event) {\n try {\n if ('composedPath' in event) {\n const path = event.composedPath();\n if (path.length) {\n return path[0];\n }\n }\n else if ('path' in event && event.path.length) {\n return event.path[0];\n }\n }\n catch {\n }\n return event && event.target;\n}\nfunction initMutationObserver(options, rootEl) {\n const mutationBuffer = new MutationBuffer();\n mutationBuffers.push(mutationBuffer);\n mutationBuffer.init(options);\n let mutationObserverCtor = window.MutationObserver ||\n window.__rrMutationObserver;\n const angularZoneSymbol = window?.Zone?.__symbol__?.('MutationObserver');\n if (angularZoneSymbol &&\n window[angularZoneSymbol]) {\n mutationObserverCtor = window[angularZoneSymbol];\n }\n const observer = new mutationObserverCtor(callbackWrapper((mutations) => {\n if (options.onMutation && options.onMutation(mutations) === false) {\n return;\n }\n mutationBuffer.processMutations.bind(mutationBuffer)(mutations);\n }));\n observer.observe(rootEl, {\n attributes: true,\n attributeOldValue: true,\n characterData: true,\n characterDataOldValue: true,\n childList: true,\n subtree: true,\n });\n return observer;\n}\nfunction initMoveObserver({ mousemoveCb, sampling, doc, mirror, }) {\n if (sampling.mousemove === false) {\n return () => {\n };\n }\n const threshold = typeof sampling.mousemove === 'number' ? sampling.mousemove : 50;\n const callbackThreshold = typeof sampling.mousemoveCallback === 'number'\n ? sampling.mousemoveCallback\n : 500;\n let positions = [];\n let timeBaseline;\n const wrappedCb = throttle$1(callbackWrapper((source) => {\n const totalOffset = Date.now() - timeBaseline;\n mousemoveCb(positions.map((p) => {\n p.timeOffset -= totalOffset;\n return p;\n }), source);\n positions = [];\n timeBaseline = null;\n }), callbackThreshold);\n const updatePosition = callbackWrapper(throttle$1(callbackWrapper((evt) => {\n const target = getEventTarget(evt);\n const { clientX, clientY } = legacy_isTouchEvent(evt)\n ? evt.changedTouches[0]\n : evt;\n if (!timeBaseline) {\n timeBaseline = nowTimestamp();\n }\n positions.push({\n x: clientX,\n y: clientY,\n id: mirror.getId(target),\n timeOffset: nowTimestamp() - timeBaseline,\n });\n wrappedCb(typeof DragEvent !== 'undefined' && evt instanceof DragEvent\n ? IncrementalSource.Drag\n : evt instanceof MouseEvent\n ? IncrementalSource.MouseMove\n : IncrementalSource.TouchMove);\n }), threshold, {\n trailing: false,\n }));\n const handlers = [\n on('mousemove', updatePosition, doc),\n on('touchmove', updatePosition, doc),\n on('drag', updatePosition, doc),\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initMouseInteractionObserver({ mouseInteractionCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\n if (sampling.mouseInteraction === false) {\n return () => {\n };\n }\n const disableMap = sampling.mouseInteraction === true ||\n sampling.mouseInteraction === undefined\n ? {}\n : sampling.mouseInteraction;\n const handlers = [];\n let currentPointerType = null;\n const getHandler = (eventKey) => {\n return (event) => {\n const target = getEventTarget(event);\n if (isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\n return;\n }\n let pointerType = null;\n let thisEventKey = eventKey;\n if ('pointerType' in event) {\n switch (event.pointerType) {\n case 'mouse':\n pointerType = PointerTypes.Mouse;\n break;\n case 'touch':\n pointerType = PointerTypes.Touch;\n break;\n case 'pen':\n pointerType = PointerTypes.Pen;\n break;\n }\n if (pointerType === PointerTypes.Touch) {\n if (MouseInteractions[eventKey] === MouseInteractions.MouseDown) {\n thisEventKey = 'TouchStart';\n }\n else if (MouseInteractions[eventKey] === MouseInteractions.MouseUp) {\n thisEventKey = 'TouchEnd';\n }\n }\n else if (pointerType === PointerTypes.Pen) ;\n }\n else if (legacy_isTouchEvent(event)) {\n pointerType = PointerTypes.Touch;\n }\n if (pointerType !== null) {\n currentPointerType = pointerType;\n if ((thisEventKey.startsWith('Touch') &&\n pointerType === PointerTypes.Touch) ||\n (thisEventKey.startsWith('Mouse') &&\n pointerType === PointerTypes.Mouse)) {\n pointerType = null;\n }\n }\n else if (MouseInteractions[eventKey] === MouseInteractions.Click) {\n pointerType = currentPointerType;\n currentPointerType = null;\n }\n const e = legacy_isTouchEvent(event) ? event.changedTouches[0] : event;\n if (!e) {\n return;\n }\n const id = mirror.getId(target);\n const { clientX, clientY } = e;\n callbackWrapper(mouseInteractionCb)({\n type: MouseInteractions[thisEventKey],\n id,\n x: clientX,\n y: clientY,\n ...(pointerType !== null && { pointerType }),\n });\n };\n };\n Object.keys(MouseInteractions)\n .filter((key) => Number.isNaN(Number(key)) &&\n !key.endsWith('_Departed') &&\n disableMap[key] !== false)\n .forEach((eventKey) => {\n let eventName = toLowerCase(eventKey);\n const handler = getHandler(eventKey);\n if (window.PointerEvent) {\n switch (MouseInteractions[eventKey]) {\n case MouseInteractions.MouseDown:\n case MouseInteractions.MouseUp:\n eventName = eventName.replace('mouse', 'pointer');\n break;\n case MouseInteractions.TouchStart:\n case MouseInteractions.TouchEnd:\n return;\n }\n }\n handlers.push(on(eventName, handler, doc));\n });\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initScrollObserver({ scrollCb, doc, mirror, blockClass, blockSelector, unblockSelector, sampling, }) {\n const updatePosition = callbackWrapper(throttle$1(callbackWrapper((evt) => {\n const target = getEventTarget(evt);\n if (!target ||\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\n return;\n }\n const id = mirror.getId(target);\n if (target === doc && doc.defaultView) {\n const scrollLeftTop = getWindowScroll(doc.defaultView);\n scrollCb({\n id,\n x: scrollLeftTop.left,\n y: scrollLeftTop.top,\n });\n }\n else {\n scrollCb({\n id,\n x: target.scrollLeft,\n y: target.scrollTop,\n });\n }\n }), sampling.scroll || 100));\n return on('scroll', updatePosition, doc);\n}\nfunction initViewportResizeObserver({ viewportResizeCb }, { win }) {\n let lastH = -1;\n let lastW = -1;\n const updateDimension = callbackWrapper(throttle$1(callbackWrapper(() => {\n const height = getWindowHeight();\n const width = getWindowWidth();\n if (lastH !== height || lastW !== width) {\n viewportResizeCb({\n width: Number(width),\n height: Number(height),\n });\n lastH = height;\n lastW = width;\n }\n }), 200));\n return on('resize', updateDimension, win);\n}\nconst INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT'];\nconst lastInputValueMap = new WeakMap();\nfunction initInputObserver({ inputCb, doc, mirror, blockClass, blockSelector, unblockSelector, ignoreClass, ignoreSelector, maskInputOptions, maskInputFn, sampling, userTriggeredOnInput, maskTextClass, unmaskTextClass, maskTextSelector, unmaskTextSelector, }) {\n function eventHandler(event) {\n let target = getEventTarget(event);\n const userTriggered = event.isTrusted;\n const tagName = target && toUpperCase(target.tagName);\n if (tagName === 'OPTION')\n target = target.parentElement;\n if (!target ||\n !tagName ||\n INPUT_TAGS.indexOf(tagName) < 0 ||\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\n return;\n }\n const el = target;\n if (el.classList.contains(ignoreClass) ||\n (ignoreSelector && el.matches(ignoreSelector))) {\n return;\n }\n const type = getInputType(target);\n let text = getInputValue(el, tagName, type);\n let isChecked = false;\n const isInputMasked = shouldMaskInput({\n maskInputOptions,\n tagName,\n type,\n });\n const forceMask = needMaskingText(target, maskTextClass, maskTextSelector, unmaskTextClass, unmaskTextSelector, isInputMasked);\n if (type === 'radio' || type === 'checkbox') {\n isChecked = target.checked;\n }\n text = maskInputValue({\n isMasked: forceMask,\n element: target,\n value: text,\n maskInputFn,\n });\n cbWithDedup(target, userTriggeredOnInput\n ? { text, isChecked, userTriggered }\n : { text, isChecked });\n const name = target.name;\n if (type === 'radio' && name && isChecked) {\n doc\n .querySelectorAll(`input[type=\"radio\"][name=\"${name}\"]`)\n .forEach((el) => {\n if (el !== target) {\n const text = maskInputValue({\n isMasked: forceMask,\n element: el,\n value: getInputValue(el, tagName, type),\n maskInputFn,\n });\n cbWithDedup(el, userTriggeredOnInput\n ? { text, isChecked: !isChecked, userTriggered: false }\n : { text, isChecked: !isChecked });\n }\n });\n }\n }\n function cbWithDedup(target, v) {\n const lastInputValue = lastInputValueMap.get(target);\n if (!lastInputValue ||\n lastInputValue.text !== v.text ||\n lastInputValue.isChecked !== v.isChecked) {\n lastInputValueMap.set(target, v);\n const id = mirror.getId(target);\n callbackWrapper(inputCb)({\n ...v,\n id,\n });\n }\n }\n const events = sampling.input === 'last' ? ['change'] : ['input', 'change'];\n const handlers = events.map((eventName) => on(eventName, callbackWrapper(eventHandler), doc));\n const currentWindow = doc.defaultView;\n if (!currentWindow) {\n return () => {\n handlers.forEach((h) => h());\n };\n }\n const propertyDescriptor = currentWindow.Object.getOwnPropertyDescriptor(currentWindow.HTMLInputElement.prototype, 'value');\n const hookProperties = [\n [currentWindow.HTMLInputElement.prototype, 'value'],\n [currentWindow.HTMLInputElement.prototype, 'checked'],\n [currentWindow.HTMLSelectElement.prototype, 'value'],\n [currentWindow.HTMLTextAreaElement.prototype, 'value'],\n [currentWindow.HTMLSelectElement.prototype, 'selectedIndex'],\n [currentWindow.HTMLOptionElement.prototype, 'selected'],\n ];\n if (propertyDescriptor && propertyDescriptor.set) {\n handlers.push(...hookProperties.map((p) => hookSetter(p[0], p[1], {\n set() {\n callbackWrapper(eventHandler)({\n target: this,\n isTrusted: false,\n });\n },\n }, false, currentWindow)));\n }\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction getNestedCSSRulePositions(rule) {\n const positions = [];\n function recurse(childRule, pos) {\n if ((hasNestedCSSRule('CSSGroupingRule') &&\n childRule.parentRule instanceof CSSGroupingRule) ||\n (hasNestedCSSRule('CSSMediaRule') &&\n childRule.parentRule instanceof CSSMediaRule) ||\n (hasNestedCSSRule('CSSSupportsRule') &&\n childRule.parentRule instanceof CSSSupportsRule) ||\n (hasNestedCSSRule('CSSConditionRule') &&\n childRule.parentRule instanceof CSSConditionRule)) {\n const rules = Array.from(childRule.parentRule.cssRules);\n const index = rules.indexOf(childRule);\n pos.unshift(index);\n }\n else if (childRule.parentStyleSheet) {\n const rules = Array.from(childRule.parentStyleSheet.cssRules);\n const index = rules.indexOf(childRule);\n pos.unshift(index);\n }\n return pos;\n }\n return recurse(rule, positions);\n}\nfunction getIdAndStyleId(sheet, mirror, styleMirror) {\n let id, styleId;\n if (!sheet)\n return {};\n if (sheet.ownerNode)\n id = mirror.getId(sheet.ownerNode);\n else\n styleId = styleMirror.getId(sheet);\n return {\n styleId,\n id,\n };\n}\nfunction initStyleSheetObserver({ styleSheetRuleCb, mirror, stylesheetManager }, { win }) {\n if (!win.CSSStyleSheet || !win.CSSStyleSheet.prototype) {\n return () => {\n };\n }\n const insertRule = win.CSSStyleSheet.prototype.insertRule;\n win.CSSStyleSheet.prototype.insertRule = new Proxy(insertRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\n styleSheetRuleCb({\n id,\n styleId,\n adds: [{ rule, index }],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n const deleteRule = win.CSSStyleSheet.prototype.deleteRule;\n win.CSSStyleSheet.prototype.deleteRule = new Proxy(deleteRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\n styleSheetRuleCb({\n id,\n styleId,\n removes: [{ index }],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n let replace;\n if (win.CSSStyleSheet.prototype.replace) {\n replace = win.CSSStyleSheet.prototype.replace;\n win.CSSStyleSheet.prototype.replace = new Proxy(replace, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\n styleSheetRuleCb({\n id,\n styleId,\n replace: text,\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n }\n let replaceSync;\n if (win.CSSStyleSheet.prototype.replaceSync) {\n replaceSync = win.CSSStyleSheet.prototype.replaceSync;\n win.CSSStyleSheet.prototype.replaceSync = new Proxy(replaceSync, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [text] = argumentsList;\n const { id, styleId } = getIdAndStyleId(thisArg, mirror, stylesheetManager.styleMirror);\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\n styleSheetRuleCb({\n id,\n styleId,\n replaceSync: text,\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n }\n const supportedNestedCSSRuleTypes = {};\n if (canMonkeyPatchNestedCSSRule('CSSGroupingRule')) {\n supportedNestedCSSRuleTypes.CSSGroupingRule = win.CSSGroupingRule;\n }\n else {\n if (canMonkeyPatchNestedCSSRule('CSSMediaRule')) {\n supportedNestedCSSRuleTypes.CSSMediaRule = win.CSSMediaRule;\n }\n if (canMonkeyPatchNestedCSSRule('CSSConditionRule')) {\n supportedNestedCSSRuleTypes.CSSConditionRule = win.CSSConditionRule;\n }\n if (canMonkeyPatchNestedCSSRule('CSSSupportsRule')) {\n supportedNestedCSSRuleTypes.CSSSupportsRule = win.CSSSupportsRule;\n }\n }\n const unmodifiedFunctions = {};\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n unmodifiedFunctions[typeKey] = {\n insertRule: type.prototype.insertRule,\n deleteRule: type.prototype.deleteRule,\n };\n type.prototype.insertRule = new Proxy(unmodifiedFunctions[typeKey].insertRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [rule, index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\n styleSheetRuleCb({\n id,\n styleId,\n adds: [\n {\n rule,\n index: [\n ...getNestedCSSRulePositions(thisArg),\n index || 0,\n ],\n },\n ],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n type.prototype.deleteRule = new Proxy(unmodifiedFunctions[typeKey].deleteRule, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [index] = argumentsList;\n const { id, styleId } = getIdAndStyleId(thisArg.parentStyleSheet, mirror, stylesheetManager.styleMirror);\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\n styleSheetRuleCb({\n id,\n styleId,\n removes: [\n { index: [...getNestedCSSRulePositions(thisArg), index] },\n ],\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n });\n return callbackWrapper(() => {\n win.CSSStyleSheet.prototype.insertRule = insertRule;\n win.CSSStyleSheet.prototype.deleteRule = deleteRule;\n replace && (win.CSSStyleSheet.prototype.replace = replace);\n replaceSync && (win.CSSStyleSheet.prototype.replaceSync = replaceSync);\n Object.entries(supportedNestedCSSRuleTypes).forEach(([typeKey, type]) => {\n type.prototype.insertRule = unmodifiedFunctions[typeKey].insertRule;\n type.prototype.deleteRule = unmodifiedFunctions[typeKey].deleteRule;\n });\n });\n}\nfunction initAdoptedStyleSheetObserver({ mirror, stylesheetManager, }, host) {\n let hostId = null;\n if (host.nodeName === '#document')\n hostId = mirror.getId(host);\n else\n hostId = mirror.getId(host.host);\n const patchTarget = host.nodeName === '#document'\n ? host.defaultView?.Document\n : host.ownerDocument?.defaultView?.ShadowRoot;\n const originalPropertyDescriptor = patchTarget?.prototype\n ? Object.getOwnPropertyDescriptor(patchTarget?.prototype, 'adoptedStyleSheets')\n : undefined;\n if (hostId === null ||\n hostId === -1 ||\n !patchTarget ||\n !originalPropertyDescriptor)\n return () => {\n };\n Object.defineProperty(host, 'adoptedStyleSheets', {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n get() {\n return originalPropertyDescriptor.get?.call(this);\n },\n set(sheets) {\n const result = originalPropertyDescriptor.set?.call(this, sheets);\n if (hostId !== null && hostId !== -1) {\n try {\n stylesheetManager.adoptStyleSheets(sheets, hostId);\n }\n catch (e) {\n }\n }\n return result;\n },\n });\n return callbackWrapper(() => {\n Object.defineProperty(host, 'adoptedStyleSheets', {\n configurable: originalPropertyDescriptor.configurable,\n enumerable: originalPropertyDescriptor.enumerable,\n get: originalPropertyDescriptor.get,\n set: originalPropertyDescriptor.set,\n });\n });\n}\nfunction initStyleDeclarationObserver({ styleDeclarationCb, mirror, ignoreCSSAttributes, stylesheetManager, }, { win }) {\n const setProperty = win.CSSStyleDeclaration.prototype.setProperty;\n win.CSSStyleDeclaration.prototype.setProperty = new Proxy(setProperty, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [property, value, priority] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return setProperty.apply(thisArg, [property, value, priority]);\n }\n const { id, styleId } = getIdAndStyleId(thisArg.parentRule?.parentStyleSheet, mirror, stylesheetManager.styleMirror);\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\n styleDeclarationCb({\n id,\n styleId,\n set: {\n property,\n value,\n priority,\n },\n index: getNestedCSSRulePositions(thisArg.parentRule),\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n const removeProperty = win.CSSStyleDeclaration.prototype.removeProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = new Proxy(removeProperty, {\n apply: callbackWrapper((target, thisArg, argumentsList) => {\n const [property] = argumentsList;\n if (ignoreCSSAttributes.has(property)) {\n return removeProperty.apply(thisArg, [property]);\n }\n const { id, styleId } = getIdAndStyleId(thisArg.parentRule?.parentStyleSheet, mirror, stylesheetManager.styleMirror);\n if ((id && id !== -1) || (styleId && styleId !== -1)) {\n styleDeclarationCb({\n id,\n styleId,\n remove: {\n property,\n },\n index: getNestedCSSRulePositions(thisArg.parentRule),\n });\n }\n return target.apply(thisArg, argumentsList);\n }),\n });\n return callbackWrapper(() => {\n win.CSSStyleDeclaration.prototype.setProperty = setProperty;\n win.CSSStyleDeclaration.prototype.removeProperty = removeProperty;\n });\n}\nfunction initMediaInteractionObserver({ mediaInteractionCb, blockClass, blockSelector, unblockSelector, mirror, sampling, doc, }) {\n const handler = callbackWrapper((type) => throttle$1(callbackWrapper((event) => {\n const target = getEventTarget(event);\n if (!target ||\n isBlocked(target, blockClass, blockSelector, unblockSelector, true)) {\n return;\n }\n const { currentTime, volume, muted, playbackRate } = target;\n mediaInteractionCb({\n type,\n id: mirror.getId(target),\n currentTime,\n volume,\n muted,\n playbackRate,\n });\n }), sampling.media || 500));\n const handlers = [\n on('play', handler(0), doc),\n on('pause', handler(1), doc),\n on('seeked', handler(2), doc),\n on('volumechange', handler(3), doc),\n on('ratechange', handler(4), doc),\n ];\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initFontObserver({ fontCb, doc }) {\n const win = doc.defaultView;\n if (!win) {\n return () => {\n };\n }\n const handlers = [];\n const fontMap = new WeakMap();\n const originalFontFace = win.FontFace;\n win.FontFace = function FontFace(family, source, descriptors) {\n const fontFace = new originalFontFace(family, source, descriptors);\n fontMap.set(fontFace, {\n family,\n buffer: typeof source !== 'string',\n descriptors,\n fontSource: typeof source === 'string'\n ? source\n : JSON.stringify(Array.from(new Uint8Array(source))),\n });\n return fontFace;\n };\n const restoreHandler = patch(doc.fonts, 'add', function (original) {\n return function (fontFace) {\n setTimeout$1(callbackWrapper(() => {\n const p = fontMap.get(fontFace);\n if (p) {\n fontCb(p);\n fontMap.delete(fontFace);\n }\n }), 0);\n return original.apply(this, [fontFace]);\n };\n });\n handlers.push(() => {\n win.FontFace = originalFontFace;\n });\n handlers.push(restoreHandler);\n return callbackWrapper(() => {\n handlers.forEach((h) => h());\n });\n}\nfunction initSelectionObserver(param) {\n const { doc, mirror, blockClass, blockSelector, unblockSelector, selectionCb, } = param;\n let collapsed = true;\n const updateSelection = callbackWrapper(() => {\n const selection = doc.getSelection();\n if (!selection || (collapsed && selection?.isCollapsed))\n return;\n collapsed = selection.isCollapsed || false;\n const ranges = [];\n const count = selection.rangeCount || 0;\n for (let i = 0; i < count; i++) {\n const range = selection.getRangeAt(i);\n const { startContainer, startOffset, endContainer, endOffset } = range;\n const blocked = isBlocked(startContainer, blockClass, blockSelector, unblockSelector, true) ||\n isBlocked(endContainer, blockClass, blockSelector, unblockSelector, true);\n if (blocked)\n continue;\n ranges.push({\n start: mirror.getId(startContainer),\n startOffset,\n end: mirror.getId(endContainer),\n endOffset,\n });\n }\n selectionCb({ ranges });\n });\n updateSelection();\n return on('selectionchange', updateSelection);\n}\nfunction initCustomElementObserver({ doc, customElementCb, }) {\n const win = doc.defaultView;\n if (!win || !win.customElements)\n return () => { };\n const restoreHandler = patch(win.customElements, 'define', function (original) {\n return function (name, constructor, options) {\n try {\n customElementCb({\n define: {\n name,\n },\n });\n }\n catch (e) {\n }\n return original.apply(this, [name, constructor, options]);\n };\n });\n return restoreHandler;\n}\nfunction initObservers(o, _hooks = {}) {\n const currentWindow = o.doc.defaultView;\n if (!currentWindow) {\n return () => {\n };\n }\n let mutationObserver;\n if (o.recordDOM) {\n mutationObserver = initMutationObserver(o, o.doc);\n }\n const mousemoveHandler = initMoveObserver(o);\n const mouseInteractionHandler = initMouseInteractionObserver(o);\n const scrollHandler = initScrollObserver(o);\n const viewportResizeHandler = initViewportResizeObserver(o, {\n win: currentWindow,\n });\n const inputHandler = initInputObserver(o);\n const mediaInteractionHandler = initMediaInteractionObserver(o);\n let styleSheetObserver = () => { };\n let adoptedStyleSheetObserver = () => { };\n let styleDeclarationObserver = () => { };\n let fontObserver = () => { };\n if (o.recordDOM) {\n styleSheetObserver = initStyleSheetObserver(o, { win: currentWindow });\n adoptedStyleSheetObserver = initAdoptedStyleSheetObserver(o, o.doc);\n styleDeclarationObserver = initStyleDeclarationObserver(o, {\n win: currentWindow,\n });\n if (o.collectFonts) {\n fontObserver = initFontObserver(o);\n }\n }\n const selectionObserver = initSelectionObserver(o);\n const customElementObserver = initCustomElementObserver(o);\n const pluginHandlers = [];\n for (const plugin of o.plugins) {\n pluginHandlers.push(plugin.observer(plugin.callback, currentWindow, plugin.options));\n }\n return callbackWrapper(() => {\n mutationBuffers.forEach((b) => b.reset());\n mutationObserver?.disconnect();\n mousemoveHandler();\n mouseInteractionHandler();\n scrollHandler();\n viewportResizeHandler();\n inputHandler();\n mediaInteractionHandler();\n styleSheetObserver();\n adoptedStyleSheetObserver();\n styleDeclarationObserver();\n fontObserver();\n selectionObserver();\n customElementObserver();\n pluginHandlers.forEach((h) => h());\n });\n}\nfunction hasNestedCSSRule(prop) {\n return typeof window[prop] !== 'undefined';\n}\nfunction canMonkeyPatchNestedCSSRule(prop) {\n return Boolean(typeof window[prop] !== 'undefined' &&\n window[prop].prototype &&\n 'insertRule' in window[prop].prototype &&\n 'deleteRule' in window[prop].prototype);\n}\n\nclass CrossOriginIframeMirror {\n constructor(generateIdFn) {\n this.generateIdFn = generateIdFn;\n this.iframeIdToRemoteIdMap = new WeakMap();\n this.iframeRemoteIdToIdMap = new WeakMap();\n }\n getId(iframe, remoteId, idToRemoteMap, remoteToIdMap) {\n const idToRemoteIdMap = idToRemoteMap || this.getIdToRemoteIdMap(iframe);\n const remoteIdToIdMap = remoteToIdMap || this.getRemoteIdToIdMap(iframe);\n let id = idToRemoteIdMap.get(remoteId);\n if (!id) {\n id = this.generateIdFn();\n idToRemoteIdMap.set(remoteId, id);\n remoteIdToIdMap.set(id, remoteId);\n }\n return id;\n }\n getIds(iframe, remoteId) {\n const idToRemoteIdMap = this.getIdToRemoteIdMap(iframe);\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n return remoteId.map((id) => this.getId(iframe, id, idToRemoteIdMap, remoteIdToIdMap));\n }\n getRemoteId(iframe, id, map) {\n const remoteIdToIdMap = map || this.getRemoteIdToIdMap(iframe);\n if (typeof id !== 'number')\n return id;\n const remoteId = remoteIdToIdMap.get(id);\n if (!remoteId)\n return -1;\n return remoteId;\n }\n getRemoteIds(iframe, ids) {\n const remoteIdToIdMap = this.getRemoteIdToIdMap(iframe);\n return ids.map((id) => this.getRemoteId(iframe, id, remoteIdToIdMap));\n }\n reset(iframe) {\n if (!iframe) {\n this.iframeIdToRemoteIdMap = new WeakMap();\n this.iframeRemoteIdToIdMap = new WeakMap();\n return;\n }\n this.iframeIdToRemoteIdMap.delete(iframe);\n this.iframeRemoteIdToIdMap.delete(iframe);\n }\n getIdToRemoteIdMap(iframe) {\n let idToRemoteIdMap = this.iframeIdToRemoteIdMap.get(iframe);\n if (!idToRemoteIdMap) {\n idToRemoteIdMap = new Map();\n this.iframeIdToRemoteIdMap.set(iframe, idToRemoteIdMap);\n }\n return idToRemoteIdMap;\n }\n getRemoteIdToIdMap(iframe) {\n let remoteIdToIdMap = this.iframeRemoteIdToIdMap.get(iframe);\n if (!remoteIdToIdMap) {\n remoteIdToIdMap = new Map();\n this.iframeRemoteIdToIdMap.set(iframe, remoteIdToIdMap);\n }\n return remoteIdToIdMap;\n }\n}\n\nclass IframeManagerNoop {\n constructor() {\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\n this.crossOriginIframeRootIdMap = new WeakMap();\n }\n addIframe() {\n }\n addLoadListener() {\n }\n attachIframe() {\n }\n}\nclass IframeManager {\n constructor(options) {\n this.iframes = new WeakMap();\n this.crossOriginIframeMap = new WeakMap();\n this.crossOriginIframeMirror = new CrossOriginIframeMirror(genId);\n this.crossOriginIframeRootIdMap = new WeakMap();\n this.mutationCb = options.mutationCb;\n this.wrappedEmit = options.wrappedEmit;\n this.stylesheetManager = options.stylesheetManager;\n this.recordCrossOriginIframes = options.recordCrossOriginIframes;\n this.crossOriginIframeStyleMirror = new CrossOriginIframeMirror(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror));\n this.mirror = options.mirror;\n if (this.recordCrossOriginIframes) {\n window.addEventListener('message', this.handleMessage.bind(this));\n }\n }\n addIframe(iframeEl) {\n this.iframes.set(iframeEl, true);\n if (iframeEl.contentWindow)\n this.crossOriginIframeMap.set(iframeEl.contentWindow, iframeEl);\n }\n addLoadListener(cb) {\n this.loadListener = cb;\n }\n attachIframe(iframeEl, childSn) {\n this.mutationCb({\n adds: [\n {\n parentId: this.mirror.getId(iframeEl),\n nextId: null,\n node: childSn,\n },\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true,\n });\n this.loadListener?.(iframeEl);\n const iframeDoc = getIFrameContentDocument(iframeEl);\n if (iframeDoc &&\n iframeDoc.adoptedStyleSheets &&\n iframeDoc.adoptedStyleSheets.length > 0)\n this.stylesheetManager.adoptStyleSheets(iframeDoc.adoptedStyleSheets, this.mirror.getId(iframeDoc));\n }\n handleMessage(message) {\n const crossOriginMessageEvent = message;\n if (crossOriginMessageEvent.data.type !== 'rrweb' ||\n crossOriginMessageEvent.origin !== crossOriginMessageEvent.data.origin)\n return;\n const iframeSourceWindow = message.source;\n if (!iframeSourceWindow)\n return;\n const iframeEl = this.crossOriginIframeMap.get(message.source);\n if (!iframeEl)\n return;\n const transformedEvent = this.transformCrossOriginEvent(iframeEl, crossOriginMessageEvent.data.event);\n if (transformedEvent)\n this.wrappedEmit(transformedEvent, crossOriginMessageEvent.data.isCheckout);\n }\n transformCrossOriginEvent(iframeEl, e) {\n switch (e.type) {\n case EventType.FullSnapshot: {\n this.crossOriginIframeMirror.reset(iframeEl);\n this.crossOriginIframeStyleMirror.reset(iframeEl);\n this.replaceIdOnNode(e.data.node, iframeEl);\n const rootId = e.data.node.id;\n this.crossOriginIframeRootIdMap.set(iframeEl, rootId);\n this.patchRootIdOnNode(e.data.node, rootId);\n return {\n timestamp: e.timestamp,\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Mutation,\n adds: [\n {\n parentId: this.mirror.getId(iframeEl),\n nextId: null,\n node: e.data.node,\n },\n ],\n removes: [],\n texts: [],\n attributes: [],\n isAttachIframe: true,\n },\n };\n }\n case EventType.Meta:\n case EventType.Load:\n case EventType.DomContentLoaded: {\n return false;\n }\n case EventType.Plugin: {\n return e;\n }\n case EventType.Custom: {\n this.replaceIds(e.data.payload, iframeEl, ['id', 'parentId', 'previousId', 'nextId']);\n return e;\n }\n case EventType.IncrementalSnapshot: {\n switch (e.data.source) {\n case IncrementalSource.Mutation: {\n e.data.adds.forEach((n) => {\n this.replaceIds(n, iframeEl, [\n 'parentId',\n 'nextId',\n 'previousId',\n ]);\n this.replaceIdOnNode(n.node, iframeEl);\n const rootId = this.crossOriginIframeRootIdMap.get(iframeEl);\n rootId && this.patchRootIdOnNode(n.node, rootId);\n });\n e.data.removes.forEach((n) => {\n this.replaceIds(n, iframeEl, ['parentId', 'id']);\n });\n e.data.attributes.forEach((n) => {\n this.replaceIds(n, iframeEl, ['id']);\n });\n e.data.texts.forEach((n) => {\n this.replaceIds(n, iframeEl, ['id']);\n });\n return e;\n }\n case IncrementalSource.Drag:\n case IncrementalSource.TouchMove:\n case IncrementalSource.MouseMove: {\n e.data.positions.forEach((p) => {\n this.replaceIds(p, iframeEl, ['id']);\n });\n return e;\n }\n case IncrementalSource.ViewportResize: {\n return false;\n }\n case IncrementalSource.MediaInteraction:\n case IncrementalSource.MouseInteraction:\n case IncrementalSource.Scroll:\n case IncrementalSource.CanvasMutation:\n case IncrementalSource.Input: {\n this.replaceIds(e.data, iframeEl, ['id']);\n return e;\n }\n case IncrementalSource.StyleSheetRule:\n case IncrementalSource.StyleDeclaration: {\n this.replaceIds(e.data, iframeEl, ['id']);\n this.replaceStyleIds(e.data, iframeEl, ['styleId']);\n return e;\n }\n case IncrementalSource.Font: {\n return e;\n }\n case IncrementalSource.Selection: {\n e.data.ranges.forEach((range) => {\n this.replaceIds(range, iframeEl, ['start', 'end']);\n });\n return e;\n }\n case IncrementalSource.AdoptedStyleSheet: {\n this.replaceIds(e.data, iframeEl, ['id']);\n this.replaceStyleIds(e.data, iframeEl, ['styleIds']);\n e.data.styles?.forEach((style) => {\n this.replaceStyleIds(style, iframeEl, ['styleId']);\n });\n return e;\n }\n }\n }\n }\n return false;\n }\n replace(iframeMirror, obj, iframeEl, keys) {\n for (const key of keys) {\n if (!Array.isArray(obj[key]) && typeof obj[key] !== 'number')\n continue;\n if (Array.isArray(obj[key])) {\n obj[key] = iframeMirror.getIds(iframeEl, obj[key]);\n }\n else {\n obj[key] = iframeMirror.getId(iframeEl, obj[key]);\n }\n }\n return obj;\n }\n replaceIds(obj, iframeEl, keys) {\n return this.replace(this.crossOriginIframeMirror, obj, iframeEl, keys);\n }\n replaceStyleIds(obj, iframeEl, keys) {\n return this.replace(this.crossOriginIframeStyleMirror, obj, iframeEl, keys);\n }\n replaceIdOnNode(node, iframeEl) {\n this.replaceIds(node, iframeEl, ['id', 'rootId']);\n if ('childNodes' in node) {\n node.childNodes.forEach((child) => {\n this.replaceIdOnNode(child, iframeEl);\n });\n }\n }\n patchRootIdOnNode(node, rootId) {\n if (node.type !== NodeType$3.Document && !node.rootId)\n node.rootId = rootId;\n if ('childNodes' in node) {\n node.childNodes.forEach((child) => {\n this.patchRootIdOnNode(child, rootId);\n });\n }\n }\n}\n\nclass ShadowDomManagerNoop {\n init() {\n }\n addShadowRoot() {\n }\n observeAttachShadow() {\n }\n reset() {\n }\n}\nclass ShadowDomManager {\n constructor(options) {\n this.shadowDoms = new WeakSet();\n this.restoreHandlers = [];\n this.mutationCb = options.mutationCb;\n this.scrollCb = options.scrollCb;\n this.bypassOptions = options.bypassOptions;\n this.mirror = options.mirror;\n this.init();\n }\n init() {\n this.reset();\n this.patchAttachShadow(Element, document);\n }\n addShadowRoot(shadowRoot, doc) {\n if (!isNativeShadowDom(shadowRoot))\n return;\n if (this.shadowDoms.has(shadowRoot))\n return;\n this.shadowDoms.add(shadowRoot);\n this.bypassOptions.canvasManager.addShadowRoot(shadowRoot);\n const observer = initMutationObserver({\n ...this.bypassOptions,\n doc,\n mutationCb: this.mutationCb,\n mirror: this.mirror,\n shadowDomManager: this,\n }, shadowRoot);\n this.restoreHandlers.push(() => observer.disconnect());\n this.restoreHandlers.push(initScrollObserver({\n ...this.bypassOptions,\n scrollCb: this.scrollCb,\n doc: shadowRoot,\n mirror: this.mirror,\n }));\n setTimeout$1(() => {\n if (shadowRoot.adoptedStyleSheets &&\n shadowRoot.adoptedStyleSheets.length > 0)\n this.bypassOptions.stylesheetManager.adoptStyleSheets(shadowRoot.adoptedStyleSheets, this.mirror.getId(shadowRoot.host));\n this.restoreHandlers.push(initAdoptedStyleSheetObserver({\n mirror: this.mirror,\n stylesheetManager: this.bypassOptions.stylesheetManager,\n }, shadowRoot));\n }, 0);\n }\n observeAttachShadow(iframeElement) {\n const iframeDoc = getIFrameContentDocument(iframeElement);\n const iframeWindow = getIFrameContentWindow(iframeElement);\n if (!iframeDoc || !iframeWindow)\n return;\n this.patchAttachShadow(iframeWindow.Element, iframeDoc);\n }\n patchAttachShadow(element, doc) {\n const manager = this;\n this.restoreHandlers.push(patch(element.prototype, 'attachShadow', function (original) {\n return function (option) {\n const shadowRoot = original.call(this, option);\n if (this.shadowRoot && inDom(this))\n manager.addShadowRoot(this.shadowRoot, doc);\n return shadowRoot;\n };\n }));\n }\n reset() {\n this.restoreHandlers.forEach((handler) => {\n try {\n handler();\n }\n catch (e) {\n }\n });\n this.restoreHandlers = [];\n this.shadowDoms = new WeakSet();\n this.bypassOptions.canvasManager.resetShadowRoots();\n }\n}\n\nclass CanvasManagerNoop {\n reset() {\n }\n freeze() {\n }\n unfreeze() {\n }\n lock() {\n }\n unlock() {\n }\n snapshot() {\n }\n addWindow() {\n }\n addShadowRoot() {\n }\n resetShadowRoots() {\n }\n}\n\nclass StylesheetManager {\n constructor(options) {\n this.trackedLinkElements = new WeakSet();\n this.styleMirror = new StyleSheetMirror();\n this.mutationCb = options.mutationCb;\n this.adoptedStyleSheetCb = options.adoptedStyleSheetCb;\n }\n attachLinkElement(linkEl, childSn) {\n if ('_cssText' in childSn.attributes)\n this.mutationCb({\n adds: [],\n removes: [],\n texts: [],\n attributes: [\n {\n id: childSn.id,\n attributes: childSn\n .attributes,\n },\n ],\n });\n this.trackLinkElement(linkEl);\n }\n trackLinkElement(linkEl) {\n if (this.trackedLinkElements.has(linkEl))\n return;\n this.trackedLinkElements.add(linkEl);\n this.trackStylesheetInLinkElement(linkEl);\n }\n adoptStyleSheets(sheets, hostId) {\n if (sheets.length === 0)\n return;\n const adoptedStyleSheetData = {\n id: hostId,\n styleIds: [],\n };\n const styles = [];\n for (const sheet of sheets) {\n let styleId;\n if (!this.styleMirror.has(sheet)) {\n styleId = this.styleMirror.add(sheet);\n styles.push({\n styleId,\n rules: Array.from(sheet.rules || CSSRule, (r, index) => ({\n rule: stringifyRule(r),\n index,\n })),\n });\n }\n else\n styleId = this.styleMirror.getId(sheet);\n adoptedStyleSheetData.styleIds.push(styleId);\n }\n if (styles.length > 0)\n adoptedStyleSheetData.styles = styles;\n this.adoptedStyleSheetCb(adoptedStyleSheetData);\n }\n reset() {\n this.styleMirror.reset();\n this.trackedLinkElements = new WeakSet();\n }\n trackStylesheetInLinkElement(linkEl) {\n }\n}\n\nclass ProcessedNodeManager {\n constructor() {\n this.nodeMap = new WeakMap();\n this.active = false;\n }\n inOtherBuffer(node, thisBuffer) {\n const buffers = this.nodeMap.get(node);\n return (buffers && Array.from(buffers).some((buffer) => buffer !== thisBuffer));\n }\n add(node, buffer) {\n if (!this.active) {\n this.active = true;\n onRequestAnimationFrame(() => {\n this.nodeMap = new WeakMap();\n this.active = false;\n });\n }\n this.nodeMap.set(node, (this.nodeMap.get(node) || new Set()).add(buffer));\n }\n destroy() {\n }\n}\n\nlet wrappedEmit;\nlet _takeFullSnapshot;\ntry {\n if (Array.from([1], (x) => x * 2)[0] !== 2) {\n const cleanFrame = document.createElement('iframe');\n document.body.appendChild(cleanFrame);\n Array.from = cleanFrame.contentWindow?.Array.from || Array.from;\n document.body.removeChild(cleanFrame);\n }\n}\ncatch (err) {\n console.debug('Unable to override Array.from', err);\n}\nconst mirror = createMirror();\nfunction record(options = {}) {\n const { emit, checkoutEveryNms, checkoutEveryNth, blockClass = 'rr-block', blockSelector = null, unblockSelector = null, ignoreClass = 'rr-ignore', ignoreSelector = null, maskAllText = false, maskTextClass = 'rr-mask', unmaskTextClass = null, maskTextSelector = null, unmaskTextSelector = null, inlineStylesheet = true, maskAllInputs, maskInputOptions: _maskInputOptions, slimDOMOptions: _slimDOMOptions, maskAttributeFn, maskInputFn, maskTextFn, maxCanvasSize = null, packFn, sampling = {}, dataURLOptions = {}, mousemoveWait, recordDOM = true, recordCanvas = false, recordCrossOriginIframes = false, recordAfter = options.recordAfter === 'DOMContentLoaded'\n ? options.recordAfter\n : 'load', userTriggeredOnInput = false, collectFonts = false, inlineImages = false, plugins, keepIframeSrcFn = () => false, ignoreCSSAttributes = new Set([]), errorHandler, onMutation, getCanvasManager, } = options;\n registerErrorHandler(errorHandler);\n const inEmittingFrame = recordCrossOriginIframes\n ? window.parent === window\n : true;\n let passEmitsToParent = false;\n if (!inEmittingFrame) {\n try {\n if (window.parent.document) {\n passEmitsToParent = false;\n }\n }\n catch (e) {\n passEmitsToParent = true;\n }\n }\n if (inEmittingFrame && !emit) {\n throw new Error('emit function is required');\n }\n if (!inEmittingFrame && !passEmitsToParent) {\n return () => {\n };\n }\n if (mousemoveWait !== undefined && sampling.mousemove === undefined) {\n sampling.mousemove = mousemoveWait;\n }\n mirror.reset();\n const maskInputOptions = maskAllInputs === true\n ? {\n color: true,\n date: true,\n 'datetime-local': true,\n email: true,\n month: true,\n number: true,\n range: true,\n search: true,\n tel: true,\n text: true,\n time: true,\n url: true,\n week: true,\n textarea: true,\n select: true,\n radio: true,\n checkbox: true,\n }\n : _maskInputOptions !== undefined\n ? _maskInputOptions\n : {};\n const slimDOMOptions = _slimDOMOptions === true || _slimDOMOptions === 'all'\n ? {\n script: true,\n comment: true,\n headFavicon: true,\n headWhitespace: true,\n headMetaSocial: true,\n headMetaRobots: true,\n headMetaHttpEquiv: true,\n headMetaVerification: true,\n headMetaAuthorship: _slimDOMOptions === 'all',\n headMetaDescKeywords: _slimDOMOptions === 'all',\n }\n : _slimDOMOptions\n ? _slimDOMOptions\n : {};\n polyfill();\n let lastFullSnapshotEvent;\n let incrementalSnapshotCount = 0;\n const eventProcessor = (e) => {\n for (const plugin of plugins || []) {\n if (plugin.eventProcessor) {\n e = plugin.eventProcessor(e);\n }\n }\n if (packFn &&\n !passEmitsToParent) {\n e = packFn(e);\n }\n return e;\n };\n wrappedEmit = (r, isCheckout) => {\n const e = r;\n e.timestamp = nowTimestamp();\n if (mutationBuffers[0]?.isFrozen() &&\n e.type !== EventType.FullSnapshot &&\n !(e.type === EventType.IncrementalSnapshot &&\n e.data.source === IncrementalSource.Mutation)) {\n mutationBuffers.forEach((buf) => buf.unfreeze());\n }\n if (inEmittingFrame) {\n emit?.(eventProcessor(e), isCheckout);\n }\n else if (passEmitsToParent) {\n const message = {\n type: 'rrweb',\n event: eventProcessor(e),\n origin: window.location.origin,\n isCheckout,\n };\n window.parent.postMessage(message, '*');\n }\n if (e.type === EventType.FullSnapshot) {\n lastFullSnapshotEvent = e;\n incrementalSnapshotCount = 0;\n }\n else if (e.type === EventType.IncrementalSnapshot) {\n if (e.data.source === IncrementalSource.Mutation &&\n e.data.isAttachIframe) {\n return;\n }\n incrementalSnapshotCount++;\n const exceedCount = checkoutEveryNth && incrementalSnapshotCount >= checkoutEveryNth;\n const exceedTime = checkoutEveryNms &&\n lastFullSnapshotEvent &&\n e.timestamp - lastFullSnapshotEvent.timestamp > checkoutEveryNms;\n if (exceedCount || exceedTime) {\n takeFullSnapshot(true);\n }\n }\n };\n const wrappedMutationEmit = (m) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Mutation,\n ...m,\n },\n });\n };\n const wrappedScrollEmit = (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Scroll,\n ...p,\n },\n });\n const wrappedCanvasMutationEmit = (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CanvasMutation,\n ...p,\n },\n });\n const wrappedAdoptedStyleSheetEmit = (a) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.AdoptedStyleSheet,\n ...a,\n },\n });\n const stylesheetManager = new StylesheetManager({\n mutationCb: wrappedMutationEmit,\n adoptedStyleSheetCb: wrappedAdoptedStyleSheetEmit,\n });\n const iframeManager = typeof __RRWEB_EXCLUDE_IFRAME__ === 'boolean' && __RRWEB_EXCLUDE_IFRAME__\n ? new IframeManagerNoop()\n : new IframeManager({\n mirror,\n mutationCb: wrappedMutationEmit,\n stylesheetManager: stylesheetManager,\n recordCrossOriginIframes,\n wrappedEmit,\n });\n for (const plugin of plugins || []) {\n if (plugin.getMirror)\n plugin.getMirror({\n nodeMirror: mirror,\n crossOriginIframeMirror: iframeManager.crossOriginIframeMirror,\n crossOriginIframeStyleMirror: iframeManager.crossOriginIframeStyleMirror,\n });\n }\n const processedNodeManager = new ProcessedNodeManager();\n const canvasManager = _getCanvasManager(getCanvasManager, {\n mirror,\n win: window,\n mutationCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CanvasMutation,\n ...p,\n },\n }),\n recordCanvas,\n blockClass,\n blockSelector,\n unblockSelector,\n maxCanvasSize,\n sampling: sampling['canvas'],\n dataURLOptions,\n errorHandler,\n });\n const shadowDomManager = typeof __RRWEB_EXCLUDE_SHADOW_DOM__ === 'boolean' &&\n __RRWEB_EXCLUDE_SHADOW_DOM__\n ? new ShadowDomManagerNoop()\n : new ShadowDomManager({\n mutationCb: wrappedMutationEmit,\n scrollCb: wrappedScrollEmit,\n bypassOptions: {\n onMutation,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskInputOptions,\n dataURLOptions,\n maskAttributeFn,\n maskTextFn,\n maskInputFn,\n recordCanvas,\n inlineImages,\n sampling,\n slimDOMOptions,\n iframeManager,\n stylesheetManager,\n canvasManager,\n keepIframeSrcFn,\n processedNodeManager,\n },\n mirror,\n });\n const takeFullSnapshot = (isCheckout = false) => {\n if (!recordDOM) {\n return;\n }\n wrappedEmit({\n type: EventType.Meta,\n data: {\n href: window.location.href,\n width: getWindowWidth(),\n height: getWindowHeight(),\n },\n }, isCheckout);\n stylesheetManager.reset();\n shadowDomManager.init();\n mutationBuffers.forEach((buf) => buf.lock());\n const node = snapshot(document, {\n mirror,\n blockClass,\n blockSelector,\n unblockSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n inlineStylesheet,\n maskAllInputs: maskInputOptions,\n maskAttributeFn,\n maskInputFn,\n maskTextFn,\n slimDOM: slimDOMOptions,\n dataURLOptions,\n recordCanvas,\n inlineImages,\n onSerialize: (n) => {\n if (isSerializedIframe(n, mirror)) {\n iframeManager.addIframe(n);\n }\n if (isSerializedStylesheet(n, mirror)) {\n stylesheetManager.trackLinkElement(n);\n }\n if (hasShadowRoot(n)) {\n shadowDomManager.addShadowRoot(n.shadowRoot, document);\n }\n },\n onIframeLoad: (iframe, childSn) => {\n iframeManager.attachIframe(iframe, childSn);\n if (iframe.contentWindow) {\n canvasManager.addWindow(iframe.contentWindow);\n }\n shadowDomManager.observeAttachShadow(iframe);\n },\n onStylesheetLoad: (linkEl, childSn) => {\n stylesheetManager.attachLinkElement(linkEl, childSn);\n },\n keepIframeSrcFn,\n });\n if (!node) {\n return console.warn('Failed to snapshot the document');\n }\n wrappedEmit({\n type: EventType.FullSnapshot,\n data: {\n node,\n initialOffset: getWindowScroll(window),\n },\n });\n mutationBuffers.forEach((buf) => buf.unlock());\n if (document.adoptedStyleSheets && document.adoptedStyleSheets.length > 0)\n stylesheetManager.adoptStyleSheets(document.adoptedStyleSheets, mirror.getId(document));\n };\n _takeFullSnapshot = takeFullSnapshot;\n try {\n const handlers = [];\n const observe = (doc) => {\n return callbackWrapper(initObservers)({\n onMutation,\n mutationCb: wrappedMutationEmit,\n mousemoveCb: (positions, source) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source,\n positions,\n },\n }),\n mouseInteractionCb: (d) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MouseInteraction,\n ...d,\n },\n }),\n scrollCb: wrappedScrollEmit,\n viewportResizeCb: (d) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.ViewportResize,\n ...d,\n },\n }),\n inputCb: (v) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Input,\n ...v,\n },\n }),\n mediaInteractionCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.MediaInteraction,\n ...p,\n },\n }),\n styleSheetRuleCb: (r) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleSheetRule,\n ...r,\n },\n }),\n styleDeclarationCb: (r) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.StyleDeclaration,\n ...r,\n },\n }),\n canvasMutationCb: wrappedCanvasMutationEmit,\n fontCb: (p) => wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Font,\n ...p,\n },\n }),\n selectionCb: (p) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.Selection,\n ...p,\n },\n });\n },\n customElementCb: (c) => {\n wrappedEmit({\n type: EventType.IncrementalSnapshot,\n data: {\n source: IncrementalSource.CustomElement,\n ...c,\n },\n });\n },\n blockClass,\n ignoreClass,\n ignoreSelector,\n maskAllText,\n maskTextClass,\n unmaskTextClass,\n maskTextSelector,\n unmaskTextSelector,\n maskInputOptions,\n inlineStylesheet,\n sampling,\n recordDOM,\n recordCanvas,\n inlineImages,\n userTriggeredOnInput,\n collectFonts,\n doc,\n maskAttributeFn,\n maskInputFn,\n maskTextFn,\n keepIframeSrcFn,\n blockSelector,\n unblockSelector,\n slimDOMOptions,\n dataURLOptions,\n mirror,\n iframeManager,\n stylesheetManager,\n shadowDomManager,\n processedNodeManager,\n canvasManager,\n ignoreCSSAttributes,\n plugins: plugins\n ?.filter((p) => p.observer)\n ?.map((p) => ({\n observer: p.observer,\n options: p.options,\n callback: (payload) => wrappedEmit({\n type: EventType.Plugin,\n data: {\n plugin: p.name,\n payload,\n },\n }),\n })) || [],\n }, {});\n };\n iframeManager.addLoadListener((iframeEl) => {\n try {\n handlers.push(observe(iframeEl.contentDocument));\n }\n catch (error) {\n console.warn(error);\n }\n });\n const init = () => {\n takeFullSnapshot();\n handlers.push(observe(document));\n };\n if (document.readyState === 'interactive' ||\n document.readyState === 'complete') {\n init();\n }\n else {\n handlers.push(on('DOMContentLoaded', () => {\n wrappedEmit({\n type: EventType.DomContentLoaded,\n data: {},\n });\n if (recordAfter === 'DOMContentLoaded')\n init();\n }));\n handlers.push(on('load', () => {\n wrappedEmit({\n type: EventType.Load,\n data: {},\n });\n if (recordAfter === 'load')\n init();\n }, window));\n }\n return () => {\n handlers.forEach((h) => h());\n processedNodeManager.destroy();\n _takeFullSnapshot = undefined;\n unregisterErrorHandler();\n };\n }\n catch (error) {\n console.warn(error);\n }\n}\nfunction takeFullSnapshot(isCheckout) {\n if (!_takeFullSnapshot) {\n throw new Error('please take full snapshot after start recording');\n }\n _takeFullSnapshot(isCheckout);\n}\nrecord.mirror = mirror;\nrecord.takeFullSnapshot = takeFullSnapshot;\nfunction _getCanvasManager(getCanvasManagerFn, options) {\n try {\n return getCanvasManagerFn\n ? getCanvasManagerFn(options)\n : new CanvasManagerNoop();\n }\n catch {\n console.warn('Unable to initialize CanvasManager');\n return new CanvasManagerNoop();\n }\n}\n\nconst ReplayEventTypeIncrementalSnapshot = 3;\nconst ReplayEventTypeCustom = 5;\n\n/**\n * Converts a timestamp to ms, if it was in s, or keeps it as ms.\n */\nfunction timestampToMs(timestamp) {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp : timestamp * 1000;\n}\n\n/**\n * Converts a timestamp to s, if it was in ms, or keeps it as s.\n */\nfunction timestampToS(timestamp) {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Add a breadcrumb event to replay.\n */\nfunction addBreadcrumbEvent(replay, breadcrumb) {\n if (breadcrumb.category === 'sentry.transaction') {\n return;\n }\n\n if (['ui.click', 'ui.input'].includes(breadcrumb.category )) {\n replay.triggerUserActivity();\n } else {\n replay.checkAndHandleExpiredSession();\n }\n\n replay.addUpdate(() => {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.throttledAddEvent({\n type: EventType.Custom,\n // TODO: We were converting from ms to seconds for breadcrumbs, spans,\n // but maybe we should just keep them as milliseconds\n timestamp: (breadcrumb.timestamp || 0) * 1000,\n data: {\n tag: 'breadcrumb',\n // normalize to max. 10 depth and 1_000 properties per object\n payload: normalize(breadcrumb, 10, 1000),\n },\n });\n\n // Do not flush after console log messages\n return breadcrumb.category === 'console';\n });\n}\n\nconst INTERACTIVE_SELECTOR = 'button,a';\n\n/** Get the closest interactive parent element, or else return the given element. */\nfunction getClosestInteractive(element) {\n const closestInteractive = element.closest(INTERACTIVE_SELECTOR);\n return closestInteractive || element;\n}\n\n/**\n * For clicks, we check if the target is inside of a button or link\n * If so, we use this as the target instead\n * This is useful because if you click on the image in ,\n * The target will be the image, not the button, which we don't want here\n */\nfunction getClickTargetNode(event) {\n const target = getTargetNode(event);\n\n if (!target || !(target instanceof Element)) {\n return target;\n }\n\n return getClosestInteractive(target);\n}\n\n/** Get the event target node. */\nfunction getTargetNode(event) {\n if (isEventWithTarget(event)) {\n return event.target ;\n }\n\n return event;\n}\n\nfunction isEventWithTarget(event) {\n return typeof event === 'object' && !!event && 'target' in event;\n}\n\nlet handlers;\n\n/**\n * Register a handler to be called when `window.open()` is called.\n * Returns a cleanup function.\n */\nfunction onWindowOpen(cb) {\n // Ensure to only register this once\n if (!handlers) {\n handlers = [];\n monkeyPatchWindowOpen();\n }\n\n handlers.push(cb);\n\n return () => {\n const pos = handlers ? handlers.indexOf(cb) : -1;\n if (pos > -1) {\n (handlers ).splice(pos, 1);\n }\n };\n}\n\nfunction monkeyPatchWindowOpen() {\n fill(WINDOW, 'open', function (originalWindowOpen) {\n return function (...args) {\n if (handlers) {\n try {\n handlers.forEach(handler => handler());\n } catch (e) {\n // ignore errors in here\n }\n }\n\n return originalWindowOpen.apply(WINDOW, args);\n };\n });\n}\n\n/** Any IncrementalSource for rrweb that we interpret as a kind of mutation. */\nconst IncrementalMutationSources = new Set([\n IncrementalSource.Mutation,\n IncrementalSource.StyleSheetRule,\n IncrementalSource.StyleDeclaration,\n IncrementalSource.AdoptedStyleSheet,\n IncrementalSource.CanvasMutation,\n IncrementalSource.Selection,\n IncrementalSource.MediaInteraction,\n]);\n\n/** Handle a click. */\nfunction handleClick(clickDetector, clickBreadcrumb, node) {\n clickDetector.handleClick(clickBreadcrumb, node);\n}\n\n/** A click detector class that can be used to detect slow or rage clicks on elements. */\nclass ClickDetector {\n // protected for testing\n\n constructor(\n replay,\n slowClickConfig,\n // Just for easier testing\n _addBreadcrumbEvent = addBreadcrumbEvent,\n ) {\n this._lastMutation = 0;\n this._lastScroll = 0;\n this._clicks = [];\n\n // We want everything in s, but options are in ms\n this._timeout = slowClickConfig.timeout / 1000;\n this._threshold = slowClickConfig.threshold / 1000;\n this._scrollTimeout = slowClickConfig.scrollTimeout / 1000;\n this._replay = replay;\n this._ignoreSelector = slowClickConfig.ignoreSelector;\n this._addBreadcrumbEvent = _addBreadcrumbEvent;\n }\n\n /** Register click detection handlers on mutation or scroll. */\n addListeners() {\n const cleanupWindowOpen = onWindowOpen(() => {\n // Treat window.open as mutation\n this._lastMutation = nowInSeconds();\n });\n\n this._teardown = () => {\n cleanupWindowOpen();\n\n this._clicks = [];\n this._lastMutation = 0;\n this._lastScroll = 0;\n };\n }\n\n /** Clean up listeners. */\n removeListeners() {\n if (this._teardown) {\n this._teardown();\n }\n\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n }\n\n /** @inheritDoc */\n handleClick(breadcrumb, node) {\n if (ignoreElement(node, this._ignoreSelector) || !isClickBreadcrumb(breadcrumb)) {\n return;\n }\n\n const newClick = {\n timestamp: timestampToS(breadcrumb.timestamp),\n clickBreadcrumb: breadcrumb,\n // Set this to 0 so we know it originates from the click breadcrumb\n clickCount: 0,\n node,\n };\n\n // If there was a click in the last 1s on the same element, ignore it - only keep a single reference per second\n if (\n this._clicks.some(click => click.node === newClick.node && Math.abs(click.timestamp - newClick.timestamp) < 1)\n ) {\n return;\n }\n\n this._clicks.push(newClick);\n\n // If this is the first new click, set a timeout to check for multi clicks\n if (this._clicks.length === 1) {\n this._scheduleCheckClicks();\n }\n }\n\n /** @inheritDoc */\n registerMutation(timestamp = Date.now()) {\n this._lastMutation = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n registerScroll(timestamp = Date.now()) {\n this._lastScroll = timestampToS(timestamp);\n }\n\n /** @inheritDoc */\n registerClick(element) {\n const node = getClosestInteractive(element);\n this._handleMultiClick(node );\n }\n\n /** Count multiple clicks on elements. */\n _handleMultiClick(node) {\n this._getClicks(node).forEach(click => {\n click.clickCount++;\n });\n }\n\n /** Get all pending clicks for a given node. */\n _getClicks(node) {\n return this._clicks.filter(click => click.node === node);\n }\n\n /** Check the clicks that happened. */\n _checkClicks() {\n const timedOutClicks = [];\n\n const now = nowInSeconds();\n\n this._clicks.forEach(click => {\n if (!click.mutationAfter && this._lastMutation) {\n click.mutationAfter = click.timestamp <= this._lastMutation ? this._lastMutation - click.timestamp : undefined;\n }\n if (!click.scrollAfter && this._lastScroll) {\n click.scrollAfter = click.timestamp <= this._lastScroll ? this._lastScroll - click.timestamp : undefined;\n }\n\n // All of these are in seconds!\n if (click.timestamp + this._timeout <= now) {\n timedOutClicks.push(click);\n }\n });\n\n // Remove \"old\" clicks\n for (const click of timedOutClicks) {\n const pos = this._clicks.indexOf(click);\n\n if (pos > -1) {\n this._generateBreadcrumbs(click);\n this._clicks.splice(pos, 1);\n }\n }\n\n // Trigger new check, unless no clicks left\n if (this._clicks.length) {\n this._scheduleCheckClicks();\n }\n }\n\n /** Generate matching breadcrumb(s) for the click. */\n _generateBreadcrumbs(click) {\n const replay = this._replay;\n const hadScroll = click.scrollAfter && click.scrollAfter <= this._scrollTimeout;\n const hadMutation = click.mutationAfter && click.mutationAfter <= this._threshold;\n\n const isSlowClick = !hadScroll && !hadMutation;\n const { clickCount, clickBreadcrumb } = click;\n\n // Slow click\n if (isSlowClick) {\n // If `mutationAfter` is set, it means a mutation happened after the threshold, but before the timeout\n // If not, it means we just timed out without scroll & mutation\n const timeAfterClickMs = Math.min(click.mutationAfter || this._timeout, this._timeout) * 1000;\n const endReason = timeAfterClickMs < this._timeout * 1000 ? 'mutation' : 'timeout';\n\n const breadcrumb = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.slowClickDetected',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n timeAfterClickMs,\n endReason,\n // If clickCount === 0, it means multiClick was not correctly captured here\n // - we still want to send 1 in this case\n clickCount: clickCount || 1,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n return;\n }\n\n // Multi click\n if (clickCount > 1) {\n const breadcrumb = {\n type: 'default',\n message: clickBreadcrumb.message,\n timestamp: clickBreadcrumb.timestamp,\n category: 'ui.multiClick',\n data: {\n ...clickBreadcrumb.data,\n url: WINDOW.location.href,\n route: replay.getCurrentRoute(),\n clickCount,\n metric: true,\n },\n };\n\n this._addBreadcrumbEvent(replay, breadcrumb);\n }\n }\n\n /** Schedule to check current clicks. */\n _scheduleCheckClicks() {\n if (this._checkClickTimeout) {\n clearTimeout(this._checkClickTimeout);\n }\n\n this._checkClickTimeout = setTimeout$3(() => this._checkClicks(), 1000);\n }\n}\n\nconst SLOW_CLICK_TAGS = ['A', 'BUTTON', 'INPUT'];\n\n/** exported for tests only */\nfunction ignoreElement(node, ignoreSelector) {\n if (!SLOW_CLICK_TAGS.includes(node.tagName)) {\n return true;\n }\n\n // If tag, we only want to consider input[type='submit'] & input[type='button']\n if (node.tagName === 'INPUT' && !['submit', 'button'].includes(node.getAttribute('type') || '')) {\n return true;\n }\n\n // If tag, detect special variants that may not lead to an action\n // If target !== _self, we may open the link somewhere else, which would lead to no action\n // Also, when downloading a file, we may not leave the page, but still not trigger an action\n if (\n node.tagName === 'A' &&\n (node.hasAttribute('download') || (node.hasAttribute('target') && node.getAttribute('target') !== '_self'))\n ) {\n return true;\n }\n\n if (ignoreSelector && node.matches(ignoreSelector)) {\n return true;\n }\n\n return false;\n}\n\nfunction isClickBreadcrumb(breadcrumb) {\n return !!(breadcrumb.data && typeof breadcrumb.data.nodeId === 'number' && breadcrumb.timestamp);\n}\n\n// This is good enough for us, and is easier to test/mock than `timestampInSeconds`\nfunction nowInSeconds() {\n return Date.now() / 1000;\n}\n\n/** Update the click detector based on a recording event of rrweb. */\nfunction updateClickDetectorForRecordingEvent(clickDetector, event) {\n try {\n // note: We only consider incremental snapshots here\n // This means that any full snapshot is ignored for mutation detection - the reason is that we simply cannot know if a mutation happened here.\n // E.g. think that we are buffering, an error happens and we take a full snapshot because we switched to session mode -\n // in this scenario, we would not know if a dead click happened because of the error, which is a key dead click scenario.\n // Instead, by ignoring full snapshots, we have the risk that we generate a false positive\n // (if a mutation _did_ happen but was \"swallowed\" by the full snapshot)\n // But this should be more unlikely as we'd generally capture the incremental snapshot right away\n\n if (!isIncrementalEvent(event)) {\n return;\n }\n\n const { source } = event.data;\n if (IncrementalMutationSources.has(source)) {\n clickDetector.registerMutation(event.timestamp);\n }\n\n if (source === IncrementalSource.Scroll) {\n clickDetector.registerScroll(event.timestamp);\n }\n\n if (isIncrementalMouseInteraction(event)) {\n const { type, id } = event.data;\n const node = record.mirror.getNode(id);\n\n if (node instanceof HTMLElement && type === MouseInteractions.Click) {\n clickDetector.registerClick(node);\n }\n }\n } catch {\n // ignore errors here, e.g. if accessing something that does not exist\n }\n}\n\nfunction isIncrementalEvent(event) {\n return event.type === ReplayEventTypeIncrementalSnapshot;\n}\n\nfunction isIncrementalMouseInteraction(\n event,\n) {\n return event.data.source === IncrementalSource.MouseInteraction;\n}\n\n/**\n * Create a breadcrumb for a replay.\n */\nfunction createBreadcrumb(\n breadcrumb,\n) {\n return {\n timestamp: Date.now() / 1000,\n type: 'default',\n ...breadcrumb,\n };\n}\n\nvar NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"Document\"] = 0] = \"Document\";\n NodeType[NodeType[\"DocumentType\"] = 1] = \"DocumentType\";\n NodeType[NodeType[\"Element\"] = 2] = \"Element\";\n NodeType[NodeType[\"Text\"] = 3] = \"Text\";\n NodeType[NodeType[\"CDATA\"] = 4] = \"CDATA\";\n NodeType[NodeType[\"Comment\"] = 5] = \"Comment\";\n})(NodeType || (NodeType = {}));\n\n// Note that these are the serialized attributes and not attributes directly on\n// the DOM Node. Attributes we are interested in:\nconst ATTRIBUTES_TO_RECORD = new Set([\n 'id',\n 'class',\n 'aria-label',\n 'role',\n 'name',\n 'alt',\n 'title',\n 'data-test-id',\n 'data-testid',\n 'disabled',\n 'aria-disabled',\n 'data-sentry-component',\n]);\n\n/**\n * Inclusion list of attributes that we want to record from the DOM element\n */\nfunction getAttributesToRecord(attributes) {\n const obj = {};\n if (!attributes['data-sentry-component'] && attributes['data-sentry-element']) {\n attributes['data-sentry-component'] = attributes['data-sentry-element'];\n }\n for (const key in attributes) {\n if (ATTRIBUTES_TO_RECORD.has(key)) {\n let normalizedKey = key;\n\n if (key === 'data-testid' || key === 'data-test-id') {\n normalizedKey = 'testId';\n }\n\n obj[normalizedKey] = attributes[key];\n }\n }\n\n return obj;\n}\n\nconst handleDomListener = (\n replay,\n) => {\n return (handlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleDom(handlerData);\n\n if (!result) {\n return;\n }\n\n const isClick = handlerData.name === 'click';\n const event = isClick ? (handlerData.event ) : undefined;\n // Ignore clicks if ctrl/alt/meta/shift keys are held down as they alter behavior of clicks (e.g. open in new tab)\n if (\n isClick &&\n replay.clickDetector &&\n event &&\n event.target &&\n !event.altKey &&\n !event.metaKey &&\n !event.ctrlKey &&\n !event.shiftKey\n ) {\n handleClick(\n replay.clickDetector,\n result ,\n getClickTargetNode(handlerData.event ) ,\n );\n }\n\n addBreadcrumbEvent(replay, result);\n };\n};\n\n/** Get the base DOM breadcrumb. */\nfunction getBaseDomBreadcrumb(target, message) {\n const nodeId = record.mirror.getId(target);\n const node = nodeId && record.mirror.getNode(nodeId);\n const meta = node && record.mirror.getMeta(node);\n const element = meta && isElement(meta) ? meta : null;\n\n return {\n message,\n data: element\n ? {\n nodeId,\n node: {\n id: nodeId,\n tagName: element.tagName,\n textContent: Array.from(element.childNodes)\n .map((node) => node.type === NodeType.Text && node.textContent)\n .filter(Boolean) // filter out empty values\n .map(text => (text ).trim())\n .join(''),\n attributes: getAttributesToRecord(element.attributes),\n },\n }\n : {},\n };\n}\n\n/**\n * An event handler to react to DOM events.\n * Exported for tests.\n */\nfunction handleDom(handlerData) {\n const { target, message } = getDomTarget(handlerData);\n\n return createBreadcrumb({\n category: `ui.${handlerData.name}`,\n ...getBaseDomBreadcrumb(target, message),\n });\n}\n\nfunction getDomTarget(handlerData) {\n const isClick = handlerData.name === 'click';\n\n let message;\n let target = null;\n\n // Accessing event.target can throw (see getsentry/raven-js#838, #768)\n try {\n target = isClick ? getClickTargetNode(handlerData.event ) : getTargetNode(handlerData.event );\n message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n } catch (e) {\n message = '';\n }\n\n return { target, message };\n}\n\nfunction isElement(node) {\n return node.type === NodeType.Element;\n}\n\n/** Handle keyboard events & create breadcrumbs. */\nfunction handleKeyboardEvent(replay, event) {\n if (!replay.isEnabled()) {\n return;\n }\n\n // Update user activity, but do not restart recording as it can create\n // noisy/low-value replays (e.g. user comes back from idle, hits alt-tab, new\n // session with a single \"keydown\" breadcrumb is created)\n replay.updateUserActivity();\n\n const breadcrumb = getKeyboardBreadcrumb(event);\n\n if (!breadcrumb) {\n return;\n }\n\n addBreadcrumbEvent(replay, breadcrumb);\n}\n\n/** exported only for tests */\nfunction getKeyboardBreadcrumb(event) {\n const { metaKey, shiftKey, ctrlKey, altKey, key, target } = event;\n\n // never capture for input fields\n if (!target || isInputElement(target ) || !key) {\n return null;\n }\n\n // Note: We do not consider shift here, as that means \"uppercase\"\n const hasModifierKey = metaKey || ctrlKey || altKey;\n const isCharacterKey = key.length === 1; // other keys like Escape, Tab, etc have a longer length\n\n // Do not capture breadcrumb if only a word key is pressed\n // This could leak e.g. user input\n if (!hasModifierKey && isCharacterKey) {\n return null;\n }\n\n const message = htmlTreeAsString(target, { maxStringLength: 200 }) || '';\n const baseBreadcrumb = getBaseDomBreadcrumb(target , message);\n\n return createBreadcrumb({\n category: 'ui.keyDown',\n message,\n data: {\n ...baseBreadcrumb.data,\n metaKey,\n shiftKey,\n ctrlKey,\n altKey,\n key,\n },\n });\n}\n\nfunction isInputElement(target) {\n return target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable;\n}\n\n// Map entryType -> function to normalize data for event\nconst ENTRY_TYPES\n\n = {\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n resource: createResourceEntry,\n paint: createPaintEntry,\n // @ts-expect-error TODO: entry type does not fit the create* functions entry type\n navigation: createNavigationEntry,\n};\n\n/**\n * Handler creater for web vitals\n */\nfunction webVitalHandler(\n getter,\n replay,\n) {\n return ({ metric }) => void replay.replayPerformanceEntries.push(getter(metric));\n}\n\n/**\n * Create replay performance entries from the browser performance entries.\n */\nfunction createPerformanceEntries(\n entries,\n) {\n return entries.map(createPerformanceEntry).filter(Boolean) ;\n}\n\nfunction createPerformanceEntry(entry) {\n const entryType = ENTRY_TYPES[entry.entryType];\n if (!entryType) {\n return null;\n }\n\n return entryType(entry);\n}\n\nfunction getAbsoluteTime(time) {\n // browserPerformanceTimeOrigin can be undefined if `performance` or\n // `performance.now` doesn't exist, but this is already checked by this integration\n return ((browserPerformanceTimeOrigin() || WINDOW.performance.timeOrigin) + time) / 1000;\n}\n\nfunction createPaintEntry(entry) {\n const { duration, entryType, name, startTime } = entry;\n\n const start = getAbsoluteTime(startTime);\n return {\n type: entryType,\n name,\n start,\n end: start + duration,\n data: undefined,\n };\n}\n\nfunction createNavigationEntry(entry) {\n const {\n entryType,\n name,\n decodedBodySize,\n duration,\n domComplete,\n encodedBodySize,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n domInteractive,\n loadEventStart,\n loadEventEnd,\n redirectCount,\n startTime,\n transferSize,\n type,\n } = entry;\n\n // Ignore entries with no duration, they do not seem to be useful and cause dupes\n if (duration === 0) {\n return null;\n }\n\n return {\n type: `${entryType}.${type}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(domComplete),\n name,\n data: {\n size: transferSize,\n decodedBodySize,\n encodedBodySize,\n duration,\n domInteractive,\n domContentLoadedEventStart,\n domContentLoadedEventEnd,\n loadEventStart,\n loadEventEnd,\n domComplete,\n redirectCount,\n },\n };\n}\n\nfunction createResourceEntry(\n entry,\n) {\n const {\n entryType,\n initiatorType,\n name,\n responseEnd,\n startTime,\n decodedBodySize,\n encodedBodySize,\n responseStatus,\n transferSize,\n } = entry;\n\n // Core SDK handles these\n if (['fetch', 'xmlhttprequest'].includes(initiatorType)) {\n return null;\n }\n\n return {\n type: `${entryType}.${initiatorType}`,\n start: getAbsoluteTime(startTime),\n end: getAbsoluteTime(responseEnd),\n name,\n data: {\n size: transferSize,\n statusCode: responseStatus,\n decodedBodySize,\n encodedBodySize,\n },\n };\n}\n\n/**\n * Add a LCP event to the replay based on a LCP metric.\n */\nfunction getLargestContentfulPaint(metric) {\n const lastEntry = metric.entries[metric.entries.length - 1] ;\n const node = lastEntry?.element ? [lastEntry.element] : undefined;\n return getWebVital(metric, 'largest-contentful-paint', node);\n}\n\nfunction isLayoutShift(entry) {\n return (entry ).sources !== undefined;\n}\n\n/**\n * Add a CLS event to the replay based on a CLS metric.\n */\nfunction getCumulativeLayoutShift(metric) {\n const layoutShifts = [];\n const nodes = [];\n for (const entry of metric.entries) {\n if (isLayoutShift(entry)) {\n const nodeIds = [];\n for (const source of entry.sources) {\n if (source.node) {\n nodes.push(source.node);\n const nodeId = record.mirror.getId(source.node);\n if (nodeId) {\n nodeIds.push(nodeId);\n }\n }\n }\n layoutShifts.push({ value: entry.value, nodeIds: nodeIds.length ? nodeIds : undefined });\n }\n }\n\n return getWebVital(metric, 'cumulative-layout-shift', nodes, layoutShifts);\n}\n\n/**\n * Add a FID event to the replay based on a FID metric.\n */\nfunction getFirstInputDelay(metric) {\n const lastEntry = metric.entries[metric.entries.length - 1] ;\n const node = lastEntry?.target ? [lastEntry.target] : undefined;\n return getWebVital(metric, 'first-input-delay', node);\n}\n\n/**\n * Add an INP event to the replay based on an INP metric.\n */\nfunction getInteractionToNextPaint(metric) {\n const lastEntry = metric.entries[metric.entries.length - 1] ;\n const node = lastEntry?.target ? [lastEntry.target] : undefined;\n return getWebVital(metric, 'interaction-to-next-paint', node);\n}\n\n/**\n * Add an web vital event to the replay based on the web vital metric.\n */\nfunction getWebVital(\n metric,\n name,\n nodes,\n attributions,\n) {\n const value = metric.value;\n const rating = metric.rating;\n\n const end = getAbsoluteTime(value);\n\n return {\n type: 'web-vital',\n name,\n start: end,\n end,\n data: {\n value,\n size: value,\n rating,\n nodeIds: nodes ? nodes.map(node => record.mirror.getId(node)) : undefined,\n attributions,\n },\n };\n}\n\n/**\n * Sets up a PerformanceObserver to listen to all performance entry types.\n * Returns a callback to stop observing.\n */\nfunction setupPerformanceObserver(replay) {\n function addPerformanceEntry(entry) {\n // It is possible for entries to come up multiple times\n if (!replay.performanceEntries.includes(entry)) {\n replay.performanceEntries.push(entry);\n }\n }\n\n function onEntries({ entries }) {\n entries.forEach(addPerformanceEntry);\n }\n\n const clearCallbacks = [];\n\n (['navigation', 'paint', 'resource'] ).forEach(type => {\n clearCallbacks.push(addPerformanceInstrumentationHandler(type, onEntries));\n });\n\n clearCallbacks.push(\n addLcpInstrumentationHandler(webVitalHandler(getLargestContentfulPaint, replay)),\n addClsInstrumentationHandler(webVitalHandler(getCumulativeLayoutShift, replay)),\n addFidInstrumentationHandler(webVitalHandler(getFirstInputDelay, replay)),\n addInpInstrumentationHandler(webVitalHandler(getInteractionToNextPaint, replay)),\n );\n\n // A callback to cleanup all handlers\n return () => {\n clearCallbacks.forEach(clearCallback => clearCallback());\n };\n}\n\n/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nconst r = `var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),s=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),a=function(t,e){for(var i=new n(31),s=0;s<31;++s)i[s]=e+=1<>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,s=0,a=new n(r);s>f]=l}else for(o=new n(i),s=0;s>15-t[s]);return o},p=new t(288);for(c=0;c<144;++c)p[c]=8;for(c=144;c<256;++c)p[c]=9;for(c=256;c<280;++c)p[c]=7;for(c=280;c<288;++c)p[c]=8;var g=new t(32);for(c=0;c<32;++c)g[c]=5;var w=d(p,9,0),y=d(g,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=[\"unexpected EOF\",\"invalid block type\",\"invalid length/literal\",\"invalid distance\",\"stream finished\",\"no stream handler\",,\"no callback\",\"invalid UTF-8 data\",\"extra field too long\",\"date not in range 1980-2099\",\"filename too long\",\"stream finishing\",\"invalid zip data\"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},_=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},x=function(r,e){for(var i=[],s=0;sd&&(d=o[s].s);var p=new n(d+1),g=A(i[c-1],p,0);if(g>e){s=0;var w=0,y=g-e,m=1<e))break;w+=m-(1<>=y;w>0;){var M=o[s].s;p[M]=0&&w;--s){var E=o[s].s;p[E]==e&&(--p[E],++w)}g=e}return{t:new t(p),l:g}},A=function(t,n,r){return-1==t.s?Math.max(A(t.l,n,r+1),A(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,s=t[0],a=1,o=function(t){e[i++]=t},h=1;h<=r;++h)if(t[h]==s&&h!=r)++a;else{if(!s&&a>2){for(;a>138;a-=138)o(32754);a>2&&(o(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(o(s),--a;a>6;a-=6)o(8304);a>2&&(o(a-3<<5|8208),a=0)}for(;a--;)o(s);a=1,s=t[h]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var s=0;s4&&!H[s[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(h,p)+T(f,g)+l,X=T(h,M)+T(f,U)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=w,P=p,Q=y,R=g;for(B=0;B255){_(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;_(r,m,Q[et]),m+=R[et],et>3&&(_(r,m,rt>>5&8191),m+=i[et])}else _(r,m,N[rt]),m+=P[rt]}return _(r,m,N[256]),m+P[256]},C=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e>>8;t=r},d:function(){return~t}}},L=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,s=0|r.length,a=0;a!=s;){for(var o=Math.min(a+2655,s);a>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},O=function(s,a,o,h,u){if(!u&&(u={l:1},a.dictionary)){var c=a.dictionary.subarray(-32768),v=new t(c.length+s.length);v.set(c),v.set(s,c.length),s=v,u.w=c.length}return function(s,a,o,h,u,c){var v=c.z||s.length,d=new t(h+v+5*(1+Math.ceil(v/7e3))+u),p=d.subarray(h,d.length-u),g=c.l,w=7&(c.r||0);if(a){w&&(p[0]=c.r>>3);for(var y=C[a-1],M=y>>13,E=8191&y,z=(1<7e3||q>24576)&&(N>423||!g)){w=U(s,p,0,F,I,S,O,q,G,j-G,w),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(s[j+Q]==s[j+Q-W]){for(var $=0;$Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;Pnt&&(nt=et,K=rt)}}}W+=(J=K)-(K=_[J])&32767}if(R){F[q++]=268435456|f[Q]<<18|l[R];var it=31&f[Q],st=31&l[R];O+=e[it]+i[st],++I[257+it],++S[st],B=j+Q,++L}else F[q++]=s[j],++I[s[j]]}}for(j=Math.max(j,B);j=v&&(p[w/8|0]=g,at=v),w=k(p,w+1,s.subarray(j,at))}c.i=v}return b(d,0,h+m(w)+u)}(s,null==a.level?6:a.level,null==a.mem?u.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):20:12+a.mem,o,h,u)},j=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},q=function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&j(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}},B=function(t){return 10+(t.filename?t.filename.length+1:0)},G=function(){function n(n,r){if(\"function\"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(O(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var s=this.b.length-this.s.z;this.b.set(n.subarray(0,s),this.s.z),this.s.z=this.b.length,this.p(this.b,!1),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(s),32768),this.s.z=n.length-s+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n.prototype.flush=function(){this.ondata||E(5),this.s.l&&E(4),this.p(this.b,!1),this.s.w=this.s.i,this.s.i-=2},n}();var H=function(){function t(t,n){this.c=L(),this.v=1,G.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),G.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=O(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=L();i.p(n.dictionary),j(t,2,i.d())}}(r,this.o),this.v=0),n&&j(r,r.length-4,this.c.d()),this.ondata(r,n)},t.prototype.flush=function(){G.prototype.flush.call(this)},t}(),J=\"undefined\"!=typeof TextEncoder&&new TextEncoder,K=\"undefined\"!=typeof TextDecoder&&new TextDecoder;try{K.decode(F,{stream:!0})}catch(t){}var N=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(P(t),this.d=n||!1)},t}();function P(n,r){if(J)return J.encode(n);for(var e=n.length,i=new t(n.length+(n.length>>1)),s=0,a=function(t){i[s++]=t},o=0;oi.length){var h=new t(s+8+(e-o<<1));h.set(i),i=h}var f=n.charCodeAt(o);f<128||r?a(f):f<2048?(a(192|f>>6),a(128|63&f)):f>55295&&f<57344?(a(240|(f=65536+(1047552&f)|1023&n.charCodeAt(++o))>>18),a(128|f>>12&63),a(128|f>>6&63),a(128|63&f)):(a(224|f>>12),a(128|f>>6&63),a(128|63&f))}return b(i,0,s)}function Q(t){return function(t,n){n||(n={});var r=S(),e=t.length;r.p(t);var i=O(t,n,B(n),8),s=i.length;return q(i,n),j(i,s-8,r.d()),j(i,s-4,e),i}(P(t))}const R=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error(\"Adding invalid event\");const n=this._hasEvents?\",\":\"\";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push(\"]\",!0);const t=function(t){let n=0;for(const r of t)n+=r.length;const r=new Uint8Array(n);for(let n=0,e=0,i=t.length;n{this._deflatedData.push(t)},this.stream=new N(((t,n)=>{this.deflate.push(t,n)})),this.stream.push(\"[\")}},V={clear:()=>{R.clear()},addEvent:t=>R.addEvent(t),finish:()=>R.finish(),compress:t=>Q(t)};addEventListener(\"message\",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in V&&\"function\"==typeof V[n])try{const t=V[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:\"init\",success:!0,response:void 0});`;\n\nfunction e(){const e=new Blob([r]);return URL.createObjectURL(e)}\n\nconst CONSOLE_LEVELS = ['info', 'warn', 'error', 'log'] ;\nconst PREFIX = '[Replay] ';\n\nfunction _addBreadcrumb(message, level = 'info') {\n addBreadcrumb(\n {\n category: 'console',\n data: {\n logger: 'replay',\n },\n level,\n message: `${PREFIX}${message}`,\n },\n { level },\n );\n}\n\nfunction makeReplayLogger() {\n let _capture = false;\n let _trace = false;\n\n const _logger = {\n exception: () => undefined,\n infoTick: () => undefined,\n setConfig: (opts) => {\n _capture = !!opts.captureExceptions;\n _trace = !!opts.traceInternals;\n },\n };\n\n if (DEBUG_BUILD) {\n CONSOLE_LEVELS.forEach(name => {\n _logger[name] = (...args) => {\n logger$1[name](PREFIX, ...args);\n if (_trace) {\n _addBreadcrumb(args.join(''), severityLevelFromString(name));\n }\n };\n });\n\n _logger.exception = (error, ...message) => {\n if (message.length && _logger.error) {\n _logger.error(...message);\n }\n\n logger$1.error(PREFIX, error);\n\n if (_capture) {\n captureException(error);\n } else if (_trace) {\n // No need for a breadcrumb if `_capture` is enabled since it should be\n // captured as an exception\n _addBreadcrumb(error, 'error');\n }\n };\n\n _logger.infoTick = (...args) => {\n logger$1.info(PREFIX, ...args);\n if (_trace) {\n // Wait a tick here to avoid race conditions for some initial logs\n // which may be added before replay is initialized\n setTimeout(() => _addBreadcrumb(args[0]), 0);\n }\n };\n } else {\n CONSOLE_LEVELS.forEach(name => {\n _logger[name] = () => undefined;\n });\n }\n\n return _logger ;\n}\n\nconst logger = makeReplayLogger();\n\n/** This error indicates that the event buffer size exceeded the limit.. */\nclass EventBufferSizeExceededError extends Error {\n constructor() {\n super(`Event buffer exceeded maximum size of ${REPLAY_MAX_EVENT_BUFFER_SIZE}.`);\n }\n}\n\n/**\n * A basic event buffer that does not do any compression.\n * Used as fallback if the compression worker cannot be loaded or is disabled.\n */\nclass EventBufferArray {\n /** All the events that are buffered to be sent. */\n\n /** @inheritdoc */\n\n /** @inheritdoc */\n\n constructor() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n this.waitForCheckout = false;\n }\n\n /** @inheritdoc */\n get hasEvents() {\n return this.events.length > 0;\n }\n\n /** @inheritdoc */\n get type() {\n return 'sync';\n }\n\n /** @inheritdoc */\n destroy() {\n this.events = [];\n }\n\n /** @inheritdoc */\n async addEvent(event) {\n const eventSize = JSON.stringify(event).length;\n this._totalSize += eventSize;\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n throw new EventBufferSizeExceededError();\n }\n\n this.events.push(event);\n }\n\n /** @inheritdoc */\n finish() {\n return new Promise(resolve => {\n // Make a copy of the events array reference and immediately clear the\n // events member so that we do not lose new events while uploading\n // attachment.\n const eventsRet = this.events;\n this.clear();\n resolve(JSON.stringify(eventsRet));\n });\n }\n\n /** @inheritdoc */\n clear() {\n this.events = [];\n this._totalSize = 0;\n this.hasCheckout = false;\n }\n\n /** @inheritdoc */\n getEarliestTimestamp() {\n const timestamp = this.events.map(event => event.timestamp).sort()[0];\n\n if (!timestamp) {\n return null;\n }\n\n return timestampToMs(timestamp);\n }\n}\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nclass WorkerHandler {\n\n constructor(worker) {\n this._worker = worker;\n this._id = 0;\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occurred.\n */\n ensureReady() {\n // Ensure we only check once\n if (this._ensureReadyPromise) {\n return this._ensureReadyPromise;\n }\n\n this._ensureReadyPromise = new Promise((resolve, reject) => {\n this._worker.addEventListener(\n 'message',\n ({ data }) => {\n if ((data ).success) {\n resolve();\n } else {\n reject();\n }\n },\n { once: true },\n );\n\n this._worker.addEventListener(\n 'error',\n error => {\n reject(error);\n },\n { once: true },\n );\n });\n\n return this._ensureReadyPromise;\n }\n\n /**\n * Destroy the worker.\n */\n destroy() {\n DEBUG_BUILD && logger.info('Destroying compression worker');\n this._worker.terminate();\n }\n\n /**\n * Post message to worker and wait for response before resolving promise.\n */\n postMessage(method, arg) {\n const id = this._getAndIncrementId();\n\n return new Promise((resolve, reject) => {\n const listener = ({ data }) => {\n const response = data ;\n if (response.method !== method) {\n return;\n }\n\n // There can be multiple listeners for a single method, the id ensures\n // that the response matches the caller.\n if (response.id !== id) {\n return;\n }\n\n // At this point, we'll always want to remove listener regardless of result status\n this._worker.removeEventListener('message', listener);\n\n if (!response.success) {\n // TODO: Do some error handling, not sure what\n DEBUG_BUILD && logger.error('Error in compression worker: ', response.response);\n\n reject(new Error('Error in compression worker'));\n return;\n }\n\n resolve(response.response );\n };\n\n // Note: we can't use `once` option because it's possible it needs to\n // listen to multiple messages\n this._worker.addEventListener('message', listener);\n this._worker.postMessage({ id, method, arg });\n });\n }\n\n /** Get the current ID and increment it for the next call. */\n _getAndIncrementId() {\n return this._id++;\n }\n}\n\n/**\n * Event buffer that uses a web worker to compress events.\n * Exported only for testing.\n */\nclass EventBufferCompressionWorker {\n /** @inheritdoc */\n\n /** @inheritdoc */\n\n constructor(worker) {\n this._worker = new WorkerHandler(worker);\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n this.waitForCheckout = false;\n }\n\n /** @inheritdoc */\n get hasEvents() {\n return !!this._earliestTimestamp;\n }\n\n /** @inheritdoc */\n get type() {\n return 'worker';\n }\n\n /**\n * Ensure the worker is ready (or not).\n * This will either resolve when the worker is ready, or reject if an error occurred.\n */\n ensureReady() {\n return this._worker.ensureReady();\n }\n\n /**\n * Destroy the event buffer.\n */\n destroy() {\n this._worker.destroy();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfully received and processed by worker.\n */\n addEvent(event) {\n const timestamp = timestampToMs(event.timestamp);\n if (!this._earliestTimestamp || timestamp < this._earliestTimestamp) {\n this._earliestTimestamp = timestamp;\n }\n\n const data = JSON.stringify(event);\n this._totalSize += data.length;\n\n if (this._totalSize > REPLAY_MAX_EVENT_BUFFER_SIZE) {\n return Promise.reject(new EventBufferSizeExceededError());\n }\n\n return this._sendEventToWorker(data);\n }\n\n /**\n * Finish the event buffer and return the compressed data.\n */\n finish() {\n return this._finishRequest();\n }\n\n /** @inheritdoc */\n clear() {\n this._earliestTimestamp = null;\n this._totalSize = 0;\n this.hasCheckout = false;\n\n // We do not wait on this, as we assume the order of messages is consistent for the worker\n this._worker.postMessage('clear').then(null, e => {\n DEBUG_BUILD && logger.exception(e, 'Sending \"clear\" message to worker failed', e);\n });\n }\n\n /** @inheritdoc */\n getEarliestTimestamp() {\n return this._earliestTimestamp;\n }\n\n /**\n * Send the event to the worker.\n */\n _sendEventToWorker(data) {\n return this._worker.postMessage('addEvent', data);\n }\n\n /**\n * Finish the request and return the compressed data from the worker.\n */\n async _finishRequest() {\n const response = await this._worker.postMessage('finish');\n\n this._earliestTimestamp = null;\n this._totalSize = 0;\n\n return response;\n }\n}\n\n/**\n * This proxy will try to use the compression worker, and fall back to use the simple buffer if an error occurs there.\n * This can happen e.g. if the worker cannot be loaded.\n * Exported only for testing.\n */\nclass EventBufferProxy {\n\n constructor(worker) {\n this._fallback = new EventBufferArray();\n this._compression = new EventBufferCompressionWorker(worker);\n this._used = this._fallback;\n\n this._ensureWorkerIsLoadedPromise = this._ensureWorkerIsLoaded();\n }\n\n /** @inheritdoc */\n get waitForCheckout() {\n return this._used.waitForCheckout;\n }\n\n /** @inheritdoc */\n get type() {\n return this._used.type;\n }\n\n /** @inheritDoc */\n get hasEvents() {\n return this._used.hasEvents;\n }\n\n /** @inheritdoc */\n get hasCheckout() {\n return this._used.hasCheckout;\n }\n /** @inheritdoc */\n set hasCheckout(value) {\n this._used.hasCheckout = value;\n }\n\n /** @inheritdoc */\n // eslint-disable-next-line @typescript-eslint/adjacent-overload-signatures\n set waitForCheckout(value) {\n this._used.waitForCheckout = value;\n }\n\n /** @inheritDoc */\n destroy() {\n this._fallback.destroy();\n this._compression.destroy();\n }\n\n /** @inheritdoc */\n clear() {\n return this._used.clear();\n }\n\n /** @inheritdoc */\n getEarliestTimestamp() {\n return this._used.getEarliestTimestamp();\n }\n\n /**\n * Add an event to the event buffer.\n *\n * Returns true if event was successfully added.\n */\n addEvent(event) {\n return this._used.addEvent(event);\n }\n\n /** @inheritDoc */\n async finish() {\n // Ensure the worker is loaded, so the sent event is compressed\n await this.ensureWorkerIsLoaded();\n\n return this._used.finish();\n }\n\n /** Ensure the worker has loaded. */\n ensureWorkerIsLoaded() {\n return this._ensureWorkerIsLoadedPromise;\n }\n\n /** Actually check if the worker has been loaded. */\n async _ensureWorkerIsLoaded() {\n try {\n await this._compression.ensureReady();\n } catch (error) {\n // If the worker fails to load, we fall back to the simple buffer.\n // Nothing more to do from our side here\n DEBUG_BUILD && logger.exception(error, 'Failed to load the compression worker, falling back to simple buffer');\n return;\n }\n\n // Now we need to switch over the array buffer to the compression worker\n await this._switchToCompressionWorker();\n }\n\n /** Switch the used buffer to the compression worker. */\n async _switchToCompressionWorker() {\n const { events, hasCheckout, waitForCheckout } = this._fallback;\n\n const addEventPromises = [];\n for (const event of events) {\n addEventPromises.push(this._compression.addEvent(event));\n }\n\n this._compression.hasCheckout = hasCheckout;\n this._compression.waitForCheckout = waitForCheckout;\n\n // We switch over to the new buffer immediately - any further events will be added\n // after the previously buffered ones\n this._used = this._compression;\n\n // Wait for original events to be re-added before resolving\n try {\n await Promise.all(addEventPromises);\n\n // Can now clear fallback buffer as it's no longer necessary\n this._fallback.clear();\n } catch (error) {\n DEBUG_BUILD && logger.exception(error, 'Failed to add events when switching buffers.');\n }\n }\n}\n\n/**\n * Create an event buffer for replays.\n */\nfunction createEventBuffer({\n useCompression,\n workerUrl: customWorkerUrl,\n}) {\n if (\n useCompression &&\n // eslint-disable-next-line no-restricted-globals\n window.Worker\n ) {\n const worker = _loadWorker(customWorkerUrl);\n\n if (worker) {\n return worker;\n }\n }\n\n DEBUG_BUILD && logger.info('Using simple buffer');\n return new EventBufferArray();\n}\n\nfunction _loadWorker(customWorkerUrl) {\n try {\n const workerUrl = customWorkerUrl || _getWorkerUrl();\n\n if (!workerUrl) {\n return;\n }\n\n DEBUG_BUILD && logger.info(`Using compression worker${customWorkerUrl ? ` from ${customWorkerUrl}` : ''}`);\n const worker = new Worker(workerUrl);\n return new EventBufferProxy(worker);\n } catch (error) {\n DEBUG_BUILD && logger.exception(error, 'Failed to create compression worker');\n // Fall back to use simple event buffer array\n }\n}\n\nfunction _getWorkerUrl() {\n if (typeof __SENTRY_EXCLUDE_REPLAY_WORKER__ === 'undefined' || !__SENTRY_EXCLUDE_REPLAY_WORKER__) {\n return e();\n }\n\n return '';\n}\n\n/** If sessionStorage is available. */\nfunction hasSessionStorage() {\n try {\n // This can throw, e.g. when being accessed in a sandboxed iframe\n return 'sessionStorage' in WINDOW && !!WINDOW.sessionStorage;\n } catch {\n return false;\n }\n}\n\n/**\n * Removes the session from Session Storage and unsets session in replay instance\n */\nfunction clearSession(replay) {\n deleteSession();\n replay.session = undefined;\n}\n\n/**\n * Deletes a session from storage\n */\nfunction deleteSession() {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.removeItem(REPLAY_SESSION_KEY);\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n\n/**\n * Given a sample rate, returns true if replay should be sampled.\n *\n * 1.0 = 100% sampling\n * 0.0 = 0% sampling\n */\nfunction isSampled(sampleRate) {\n if (sampleRate === undefined) {\n return false;\n }\n\n // Math.random() returns a number in range of 0 to 1 (inclusive of 0, but not 1)\n return Math.random() < sampleRate;\n}\n\n/**\n * Get a session with defaults & applied sampling.\n */\nfunction makeSession(session) {\n const now = Date.now();\n const id = session.id || uuid4();\n // Note that this means we cannot set a started/lastActivity of `0`, but this should not be relevant outside of tests.\n const started = session.started || now;\n const lastActivity = session.lastActivity || now;\n const segmentId = session.segmentId || 0;\n const sampled = session.sampled;\n const previousSessionId = session.previousSessionId;\n\n return {\n id,\n started,\n lastActivity,\n segmentId,\n sampled,\n previousSessionId,\n };\n}\n\n/**\n * Save a session to session storage.\n */\nfunction saveSession(session) {\n if (!hasSessionStorage()) {\n return;\n }\n\n try {\n WINDOW.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));\n } catch {\n // Ignore potential SecurityError exceptions\n }\n}\n\n/**\n * Get the sampled status for a session based on sample rates & current sampled status.\n */\nfunction getSessionSampleType(sessionSampleRate, allowBuffering) {\n return isSampled(sessionSampleRate) ? 'session' : allowBuffering ? 'buffer' : false;\n}\n\n/**\n * Create a new session, which in its current implementation is a Sentry event\n * that all replays will be saved to as attachments. Currently, we only expect\n * one of these Sentry events per \"replay session\".\n */\nfunction createSession(\n { sessionSampleRate, allowBuffering, stickySession = false },\n { previousSessionId } = {},\n) {\n const sampled = getSessionSampleType(sessionSampleRate, allowBuffering);\n const session = makeSession({\n sampled,\n previousSessionId,\n });\n\n if (stickySession) {\n saveSession(session);\n }\n\n return session;\n}\n\n/**\n * Fetches a session from storage\n */\nfunction fetchSession() {\n if (!hasSessionStorage()) {\n return null;\n }\n\n try {\n // This can throw if cookies are disabled\n const sessionStringFromStorage = WINDOW.sessionStorage.getItem(REPLAY_SESSION_KEY);\n\n if (!sessionStringFromStorage) {\n return null;\n }\n\n const sessionObj = JSON.parse(sessionStringFromStorage) ;\n\n DEBUG_BUILD && logger.infoTick('Loading existing session');\n\n return makeSession(sessionObj);\n } catch {\n return null;\n }\n}\n\n/**\n * Given an initial timestamp and an expiry duration, checks to see if current\n * time should be considered as expired.\n */\nfunction isExpired(\n initialTime,\n expiry,\n targetTime = +new Date(),\n) {\n // Always expired if < 0\n if (initialTime === null || expiry === undefined || expiry < 0) {\n return true;\n }\n\n // Never expires if == 0\n if (expiry === 0) {\n return false;\n }\n\n return initialTime + expiry <= targetTime;\n}\n\n/**\n * Checks to see if session is expired\n */\nfunction isSessionExpired(\n session,\n {\n maxReplayDuration,\n sessionIdleExpire,\n targetTime = Date.now(),\n },\n) {\n return (\n // First, check that maximum session length has not been exceeded\n isExpired(session.started, maxReplayDuration, targetTime) ||\n // check that the idle timeout has not been exceeded (i.e. user has\n // performed an action within the last `sessionIdleExpire` ms)\n isExpired(session.lastActivity, sessionIdleExpire, targetTime)\n );\n}\n\n/** If the session should be refreshed or not. */\nfunction shouldRefreshSession(\n session,\n { sessionIdleExpire, maxReplayDuration },\n) {\n // If not expired, all good, just keep the session\n if (!isSessionExpired(session, { sessionIdleExpire, maxReplayDuration })) {\n return false;\n }\n\n // If we are buffering & haven't ever flushed yet, always continue\n if (session.sampled === 'buffer' && session.segmentId === 0) {\n return false;\n }\n\n return true;\n}\n\n/**\n * Get or create a session, when initializing the replay.\n * Returns a session that may be unsampled.\n */\nfunction loadOrCreateSession(\n {\n sessionIdleExpire,\n maxReplayDuration,\n previousSessionId,\n }\n\n,\n sessionOptions,\n) {\n const existingSession = sessionOptions.stickySession && fetchSession();\n\n // No session exists yet, just create a new one\n if (!existingSession) {\n DEBUG_BUILD && logger.infoTick('Creating new session');\n return createSession(sessionOptions, { previousSessionId });\n }\n\n if (!shouldRefreshSession(existingSession, { sessionIdleExpire, maxReplayDuration })) {\n return existingSession;\n }\n\n DEBUG_BUILD && logger.infoTick('Session in sessionStorage is expired, creating new one...');\n return createSession(sessionOptions, { previousSessionId: existingSession.id });\n}\n\nfunction isCustomEvent(event) {\n return event.type === EventType.Custom;\n}\n\n/**\n * Add an event to the event buffer.\n * In contrast to `addEvent`, this does not return a promise & does not wait for the adding of the event to succeed/fail.\n * Instead this returns `true` if we tried to add the event, else false.\n * It returns `false` e.g. if we are paused, disabled, or out of the max replay duration.\n *\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nfunction addEventSync(replay, event, isCheckout) {\n if (!shouldAddEvent(replay, event)) {\n return false;\n }\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n _addEvent(replay, event, isCheckout);\n\n return true;\n}\n\n/**\n * Add an event to the event buffer.\n * Resolves to `null` if no event was added, else to `void`.\n *\n * `isCheckout` is true if this is either the very first event, or an event triggered by `checkoutEveryNms`.\n */\nfunction addEvent(\n replay,\n event,\n isCheckout,\n) {\n if (!shouldAddEvent(replay, event)) {\n return Promise.resolve(null);\n }\n\n return _addEvent(replay, event, isCheckout);\n}\n\nasync function _addEvent(\n replay,\n event,\n isCheckout,\n) {\n const { eventBuffer } = replay;\n\n if (!eventBuffer || (eventBuffer.waitForCheckout && !isCheckout)) {\n return null;\n }\n\n const isBufferMode = replay.recordingMode === 'buffer';\n\n try {\n if (isCheckout && isBufferMode) {\n eventBuffer.clear();\n }\n\n if (isCheckout) {\n eventBuffer.hasCheckout = true;\n eventBuffer.waitForCheckout = false;\n }\n\n const replayOptions = replay.getOptions();\n\n const eventAfterPossibleCallback = maybeApplyCallback(event, replayOptions.beforeAddRecordingEvent);\n\n if (!eventAfterPossibleCallback) {\n return;\n }\n\n return await eventBuffer.addEvent(eventAfterPossibleCallback);\n } catch (error) {\n const isExceeded = error && error instanceof EventBufferSizeExceededError;\n const reason = isExceeded ? 'addEventSizeExceeded' : 'addEvent';\n\n if (isExceeded && isBufferMode) {\n // Clear buffer and wait for next checkout\n eventBuffer.clear();\n eventBuffer.waitForCheckout = true;\n\n return null;\n }\n\n replay.handleException(error);\n\n await replay.stop({ reason });\n\n const client = getClient();\n\n if (client) {\n client.recordDroppedEvent('internal_sdk_error', 'replay');\n }\n }\n}\n\n/** Exported only for tests. */\nfunction shouldAddEvent(replay, event) {\n if (!replay.eventBuffer || replay.isPaused() || !replay.isEnabled()) {\n return false;\n }\n\n const timestampInMs = timestampToMs(event.timestamp);\n\n // Throw out events that happen more than 5 minutes ago. This can happen if\n // page has been left open and idle for a long period of time and user\n // comes back to trigger a new session. The performance entries rely on\n // `performance.timeOrigin`, which is when the page first opened.\n if (timestampInMs + replay.timeouts.sessionIdlePause < Date.now()) {\n return false;\n }\n\n // Throw out events that are +60min from the initial timestamp\n if (timestampInMs > replay.getContext().initialTimestamp + replay.getOptions().maxReplayDuration) {\n DEBUG_BUILD &&\n logger.infoTick(`Skipping event with timestamp ${timestampInMs} because it is after maxReplayDuration`);\n return false;\n }\n\n return true;\n}\n\nfunction maybeApplyCallback(\n event,\n callback,\n) {\n try {\n if (typeof callback === 'function' && isCustomEvent(event)) {\n return callback(event);\n }\n } catch (error) {\n DEBUG_BUILD &&\n logger.exception(error, 'An error occurred in the `beforeAddRecordingEvent` callback, skipping the event...');\n return null;\n }\n\n return event;\n}\n\n/** If the event is an error event */\nfunction isErrorEvent(event) {\n return !event.type;\n}\n\n/** If the event is a transaction event */\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\n/** If the event is an replay event */\nfunction isReplayEvent(event) {\n return event.type === 'replay_event';\n}\n\n/** If the event is a feedback event */\nfunction isFeedbackEvent(event) {\n return event.type === 'feedback';\n}\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nfunction handleAfterSendEvent(replay) {\n return (event, sendResponse) => {\n if (!replay.isEnabled() || (!isErrorEvent(event) && !isTransactionEvent(event))) {\n return;\n }\n\n const statusCode = sendResponse?.statusCode;\n\n // We only want to do stuff on successful error sending, otherwise you get error replays without errors attached\n // If not using the base transport, we allow `undefined` response (as a custom transport may not implement this correctly yet)\n // If we do use the base transport, we skip if we encountered an non-OK status code\n if (!statusCode || statusCode < 200 || statusCode >= 300) {\n return;\n }\n\n if (isTransactionEvent(event)) {\n handleTransactionEvent(replay, event);\n return;\n }\n\n handleErrorEvent(replay, event);\n };\n}\n\nfunction handleTransactionEvent(replay, event) {\n const replayContext = replay.getContext();\n\n // Collect traceIds in _context regardless of `recordingMode`\n // In error mode, _context gets cleared on every checkout\n // We limit to max. 100 transactions linked\n if (event.contexts?.trace?.trace_id && replayContext.traceIds.size < 100) {\n replayContext.traceIds.add(event.contexts.trace.trace_id);\n }\n}\n\nfunction handleErrorEvent(replay, event) {\n const replayContext = replay.getContext();\n\n // Add error to list of errorIds of replay. This is ok to do even if not\n // sampled because context will get reset at next checkout.\n // XXX: There is also a race condition where it's possible to capture an\n // error to Sentry before Replay SDK has loaded, but response returns after\n // it was loaded, and this gets called.\n // We limit to max. 100 errors linked\n if (event.event_id && replayContext.errorIds.size < 100) {\n replayContext.errorIds.add(event.event_id);\n }\n\n // If error event is tagged with replay id it means it was sampled (when in buffer mode)\n // Need to be very careful that this does not cause an infinite loop\n if (replay.recordingMode !== 'buffer' || !event.tags || !event.tags.replayId) {\n return;\n }\n\n const { beforeErrorSampling } = replay.getOptions();\n if (typeof beforeErrorSampling === 'function' && !beforeErrorSampling(event)) {\n return;\n }\n\n setTimeout$3(async () => {\n try {\n // Capture current event buffer as new replay\n await replay.sendBufferedReplayOrFlush();\n } catch (err) {\n replay.handleException(err);\n }\n });\n}\n\n/**\n * Returns a listener to be added to `client.on('afterSendErrorEvent, listener)`.\n */\nfunction handleBeforeSendEvent(replay) {\n return (event) => {\n if (!replay.isEnabled() || !isErrorEvent(event)) {\n return;\n }\n\n handleHydrationError(replay, event);\n };\n}\n\nfunction handleHydrationError(replay, event) {\n const exceptionValue = event.exception?.values?.[0]?.value;\n if (typeof exceptionValue !== 'string') {\n return;\n }\n\n if (\n // Only matches errors in production builds of react-dom\n // Example https://reactjs.org/docs/error-decoder.html?invariant=423\n // With newer React versions, the messages changed to a different website https://react.dev/errors/418\n exceptionValue.match(\n /(reactjs\\.org\\/docs\\/error-decoder\\.html\\?invariant=|react\\.dev\\/errors\\/)(418|419|422|423|425)/,\n ) ||\n // Development builds of react-dom\n // Error 1: Hydration failed because the initial UI does not match what was rendered on the server.\n // Error 2: Text content does not match server-rendered HTML. Warning: Text content did not match.\n exceptionValue.match(/(does not match server-rendered HTML|Hydration failed because)/i)\n ) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.hydrate-error',\n data: {\n url: getLocationHref(),\n },\n });\n addBreadcrumbEvent(replay, breadcrumb);\n }\n}\n\n/**\n * Handle breadcrumbs that Sentry captures, and make sure to capture relevant breadcrumbs to Replay as well.\n */\nfunction handleBreadcrumbs(replay) {\n const client = getClient();\n\n if (!client) {\n return;\n }\n\n client.on('beforeAddBreadcrumb', breadcrumb => beforeAddBreadcrumb(replay, breadcrumb));\n}\n\nfunction beforeAddBreadcrumb(replay, breadcrumb) {\n if (!replay.isEnabled() || !isBreadcrumbWithCategory(breadcrumb)) {\n return;\n }\n\n const result = normalizeBreadcrumb(breadcrumb);\n if (result) {\n addBreadcrumbEvent(replay, result);\n }\n}\n\n/** Exported only for tests. */\nfunction normalizeBreadcrumb(breadcrumb) {\n if (\n !isBreadcrumbWithCategory(breadcrumb) ||\n [\n // fetch & xhr are handled separately,in handleNetworkBreadcrumbs\n 'fetch',\n 'xhr',\n // These two are breadcrumbs for emitted sentry events, we don't care about them\n 'sentry.event',\n 'sentry.transaction',\n ].includes(breadcrumb.category) ||\n // We capture UI breadcrumbs separately\n breadcrumb.category.startsWith('ui.')\n ) {\n return null;\n }\n\n if (breadcrumb.category === 'console') {\n return normalizeConsoleBreadcrumb(breadcrumb);\n }\n\n return createBreadcrumb(breadcrumb);\n}\n\n/** exported for tests only */\nfunction normalizeConsoleBreadcrumb(\n breadcrumb,\n) {\n const args = breadcrumb.data?.arguments;\n\n if (!Array.isArray(args) || args.length === 0) {\n return createBreadcrumb(breadcrumb);\n }\n\n let isTruncated = false;\n\n // Avoid giant args captures\n const normalizedArgs = args.map(arg => {\n if (!arg) {\n return arg;\n }\n if (typeof arg === 'string') {\n if (arg.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n return `${arg.slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n\n return arg;\n }\n if (typeof arg === 'object') {\n try {\n const normalizedArg = normalize(arg, 7);\n const stringified = JSON.stringify(normalizedArg);\n if (stringified.length > CONSOLE_ARG_MAX_SIZE) {\n isTruncated = true;\n // We use the pretty printed JSON string here as a base\n return `${JSON.stringify(normalizedArg, null, 2).slice(0, CONSOLE_ARG_MAX_SIZE)}…`;\n }\n return normalizedArg;\n } catch {\n // fall back to default\n }\n }\n\n return arg;\n });\n\n return createBreadcrumb({\n ...breadcrumb,\n data: {\n ...breadcrumb.data,\n arguments: normalizedArgs,\n ...(isTruncated ? { _meta: { warnings: ['CONSOLE_ARG_TRUNCATED'] } } : {}),\n },\n });\n}\n\nfunction isBreadcrumbWithCategory(breadcrumb) {\n return !!breadcrumb.category;\n}\n\n/**\n * Returns true if we think the given event is an error originating inside of rrweb.\n */\nfunction isRrwebError(event, hint) {\n if (event.type || !event.exception || !event.exception.values || !event.exception.values.length) {\n return false;\n }\n\n // @ts-expect-error this may be set by rrweb when it finds errors\n if (hint.originalException?.__rrweb__) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Reset the `replay_id` field on the DSC.\n */\nfunction resetReplayIdOnDynamicSamplingContext() {\n // Reset DSC on the current scope, if there is one\n const dsc = getCurrentScope().getPropagationContext().dsc;\n if (dsc) {\n delete dsc.replay_id;\n }\n\n // Clear it from frozen DSC on the active span\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n const dsc = getDynamicSamplingContextFromSpan(activeSpan);\n delete (dsc ).replay_id;\n }\n}\n\n/**\n * Add a feedback breadcrumb event to replay.\n */\nfunction addFeedbackBreadcrumb(replay, event) {\n replay.triggerUserActivity();\n replay.addUpdate(() => {\n if (!event.timestamp) {\n // Ignore events that don't have timestamps (this shouldn't happen, more of a typing issue)\n // Return true here so that we don't flush\n return true;\n }\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: event.timestamp * 1000,\n data: {\n tag: 'breadcrumb',\n payload: {\n timestamp: event.timestamp,\n type: 'default',\n category: 'sentry.feedback',\n data: {\n feedbackId: event.event_id,\n },\n },\n },\n } );\n\n return false;\n });\n}\n\n/**\n * Determine if event should be sampled (only applies in buffer mode).\n * When an event is captured by `handleGlobalEvent`, when in buffer mode\n * we determine if we want to sample the error or not.\n */\nfunction shouldSampleForBufferEvent(replay, event) {\n if (replay.recordingMode !== 'buffer') {\n return false;\n }\n\n // ignore this error because otherwise we could loop indefinitely with\n // trying to capture replay and failing\n if (event.message === UNABLE_TO_SEND_REPLAY) {\n return false;\n }\n\n // Require the event to be an error event & to have an exception\n if (!event.exception || event.type) {\n return false;\n }\n\n return isSampled(replay.getOptions().errorSampleRate);\n}\n\n/**\n * Returns a listener to be added to `addEventProcessor(listener)`.\n */\nfunction handleGlobalEventListener(replay) {\n return Object.assign(\n (event, hint) => {\n // Do nothing if replay has been disabled or paused\n if (!replay.isEnabled() || replay.isPaused()) {\n return event;\n }\n\n if (isReplayEvent(event)) {\n // Replays have separate set of breadcrumbs, do not include breadcrumbs\n // from core SDK\n delete event.breadcrumbs;\n return event;\n }\n\n // We only want to handle errors, transactions, and feedbacks, nothing else\n if (!isErrorEvent(event) && !isTransactionEvent(event) && !isFeedbackEvent(event)) {\n return event;\n }\n\n // Ensure we do not add replay_id if the session is expired\n const isSessionActive = replay.checkAndHandleExpiredSession();\n if (!isSessionActive) {\n // prevent exceeding replay durations by removing the expired replayId from the DSC\n resetReplayIdOnDynamicSamplingContext();\n return event;\n }\n\n if (isFeedbackEvent(event)) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n replay.flush();\n event.contexts.feedback.replay_id = replay.getSessionId();\n // Add a replay breadcrumb for this piece of feedback\n addFeedbackBreadcrumb(replay, event);\n return event;\n }\n\n // Unless `captureExceptions` is enabled, we want to ignore errors coming from rrweb\n // As there can be a bunch of stuff going wrong in internals there, that we don't want to bubble up to users\n if (isRrwebError(event, hint) && !replay.getOptions()._experiments.captureExceptions) {\n DEBUG_BUILD && logger.log('Ignoring error from rrweb internals', event);\n return null;\n }\n\n // When in buffer mode, we decide to sample here.\n // Later, in `handleAfterSendEvent`, if the replayId is set, we know that we sampled\n // And convert the buffer session to a full session\n const isErrorEventSampled = shouldSampleForBufferEvent(replay, event);\n\n // Tag errors if it has been sampled in buffer mode, or if it is session mode\n // Only tag transactions if in session mode\n const shouldTagReplayId = isErrorEventSampled || replay.recordingMode === 'session';\n\n if (shouldTagReplayId) {\n event.tags = { ...event.tags, replayId: replay.getSessionId() };\n }\n\n return event;\n },\n { id: 'Replay' },\n );\n}\n\n/**\n * Create a \"span\" for each performance entry.\n */\nfunction createPerformanceSpans(\n replay,\n entries,\n) {\n return entries.map(({ type, start, end, name, data }) => {\n const response = replay.throttledAddEvent({\n type: EventType.Custom,\n timestamp: start,\n data: {\n tag: 'performanceSpan',\n payload: {\n op: type,\n description: name,\n startTimestamp: start,\n endTimestamp: end,\n data,\n },\n },\n });\n\n // If response is a string, it means its either THROTTLED or SKIPPED\n return typeof response === 'string' ? Promise.resolve(null) : response;\n });\n}\n\nfunction handleHistory(handlerData) {\n const { from, to } = handlerData;\n\n const now = Date.now() / 1000;\n\n return {\n type: 'navigation.push',\n start: now,\n end: now,\n name: to,\n data: {\n previous: from,\n },\n };\n}\n\n/**\n * Returns a listener to be added to `addHistoryInstrumentationHandler(listener)`.\n */\nfunction handleHistorySpanListener(replay) {\n return (handlerData) => {\n if (!replay.isEnabled()) {\n return;\n }\n\n const result = handleHistory(handlerData);\n\n if (result === null) {\n return;\n }\n\n // Need to collect visited URLs\n replay.getContext().urls.push(result.name);\n replay.triggerUserActivity();\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning false to flush\n return false;\n });\n };\n}\n\n/**\n * Check whether a given request URL should be filtered out. This is so we\n * don't log Sentry ingest requests.\n */\nfunction shouldFilterRequest(replay, url) {\n // If we enabled the `traceInternals` experiment, we want to trace everything\n if (DEBUG_BUILD && replay.getOptions()._experiments.traceInternals) {\n return false;\n }\n\n return isSentryRequestUrl(url, getClient());\n}\n\n/** Add a performance entry breadcrumb */\nfunction addNetworkBreadcrumb(\n replay,\n result,\n) {\n if (!replay.isEnabled()) {\n return;\n }\n\n if (result === null) {\n return;\n }\n\n if (shouldFilterRequest(replay, result.name)) {\n return;\n }\n\n replay.addUpdate(() => {\n createPerformanceSpans(replay, [result]);\n // Returning true will cause `addUpdate` to not flush\n // We do not want network requests to cause a flush. This will prevent\n // recurring/polling requests from keeping the replay session alive.\n return true;\n });\n}\n\n/** Get the size of a body. */\nfunction getBodySize(body) {\n if (!body) {\n return undefined;\n }\n\n const textEncoder = new TextEncoder();\n\n try {\n if (typeof body === 'string') {\n return textEncoder.encode(body).length;\n }\n\n if (body instanceof URLSearchParams) {\n return textEncoder.encode(body.toString()).length;\n }\n\n if (body instanceof FormData) {\n const formDataStr = serializeFormData(body);\n return textEncoder.encode(formDataStr).length;\n }\n\n if (body instanceof Blob) {\n return body.size;\n }\n\n if (body instanceof ArrayBuffer) {\n return body.byteLength;\n }\n\n // Currently unhandled types: ArrayBufferView, ReadableStream\n } catch {\n // just return undefined\n }\n\n return undefined;\n}\n\n/** Convert a Content-Length header to number/undefined. */\nfunction parseContentLengthHeader(header) {\n if (!header) {\n return undefined;\n }\n\n const size = parseInt(header, 10);\n return isNaN(size) ? undefined : size;\n}\n\n/** Merge a warning into an existing network request/response. */\nfunction mergeWarning(\n info,\n warning,\n) {\n if (!info) {\n return {\n headers: {},\n size: undefined,\n _meta: {\n warnings: [warning],\n },\n };\n }\n\n const newMeta = { ...info._meta };\n const existingWarnings = newMeta.warnings || [];\n newMeta.warnings = [...existingWarnings, warning];\n\n info._meta = newMeta;\n return info;\n}\n\n/** Convert ReplayNetworkRequestData to a PerformanceEntry. */\nfunction makeNetworkReplayBreadcrumb(\n type,\n data,\n) {\n if (!data) {\n return null;\n }\n\n const { startTimestamp, endTimestamp, url, method, statusCode, request, response } = data;\n\n const result = {\n type,\n start: startTimestamp / 1000,\n end: endTimestamp / 1000,\n name: url,\n data: dropUndefinedKeys({\n method,\n statusCode,\n request,\n response,\n }),\n };\n\n return result;\n}\n\n/** Build the request or response part of a replay network breadcrumb that was skipped. */\nfunction buildSkippedNetworkRequestOrResponse(bodySize) {\n return {\n headers: {},\n size: bodySize,\n _meta: {\n warnings: ['URL_SKIPPED'],\n },\n };\n}\n\n/** Build the request or response part of a replay network breadcrumb. */\nfunction buildNetworkRequestOrResponse(\n headers,\n bodySize,\n body,\n) {\n if (!bodySize && Object.keys(headers).length === 0) {\n return undefined;\n }\n\n if (!bodySize) {\n return {\n headers,\n };\n }\n\n if (!body) {\n return {\n headers,\n size: bodySize,\n };\n }\n\n const info = {\n headers,\n size: bodySize,\n };\n\n const { body: normalizedBody, warnings } = normalizeNetworkBody(body);\n info.body = normalizedBody;\n if (warnings?.length) {\n info._meta = {\n warnings,\n };\n }\n\n return info;\n}\n\n/** Filter a set of headers */\nfunction getAllowedHeaders(headers, allowedHeaders) {\n return Object.entries(headers).reduce((filteredHeaders, [key, value]) => {\n const normalizedKey = key.toLowerCase();\n // Avoid putting empty strings into the headers\n if (allowedHeaders.includes(normalizedKey) && headers[key]) {\n filteredHeaders[normalizedKey] = value;\n }\n return filteredHeaders;\n }, {});\n}\n\nfunction normalizeNetworkBody(body)\n\n {\n if (!body || typeof body !== 'string') {\n return {\n body,\n };\n }\n\n const exceedsSizeLimit = body.length > NETWORK_BODY_MAX_SIZE;\n const isProbablyJson = _strIsProbablyJson(body);\n\n if (exceedsSizeLimit) {\n const truncatedBody = body.slice(0, NETWORK_BODY_MAX_SIZE);\n\n if (isProbablyJson) {\n return {\n body: truncatedBody,\n warnings: ['MAYBE_JSON_TRUNCATED'],\n };\n }\n\n return {\n body: `${truncatedBody}…`,\n warnings: ['TEXT_TRUNCATED'],\n };\n }\n\n if (isProbablyJson) {\n try {\n const jsonBody = JSON.parse(body);\n return {\n body: jsonBody,\n };\n } catch {\n // fall back to just send the body as string\n }\n }\n\n return {\n body,\n };\n}\n\nfunction _strIsProbablyJson(str) {\n const first = str[0];\n const last = str[str.length - 1];\n\n // Simple check: If this does not start & end with {} or [], it's not JSON\n return (first === '[' && last === ']') || (first === '{' && last === '}');\n}\n\n/** Match an URL against a list of strings/Regex. */\nfunction urlMatches(url, urls) {\n const fullUrl = getFullUrl(url);\n\n return stringMatchesSomePattern(fullUrl, urls);\n}\n\n/** exported for tests */\nfunction getFullUrl(url, baseURI = WINDOW.document.baseURI) {\n // Short circuit for common cases:\n if (url.startsWith('http://') || url.startsWith('https://') || url.startsWith(WINDOW.location.origin)) {\n return url;\n }\n const fixedUrl = new URL(url, baseURI);\n\n // If these do not match, we are not dealing with a relative URL, so just return it\n if (fixedUrl.origin !== new URL(baseURI).origin) {\n return url;\n }\n\n const fullUrl = fixedUrl.href;\n\n // Remove trailing slashes, if they don't match the original URL\n if (!url.endsWith('/') && fullUrl.endsWith('/')) {\n return fullUrl.slice(0, -1);\n }\n\n return fullUrl;\n}\n\n/**\n * Capture a fetch breadcrumb to a replay.\n * This adds additional data (where appropriate).\n */\nasync function captureFetchBreadcrumbToReplay(\n breadcrumb,\n hint,\n options\n\n,\n) {\n try {\n const data = await _prepareFetchData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.fetch', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && logger.exception(error, 'Failed to capture fetch breadcrumb');\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nfunction enrichFetchBreadcrumb(\n breadcrumb,\n hint,\n) {\n const { input, response } = hint;\n\n const body = input ? getFetchRequestArgBody(input) : undefined;\n const reqSize = getBodySize(body);\n\n const resSize = response ? parseContentLengthHeader(response.headers.get('content-length')) : undefined;\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nasync function _prepareFetchData(\n breadcrumb,\n hint,\n options,\n) {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n const captureDetails =\n urlMatches(url, options.networkDetailAllowUrls) && !urlMatches(url, options.networkDetailDenyUrls);\n\n const request = captureDetails\n ? _getRequestInfo(options, hint.input, requestBodySize)\n : buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = await _getResponseInfo(captureDetails, options, hint.response, responseBodySize);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n}\n\nfunction _getRequestInfo(\n { networkCaptureBodies, networkRequestHeaders },\n input,\n requestBodySize,\n) {\n const headers = input ? getRequestHeaders(input, networkRequestHeaders) : {};\n\n if (!networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, requestBodySize, undefined);\n }\n\n // We only want to transmit string or string-like bodies\n const requestBody = getFetchRequestArgBody(input);\n const [bodyStr, warning] = getBodyString(requestBody, logger);\n const data = buildNetworkRequestOrResponse(headers, requestBodySize, bodyStr);\n\n if (warning) {\n return mergeWarning(data, warning);\n }\n\n return data;\n}\n\n/** Exported only for tests. */\nasync function _getResponseInfo(\n captureDetails,\n {\n networkCaptureBodies,\n networkResponseHeaders,\n },\n response,\n responseBodySize,\n) {\n if (!captureDetails && responseBodySize !== undefined) {\n return buildSkippedNetworkRequestOrResponse(responseBodySize);\n }\n\n const headers = response ? getAllHeaders(response.headers, networkResponseHeaders) : {};\n\n if (!response || (!networkCaptureBodies && responseBodySize !== undefined)) {\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n\n const [bodyText, warning] = await _parseFetchResponseBody(response);\n const result = getResponseData(bodyText, {\n networkCaptureBodies,\n\n responseBodySize,\n captureDetails,\n headers,\n });\n\n if (warning) {\n return mergeWarning(result, warning);\n }\n\n return result;\n}\n\nfunction getResponseData(\n bodyText,\n {\n networkCaptureBodies,\n responseBodySize,\n captureDetails,\n headers,\n }\n\n,\n) {\n try {\n const size = bodyText?.length && responseBodySize === undefined ? getBodySize(bodyText) : responseBodySize;\n\n if (!captureDetails) {\n return buildSkippedNetworkRequestOrResponse(size);\n }\n\n if (networkCaptureBodies) {\n return buildNetworkRequestOrResponse(headers, size, bodyText);\n }\n\n return buildNetworkRequestOrResponse(headers, size, undefined);\n } catch (error) {\n DEBUG_BUILD && logger.exception(error, 'Failed to serialize response body');\n // fallback\n return buildNetworkRequestOrResponse(headers, responseBodySize, undefined);\n }\n}\n\nasync function _parseFetchResponseBody(response) {\n const res = _tryCloneResponse(response);\n\n if (!res) {\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n try {\n const text = await _tryGetResponseText(res);\n return [text];\n } catch (error) {\n if (error instanceof Error && error.message.indexOf('Timeout') > -1) {\n DEBUG_BUILD && logger.warn('Parsing text body from response timed out');\n return [undefined, 'BODY_PARSE_TIMEOUT'];\n }\n\n DEBUG_BUILD && logger.exception(error, 'Failed to get text body from response');\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n}\n\nfunction getAllHeaders(headers, allowedHeaders) {\n const allHeaders = {};\n\n allowedHeaders.forEach(header => {\n if (headers.get(header)) {\n allHeaders[header] = headers.get(header) ;\n }\n });\n\n return allHeaders;\n}\n\nfunction getRequestHeaders(fetchArgs, allowedHeaders) {\n if (fetchArgs.length === 1 && typeof fetchArgs[0] !== 'string') {\n return getHeadersFromOptions(fetchArgs[0] , allowedHeaders);\n }\n\n if (fetchArgs.length === 2) {\n return getHeadersFromOptions(fetchArgs[1] , allowedHeaders);\n }\n\n return {};\n}\n\nfunction getHeadersFromOptions(\n input,\n allowedHeaders,\n) {\n if (!input) {\n return {};\n }\n\n const headers = input.headers;\n\n if (!headers) {\n return {};\n }\n\n if (headers instanceof Headers) {\n return getAllHeaders(headers, allowedHeaders);\n }\n\n // We do not support this, as it is not really documented (anymore?)\n if (Array.isArray(headers)) {\n return {};\n }\n\n return getAllowedHeaders(headers, allowedHeaders);\n}\n\nfunction _tryCloneResponse(response) {\n try {\n // We have to clone this, as the body can only be read once\n return response.clone();\n } catch (error) {\n // this can throw if the response was already consumed before\n DEBUG_BUILD && logger.exception(error, 'Failed to clone response body');\n }\n}\n\n/**\n * Get the response body of a fetch request, or timeout after 500ms.\n * Fetch can return a streaming body, that may not resolve (or not for a long time).\n * If that happens, we rather abort after a short time than keep waiting for this.\n */\nfunction _tryGetResponseText(response) {\n return new Promise((resolve, reject) => {\n const timeout = setTimeout$3(() => reject(new Error('Timeout while trying to read response body')), 500);\n\n _getResponseText(response)\n .then(\n txt => resolve(txt),\n reason => reject(reason),\n )\n .finally(() => clearTimeout(timeout));\n });\n}\n\nasync function _getResponseText(response) {\n // Force this to be a promise, just to be safe\n // eslint-disable-next-line no-return-await\n return await response.text();\n}\n\n/**\n * Capture an XHR breadcrumb to a replay.\n * This adds additional data (where appropriate).\n */\nasync function captureXhrBreadcrumbToReplay(\n breadcrumb,\n hint,\n options,\n) {\n try {\n const data = _prepareXhrData(breadcrumb, hint, options);\n\n // Create a replay performance entry from this breadcrumb\n const result = makeNetworkReplayBreadcrumb('resource.xhr', data);\n addNetworkBreadcrumb(options.replay, result);\n } catch (error) {\n DEBUG_BUILD && logger.exception(error, 'Failed to capture xhr breadcrumb');\n }\n}\n\n/**\n * Enrich a breadcrumb with additional data.\n * This has to be sync & mutate the given breadcrumb,\n * as the breadcrumb is afterwards consumed by other handlers.\n */\nfunction enrichXhrBreadcrumb(\n breadcrumb,\n hint,\n) {\n const { xhr, input } = hint;\n\n if (!xhr) {\n return;\n }\n\n const reqSize = getBodySize(input);\n const resSize = xhr.getResponseHeader('content-length')\n ? parseContentLengthHeader(xhr.getResponseHeader('content-length'))\n : _getBodySize(xhr.response, xhr.responseType);\n\n if (reqSize !== undefined) {\n breadcrumb.data.request_body_size = reqSize;\n }\n if (resSize !== undefined) {\n breadcrumb.data.response_body_size = resSize;\n }\n}\n\nfunction _prepareXhrData(\n breadcrumb,\n hint,\n options,\n) {\n const now = Date.now();\n const { startTimestamp = now, endTimestamp = now, input, xhr } = hint;\n\n const {\n url,\n method,\n status_code: statusCode = 0,\n request_body_size: requestBodySize,\n response_body_size: responseBodySize,\n } = breadcrumb.data;\n\n if (!url) {\n return null;\n }\n\n if (!xhr || !urlMatches(url, options.networkDetailAllowUrls) || urlMatches(url, options.networkDetailDenyUrls)) {\n const request = buildSkippedNetworkRequestOrResponse(requestBodySize);\n const response = buildSkippedNetworkRequestOrResponse(responseBodySize);\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request,\n response,\n };\n }\n\n const xhrInfo = xhr[SENTRY_XHR_DATA_KEY];\n const networkRequestHeaders = xhrInfo\n ? getAllowedHeaders(xhrInfo.request_headers, options.networkRequestHeaders)\n : {};\n const networkResponseHeaders = getAllowedHeaders(getResponseHeaders(xhr), options.networkResponseHeaders);\n\n const [requestBody, requestWarning] = options.networkCaptureBodies ? getBodyString(input, logger) : [undefined];\n const [responseBody, responseWarning] = options.networkCaptureBodies ? _getXhrResponseBody(xhr) : [undefined];\n\n const request = buildNetworkRequestOrResponse(networkRequestHeaders, requestBodySize, requestBody);\n const response = buildNetworkRequestOrResponse(networkResponseHeaders, responseBodySize, responseBody);\n\n return {\n startTimestamp,\n endTimestamp,\n url,\n method,\n statusCode,\n request: requestWarning ? mergeWarning(request, requestWarning) : request,\n response: responseWarning ? mergeWarning(response, responseWarning) : response,\n };\n}\n\nfunction getResponseHeaders(xhr) {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc, line) => {\n const [key, value] = line.split(': ') ;\n if (value) {\n acc[key.toLowerCase()] = value;\n }\n return acc;\n }, {});\n}\n\nfunction _getXhrResponseBody(xhr) {\n // We collect errors that happen, but only log them if we can't get any response body\n const errors = [];\n\n try {\n return [xhr.responseText];\n } catch (e) {\n errors.push(e);\n }\n\n // Try to manually parse the response body, if responseText fails\n try {\n return _parseXhrResponse(xhr.response, xhr.responseType);\n } catch (e) {\n errors.push(e);\n }\n\n DEBUG_BUILD && logger.warn('Failed to get xhr response body', ...errors);\n\n return [undefined];\n}\n\n/**\n * Get the string representation of the XHR response.\n * Based on MDN, these are the possible types of the response:\n * string\n * ArrayBuffer\n * Blob\n * Document\n * POJO\n *\n * Exported only for tests.\n */\nfunction _parseXhrResponse(\n body,\n responseType,\n) {\n try {\n if (typeof body === 'string') {\n return [body];\n }\n\n if (body instanceof Document) {\n return [body.body.outerHTML];\n }\n\n if (responseType === 'json' && body && typeof body === 'object') {\n return [JSON.stringify(body)];\n }\n\n if (!body) {\n return [undefined];\n }\n } catch (error) {\n DEBUG_BUILD && logger.exception(error, 'Failed to serialize body', body);\n return [undefined, 'BODY_PARSE_ERROR'];\n }\n\n DEBUG_BUILD && logger.info('Skipping network body because of body type', body);\n\n return [undefined, 'UNPARSEABLE_BODY_TYPE'];\n}\n\nfunction _getBodySize(\n body,\n responseType,\n) {\n try {\n const bodyStr = responseType === 'json' && body && typeof body === 'object' ? JSON.stringify(body) : body;\n return getBodySize(bodyStr);\n } catch {\n return undefined;\n }\n}\n\n/**\n * This method does two things:\n * - It enriches the regular XHR/fetch breadcrumbs with request/response size data\n * - It captures the XHR/fetch breadcrumbs to the replay\n * (enriching it with further data that is _not_ added to the regular breadcrumbs)\n */\nfunction handleNetworkBreadcrumbs(replay) {\n const client = getClient();\n\n try {\n const {\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n } = replay.getOptions();\n\n const options = {\n replay,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders,\n networkResponseHeaders,\n };\n\n if (client) {\n client.on('beforeAddBreadcrumb', (breadcrumb, hint) => beforeAddNetworkBreadcrumb(options, breadcrumb, hint));\n }\n } catch {\n // Do nothing\n }\n}\n\n/** just exported for tests */\nfunction beforeAddNetworkBreadcrumb(\n options,\n breadcrumb,\n hint,\n) {\n if (!breadcrumb.data) {\n return;\n }\n\n try {\n if (_isXhrBreadcrumb(breadcrumb) && _isXhrHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichXhrBreadcrumb(breadcrumb, hint);\n\n // This call should not reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n captureXhrBreadcrumbToReplay(breadcrumb, hint, options);\n }\n\n if (_isFetchBreadcrumb(breadcrumb) && _isFetchHint(hint)) {\n // This has to be sync, as we need to ensure the breadcrumb is enriched in the same tick\n // Because the hook runs synchronously, and the breadcrumb is afterwards passed on\n // So any async mutations to it will not be reflected in the final breadcrumb\n enrichFetchBreadcrumb(breadcrumb, hint);\n\n // This call should not reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n captureFetchBreadcrumbToReplay(breadcrumb, hint, options);\n }\n } catch (e) {\n DEBUG_BUILD && logger.exception(e, 'Error when enriching network breadcrumb');\n }\n}\n\nfunction _isXhrBreadcrumb(breadcrumb) {\n return breadcrumb.category === 'xhr';\n}\n\nfunction _isFetchBreadcrumb(breadcrumb) {\n return breadcrumb.category === 'fetch';\n}\n\nfunction _isXhrHint(hint) {\n return hint?.xhr;\n}\n\nfunction _isFetchHint(hint) {\n return hint?.response;\n}\n\n/**\n * Add global listeners that cannot be removed.\n */\nfunction addGlobalListeners(\n replay,\n { autoFlushOnFeedback },\n) {\n // Listeners from core SDK //\n const client = getClient();\n\n addClickKeypressInstrumentationHandler(handleDomListener(replay));\n addHistoryInstrumentationHandler(handleHistorySpanListener(replay));\n handleBreadcrumbs(replay);\n handleNetworkBreadcrumbs(replay);\n\n // Tag all (non replay) events that get sent to Sentry with the current\n // replay ID so that we can reference them later in the UI\n const eventProcessor = handleGlobalEventListener(replay);\n addEventProcessor(eventProcessor);\n\n // If a custom client has no hooks yet, we continue to use the \"old\" implementation\n if (client) {\n client.on('beforeSendEvent', handleBeforeSendEvent(replay));\n client.on('afterSendEvent', handleAfterSendEvent(replay));\n client.on('createDsc', (dsc) => {\n const replayId = replay.getSessionId();\n // We do not want to set the DSC when in buffer mode, as that means the replay has not been sent (yet)\n if (replayId && replay.isEnabled() && replay.recordingMode === 'session') {\n // Ensure to check that the session is still active - it could have expired in the meanwhile\n const isSessionActive = replay.checkAndHandleExpiredSession();\n if (isSessionActive) {\n dsc.replay_id = replayId;\n }\n }\n });\n\n client.on('spanStart', span => {\n replay.lastActiveSpan = span;\n });\n\n // We may be missing the initial spanStart due to timing issues,\n // so we capture it on finish again.\n client.on('spanEnd', span => {\n replay.lastActiveSpan = span;\n });\n\n // We want to attach the replay id to the feedback event\n client.on('beforeSendFeedback', async (feedbackEvent, options) => {\n const replayId = replay.getSessionId();\n if (options?.includeReplay && replay.isEnabled() && replayId && feedbackEvent.contexts?.feedback) {\n // In case the feedback is sent via API and not through our widget, we want to flush replay\n if (feedbackEvent.contexts.feedback.source === 'api' && autoFlushOnFeedback) {\n await replay.flush();\n }\n feedbackEvent.contexts.feedback.replay_id = replayId;\n }\n });\n\n if (autoFlushOnFeedback) {\n client.on('openFeedbackWidget', async () => {\n await replay.flush();\n });\n }\n }\n}\n\n/**\n * Create a \"span\" for the total amount of memory being used by JS objects\n * (including v8 internal objects).\n */\nasync function addMemoryEntry(replay) {\n // window.performance.memory is a non-standard API and doesn't work on all browsers, so we try-catch this\n try {\n return Promise.all(\n createPerformanceSpans(replay, [\n // @ts-expect-error memory doesn't exist on type Performance as the API is non-standard (we check that it exists above)\n createMemoryEntry(WINDOW.performance.memory),\n ]),\n );\n } catch (error) {\n // Do nothing\n return [];\n }\n}\n\nfunction createMemoryEntry(memoryEntry) {\n const { jsHeapSizeLimit, totalJSHeapSize, usedJSHeapSize } = memoryEntry;\n // we don't want to use `getAbsoluteTime` because it adds the event time to the\n // time origin, so we get the current timestamp instead\n const time = Date.now() / 1000;\n return {\n type: 'memory',\n name: 'memory',\n start: time,\n end: time,\n data: {\n memory: {\n jsHeapSizeLimit,\n totalJSHeapSize,\n usedJSHeapSize,\n },\n },\n };\n}\n\n/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n * debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n * was already invoked in the meantime, return @param func's return value.\n * The debounced function has two additional properties:\n * - `flush`: Invokes the debounced function immediately and returns its return value\n * - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nfunction debounce(func, wait, options) {\n let callbackReturnValue;\n\n let timerId;\n let maxTimerId;\n\n const maxWait = options?.maxWait ? Math.max(options.maxWait, wait) : 0;\n\n function invokeFunc() {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers() {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush() {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced() {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeout$3(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeout$3(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\n\nconst NAVIGATOR = GLOBAL_OBJ.navigator;\n\n/**\n * Disable sampling mousemove events on iOS browsers as this can cause blocking the main thread\n * https://github.com/getsentry/sentry-javascript/issues/14534\n */\nfunction getRecordingSamplingOptions() {\n if (\n /iPhone|iPad|iPod/i.test(NAVIGATOR?.userAgent ?? '') ||\n (/Macintosh/i.test(NAVIGATOR?.userAgent ?? '') && NAVIGATOR?.maxTouchPoints && NAVIGATOR?.maxTouchPoints > 1)\n ) {\n return {\n sampling: {\n mousemove: false,\n },\n };\n }\n\n return {};\n}\n\n/**\n * Handler for recording events.\n *\n * Adds to event buffer, and has varying flushing behaviors if the event was a checkout.\n */\nfunction getHandleRecordingEmit(replay) {\n let hadFirstEvent = false;\n\n return (event, _isCheckout) => {\n // If this is false, it means session is expired, create and a new session and wait for checkout\n if (!replay.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && logger.warn('Received replay event after session expired.');\n\n return;\n }\n\n // `_isCheckout` is only set when the checkout is due to `checkoutEveryNms`\n // We also want to treat the first event as a checkout, so we handle this specifically here\n const isCheckout = _isCheckout || !hadFirstEvent;\n hadFirstEvent = true;\n\n if (replay.clickDetector) {\n updateClickDetectorForRecordingEvent(replay.clickDetector, event);\n }\n\n // The handler returns `true` if we do not want to trigger debounced flush, `false` if we want to debounce flush.\n replay.addUpdate(() => {\n // The session is always started immediately on pageload/init, but for\n // error-only replays, it should reflect the most recent checkout\n // when an error occurs. Clear any state that happens before this current\n // checkout. This needs to happen before `addEvent()` which updates state\n // dependent on this reset.\n if (replay.recordingMode === 'buffer' && isCheckout) {\n replay.setInitialState();\n }\n\n // If the event is not added (e.g. due to being paused, disabled, or out of the max replay duration),\n // Skip all further steps\n if (!addEventSync(replay, event, isCheckout)) {\n // Return true to skip scheduling a debounced flush\n return true;\n }\n\n // Different behavior for full snapshots (type=2), ignore other event types\n // See https://github.com/rrweb-io/rrweb/blob/d8f9290ca496712aa1e7d472549480c4e7876594/packages/rrweb/src/types.ts#L16\n if (!isCheckout) {\n return false;\n }\n\n const session = replay.session;\n\n // Additionally, create a meta event that will capture certain SDK settings.\n // In order to handle buffer mode, this needs to either be done when we\n // receive checkout events or at flush time. We have an experimental mode\n // to perform multiple checkouts a session (the idea is to improve\n // seeking during playback), so also only include if segmentId is 0\n // (handled in `addSettingsEvent`).\n //\n // `isCheckout` is always true, but want to be explicit that it should\n // only be added for checkouts\n addSettingsEvent(replay, isCheckout);\n\n // When in buffer mode, make sure we adjust the session started date to the current earliest event of the buffer\n // this should usually be the timestamp of the checkout event, but to be safe...\n if (replay.recordingMode === 'buffer' && session && replay.eventBuffer) {\n const earliestEvent = replay.eventBuffer.getEarliestTimestamp();\n if (earliestEvent) {\n DEBUG_BUILD &&\n logger.info(`Updating session start time to earliest event in buffer to ${new Date(earliestEvent)}`);\n\n session.started = earliestEvent;\n\n if (replay.getOptions().stickySession) {\n saveSession(session);\n }\n }\n }\n\n // If there is a previousSessionId after a full snapshot occurs, then\n // the replay session was started due to session expiration. The new session\n // is started before triggering a new checkout and contains the id\n // of the previous session. Do not immediately flush in this case\n // to avoid capturing only the checkout and instead the replay will\n // be captured if they perform any follow-up actions.\n if (session?.previousSessionId) {\n return true;\n }\n\n if (replay.recordingMode === 'session') {\n // If the full snapshot is due to an initial load, we will not have\n // a previous session ID. In this case, we want to buffer events\n // for a set amount of time before flushing. This can help avoid\n // capturing replays of users that immediately close the window.\n\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n void replay.flush();\n }\n\n return true;\n });\n };\n}\n\n/**\n * Exported for tests\n */\nfunction createOptionsEvent(replay) {\n const options = replay.getOptions();\n return {\n type: EventType.Custom,\n timestamp: Date.now(),\n data: {\n tag: 'options',\n payload: {\n shouldRecordCanvas: replay.isRecordingCanvas(),\n sessionSampleRate: options.sessionSampleRate,\n errorSampleRate: options.errorSampleRate,\n useCompressionOption: options.useCompression,\n blockAllMedia: options.blockAllMedia,\n maskAllText: options.maskAllText,\n maskAllInputs: options.maskAllInputs,\n useCompression: replay.eventBuffer ? replay.eventBuffer.type === 'worker' : false,\n networkDetailHasUrls: options.networkDetailAllowUrls.length > 0,\n networkCaptureBodies: options.networkCaptureBodies,\n networkRequestHasHeaders: options.networkRequestHeaders.length > 0,\n networkResponseHasHeaders: options.networkResponseHeaders.length > 0,\n },\n },\n };\n}\n\n/**\n * Add a \"meta\" event that contains a simplified view on current configuration\n * options. This should only be included on the first segment of a recording.\n */\nfunction addSettingsEvent(replay, isCheckout) {\n // Only need to add this event when sending the first segment\n if (!isCheckout || !replay.session || replay.session.segmentId !== 0) {\n return;\n }\n\n addEventSync(replay, createOptionsEvent(replay), false);\n}\n\n/**\n * Create a replay envelope ready to be sent.\n * This includes both the replay event, as well as the recording data.\n */\nfunction createReplayEnvelope(\n replayEvent,\n recordingData,\n dsn,\n tunnel,\n) {\n return createEnvelope(\n createEventEnvelopeHeaders(replayEvent, getSdkMetadataForEnvelopeHeader(replayEvent), tunnel, dsn),\n [\n [{ type: 'replay_event' }, replayEvent],\n [\n {\n type: 'replay_recording',\n // If string then we need to encode to UTF8, otherwise will have\n // wrong size. TextEncoder has similar browser support to\n // MutationObserver, although it does not accept IE11.\n length:\n typeof recordingData === 'string' ? new TextEncoder().encode(recordingData).length : recordingData.length,\n },\n recordingData,\n ],\n ],\n );\n}\n\n/**\n * Prepare the recording data ready to be sent.\n */\nfunction prepareRecordingData({\n recordingData,\n headers,\n}\n\n) {\n let payloadWithSequence;\n\n // XXX: newline is needed to separate sequence id from events\n const replayHeaders = `${JSON.stringify(headers)}\n`;\n\n if (typeof recordingData === 'string') {\n payloadWithSequence = `${replayHeaders}${recordingData}`;\n } else {\n const enc = new TextEncoder();\n // XXX: newline is needed to separate sequence id from events\n const sequence = enc.encode(replayHeaders);\n // Merge the two Uint8Arrays\n payloadWithSequence = new Uint8Array(sequence.length + recordingData.length);\n payloadWithSequence.set(sequence);\n payloadWithSequence.set(recordingData, sequence.length);\n }\n\n return payloadWithSequence;\n}\n\n/**\n * Prepare a replay event & enrich it with the SDK metadata.\n */\nasync function prepareReplayEvent({\n client,\n scope,\n replayId: event_id,\n event,\n}\n\n) {\n const integrations =\n typeof client['_integrations'] === 'object' &&\n client['_integrations'] !== null &&\n !Array.isArray(client['_integrations'])\n ? Object.keys(client['_integrations'])\n : undefined;\n\n const eventHint = { event_id, integrations };\n\n client.emit('preprocessEvent', event, eventHint);\n\n const preparedEvent = (await prepareEvent(\n client.getOptions(),\n event,\n eventHint,\n scope,\n client,\n getIsolationScope(),\n )) ;\n\n // If e.g. a global event processor returned null\n if (!preparedEvent) {\n return null;\n }\n\n client.emit('postprocessEvent', preparedEvent, eventHint);\n\n // This normally happens in browser client \"_prepareEvent\"\n // but since we do not use this private method from the client, but rather the plain import\n // we need to do this manually.\n preparedEvent.platform = preparedEvent.platform || 'javascript';\n\n // extract the SDK name because `client._prepareEvent` doesn't add it to the event\n const metadata = client.getSdkMetadata();\n const { name, version } = metadata?.sdk || {};\n\n preparedEvent.sdk = {\n ...preparedEvent.sdk,\n name: name || 'sentry.javascript.unknown',\n version: version || '0.0.0',\n };\n\n return preparedEvent;\n}\n\n/**\n * Send replay attachment using `fetch()`\n */\nasync function sendReplayRequest({\n recordingData,\n replayId,\n segmentId: segment_id,\n eventContext,\n timestamp,\n session,\n}) {\n const preparedRecordingData = prepareRecordingData({\n recordingData,\n headers: {\n segment_id,\n },\n });\n\n const { urls, errorIds, traceIds, initialTimestamp } = eventContext;\n\n const client = getClient();\n const scope = getCurrentScope();\n const transport = client?.getTransport();\n const dsn = client?.getDsn();\n\n if (!client || !transport || !dsn || !session.sampled) {\n return resolvedSyncPromise({});\n }\n\n const baseEvent = {\n type: REPLAY_EVENT_NAME,\n replay_start_timestamp: initialTimestamp / 1000,\n timestamp: timestamp / 1000,\n error_ids: errorIds,\n trace_ids: traceIds,\n urls,\n replay_id: replayId,\n segment_id,\n replay_type: session.sampled,\n };\n\n const replayEvent = await prepareReplayEvent({ scope, client, replayId, event: baseEvent });\n\n if (!replayEvent) {\n // Taken from baseclient's `_processEvent` method, where this is handled for errors/transactions\n client.recordDroppedEvent('event_processor', 'replay');\n DEBUG_BUILD && logger.info('An event processor returned `null`, will not send event.');\n return resolvedSyncPromise({});\n }\n\n /*\n For reference, the fully built event looks something like this:\n {\n \"type\": \"replay_event\",\n \"timestamp\": 1670837008.634,\n \"error_ids\": [\n \"errorId\"\n ],\n \"trace_ids\": [\n \"traceId\"\n ],\n \"urls\": [\n \"https://example.com\"\n ],\n \"replay_id\": \"eventId\",\n \"segment_id\": 3,\n \"replay_type\": \"error\",\n \"platform\": \"javascript\",\n \"event_id\": \"eventId\",\n \"environment\": \"production\",\n \"sdk\": {\n \"integrations\": [\n \"BrowserTracing\",\n \"Replay\"\n ],\n \"name\": \"sentry.javascript.browser\",\n \"version\": \"7.25.0\"\n },\n \"sdkProcessingMetadata\": {},\n \"contexts\": {\n },\n }\n */\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete replayEvent.sdkProcessingMetadata;\n\n const envelope = createReplayEnvelope(replayEvent, preparedRecordingData, dsn, client.getOptions().tunnel);\n\n let response;\n\n try {\n response = await transport.send(envelope);\n } catch (err) {\n const error = new Error(UNABLE_TO_SEND_REPLAY);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n throw error;\n }\n\n // If the status code is invalid, we want to immediately stop & not retry\n if (typeof response.statusCode === 'number' && (response.statusCode < 200 || response.statusCode >= 300)) {\n throw new TransportStatusCodeError(response.statusCode);\n }\n\n const rateLimits = updateRateLimits({}, response);\n if (isRateLimited(rateLimits, 'replay')) {\n throw new RateLimitError(rateLimits);\n }\n\n return response;\n}\n\n/**\n * This error indicates that the transport returned an invalid status code.\n */\nclass TransportStatusCodeError extends Error {\n constructor(statusCode) {\n super(`Transport returned status code ${statusCode}`);\n }\n}\n\n/**\n * This error indicates that we hit a rate limit API error.\n */\nclass RateLimitError extends Error {\n\n constructor(rateLimits) {\n super('Rate limit hit');\n this.rateLimits = rateLimits;\n }\n}\n\n/**\n * Finalize and send the current replay event to Sentry\n */\nasync function sendReplay(\n replayData,\n retryConfig = {\n count: 0,\n interval: RETRY_BASE_INTERVAL,\n },\n) {\n const { recordingData, onError } = replayData;\n\n // short circuit if there's no events to upload (this shouldn't happen as _runFlush makes this check)\n if (!recordingData.length) {\n return;\n }\n\n try {\n await sendReplayRequest(replayData);\n return true;\n } catch (err) {\n if (err instanceof TransportStatusCodeError || err instanceof RateLimitError) {\n throw err;\n }\n\n // Capture error for every failed replay\n setContext('Replays', {\n _retryCount: retryConfig.count,\n });\n\n if (onError) {\n onError(err);\n }\n\n // If an error happened here, it's likely that uploading the attachment\n // failed, we'll can retry with the same events payload\n if (retryConfig.count >= RETRY_MAX_COUNT) {\n const error = new Error(`${UNABLE_TO_SEND_REPLAY} - max retries exceeded`);\n\n try {\n // In case browsers don't allow this property to be writable\n // @ts-expect-error This needs lib es2022 and newer\n error.cause = err;\n } catch {\n // nothing to do\n }\n\n throw error;\n }\n\n // will retry in intervals of 5, 10, 30\n retryConfig.interval *= ++retryConfig.count;\n\n return new Promise((resolve, reject) => {\n setTimeout$3(async () => {\n try {\n await sendReplay(replayData, retryConfig);\n resolve(true);\n } catch (err) {\n reject(err);\n }\n }, retryConfig.interval);\n });\n }\n}\n\nconst THROTTLED = '__THROTTLED';\nconst SKIPPED = '__SKIPPED';\n\n/**\n * Create a throttled function off a given function.\n * When calling the throttled function, it will call the original function only\n * if it hasn't been called more than `maxCount` times in the last `durationSeconds`.\n *\n * Returns `THROTTLED` if throttled for the first time, after that `SKIPPED`,\n * or else the return value of the original function.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction throttle(\n fn,\n maxCount,\n durationSeconds,\n) {\n const counter = new Map();\n\n const _cleanup = (now) => {\n const threshold = now - durationSeconds;\n counter.forEach((_value, key) => {\n if (key < threshold) {\n counter.delete(key);\n }\n });\n };\n\n const _getTotalCount = () => {\n return [...counter.values()].reduce((a, b) => a + b, 0);\n };\n\n let isThrottled = false;\n\n return (...rest) => {\n // Date in second-precision, which we use as basis for the throttling\n const now = Math.floor(Date.now() / 1000);\n\n // First, make sure to delete any old entries\n _cleanup(now);\n\n // If already over limit, do nothing\n if (_getTotalCount() >= maxCount) {\n const wasThrottled = isThrottled;\n isThrottled = true;\n return wasThrottled ? SKIPPED : THROTTLED;\n }\n\n isThrottled = false;\n const count = counter.get(now) || 0;\n counter.set(now, count + 1);\n\n return fn(...rest);\n };\n}\n\n/* eslint-disable max-lines */ // TODO: We might want to split this file up\n\n/**\n * The main replay container class, which holds all the state and methods for recording and sending replays.\n */\nclass ReplayContainer {\n\n /**\n * Recording can happen in one of two modes:\n * - session: Record the whole session, sending it continuously\n * - buffer: Always keep the last 60s of recording, requires:\n * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs\n * - or calling `flush()` to send the replay\n */\n\n /**\n * The current or last active span.\n * This is only available when performance is enabled.\n */\n\n /**\n * These are here so we can overwrite them in tests etc.\n * @hidden\n */\n\n /** The replay has to be manually started, because no sample rate (neither session or error) was provided. */\n\n /**\n * Options to pass to `rrweb.record()`\n */\n\n /**\n * Timestamp of the last user activity. This lives across sessions.\n */\n\n /**\n * Is the integration currently active?\n */\n\n /**\n * Paused is a state where:\n * - DOM Recording is not listening at all\n * - Nothing will be added to event buffer (e.g. core SDK events)\n */\n\n /**\n * Have we attached listeners to the core SDK?\n * Note we have to track this as there is no way to remove instrumentation handlers.\n */\n\n /**\n * Function to stop recording\n */\n\n /**\n * Internal use for canvas recording options\n */\n\n /**\n * Handle when visibility of the page content changes. Opening a new tab will\n * cause the state to change to hidden because of content of current page will\n * be hidden. Likewise, moving a different window to cover the contents of the\n * page will also trigger a change to a hidden state.\n */\n\n /**\n * Handle when page is blurred\n */\n\n /**\n * Handle when page is focused\n */\n\n /** Ensure page remains active when a key is pressed. */\n\n constructor({\n options,\n recordingOptions,\n }\n\n) {\n this.eventBuffer = null;\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n this.recordingMode = 'session';\n this.timeouts = {\n sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,\n sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,\n } ;\n this._lastActivity = Date.now();\n this._isEnabled = false;\n this._isPaused = false;\n this._requiresManualStart = false;\n this._hasInitializedCoreListeners = false;\n this._context = {\n errorIds: new Set(),\n traceIds: new Set(),\n urls: [],\n initialTimestamp: Date.now(),\n initialUrl: '',\n };\n\n this._recordingOptions = recordingOptions;\n this._options = options;\n\n this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {\n maxWait: this._options.flushMaxDelay,\n });\n\n this._throttledAddEvent = throttle(\n (event, isCheckout) => addEvent(this, event, isCheckout),\n // Max 300 events...\n 300,\n // ... per 5s\n 5,\n );\n\n const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions();\n\n const slowClickConfig = slowClickTimeout\n ? {\n threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout),\n timeout: slowClickTimeout,\n scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT,\n ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(',') : '',\n }\n : undefined;\n\n if (slowClickConfig) {\n this.clickDetector = new ClickDetector(this, slowClickConfig);\n }\n\n // Configure replay logger w/ experimental options\n if (DEBUG_BUILD) {\n const experiments = options._experiments;\n logger.setConfig({\n captureExceptions: !!experiments.captureExceptions,\n traceInternals: !!experiments.traceInternals,\n });\n }\n\n // We set these handler properties as class properties, to make binding/unbinding them easier\n this._handleVisibilityChange = () => {\n if (WINDOW.document.visibilityState === 'visible') {\n this._doChangeToForegroundTasks();\n } else {\n this._doChangeToBackgroundTasks();\n }\n };\n\n /**\n * Handle when page is blurred\n */\n this._handleWindowBlur = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.blur',\n });\n\n // Do not count blur as a user action -- it's part of the process of them\n // leaving the page\n this._doChangeToBackgroundTasks(breadcrumb);\n };\n\n this._handleWindowFocus = () => {\n const breadcrumb = createBreadcrumb({\n category: 'ui.focus',\n });\n\n // Do not count focus as a user action -- instead wait until they focus and\n // interactive with page\n this._doChangeToForegroundTasks(breadcrumb);\n };\n\n /** Ensure page remains active when a key is pressed. */\n this._handleKeyboardEvent = (event) => {\n handleKeyboardEvent(this, event);\n };\n }\n\n /** Get the event context. */\n getContext() {\n return this._context;\n }\n\n /** If recording is currently enabled. */\n isEnabled() {\n return this._isEnabled;\n }\n\n /** If recording is currently paused. */\n isPaused() {\n return this._isPaused;\n }\n\n /**\n * Determine if canvas recording is enabled\n */\n isRecordingCanvas() {\n return Boolean(this._canvas);\n }\n\n /** Get the replay integration options. */\n getOptions() {\n return this._options;\n }\n\n /** A wrapper to conditionally capture exceptions. */\n handleException(error) {\n DEBUG_BUILD && logger.exception(error);\n if (this._options.onError) {\n this._options.onError(error);\n }\n }\n\n /**\n * Initializes the plugin based on sampling configuration. Should not be\n * called outside of constructor.\n */\n initializeSampling(previousSessionId) {\n const { errorSampleRate, sessionSampleRate } = this._options;\n\n // If neither sample rate is > 0, then do nothing - user will need to call one of\n // `start()` or `startBuffering` themselves.\n const requiresManualStart = errorSampleRate <= 0 && sessionSampleRate <= 0;\n\n this._requiresManualStart = requiresManualStart;\n\n if (requiresManualStart) {\n return;\n }\n\n // Otherwise if there is _any_ sample rate set, try to load an existing\n // session, or create a new one.\n this._initializeSessionForSampling(previousSessionId);\n\n if (!this.session) {\n // This should not happen, something wrong has occurred\n DEBUG_BUILD && logger.exception(new Error('Unable to initialize and create session'));\n return;\n }\n\n if (this.session.sampled === false) {\n // This should only occur if `errorSampleRate` is 0 and was unsampled for\n // session-based replay. In this case there is nothing to do.\n return;\n }\n\n // If segmentId > 0, it means we've previously already captured this session\n // In this case, we still want to continue in `session` recording mode\n this.recordingMode = this.session.sampled === 'buffer' && this.session.segmentId === 0 ? 'buffer' : 'session';\n\n DEBUG_BUILD && logger.infoTick(`Starting replay in ${this.recordingMode} mode`);\n\n this._initializeRecording();\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will log a message if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * _performanceObserver, Recording, Sentry SDK, etc)\n */\n start() {\n if (this._isEnabled && this.recordingMode === 'session') {\n DEBUG_BUILD && logger.info('Recording is already in progress');\n return;\n }\n\n if (this._isEnabled && this.recordingMode === 'buffer') {\n DEBUG_BUILD && logger.info('Buffering is in progress, call `flush()` to save the replay');\n return;\n }\n\n DEBUG_BUILD && logger.infoTick('Starting replay in session mode');\n\n // Required as user activity is initially set in\n // constructor, so if `start()` is called after\n // session idle expiration, a replay will not be\n // created due to an idle timeout.\n this._updateUserActivity();\n\n const session = loadOrCreateSession(\n {\n maxReplayDuration: this._options.maxReplayDuration,\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n },\n {\n stickySession: this._options.stickySession,\n // This is intentional: create a new session-based replay when calling `start()`\n sessionSampleRate: 1,\n allowBuffering: false,\n },\n );\n\n this.session = session;\n\n this._initializeRecording();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, an error occurs.\n */\n startBuffering() {\n if (this._isEnabled) {\n DEBUG_BUILD && logger.info('Buffering is in progress, call `flush()` to save the replay');\n return;\n }\n\n DEBUG_BUILD && logger.infoTick('Starting replay in buffer mode');\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n },\n {\n stickySession: this._options.stickySession,\n sessionSampleRate: 0,\n allowBuffering: true,\n },\n );\n\n this.session = session;\n\n this.recordingMode = 'buffer';\n this._initializeRecording();\n }\n\n /**\n * Start recording.\n *\n * Note that this will cause a new DOM checkout\n */\n startRecording() {\n try {\n const canvasOptions = this._canvas;\n\n this._stopRecording = record({\n ...this._recordingOptions,\n // When running in error sampling mode, we need to overwrite `checkoutEveryNms`\n // Without this, it would record forever, until an error happens, which we don't want\n // instead, we'll always keep the last 60 seconds of replay before an error happened\n ...(this.recordingMode === 'buffer'\n ? { checkoutEveryNms: BUFFER_CHECKOUT_TIME }\n : // Otherwise, use experimental option w/ min checkout time of 6 minutes\n // This is to improve playback seeking as there could potentially be\n // less mutations to process in the worse cases.\n //\n // checkout by \"N\" events is probably ideal, but means we have less\n // control about the number of checkouts we make (which generally\n // increases replay size)\n this._options._experiments.continuousCheckout && {\n // Minimum checkout time is 6 minutes\n checkoutEveryNms: Math.max(360000, this._options._experiments.continuousCheckout),\n }),\n emit: getHandleRecordingEmit(this),\n ...getRecordingSamplingOptions(),\n onMutation: this._onMutationHandler.bind(this),\n ...(canvasOptions\n ? {\n recordCanvas: canvasOptions.recordCanvas,\n getCanvasManager: canvasOptions.getCanvasManager,\n sampling: canvasOptions.sampling,\n dataURLOptions: canvasOptions.dataURLOptions,\n }\n : {}),\n });\n } catch (err) {\n this.handleException(err);\n }\n }\n\n /**\n * Stops the recording, if it was running.\n *\n * Returns true if it was previously stopped, or is now stopped,\n * otherwise false.\n */\n stopRecording() {\n try {\n if (this._stopRecording) {\n this._stopRecording();\n this._stopRecording = undefined;\n }\n\n return true;\n } catch (err) {\n this.handleException(err);\n return false;\n }\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n async stop({ forceFlush = false, reason } = {}) {\n if (!this._isEnabled) {\n return;\n }\n\n // We can't move `_isEnabled` after awaiting a flush, otherwise we can\n // enter into an infinite loop when `stop()` is called while flushing.\n this._isEnabled = false;\n\n try {\n DEBUG_BUILD && logger.info(`Stopping Replay${reason ? ` triggered by ${reason}` : ''}`);\n\n resetReplayIdOnDynamicSamplingContext();\n\n this._removeListeners();\n this.stopRecording();\n\n this._debouncedFlush.cancel();\n // See comment above re: `_isEnabled`, we \"force\" a flush, ignoring the\n // `_isEnabled` state of the plugin since it was disabled above.\n if (forceFlush) {\n await this._flush({ force: true });\n }\n\n // After flush, destroy event buffer\n this.eventBuffer?.destroy();\n this.eventBuffer = null;\n\n // Clear session from session storage, note this means if a new session\n // is started after, it will not have `previousSessionId`\n clearSession(this);\n } catch (err) {\n this.handleException(err);\n }\n }\n\n /**\n * Pause some replay functionality. See comments for `_isPaused`.\n * This differs from stop as this only stops DOM recording, it is\n * not as thorough of a shutdown as `stop()`.\n */\n pause() {\n if (this._isPaused) {\n return;\n }\n\n this._isPaused = true;\n this.stopRecording();\n\n DEBUG_BUILD && logger.info('Pausing replay');\n }\n\n /**\n * Resumes recording, see notes for `pause().\n *\n * Note that calling `startRecording()` here will cause a\n * new DOM checkout.`\n */\n resume() {\n if (!this._isPaused || !this._checkSession()) {\n return;\n }\n\n this._isPaused = false;\n this.startRecording();\n\n DEBUG_BUILD && logger.info('Resuming replay');\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n async sendBufferedReplayOrFlush({ continueRecording = true } = {}) {\n if (this.recordingMode === 'session') {\n return this.flushImmediate();\n }\n\n const activityTime = Date.now();\n\n DEBUG_BUILD && logger.info('Converting buffer to session');\n\n // Allow flush to complete before resuming as a session recording, otherwise\n // the checkout from `startRecording` may be included in the payload.\n // Prefer to keep the error replay as a separate (and smaller) segment\n // than the session replay.\n await this.flushImmediate();\n\n const hasStoppedRecording = this.stopRecording();\n\n if (!continueRecording || !hasStoppedRecording) {\n return;\n }\n\n // To avoid race conditions where this is called multiple times, we check here again that we are still buffering\n if ((this.recordingMode ) === 'session') {\n return;\n }\n\n // Re-start recording in session-mode\n this.recordingMode = 'session';\n\n // Once this session ends, we do not want to refresh it\n if (this.session) {\n this._updateUserActivity(activityTime);\n this._updateSessionActivity(activityTime);\n this._maybeSaveSession();\n }\n\n this.startRecording();\n }\n\n /**\n * We want to batch uploads of replay events. Save events only if\n * `` milliseconds have elapsed since the last event\n * *OR* if `` milliseconds have elapsed.\n *\n * Accepts a callback to perform side-effects and returns true to stop batch\n * processing and hand back control to caller.\n */\n addUpdate(cb) {\n // We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)\n const cbResult = cb();\n\n // If this option is turned on then we will only want to call `flush`\n // explicitly\n if (this.recordingMode === 'buffer') {\n return;\n }\n\n // If callback is true, we do not want to continue with flushing -- the\n // caller will need to handle it.\n if (cbResult === true) {\n return;\n }\n\n // addUpdate is called quite frequently - use _debouncedFlush so that it\n // respects the flush delays and does not flush immediately\n this._debouncedFlush();\n }\n\n /**\n * Updates the user activity timestamp and resumes recording. This should be\n * called in an event handler for a user action that we consider as the user\n * being \"active\" (e.g. a mouse click).\n */\n triggerUserActivity() {\n this._updateUserActivity();\n\n // This case means that recording was once stopped due to inactivity.\n // Ensure that recording is resumed.\n if (!this._stopRecording) {\n // Create a new session, otherwise when the user action is flushed, it\n // will get rejected due to an expired session.\n if (!this._checkSession()) {\n return;\n }\n\n // Note: This will cause a new DOM checkout\n this.resume();\n return;\n }\n\n // Otherwise... recording was never suspended, continue as normalish\n this.checkAndHandleExpiredSession();\n\n this._updateSessionActivity();\n }\n\n /**\n * Updates the user activity timestamp *without* resuming\n * recording. Some user events (e.g. keydown) can be create\n * low-value replays that only contain the keypress as a\n * breadcrumb. Instead this would require other events to\n * create a new replay after a session has expired.\n */\n updateUserActivity() {\n this._updateUserActivity();\n this._updateSessionActivity();\n }\n\n /**\n * Only flush if `this.recordingMode === 'session'`\n */\n conditionalFlush() {\n if (this.recordingMode === 'buffer') {\n return Promise.resolve();\n }\n\n return this.flushImmediate();\n }\n\n /**\n * Flush using debounce flush\n */\n flush() {\n return this._debouncedFlush() ;\n }\n\n /**\n * Always flush via `_debouncedFlush` so that we do not have flushes triggered\n * from calling both `flush` and `_debouncedFlush`. Otherwise, there could be\n * cases of multiple flushes happening closely together.\n */\n flushImmediate() {\n this._debouncedFlush();\n // `.flush` is provided by the debounced function, analogously to lodash.debounce\n return this._debouncedFlush.flush() ;\n }\n\n /**\n * Cancels queued up flushes.\n */\n cancelFlush() {\n this._debouncedFlush.cancel();\n }\n\n /** Get the current session (=replay) ID */\n getSessionId() {\n return this.session?.id;\n }\n\n /**\n * Checks if recording should be stopped due to user inactivity. Otherwise\n * check if session is expired and create a new session if so. Triggers a new\n * full snapshot on new session.\n *\n * Returns true if session is not expired, false otherwise.\n * @hidden\n */\n checkAndHandleExpiredSession() {\n // Prevent starting a new session if the last user activity is older than\n // SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new\n // session+recording. This creates noisy replays that do not have much\n // content in them.\n if (\n this._lastActivity &&\n isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&\n this.session &&\n this.session.sampled === 'session'\n ) {\n // Pause recording only for session-based replays. Otherwise, resuming\n // will create a new replay and will conflict with users who only choose\n // to record error-based replays only. (e.g. the resumed replay will not\n // contain a reference to an error)\n this.pause();\n return;\n }\n\n // --- There is recent user activity --- //\n // This will create a new session if expired, based on expiry length\n if (!this._checkSession()) {\n // Check session handles the refreshing itself\n return false;\n }\n\n return true;\n }\n\n /**\n * Capture some initial state that can change throughout the lifespan of the\n * replay. This is required because otherwise they would be captured at the\n * first flush.\n */\n setInitialState() {\n const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`;\n const url = `${WINDOW.location.origin}${urlPath}`;\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n // Reset _context as well\n this._clearContext();\n\n this._context.initialUrl = url;\n this._context.initialTimestamp = Date.now();\n this._context.urls.push(url);\n }\n\n /**\n * Add a breadcrumb event, that may be throttled.\n * If it was throttled, we add a custom breadcrumb to indicate that.\n */\n throttledAddEvent(\n event,\n isCheckout,\n ) {\n const res = this._throttledAddEvent(event, isCheckout);\n\n // If this is THROTTLED, it means we have throttled the event for the first time\n // In this case, we want to add a breadcrumb indicating that something was skipped\n if (res === THROTTLED) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.throttled',\n });\n\n this.addUpdate(() => {\n // Return `false` if the event _was_ added, as that means we schedule a flush\n return !addEventSync(this, {\n type: ReplayEventTypeCustom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n metric: true,\n },\n });\n });\n }\n\n return res;\n }\n\n /**\n * This will get the parametrized route name of the current page.\n * This is only available if performance is enabled, and if an instrumented router is used.\n */\n getCurrentRoute() {\n const lastActiveSpan = this.lastActiveSpan || getActiveSpan();\n const lastRootSpan = lastActiveSpan && getRootSpan(lastActiveSpan);\n\n const attributes = (lastRootSpan && spanToJSON(lastRootSpan).data) || {};\n const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n if (!lastRootSpan || !source || !['route', 'custom'].includes(source)) {\n return undefined;\n }\n\n return spanToJSON(lastRootSpan).description;\n }\n\n /**\n * Initialize and start all listeners to varying events (DOM,\n * Performance Observer, Recording, Sentry SDK, etc)\n */\n _initializeRecording() {\n this.setInitialState();\n\n // this method is generally called on page load or manually - in both cases\n // we should treat it as an activity\n this._updateSessionActivity();\n\n this.eventBuffer = createEventBuffer({\n useCompression: this._options.useCompression,\n workerUrl: this._options.workerUrl,\n });\n\n this._removeListeners();\n this._addListeners();\n\n // Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout\n this._isEnabled = true;\n this._isPaused = false;\n\n this.startRecording();\n }\n\n /**\n * Loads (or refreshes) the current session.\n */\n _initializeSessionForSampling(previousSessionId) {\n // Whenever there is _any_ error sample rate, we always allow buffering\n // Because we decide on sampling when an error occurs, we need to buffer at all times if sampling for errors\n const allowBuffering = this._options.errorSampleRate > 0;\n\n const session = loadOrCreateSession(\n {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n previousSessionId,\n },\n {\n stickySession: this._options.stickySession,\n sessionSampleRate: this._options.sessionSampleRate,\n allowBuffering,\n },\n );\n\n this.session = session;\n }\n\n /**\n * Checks and potentially refreshes the current session.\n * Returns false if session is not recorded.\n */\n _checkSession() {\n // If there is no session yet, we do not want to refresh anything\n // This should generally not happen, but to be safe....\n if (!this.session) {\n return false;\n }\n\n const currentSession = this.session;\n\n if (\n shouldRefreshSession(currentSession, {\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n maxReplayDuration: this._options.maxReplayDuration,\n })\n ) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this._refreshSession(currentSession);\n return false;\n }\n\n return true;\n }\n\n /**\n * Refresh a session with a new one.\n * This stops the current session (without forcing a flush, as that would never work since we are expired),\n * and then does a new sampling based on the refreshed session.\n */\n async _refreshSession(session) {\n if (!this._isEnabled) {\n return;\n }\n await this.stop({ reason: 'refresh session' });\n this.initializeSampling(session.id);\n }\n\n /**\n * Adds listeners to record events for the replay\n */\n _addListeners() {\n try {\n WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);\n WINDOW.addEventListener('blur', this._handleWindowBlur);\n WINDOW.addEventListener('focus', this._handleWindowFocus);\n WINDOW.addEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.addListeners();\n }\n\n // There is no way to remove these listeners, so ensure they are only added once\n if (!this._hasInitializedCoreListeners) {\n addGlobalListeners(this, { autoFlushOnFeedback: this._options._experiments.autoFlushOnFeedback });\n\n this._hasInitializedCoreListeners = true;\n }\n } catch (err) {\n this.handleException(err);\n }\n\n this._performanceCleanupCallback = setupPerformanceObserver(this);\n }\n\n /**\n * Cleans up listeners that were created in `_addListeners`\n */\n _removeListeners() {\n try {\n WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);\n\n WINDOW.removeEventListener('blur', this._handleWindowBlur);\n WINDOW.removeEventListener('focus', this._handleWindowFocus);\n WINDOW.removeEventListener('keydown', this._handleKeyboardEvent);\n\n if (this.clickDetector) {\n this.clickDetector.removeListeners();\n }\n\n if (this._performanceCleanupCallback) {\n this._performanceCleanupCallback();\n }\n } catch (err) {\n this.handleException(err);\n }\n }\n\n /**\n * Tasks to run when we consider a page to be hidden (via blurring and/or visibility)\n */\n _doChangeToBackgroundTasks(breadcrumb) {\n if (!this.session) {\n return;\n }\n\n const expired = isSessionExpired(this.session, {\n maxReplayDuration: this._options.maxReplayDuration,\n sessionIdleExpire: this.timeouts.sessionIdleExpire,\n });\n\n if (expired) {\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Send replay when the page/tab becomes hidden. There is no reason to send\n // replay if it becomes visible, since no actions we care about were done\n // while it was hidden\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n void this.conditionalFlush();\n }\n\n /**\n * Tasks to run when we consider a page to be visible (via focus and/or visibility)\n */\n _doChangeToForegroundTasks(breadcrumb) {\n if (!this.session) {\n return;\n }\n\n const isSessionActive = this.checkAndHandleExpiredSession();\n\n if (!isSessionActive) {\n // If the user has come back to the page within SESSION_IDLE_PAUSE_DURATION\n // ms, we will re-use the existing session, otherwise create a new\n // session\n DEBUG_BUILD && logger.info('Document has become active, but session has expired');\n return;\n }\n\n if (breadcrumb) {\n this._createCustomBreadcrumb(breadcrumb);\n }\n }\n\n /**\n * Update user activity (across session lifespans)\n */\n _updateUserActivity(_lastActivity = Date.now()) {\n this._lastActivity = _lastActivity;\n }\n\n /**\n * Updates the session's last activity timestamp\n */\n _updateSessionActivity(_lastActivity = Date.now()) {\n if (this.session) {\n this.session.lastActivity = _lastActivity;\n this._maybeSaveSession();\n }\n }\n\n /**\n * Helper to create (and buffer) a replay breadcrumb from a core SDK breadcrumb\n */\n _createCustomBreadcrumb(breadcrumb) {\n this.addUpdate(() => {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.throttledAddEvent({\n type: EventType.Custom,\n timestamp: breadcrumb.timestamp || 0,\n data: {\n tag: 'breadcrumb',\n payload: breadcrumb,\n },\n });\n });\n }\n\n /**\n * Observed performance events are added to `this.performanceEntries`. These\n * are included in the replay event before it is finished and sent to Sentry.\n */\n _addPerformanceEntries() {\n let performanceEntries = createPerformanceEntries(this.performanceEntries).concat(this.replayPerformanceEntries);\n\n this.performanceEntries = [];\n this.replayPerformanceEntries = [];\n\n // If we are manually starting, we want to ensure we only include performance entries\n // that are after the initial timestamp\n // The reason for this is that we may have performance entries from the page load, but may decide to start\n // the replay later on, in which case we do not want to include these entries.\n // without this, manually started replays can have events long before the actual replay recording starts,\n // which messes with the timeline etc.\n if (this._requiresManualStart) {\n const initialTimestampInSeconds = this._context.initialTimestamp / 1000;\n performanceEntries = performanceEntries.filter(entry => entry.start >= initialTimestampInSeconds);\n }\n\n return Promise.all(createPerformanceSpans(this, performanceEntries));\n }\n\n /**\n * Clear _context\n */\n _clearContext() {\n // XXX: `initialTimestamp` and `initialUrl` do not get cleared\n this._context.errorIds.clear();\n this._context.traceIds.clear();\n this._context.urls = [];\n }\n\n /** Update the initial timestamp based on the buffer content. */\n _updateInitialTimestampFromEventBuffer() {\n const { session, eventBuffer } = this;\n // If replay was started manually (=no sample rate was given),\n // We do not want to back-port the initial timestamp\n if (!session || !eventBuffer || this._requiresManualStart) {\n return;\n }\n\n // we only ever update this on the initial segment\n if (session.segmentId) {\n return;\n }\n\n const earliestEvent = eventBuffer.getEarliestTimestamp();\n if (earliestEvent && earliestEvent < this._context.initialTimestamp) {\n this._context.initialTimestamp = earliestEvent;\n }\n }\n\n /**\n * Return and clear _context\n */\n _popEventContext() {\n const _context = {\n initialTimestamp: this._context.initialTimestamp,\n initialUrl: this._context.initialUrl,\n errorIds: Array.from(this._context.errorIds),\n traceIds: Array.from(this._context.traceIds),\n urls: this._context.urls,\n };\n\n this._clearContext();\n\n return _context;\n }\n\n /**\n * Flushes replay event buffer to Sentry.\n *\n * Performance events are only added right before flushing - this is\n * due to the buffered performance observer events.\n *\n * Should never be called directly, only by `flush`\n */\n async _runFlush() {\n const replayId = this.getSessionId();\n\n if (!this.session || !this.eventBuffer || !replayId) {\n DEBUG_BUILD && logger.error('No session or eventBuffer found to flush.');\n return;\n }\n\n await this._addPerformanceEntries();\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer?.hasEvents) {\n return;\n }\n\n // Only attach memory event if eventBuffer is not empty\n await addMemoryEntry(this);\n\n // Check eventBuffer again, as it could have been stopped in the meanwhile\n if (!this.eventBuffer) {\n return;\n }\n\n // if this changed in the meanwhile, e.g. because the session was refreshed or similar, we abort here\n if (replayId !== this.getSessionId()) {\n return;\n }\n\n try {\n // This uses the data from the eventBuffer, so we need to call this before `finish()\n this._updateInitialTimestampFromEventBuffer();\n\n const timestamp = Date.now();\n\n // Check total duration again, to avoid sending outdated stuff\n // We leave 30s wiggle room to accommodate late flushing etc.\n // This _could_ happen when the browser is suspended during flushing, in which case we just want to stop\n if (timestamp - this._context.initialTimestamp > this._options.maxReplayDuration + 30000) {\n throw new Error('Session is too long, not sending replay');\n }\n\n const eventContext = this._popEventContext();\n // Always increment segmentId regardless of outcome of sending replay\n const segmentId = this.session.segmentId++;\n this._maybeSaveSession();\n\n // Note this empties the event buffer regardless of outcome of sending replay\n const recordingData = await this.eventBuffer.finish();\n\n await sendReplay({\n replayId,\n recordingData,\n segmentId,\n eventContext,\n session: this.session,\n timestamp,\n onError: err => this.handleException(err),\n });\n } catch (err) {\n this.handleException(err);\n\n // This means we retried 3 times and all of them failed,\n // or we ran into a problem we don't want to retry, like rate limiting.\n // In this case, we want to completely stop the replay - otherwise, we may get inconsistent segments\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.stop({ reason: 'sendReplay' });\n\n const client = getClient();\n\n if (client) {\n const dropReason = err instanceof RateLimitError ? 'ratelimit_backoff' : 'send_error';\n client.recordDroppedEvent(dropReason, 'replay');\n }\n }\n }\n\n /**\n * Flush recording data to Sentry. Creates a lock so that only a single flush\n * can be active at a time. Do not call this directly.\n */\n async _flush({\n force = false,\n }\n\n = {}) {\n if (!this._isEnabled && !force) {\n // This can happen if e.g. the replay was stopped because of exceeding the retry limit\n return;\n }\n\n if (!this.checkAndHandleExpiredSession()) {\n DEBUG_BUILD && logger.error('Attempting to finish replay event after session expired.');\n return;\n }\n\n if (!this.session) {\n // should never happen, as we would have bailed out before\n return;\n }\n\n const start = this.session.started;\n const now = Date.now();\n const duration = now - start;\n\n // A flush is about to happen, cancel any queued flushes\n this._debouncedFlush.cancel();\n\n // If session is too short, or too long (allow some wiggle room over maxReplayDuration), do not send it\n // This _should_ not happen, but it may happen if flush is triggered due to a page activity change or similar\n const tooShort = duration < this._options.minReplayDuration;\n const tooLong = duration > this._options.maxReplayDuration + 5000;\n if (tooShort || tooLong) {\n DEBUG_BUILD &&\n logger.info(\n `Session duration (${Math.floor(duration / 1000)}s) is too ${\n tooShort ? 'short' : 'long'\n }, not sending replay.`,\n );\n\n if (tooShort) {\n this._debouncedFlush();\n }\n return;\n }\n\n const eventBuffer = this.eventBuffer;\n if (eventBuffer && this.session.segmentId === 0 && !eventBuffer.hasCheckout) {\n DEBUG_BUILD && logger.info('Flushing initial segment without checkout.');\n // TODO FN: Evaluate if we want to stop here, or remove this again?\n }\n\n const _flushInProgress = !!this._flushLock;\n\n // this._flushLock acts as a lock so that future calls to `_flush()` will\n // be blocked until current flush is finished (i.e. this promise resolves)\n if (!this._flushLock) {\n this._flushLock = this._runFlush();\n }\n\n try {\n await this._flushLock;\n } catch (err) {\n this.handleException(err);\n } finally {\n this._flushLock = undefined;\n\n if (_flushInProgress) {\n // Wait for previous flush to finish, then call the debounced\n // `_flush()`. It's possible there are other flush requests queued and\n // waiting for it to resolve. We want to reduce all outstanding\n // requests (as well as any new flush requests that occur within a\n // second of the locked flush completing) into a single flush.\n this._debouncedFlush();\n }\n }\n }\n\n /** Save the session, if it is sticky */\n _maybeSaveSession() {\n if (this.session && this._options.stickySession) {\n saveSession(this.session);\n }\n }\n\n /** Handler for rrweb.record.onMutation */\n _onMutationHandler(mutations) {\n const count = mutations.length;\n\n const mutationLimit = this._options.mutationLimit;\n const mutationBreadcrumbLimit = this._options.mutationBreadcrumbLimit;\n const overMutationLimit = mutationLimit && count > mutationLimit;\n\n // Create a breadcrumb if a lot of mutations happen at the same time\n // We can show this in the UI as an information with potential performance improvements\n if (count > mutationBreadcrumbLimit || overMutationLimit) {\n const breadcrumb = createBreadcrumb({\n category: 'replay.mutations',\n data: {\n count,\n limit: overMutationLimit,\n },\n });\n this._createCustomBreadcrumb(breadcrumb);\n }\n\n // Stop replay if over the mutation limit\n if (overMutationLimit) {\n // This should never reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.stop({ reason: 'mutationLimit', forceFlush: this.recordingMode === 'session' });\n return false;\n }\n\n // `true` means we use the regular mutation handling by rrweb\n return true;\n }\n}\n\nfunction getOption(selectors, defaultSelectors) {\n return [\n ...selectors,\n // sentry defaults\n ...defaultSelectors,\n ].join(',');\n}\n\n/**\n * Returns privacy related configuration for use in rrweb\n */\nfunction getPrivacyOptions({ mask, unmask, block, unblock, ignore }) {\n const defaultBlockedElements = ['base', 'iframe[srcdoc]:not([src])'];\n\n const maskSelector = getOption(mask, ['.sentry-mask', '[data-sentry-mask]']);\n const unmaskSelector = getOption(unmask, []);\n\n const options = {\n // We are making the decision to make text and input selectors the same\n maskTextSelector: maskSelector,\n unmaskTextSelector: unmaskSelector,\n\n blockSelector: getOption(block, ['.sentry-block', '[data-sentry-block]', ...defaultBlockedElements]),\n unblockSelector: getOption(unblock, []),\n ignoreSelector: getOption(ignore, ['.sentry-ignore', '[data-sentry-ignore]', 'input[type=\"file\"]']),\n };\n\n return options;\n}\n\n/**\n * Masks an attribute if necessary, otherwise return attribute value as-is.\n */\nfunction maskAttribute({\n el,\n key,\n maskAttributes,\n maskAllText,\n privacyOptions,\n value,\n}) {\n // We only mask attributes if `maskAllText` is true\n if (!maskAllText) {\n return value;\n }\n\n // unmaskTextSelector takes precedence\n if (privacyOptions.unmaskTextSelector && el.matches(privacyOptions.unmaskTextSelector)) {\n return value;\n }\n\n if (\n maskAttributes.includes(key) ||\n // Need to mask `value` attribute for `` if it's a button-like\n // type\n (key === 'value' && el.tagName === 'INPUT' && ['submit', 'button'].includes(el.getAttribute('type') || ''))\n ) {\n return value.replace(/[\\S]/g, '*');\n }\n\n return value;\n}\n\nconst MEDIA_SELECTORS =\n 'img,image,svg,video,object,picture,embed,map,audio,link[rel=\"icon\"],link[rel=\"apple-touch-icon\"]';\n\nconst DEFAULT_NETWORK_HEADERS = ['content-length', 'content-type', 'accept'];\n\nlet _initialized = false;\n\n/**\n * Sentry integration for [Session Replay](https://sentry.io/for/session-replay/).\n *\n * See the [Replay documentation](https://docs.sentry.io/platforms/javascript/guides/session-replay/) for more information.\n *\n * @example\n *\n * ```\n * Sentry.init({\n * dsn: '__DSN__',\n * integrations: [Sentry.replayIntegration()],\n * });\n * ```\n */\nconst replayIntegration = ((options) => {\n return new Replay(options);\n}) ;\n\n/**\n * Replay integration\n */\nclass Replay {\n /**\n * @inheritDoc\n */\n\n /**\n * Options to pass to `rrweb.record()`\n */\n\n /**\n * Initial options passed to the replay integration, merged with default values.\n * Note: `sessionSampleRate` and `errorSampleRate` are not required here, as they\n * can only be finally set when setupOnce() is called.\n *\n * @private\n */\n\n constructor({\n flushMinDelay = DEFAULT_FLUSH_MIN_DELAY,\n flushMaxDelay = DEFAULT_FLUSH_MAX_DELAY,\n minReplayDuration = MIN_REPLAY_DURATION,\n maxReplayDuration = MAX_REPLAY_DURATION,\n stickySession = true,\n useCompression = true,\n workerUrl,\n _experiments = {},\n maskAllText = true,\n maskAllInputs = true,\n blockAllMedia = true,\n\n mutationBreadcrumbLimit = 750,\n mutationLimit = 10000,\n\n slowClickTimeout = 7000,\n slowClickIgnoreSelectors = [],\n\n networkDetailAllowUrls = [],\n networkDetailDenyUrls = [],\n networkCaptureBodies = true,\n networkRequestHeaders = [],\n networkResponseHeaders = [],\n\n mask = [],\n maskAttributes = ['title', 'placeholder'],\n unmask = [],\n block = [],\n unblock = [],\n ignore = [],\n maskFn,\n\n beforeAddRecordingEvent,\n beforeErrorSampling,\n onError,\n } = {}) {\n this.name = 'Replay';\n\n const privacyOptions = getPrivacyOptions({\n mask,\n unmask,\n block,\n unblock,\n ignore,\n });\n\n this._recordingOptions = {\n maskAllInputs,\n maskAllText,\n maskInputOptions: { password: true },\n maskTextFn: maskFn,\n maskInputFn: maskFn,\n maskAttributeFn: (key, value, el) =>\n maskAttribute({\n maskAttributes,\n maskAllText,\n privacyOptions,\n key,\n value,\n el,\n }),\n\n ...privacyOptions,\n\n // Our defaults\n slimDOMOptions: 'all',\n inlineStylesheet: true,\n // Disable inline images as it will increase segment/replay size\n inlineImages: false,\n // collect fonts, but be aware that `sentry.io` needs to be an allowed\n // origin for playback\n collectFonts: true,\n errorHandler: (err) => {\n try {\n err.__rrweb__ = true;\n } catch (error) {\n // ignore errors here\n // this can happen if the error is frozen or does not allow mutation for other reasons\n }\n },\n };\n\n this._initialOptions = {\n flushMinDelay,\n flushMaxDelay,\n minReplayDuration: Math.min(minReplayDuration, MIN_REPLAY_DURATION_LIMIT),\n maxReplayDuration: Math.min(maxReplayDuration, MAX_REPLAY_DURATION),\n stickySession,\n useCompression,\n workerUrl,\n blockAllMedia,\n maskAllInputs,\n maskAllText,\n mutationBreadcrumbLimit,\n mutationLimit,\n slowClickTimeout,\n slowClickIgnoreSelectors,\n networkDetailAllowUrls,\n networkDetailDenyUrls,\n networkCaptureBodies,\n networkRequestHeaders: _getMergedNetworkHeaders(networkRequestHeaders),\n networkResponseHeaders: _getMergedNetworkHeaders(networkResponseHeaders),\n beforeAddRecordingEvent,\n beforeErrorSampling,\n onError,\n\n _experiments,\n };\n\n if (this._initialOptions.blockAllMedia) {\n // `blockAllMedia` is a more user friendly option to configure blocking\n // embedded media elements\n this._recordingOptions.blockSelector = !this._recordingOptions.blockSelector\n ? MEDIA_SELECTORS\n : `${this._recordingOptions.blockSelector},${MEDIA_SELECTORS}`;\n }\n\n if (this._isInitialized && isBrowser()) {\n throw new Error('Multiple Sentry Session Replay instances are not supported');\n }\n\n this._isInitialized = true;\n }\n\n /** If replay has already been initialized */\n get _isInitialized() {\n return _initialized;\n }\n\n /** Update _isInitialized */\n set _isInitialized(value) {\n _initialized = value;\n }\n\n /**\n * Setup and initialize replay container\n */\n afterAllSetup(client) {\n if (!isBrowser() || this._replay) {\n return;\n }\n\n this._setup(client);\n this._initialize(client);\n }\n\n /**\n * Start a replay regardless of sampling rate. Calling this will always\n * create a new session. Will log a message if replay is already in progress.\n *\n * Creates or loads a session, attaches listeners to varying events (DOM,\n * PerformanceObserver, Recording, Sentry SDK, etc)\n */\n start() {\n if (!this._replay) {\n return;\n }\n this._replay.start();\n }\n\n /**\n * Start replay buffering. Buffers until `flush()` is called or, if\n * `replaysOnErrorSampleRate` > 0, until an error occurs.\n */\n startBuffering() {\n if (!this._replay) {\n return;\n }\n\n this._replay.startBuffering();\n }\n\n /**\n * Currently, this needs to be manually called (e.g. for tests). Sentry SDK\n * does not support a teardown\n */\n stop() {\n if (!this._replay) {\n return Promise.resolve();\n }\n\n return this._replay.stop({ forceFlush: this._replay.recordingMode === 'session' });\n }\n\n /**\n * If not in \"session\" recording mode, flush event buffer which will create a new replay.\n * If replay is not enabled, a new session replay is started.\n * Unless `continueRecording` is false, the replay will continue to record and\n * behave as a \"session\"-based replay.\n *\n * Otherwise, queue up a flush.\n */\n flush(options) {\n if (!this._replay) {\n return Promise.resolve();\n }\n\n // assuming a session should be recorded in this case\n if (!this._replay.isEnabled()) {\n this._replay.start();\n return Promise.resolve();\n }\n\n return this._replay.sendBufferedReplayOrFlush(options);\n }\n\n /**\n * Get the current session ID.\n */\n getReplayId() {\n if (!this._replay?.isEnabled()) {\n return;\n }\n\n return this._replay.getSessionId();\n }\n\n /**\n * Get the current recording mode. This can be either `session` or `buffer`.\n *\n * `session`: Recording the whole session, sending it continuously\n * `buffer`: Always keeping the last 60s of recording, requires:\n * - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs\n * - or calling `flush()` to send the replay\n */\n getRecordingMode() {\n if (!this._replay?.isEnabled()) {\n return;\n }\n\n return this._replay.recordingMode;\n }\n\n /**\n * Initializes replay.\n */\n _initialize(client) {\n if (!this._replay) {\n return;\n }\n\n this._maybeLoadFromReplayCanvasIntegration(client);\n this._replay.initializeSampling();\n }\n\n /** Setup the integration. */\n _setup(client) {\n // Client is not available in constructor, so we need to wait until setupOnce\n const finalOptions = loadReplayOptionsFromClient(this._initialOptions, client);\n\n this._replay = new ReplayContainer({\n options: finalOptions,\n recordingOptions: this._recordingOptions,\n });\n }\n\n /** Get canvas options from ReplayCanvas integration, if it is also added. */\n _maybeLoadFromReplayCanvasIntegration(client) {\n // To save bundle size, we skip checking for stuff here\n // and instead just try-catch everything - as generally this should all be defined\n /* eslint-disable @typescript-eslint/no-non-null-assertion */\n try {\n const canvasIntegration = client.getIntegrationByName('ReplayCanvas')\n\n;\n if (!canvasIntegration) {\n return;\n }\n\n this._replay['_canvas'] = canvasIntegration.getOptions();\n } catch {\n // ignore errors here\n }\n /* eslint-enable @typescript-eslint/no-non-null-assertion */\n }\n}\n\n/** Parse Replay-related options from SDK options */\nfunction loadReplayOptionsFromClient(initialOptions, client) {\n const opt = client.getOptions() ;\n\n const finalOptions = {\n sessionSampleRate: 0,\n errorSampleRate: 0,\n ...dropUndefinedKeys(initialOptions),\n };\n\n const replaysSessionSampleRate = parseSampleRate(opt.replaysSessionSampleRate);\n const replaysOnErrorSampleRate = parseSampleRate(opt.replaysOnErrorSampleRate);\n\n if (replaysSessionSampleRate == null && replaysOnErrorSampleRate == null) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n 'Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.',\n );\n });\n }\n\n if (replaysSessionSampleRate != null) {\n finalOptions.sessionSampleRate = replaysSessionSampleRate;\n }\n\n if (replaysOnErrorSampleRate != null) {\n finalOptions.errorSampleRate = replaysOnErrorSampleRate;\n }\n\n return finalOptions;\n}\n\nfunction _getMergedNetworkHeaders(headers) {\n return [...DEFAULT_NETWORK_HEADERS, ...headers.map(header => header.toLowerCase())];\n}\n\n/**\n * This is a small utility to get a type-safe instance of the Replay integration.\n */\nfunction getReplay() {\n const client = getClient();\n return client?.getIntegrationByName('Replay');\n}\n\nexport { getReplay, replayIntegration };\n//# sourceMappingURL=index.js.map\n","import { addXhrInstrumentationHandler, addPerformanceInstrumentationHandler, extractNetworkProtocol, SENTRY_XHR_DATA_KEY } from '@sentry-internal/browser-utils';\nimport { addFetchEndInstrumentationHandler, addFetchInstrumentationHandler, instrumentFetchRequest, parseUrl, spanToJSON, browserPerformanceTimeOrigin, hasSpansEnabled, setHttpStatus, getActiveSpan, startInactiveSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP, SentryNonRecordingSpan, getClient, getTraceData, getLocationHref, stringMatchesSomePattern } from '@sentry/core';\nimport { WINDOW } from '../helpers.js';\n\n/** Options for Request Instrumentation */\n\nconst responseToSpanId = new WeakMap();\nconst spanIdToEndTimestamp = new Map();\n\nconst defaultRequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n enableHTTPTimings: true,\n trackFetchStreamPerformance: false,\n};\n\n/** Registers span creators for xhr and fetch requests */\nfunction instrumentOutgoingRequests(client, _options) {\n const {\n traceFetch,\n traceXHR,\n trackFetchStreamPerformance,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n tracePropagationTargets,\n } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n trackFetchStreamPerformance: defaultRequestInstrumentationOptions.trackFetchStreamPerformance,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_) => true;\n\n const shouldAttachHeadersWithTargets = (url) => shouldAttachHeaders(url, tracePropagationTargets);\n\n const spans = {};\n\n if (traceFetch) {\n // Keeping track of http requests, whose body payloads resolved later than the initial resolved request\n // e.g. streaming using server sent events (SSE)\n client.addEventProcessor(event => {\n if (event.type === 'transaction' && event.spans) {\n event.spans.forEach(span => {\n if (span.op === 'http.client') {\n const updatedTimestamp = spanIdToEndTimestamp.get(span.span_id);\n if (updatedTimestamp) {\n span.timestamp = updatedTimestamp / 1000;\n spanIdToEndTimestamp.delete(span.span_id);\n }\n }\n });\n }\n return event;\n });\n\n if (trackFetchStreamPerformance) {\n addFetchEndInstrumentationHandler(handlerData => {\n if (handlerData.response) {\n const span = responseToSpanId.get(handlerData.response);\n if (span && handlerData.endTimestamp) {\n spanIdToEndTimestamp.set(span, handlerData.endTimestamp);\n }\n }\n });\n }\n\n addFetchInstrumentationHandler(handlerData => {\n const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n\n if (handlerData.response && handlerData.fetchData.__span) {\n responseToSpanId.set(handlerData.response, handlerData.fetchData.__span);\n }\n\n // We cannot use `window.location` in the generic fetch instrumentation,\n // but we need it for reliable `server.address` attribute.\n // so we extend this in here\n if (createdSpan) {\n const fullUrl = getFullURL(handlerData.fetchData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n createdSpan.setAttributes({\n 'http.url': fullUrl,\n 'server.address': host,\n });\n }\n\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n\n if (traceXHR) {\n addXhrInstrumentationHandler(handlerData => {\n const createdSpan = xhrCallback(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n}\n\nfunction isPerformanceResourceTiming(entry) {\n return (\n entry.entryType === 'resource' &&\n 'initiatorType' in entry &&\n typeof (entry ).nextHopProtocol === 'string' &&\n (entry.initiatorType === 'fetch' || entry.initiatorType === 'xmlhttprequest')\n );\n}\n\n/**\n * Creates a temporary observer to listen to the next fetch/xhr resourcing timings,\n * so that when timings hit their per-browser limit they don't need to be removed.\n *\n * @param span A span that has yet to be finished, must contain `url` on data.\n */\nfunction addHTTPTimings(span) {\n const { url } = spanToJSON(span).data;\n\n if (!url || typeof url !== 'string') {\n return;\n }\n\n const cleanup = addPerformanceInstrumentationHandler('resource', ({ entries }) => {\n entries.forEach(entry => {\n if (isPerformanceResourceTiming(entry) && entry.name.endsWith(url)) {\n const spanData = resourceTimingEntryToSpanData(entry);\n spanData.forEach(data => span.setAttribute(...data));\n // In the next tick, clean this handler up\n // We have to wait here because otherwise this cleans itself up before it is fully done\n setTimeout(cleanup);\n }\n });\n });\n}\n\nfunction getAbsoluteTime(time = 0) {\n return ((browserPerformanceTimeOrigin() || performance.timeOrigin) + time) / 1000;\n}\n\nfunction resourceTimingEntryToSpanData(resourceTiming) {\n const { name, version } = extractNetworkProtocol(resourceTiming.nextHopProtocol);\n\n const timingSpanData = [];\n\n timingSpanData.push(['network.protocol.version', version], ['network.protocol.name', name]);\n\n if (!browserPerformanceTimeOrigin()) {\n return timingSpanData;\n }\n return [\n ...timingSpanData,\n ['http.request.redirect_start', getAbsoluteTime(resourceTiming.redirectStart)],\n ['http.request.fetch_start', getAbsoluteTime(resourceTiming.fetchStart)],\n ['http.request.domain_lookup_start', getAbsoluteTime(resourceTiming.domainLookupStart)],\n ['http.request.domain_lookup_end', getAbsoluteTime(resourceTiming.domainLookupEnd)],\n ['http.request.connect_start', getAbsoluteTime(resourceTiming.connectStart)],\n ['http.request.secure_connection_start', getAbsoluteTime(resourceTiming.secureConnectionStart)],\n ['http.request.connection_end', getAbsoluteTime(resourceTiming.connectEnd)],\n ['http.request.request_start', getAbsoluteTime(resourceTiming.requestStart)],\n ['http.request.response_start', getAbsoluteTime(resourceTiming.responseStart)],\n ['http.request.response_end', getAbsoluteTime(resourceTiming.responseEnd)],\n ];\n}\n\n/**\n * A function that determines whether to attach tracing headers to a request.\n * We only export this function for testing purposes.\n */\nfunction shouldAttachHeaders(\n targetUrl,\n tracePropagationTargets,\n) {\n // window.location.href not being defined is an edge case in the browser but we need to handle it.\n // Potentially dangerous situations where it may not be defined: Browser Extensions, Web Workers, patching of the location obj\n const href = getLocationHref();\n\n if (!href) {\n // If there is no window.location.origin, we default to only attaching tracing headers to relative requests, i.e. ones that start with `/`\n // BIG DISCLAIMER: Users can call URLs with a double slash (fetch(\"//example.com/api\")), this is a shorthand for \"send to the same protocol\",\n // so we need a to exclude those requests, because they might be cross origin.\n const isRelativeSameOriginRequest = !!targetUrl.match(/^\\/(?!\\/)/);\n if (!tracePropagationTargets) {\n return isRelativeSameOriginRequest;\n } else {\n return stringMatchesSomePattern(targetUrl, tracePropagationTargets);\n }\n } else {\n let resolvedUrl;\n let currentOrigin;\n\n // URL parsing may fail, we default to not attaching trace headers in that case.\n try {\n resolvedUrl = new URL(targetUrl, href);\n currentOrigin = new URL(href).origin;\n } catch (e) {\n return false;\n }\n\n const isSameOriginRequest = resolvedUrl.origin === currentOrigin;\n if (!tracePropagationTargets) {\n return isSameOriginRequest;\n } else {\n return (\n stringMatchesSomePattern(resolvedUrl.toString(), tracePropagationTargets) ||\n (isSameOriginRequest && stringMatchesSomePattern(resolvedUrl.pathname, tracePropagationTargets))\n );\n }\n }\n}\n\n/**\n * Create and track xhr request spans\n *\n * @returns Span if a span was created, otherwise void.\n */\nfunction xhrCallback(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n) {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr?.[SENTRY_XHR_DATA_KEY];\n\n if (!xhr || xhr.__sentry_own_request__ || !sentryXhrData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = hasSpansEnabled() && shouldCreateSpan(sentryXhrData.url);\n\n // check first if the request has finished and is tracked by an existing span which should now end\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = xhr.__sentry_xhr_span_id__;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span && sentryXhrData.status_code !== undefined) {\n setHttpStatus(span, sentryXhrData.status_code);\n span.end();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const fullUrl = getFullURL(sentryXhrData.url);\n const host = fullUrl ? parseUrl(fullUrl).host : undefined;\n\n const hasParent = !!getActiveSpan();\n\n const span =\n shouldCreateSpanResult && hasParent\n ? startInactiveSpan({\n name: `${sentryXhrData.method} ${sentryXhrData.url}`,\n attributes: {\n type: 'xhr',\n 'http.method': sentryXhrData.method,\n 'http.url': fullUrl,\n url: sentryXhrData.url,\n 'server.address': host,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.browser',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.client',\n },\n })\n : new SentryNonRecordingSpan();\n\n xhr.__sentry_xhr_span_id__ = span.spanContext().spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n\n if (shouldAttachHeaders(sentryXhrData.url)) {\n addTracingHeadersToXhrRequest(\n xhr,\n // If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction),\n // we do not want to use the span as base for the trace headers,\n // which means that the headers will be generated from the scope and the sampling decision is deferred\n hasSpansEnabled() && hasParent ? span : undefined,\n );\n }\n\n const client = getClient();\n if (client) {\n client.emit('beforeOutgoingRequestSpan', span, handlerData );\n }\n\n return span;\n}\n\nfunction addTracingHeadersToXhrRequest(xhr, span) {\n const { 'sentry-trace': sentryTrace, baggage } = getTraceData({ span });\n\n if (sentryTrace) {\n setHeaderOnXhr(xhr, sentryTrace, baggage);\n }\n}\n\nfunction setHeaderOnXhr(\n xhr,\n sentryTraceHeader,\n sentryBaggageHeader,\n) {\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader('sentry-trace', sentryTraceHeader);\n if (sentryBaggageHeader) {\n // From MDN: \"If this method is called several times with the same header, the values are merged into one single request header.\"\n // We can therefore simply set a baggage header without checking what was there before\n // https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n xhr.setRequestHeader('baggage', sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n}\n\nfunction getFullURL(url) {\n try {\n // By adding a base URL to new URL(), this will also work for relative urls\n // If `url` is a full URL, the base URL is ignored anyhow\n const parsed = new URL(url, WINDOW.location.origin);\n return parsed.href;\n } catch {\n return undefined;\n }\n}\n\nexport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests, shouldAttachHeaders, xhrCallback };\n//# sourceMappingURL=request.js.map\n","import { getActiveSpan, getRootSpan, spanToJSON, logger, SPAN_STATUS_ERROR } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\n\n/**\n * Add a listener that cancels and finishes a transaction when the global\n * document is hidden.\n */\nfunction registerBackgroundTabDetection() {\n if (WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n const activeSpan = getActiveSpan();\n if (!activeSpan) {\n return;\n }\n\n const rootSpan = getRootSpan(activeSpan);\n\n if (WINDOW.document.hidden && rootSpan) {\n const cancelledStatus = 'cancelled';\n\n const { op, status } = spanToJSON(rootSpan);\n\n if (DEBUG_BUILD) {\n logger.log(`[Tracing] Transaction: ${cancelledStatus} -> since tab moved to the background, op: ${op}`);\n }\n\n // We should not set status if it is already set, this prevent important statuses like\n // error or data loss from being overwritten on transaction.\n if (!status) {\n rootSpan.setStatus({ code: SPAN_STATUS_ERROR, message: cancelledStatus });\n }\n\n rootSpan.setAttribute('sentry.cancellation_reason', 'document.hidden');\n rootSpan.end();\n }\n });\n } else {\n DEBUG_BUILD && logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n\nexport { registerBackgroundTabDetection };\n//# sourceMappingURL=backgroundtab.js.map\n","import { startTrackingWebVitals, startTrackingINP, startTrackingLongAnimationFrames, startTrackingLongTasks, startTrackingInteractions, addHistoryInstrumentationHandler, registerInpInteractionListener, addPerformanceEntries } from '@sentry-internal/browser-utils';\nimport { TRACING_DEFAULTS, registerSpanErrorInstrumentation, GLOBAL_OBJ, getLocationHref, getClient, getIsolationScope, generateTraceId, getCurrentScope, propagationContextFromHeaders, browserPerformanceTimeOrigin, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startIdleSpan, spanIsSampled, getDynamicSamplingContextFromSpan, spanToJSON, logger, addNonEnumerableProperty, SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { WINDOW } from '../helpers.js';\nimport { registerBackgroundTabDetection } from './backgroundtab.js';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request.js';\n\n/* eslint-disable max-lines */\n\nconst BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS = {\n ...TRACING_DEFAULTS,\n instrumentNavigation: true,\n instrumentPageLoad: true,\n markBackgroundSpan: true,\n enableLongTask: true,\n enableLongAnimationFrame: true,\n enableInp: true,\n _experiments: {},\n ...defaultRequestInstrumentationOptions,\n};\n\n/**\n * The Browser Tracing integration automatically instruments browser pageload/navigation\n * actions as transactions, and captures requests, metrics and errors as spans.\n *\n * The integration can be configured with a variety of options, and can be extended to use\n * any routing library.\n *\n * We explicitly export the proper type here, as this has to be extended in some cases.\n */\nconst browserTracingIntegration = ((_options = {}) => {\n /**\n * This is just a small wrapper that makes `document` optional.\n * We want to be extra-safe and always check that this exists, to ensure weird environments do not blow up.\n */\n const optionalWindowDocument = WINDOW.document ;\n\n registerSpanErrorInstrumentation();\n\n const {\n enableInp,\n enableLongTask,\n enableLongAnimationFrame,\n _experiments: { enableInteractions, enableStandaloneClsSpans },\n beforeStartSpan,\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n markBackgroundSpan,\n traceFetch,\n traceXHR,\n trackFetchStreamPerformance,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n instrumentPageLoad,\n instrumentNavigation,\n } = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n const _collectWebVitals = startTrackingWebVitals({ recordClsStandaloneSpans: enableStandaloneClsSpans || false });\n\n if (enableInp) {\n startTrackingINP();\n }\n\n if (\n enableLongAnimationFrame &&\n GLOBAL_OBJ.PerformanceObserver &&\n PerformanceObserver.supportedEntryTypes &&\n PerformanceObserver.supportedEntryTypes.includes('long-animation-frame')\n ) {\n startTrackingLongAnimationFrames();\n } else if (enableLongTask) {\n startTrackingLongTasks();\n }\n\n if (enableInteractions) {\n startTrackingInteractions();\n }\n\n const latestRoute = {\n name: undefined,\n source: undefined,\n };\n\n /** Create routing idle transaction. */\n function _createRouteSpan(client, startSpanOptions) {\n const isPageloadTransaction = startSpanOptions.op === 'pageload';\n\n const finalStartSpanOptions = beforeStartSpan\n ? beforeStartSpan(startSpanOptions)\n : startSpanOptions;\n\n const attributes = finalStartSpanOptions.attributes || {};\n\n // If `finalStartSpanOptions.name` is different than `startSpanOptions.name`\n // it is because `beforeStartSpan` set a custom name. Therefore we set the source to 'custom'.\n if (startSpanOptions.name !== finalStartSpanOptions.name) {\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'custom';\n finalStartSpanOptions.attributes = attributes;\n }\n\n latestRoute.name = finalStartSpanOptions.name;\n latestRoute.source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n const idleSpan = startIdleSpan(finalStartSpanOptions, {\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n // should wait for finish signal if it's a pageload transaction\n disableAutoFinish: isPageloadTransaction,\n beforeSpanEnd: span => {\n _collectWebVitals();\n addPerformanceEntries(span, { recordClsOnPageloadSpan: !enableStandaloneClsSpans });\n setActiveIdleSpan(client, undefined);\n\n // A trace should stay consistent over the entire timespan of one route - even after the pageload/navigation ended.\n // Only when another navigation happens, we want to create a new trace.\n // This way, e.g. errors that occur after the pageload span ended are still associated to the pageload trace.\n const scope = getCurrentScope();\n const oldPropagationContext = scope.getPropagationContext();\n\n scope.setPropagationContext({\n ...oldPropagationContext,\n traceId: idleSpan.spanContext().traceId,\n sampled: spanIsSampled(idleSpan),\n dsc: getDynamicSamplingContextFromSpan(span),\n });\n },\n });\n setActiveIdleSpan(client, idleSpan);\n\n function emitFinish() {\n if (optionalWindowDocument && ['interactive', 'complete'].includes(optionalWindowDocument.readyState)) {\n client.emit('idleSpanEnableAutoFinish', idleSpan);\n }\n }\n\n if (isPageloadTransaction && optionalWindowDocument) {\n optionalWindowDocument.addEventListener('readystatechange', () => {\n emitFinish();\n });\n\n emitFinish();\n }\n }\n\n return {\n name: BROWSER_TRACING_INTEGRATION_ID,\n afterAllSetup(client) {\n let startingUrl = getLocationHref();\n\n function maybeEndActiveSpan() {\n const activeSpan = getActiveIdleSpan(client);\n\n if (activeSpan && !spanToJSON(activeSpan).timestamp) {\n DEBUG_BUILD && logger.log(`[Tracing] Finishing current active span with op: ${spanToJSON(activeSpan).op}`);\n // If there's an open active span, we need to finish it before creating an new one.\n activeSpan.end();\n }\n }\n\n client.on('startNavigationSpan', startSpanOptions => {\n if (getClient() !== client) {\n return;\n }\n\n maybeEndActiveSpan();\n\n getIsolationScope().setPropagationContext({ traceId: generateTraceId(), sampleRand: Math.random() });\n getCurrentScope().setPropagationContext({ traceId: generateTraceId(), sampleRand: Math.random() });\n\n _createRouteSpan(client, {\n op: 'navigation',\n ...startSpanOptions,\n });\n });\n\n client.on('startPageLoadSpan', (startSpanOptions, traceOptions = {}) => {\n if (getClient() !== client) {\n return;\n }\n maybeEndActiveSpan();\n\n const sentryTrace = traceOptions.sentryTrace || getMetaContent('sentry-trace');\n const baggage = traceOptions.baggage || getMetaContent('baggage');\n\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n getCurrentScope().setPropagationContext(propagationContext);\n\n _createRouteSpan(client, {\n op: 'pageload',\n ...startSpanOptions,\n });\n });\n\n if (WINDOW.location) {\n if (instrumentPageLoad) {\n const origin = browserPerformanceTimeOrigin();\n startBrowserTracingPageLoadSpan(client, {\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTime: origin ? origin / 1000 : undefined,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.pageload.browser',\n },\n });\n }\n\n if (instrumentNavigation) {\n addHistoryInstrumentationHandler(({ to, from }) => {\n /**\n * This early return is there to account for some cases where a navigation transaction starts right after\n * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't\n * create an uneccessary navigation transaction.\n *\n * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also\n * only be caused in certain development environments where the usage of a hot module reloader is causing\n * errors.\n */\n if (from === undefined && startingUrl?.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n startBrowserTracingNavigationSpan(client, {\n name: WINDOW.location.pathname,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.navigation.browser',\n },\n });\n }\n });\n }\n }\n\n if (markBackgroundSpan) {\n registerBackgroundTabDetection();\n }\n\n if (enableInteractions) {\n registerInteractionListener(client, idleTimeout, finalTimeout, childSpanTimeout, latestRoute);\n }\n\n if (enableInp) {\n registerInpInteractionListener();\n }\n\n instrumentOutgoingRequests(client, {\n traceFetch,\n traceXHR,\n trackFetchStreamPerformance,\n tracePropagationTargets: client.getOptions().tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n });\n },\n };\n}) ;\n\n/**\n * Manually start a page load span.\n * This will only do something if a browser tracing integration integration has been setup.\n *\n * If you provide a custom `traceOptions` object, it will be used to continue the trace\n * instead of the default behavior, which is to look it up on the tags.\n */\nfunction startBrowserTracingPageLoadSpan(\n client,\n spanOptions,\n traceOptions,\n) {\n client.emit('startPageLoadSpan', spanOptions, traceOptions);\n getCurrentScope().setTransactionName(spanOptions.name);\n\n return getActiveIdleSpan(client);\n}\n\n/**\n * Manually start a navigation span.\n * This will only do something if a browser tracing integration has been setup.\n */\nfunction startBrowserTracingNavigationSpan(client, spanOptions) {\n client.emit('startNavigationSpan', spanOptions);\n\n getCurrentScope().setTransactionName(spanOptions.name);\n\n return getActiveIdleSpan(client);\n}\n\n/** Returns the value of a meta tag */\nfunction getMetaContent(metaName) {\n /**\n * This is just a small wrapper that makes `document` optional.\n * We want to be extra-safe and always check that this exists, to ensure weird environments do not blow up.\n */\n const optionalWindowDocument = WINDOW.document ;\n\n const metaTag = optionalWindowDocument?.querySelector(`meta[name=${metaName}]`);\n return metaTag?.getAttribute('content') || undefined;\n}\n\n/** Start listener for interaction transactions */\nfunction registerInteractionListener(\n client,\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n latestRoute,\n) {\n /**\n * This is just a small wrapper that makes `document` optional.\n * We want to be extra-safe and always check that this exists, to ensure weird environments do not blow up.\n */\n const optionalWindowDocument = WINDOW.document ;\n\n let inflightInteractionSpan;\n const registerInteractionTransaction = () => {\n const op = 'ui.action.click';\n\n const activeIdleSpan = getActiveIdleSpan(client);\n if (activeIdleSpan) {\n const currentRootSpanOp = spanToJSON(activeIdleSpan).op;\n if (['navigation', 'pageload'].includes(currentRootSpanOp )) {\n DEBUG_BUILD &&\n logger.warn(`[Tracing] Did not create ${op} span because a pageload or navigation span is in progress.`);\n return undefined;\n }\n }\n\n if (inflightInteractionSpan) {\n inflightInteractionSpan.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, 'interactionInterrupted');\n inflightInteractionSpan.end();\n inflightInteractionSpan = undefined;\n }\n\n if (!latestRoute.name) {\n DEBUG_BUILD && logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n inflightInteractionSpan = startIdleSpan(\n {\n name: latestRoute.name,\n op,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: latestRoute.source || 'url',\n },\n },\n {\n idleTimeout,\n finalTimeout,\n childSpanTimeout,\n },\n );\n };\n\n if (optionalWindowDocument) {\n addEventListener('click', registerInteractionTransaction, { once: false, capture: true });\n }\n}\n\n// We store the active idle span on the client object, so we can access it from exported functions\nconst ACTIVE_IDLE_SPAN_PROPERTY = '_sentry_idleSpan';\nfunction getActiveIdleSpan(client) {\n return (client )[ACTIVE_IDLE_SPAN_PROPERTY];\n}\n\nfunction setActiveIdleSpan(client, span) {\n addNonEnumerableProperty(client, ACTIVE_IDLE_SPAN_PROPERTY, span);\n}\n\nexport { BROWSER_TRACING_INTEGRATION_ID, browserTracingIntegration, getMetaContent, startBrowserTracingNavigationSpan, startBrowserTracingPageLoadSpan };\n//# sourceMappingURL=browserTracingIntegration.js.map\n","import { setContext, init as init$1 } from '@sentry/browser';\nimport { applySdkMetadata } from '@sentry/core';\nimport { version } from 'react';\n\n/**\n * Inits the React SDK\n */\nfunction init(options) {\n const opts = {\n ...options,\n };\n\n applySdkMetadata(opts, 'react');\n setContext('react', { version });\n return init$1(opts);\n}\n\nexport { init };\n//# sourceMappingURL=sdk.js.map\n","/** @license React v16.13.1\n * react-is.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\n'use strict';var b=\"function\"===typeof Symbol&&Symbol.for,c=b?Symbol.for(\"react.element\"):60103,d=b?Symbol.for(\"react.portal\"):60106,e=b?Symbol.for(\"react.fragment\"):60107,f=b?Symbol.for(\"react.strict_mode\"):60108,g=b?Symbol.for(\"react.profiler\"):60114,h=b?Symbol.for(\"react.provider\"):60109,k=b?Symbol.for(\"react.context\"):60110,l=b?Symbol.for(\"react.async_mode\"):60111,m=b?Symbol.for(\"react.concurrent_mode\"):60111,n=b?Symbol.for(\"react.forward_ref\"):60112,p=b?Symbol.for(\"react.suspense\"):60113,q=b?\nSymbol.for(\"react.suspense_list\"):60120,r=b?Symbol.for(\"react.memo\"):60115,t=b?Symbol.for(\"react.lazy\"):60116,v=b?Symbol.for(\"react.block\"):60121,w=b?Symbol.for(\"react.fundamental\"):60117,x=b?Symbol.for(\"react.responder\"):60118,y=b?Symbol.for(\"react.scope\"):60119;\nfunction z(a){if(\"object\"===typeof a&&null!==a){var u=a.$$typeof;switch(u){case c:switch(a=a.type,a){case l:case m:case e:case g:case f:case p:return a;default:switch(a=a&&a.$$typeof,a){case k:case n:case t:case r:case h:return a;default:return u}}case d:return u}}}function A(a){return z(a)===m}exports.AsyncMode=l;exports.ConcurrentMode=m;exports.ContextConsumer=k;exports.ContextProvider=h;exports.Element=c;exports.ForwardRef=n;exports.Fragment=e;exports.Lazy=t;exports.Memo=r;exports.Portal=d;\nexports.Profiler=g;exports.StrictMode=f;exports.Suspense=p;exports.isAsyncMode=function(a){return A(a)||z(a)===l};exports.isConcurrentMode=A;exports.isContextConsumer=function(a){return z(a)===k};exports.isContextProvider=function(a){return z(a)===h};exports.isElement=function(a){return\"object\"===typeof a&&null!==a&&a.$$typeof===c};exports.isForwardRef=function(a){return z(a)===n};exports.isFragment=function(a){return z(a)===e};exports.isLazy=function(a){return z(a)===t};\nexports.isMemo=function(a){return z(a)===r};exports.isPortal=function(a){return z(a)===d};exports.isProfiler=function(a){return z(a)===g};exports.isStrictMode=function(a){return z(a)===f};exports.isSuspense=function(a){return z(a)===p};\nexports.isValidElementType=function(a){return\"string\"===typeof a||\"function\"===typeof a||a===e||a===m||a===g||a===f||a===p||a===q||\"object\"===typeof a&&null!==a&&(a.$$typeof===t||a.$$typeof===r||a.$$typeof===h||a.$$typeof===k||a.$$typeof===n||a.$$typeof===w||a.$$typeof===x||a.$$typeof===y||a.$$typeof===v)};exports.typeOf=z;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-is.production.min.js');\n} else {\n module.exports = require('./cjs/react-is.development.js');\n}\n","'use strict';\n\nvar reactIs = require('react-is');\n\n/**\n * Copyright 2015, Yahoo! Inc.\n * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.\n */\nvar REACT_STATICS = {\n childContextTypes: true,\n contextType: true,\n contextTypes: true,\n defaultProps: true,\n displayName: true,\n getDefaultProps: true,\n getDerivedStateFromError: true,\n getDerivedStateFromProps: true,\n mixins: true,\n propTypes: true,\n type: true\n};\nvar KNOWN_STATICS = {\n name: true,\n length: true,\n prototype: true,\n caller: true,\n callee: true,\n arguments: true,\n arity: true\n};\nvar FORWARD_REF_STATICS = {\n '$$typeof': true,\n render: true,\n defaultProps: true,\n displayName: true,\n propTypes: true\n};\nvar MEMO_STATICS = {\n '$$typeof': true,\n compare: true,\n defaultProps: true,\n displayName: true,\n propTypes: true,\n type: true\n};\nvar TYPE_STATICS = {};\nTYPE_STATICS[reactIs.ForwardRef] = FORWARD_REF_STATICS;\nTYPE_STATICS[reactIs.Memo] = MEMO_STATICS;\n\nfunction getStatics(component) {\n // React v16.11 and below\n if (reactIs.isMemo(component)) {\n return MEMO_STATICS;\n } // React v16.12 and above\n\n\n return TYPE_STATICS[component['$$typeof']] || REACT_STATICS;\n}\n\nvar defineProperty = Object.defineProperty;\nvar getOwnPropertyNames = Object.getOwnPropertyNames;\nvar getOwnPropertySymbols = Object.getOwnPropertySymbols;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar getPrototypeOf = Object.getPrototypeOf;\nvar objectPrototype = Object.prototype;\nfunction hoistNonReactStatics(targetComponent, sourceComponent, blacklist) {\n if (typeof sourceComponent !== 'string') {\n // don't hoist over string (html) components\n if (objectPrototype) {\n var inheritedComponent = getPrototypeOf(sourceComponent);\n\n if (inheritedComponent && inheritedComponent !== objectPrototype) {\n hoistNonReactStatics(targetComponent, inheritedComponent, blacklist);\n }\n }\n\n var keys = getOwnPropertyNames(sourceComponent);\n\n if (getOwnPropertySymbols) {\n keys = keys.concat(getOwnPropertySymbols(sourceComponent));\n }\n\n var targetStatics = getStatics(targetComponent);\n var sourceStatics = getStatics(sourceComponent);\n\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n\n if (!KNOWN_STATICS[key] && !(blacklist && blacklist[key]) && !(sourceStatics && sourceStatics[key]) && !(targetStatics && targetStatics[key])) {\n var descriptor = getOwnPropertyDescriptor(sourceComponent, key);\n\n try {\n // Avoid failures from read-only properties\n defineProperty(targetComponent, key, descriptor);\n } catch (e) {}\n }\n }\n }\n\n return targetComponent;\n}\n\nmodule.exports = hoistNonReactStatics;\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Logging constants\nconst AWS_CLOUDWATCH_CATEGORY = 'Logging';\nconst USER_AGENT_HEADER = 'x-amz-user-agent';\n// Error exception code constants\nconst NO_HUBCALLBACK_PROVIDED_EXCEPTION = 'NoHubcallbackProvidedException';\n\nexport { AWS_CLOUDWATCH_CATEGORY, NO_HUBCALLBACK_PROVIDED_EXCEPTION, USER_AGENT_HEADER };\n//# sourceMappingURL=constants.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nvar LogType;\n(function (LogType) {\n LogType[\"DEBUG\"] = \"DEBUG\";\n LogType[\"ERROR\"] = \"ERROR\";\n LogType[\"INFO\"] = \"INFO\";\n LogType[\"WARN\"] = \"WARN\";\n LogType[\"VERBOSE\"] = \"VERBOSE\";\n LogType[\"NONE\"] = \"NONE\";\n})(LogType || (LogType = {}));\n\nexport { LogType };\n//# sourceMappingURL=types.mjs.map\n","import { AWS_CLOUDWATCH_CATEGORY } from '../constants.mjs';\nimport { LogType } from './types.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst LOG_LEVELS = {\n VERBOSE: 1,\n DEBUG: 2,\n INFO: 3,\n WARN: 4,\n ERROR: 5,\n NONE: 6,\n};\n/**\n * Write logs\n * @class Logger\n */\nclass ConsoleLogger {\n /**\n * @constructor\n * @param {string} name - Name of the logger\n */\n constructor(name, level = LogType.WARN) {\n this.name = name;\n this.level = level;\n this._pluggables = [];\n }\n _padding(n) {\n return n < 10 ? '0' + n : '' + n;\n }\n _ts() {\n const dt = new Date();\n return ([this._padding(dt.getMinutes()), this._padding(dt.getSeconds())].join(':') +\n '.' +\n dt.getMilliseconds());\n }\n configure(config) {\n if (!config)\n return this._config;\n this._config = config;\n return this._config;\n }\n /**\n * Write log\n * @method\n * @memeberof Logger\n * @param {LogType|string} type - log type, default INFO\n * @param {string|object} msg - Logging message or object\n */\n _log(type, ...msg) {\n let loggerLevelName = this.level;\n if (ConsoleLogger.LOG_LEVEL) {\n loggerLevelName = ConsoleLogger.LOG_LEVEL;\n }\n if (typeof window !== 'undefined' && window.LOG_LEVEL) {\n loggerLevelName = window.LOG_LEVEL;\n }\n const loggerLevel = LOG_LEVELS[loggerLevelName];\n const typeLevel = LOG_LEVELS[type];\n if (!(typeLevel >= loggerLevel)) {\n // Do nothing if type is not greater than or equal to logger level (handle undefined)\n return;\n }\n let log = console.log.bind(console);\n if (type === LogType.ERROR && console.error) {\n log = console.error.bind(console);\n }\n if (type === LogType.WARN && console.warn) {\n log = console.warn.bind(console);\n }\n if (ConsoleLogger.BIND_ALL_LOG_LEVELS) {\n if (type === LogType.INFO && console.info) {\n log = console.info.bind(console);\n }\n if (type === LogType.DEBUG && console.debug) {\n log = console.debug.bind(console);\n }\n }\n const prefix = `[${type}] ${this._ts()} ${this.name}`;\n let message = '';\n if (msg.length === 1 && typeof msg[0] === 'string') {\n message = `${prefix} - ${msg[0]}`;\n log(message);\n }\n else if (msg.length === 1) {\n message = `${prefix} ${msg[0]}`;\n log(prefix, msg[0]);\n }\n else if (typeof msg[0] === 'string') {\n let obj = msg.slice(1);\n if (obj.length === 1) {\n obj = obj[0];\n }\n message = `${prefix} - ${msg[0]} ${obj}`;\n log(`${prefix} - ${msg[0]}`, obj);\n }\n else {\n message = `${prefix} ${msg}`;\n log(prefix, msg);\n }\n for (const plugin of this._pluggables) {\n const logEvent = { message, timestamp: Date.now() };\n plugin.pushLogs([logEvent]);\n }\n }\n /**\n * Write General log. Default to INFO\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n log(...msg) {\n this._log(LogType.INFO, ...msg);\n }\n /**\n * Write INFO log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n info(...msg) {\n this._log(LogType.INFO, ...msg);\n }\n /**\n * Write WARN log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n warn(...msg) {\n this._log(LogType.WARN, ...msg);\n }\n /**\n * Write ERROR log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n error(...msg) {\n this._log(LogType.ERROR, ...msg);\n }\n /**\n * Write DEBUG log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n debug(...msg) {\n this._log(LogType.DEBUG, ...msg);\n }\n /**\n * Write VERBOSE log\n * @method\n * @memeberof Logger\n * @param {string|object} msg - Logging message or object\n */\n verbose(...msg) {\n this._log(LogType.VERBOSE, ...msg);\n }\n addPluggable(pluggable) {\n if (pluggable && pluggable.getCategoryName() === AWS_CLOUDWATCH_CATEGORY) {\n this._pluggables.push(pluggable);\n pluggable.configure(this._config);\n }\n }\n listPluggables() {\n return this._pluggables;\n }\n}\nConsoleLogger.LOG_LEVEL = null;\nConsoleLogger.BIND_ALL_LOG_LEVELS = false;\n\nexport { ConsoleLogger };\n//# sourceMappingURL=ConsoleLogger.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass AmplifyError extends Error {\n /**\n * Constructs an AmplifyError.\n *\n * @param message text that describes the main problem.\n * @param underlyingError the underlying cause of the error.\n * @param recoverySuggestion suggestion to recover from the error.\n *\n */\n constructor({ message, name, recoverySuggestion, underlyingError, }) {\n super(message);\n this.name = name;\n this.underlyingError = underlyingError;\n this.recoverySuggestion = recoverySuggestion;\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n this.constructor = AmplifyError;\n Object.setPrototypeOf(this, AmplifyError.prototype);\n }\n}\n\nexport { AmplifyError };\n//# sourceMappingURL=AmplifyError.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nvar AmplifyErrorCode;\n(function (AmplifyErrorCode) {\n AmplifyErrorCode[\"NoEndpointId\"] = \"NoEndpointId\";\n AmplifyErrorCode[\"PlatformNotSupported\"] = \"PlatformNotSupported\";\n AmplifyErrorCode[\"Unknown\"] = \"Unknown\";\n AmplifyErrorCode[\"NetworkError\"] = \"NetworkError\";\n})(AmplifyErrorCode || (AmplifyErrorCode = {}));\n\nexport { AmplifyErrorCode };\n//# sourceMappingURL=errors.mjs.map\n","import { AmplifyError } from './AmplifyError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createAssertionFunction = (errorMap, AssertionError = AmplifyError) => (assertion, name, additionalContext) => {\n const { message, recoverySuggestion } = errorMap[name];\n if (!assertion) {\n throw new AssertionError({\n name,\n message: additionalContext\n ? `${message} ${additionalContext}`\n : message,\n recoverySuggestion,\n });\n }\n};\n\nexport { createAssertionFunction };\n//# sourceMappingURL=createAssertionFunction.mjs.map\n","import { ConsoleLogger } from '../Logger/ConsoleLogger.mjs';\nimport { NO_HUBCALLBACK_PROVIDED_EXCEPTION } from '../constants.mjs';\nimport { AmplifyError } from '../errors/AmplifyError.mjs';\nimport '../types/errors.mjs';\nimport '../errors/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined'\n ? Symbol('amplify_default')\n : '@@amplify_default');\nconst logger = new ConsoleLogger('Hub');\nclass HubClass {\n constructor(name) {\n this.listeners = new Map();\n this.protectedChannels = [\n 'core',\n 'auth',\n 'api',\n 'analytics',\n 'interactions',\n 'pubsub',\n 'storage',\n 'ui',\n 'xr',\n ];\n this.name = name;\n }\n /**\n * Used internally to remove a Hub listener.\n *\n * @remarks\n * This private method is for internal use only. Instead of calling Hub.remove, call the result of Hub.listen.\n */\n _remove(channel, listener) {\n const holder = this.listeners.get(channel);\n if (!holder) {\n logger.warn(`No listeners for ${channel}`);\n return;\n }\n this.listeners.set(channel, [\n ...holder.filter(({ callback }) => callback !== listener),\n ]);\n }\n dispatch(channel, payload, source, ampSymbol) {\n if (typeof channel === 'string' &&\n this.protectedChannels.indexOf(channel) > -1) {\n const hasAccess = ampSymbol === AMPLIFY_SYMBOL;\n if (!hasAccess) {\n logger.warn(`WARNING: ${channel} is protected and dispatching on it can have unintended consequences`);\n }\n }\n const capsule = {\n channel,\n payload: { ...payload },\n source,\n patternInfo: [],\n };\n try {\n this._toListeners(capsule);\n }\n catch (e) {\n logger.error(e);\n }\n }\n listen(channel, callback, listenerName = 'noname') {\n let cb;\n if (typeof callback !== 'function') {\n throw new AmplifyError({\n name: NO_HUBCALLBACK_PROVIDED_EXCEPTION,\n message: 'No callback supplied to Hub',\n });\n }\n else {\n // Needs to be casted as a more generic type\n cb = callback;\n }\n let holder = this.listeners.get(channel);\n if (!holder) {\n holder = [];\n this.listeners.set(channel, holder);\n }\n holder.push({\n name: listenerName,\n callback: cb,\n });\n return () => {\n this._remove(channel, cb);\n };\n }\n _toListeners(capsule) {\n const { channel, payload } = capsule;\n const holder = this.listeners.get(channel);\n if (holder) {\n holder.forEach(listener => {\n logger.debug(`Dispatching to ${channel} with `, payload);\n try {\n listener.callback(capsule);\n }\n catch (e) {\n logger.error(e);\n }\n });\n }\n }\n}\n/* We export a __default__ instance of HubClass to use it as a\npseudo Singleton for the main messaging bus, however you can still create\nyour own instance of HubClass() for a separate \"private bus\" of events. */\nconst Hub = new HubClass('__default__');\n/**\n * @internal\n *\n * Internal hub used for core Amplify functionality. Not intended for use outside of Amplify.\n *\n */\nconst HubInternal = new HubClass('internal-hub');\n\nexport { AMPLIFY_SYMBOL, Hub, HubClass, HubInternal };\n//# sourceMappingURL=index.mjs.map\n","import { AmplifyError } from '../../errors/AmplifyError.mjs';\nimport '../../types/errors.mjs';\nimport '../../errors/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst getCrypto = () => {\n if (typeof window === 'object' && typeof window.crypto === 'object') {\n return window.crypto;\n }\n // Next.js global polyfill\n if (typeof crypto === 'object') {\n return crypto;\n }\n throw new AmplifyError({\n name: 'MissingPolyfill',\n message: 'Cannot resolve the `crypto` function from the environment.',\n });\n};\nconst getBtoa = () => {\n // browser\n if (typeof window !== 'undefined' && typeof window.btoa === 'function') {\n return window.btoa;\n }\n // Next.js global polyfill\n if (typeof btoa === 'function') {\n return btoa;\n }\n throw new AmplifyError({\n name: 'Base64EncoderError',\n message: 'Cannot resolve the `btoa` function from the environment.',\n });\n};\nconst getAtob = () => {\n // browser\n if (typeof window !== 'undefined' && typeof window.atob === 'function') {\n return window.atob;\n }\n // Next.js global polyfill\n if (typeof atob === 'function') {\n return atob;\n }\n throw new AmplifyError({\n name: 'Base64EncoderError',\n message: 'Cannot resolve the `atob` function from the environment.',\n });\n};\n\nexport { getAtob, getBtoa, getCrypto };\n//# sourceMappingURL=index.mjs.map\n","import { getAtob } from '../../globalHelpers/index.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst base64Decoder = {\n convert(input, options) {\n let inputStr = input;\n // urlSafe character replacement options conform to the base64 url spec\n // https://datatracker.ietf.org/doc/html/rfc4648#page-7\n if (options?.urlSafe) {\n inputStr = inputStr.replace(/-/g, '+').replace(/_/g, '/');\n }\n return getAtob()(inputStr);\n },\n};\n\nexport { base64Decoder };\n//# sourceMappingURL=base64Decoder.mjs.map\n","import { createAssertionFunction } from '../../../errors/createAssertionFunction.mjs';\nimport '../../../types/errors.mjs';\nimport '../../../errors/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nvar AuthConfigurationErrorCode;\n(function (AuthConfigurationErrorCode) {\n AuthConfigurationErrorCode[\"AuthTokenConfigException\"] = \"AuthTokenConfigException\";\n AuthConfigurationErrorCode[\"AuthUserPoolAndIdentityPoolException\"] = \"AuthUserPoolAndIdentityPoolException\";\n AuthConfigurationErrorCode[\"AuthUserPoolException\"] = \"AuthUserPoolException\";\n AuthConfigurationErrorCode[\"InvalidIdentityPoolIdException\"] = \"InvalidIdentityPoolIdException\";\n AuthConfigurationErrorCode[\"OAuthNotConfigureException\"] = \"OAuthNotConfigureException\";\n})(AuthConfigurationErrorCode || (AuthConfigurationErrorCode = {}));\nconst authConfigurationErrorMap = {\n [AuthConfigurationErrorCode.AuthTokenConfigException]: {\n message: 'Auth Token Provider not configured.',\n recoverySuggestion: 'Make sure to call Amplify.configure in your app.',\n },\n [AuthConfigurationErrorCode.AuthUserPoolAndIdentityPoolException]: {\n message: 'Auth UserPool or IdentityPool not configured.',\n recoverySuggestion: 'Make sure to call Amplify.configure in your app with UserPoolId and IdentityPoolId.',\n },\n [AuthConfigurationErrorCode.AuthUserPoolException]: {\n message: 'Auth UserPool not configured.',\n recoverySuggestion: 'Make sure to call Amplify.configure in your app with userPoolId and userPoolClientId.',\n },\n [AuthConfigurationErrorCode.InvalidIdentityPoolIdException]: {\n message: 'Invalid identity pool id provided.',\n recoverySuggestion: 'Make sure a valid identityPoolId is given in the config.',\n },\n [AuthConfigurationErrorCode.OAuthNotConfigureException]: {\n message: 'oauth param not configured.',\n recoverySuggestion: 'Make sure to call Amplify.configure with oauth parameter in your app.',\n },\n};\nconst assert = createAssertionFunction(authConfigurationErrorMap);\n\nexport { AuthConfigurationErrorCode, assert };\n//# sourceMappingURL=errorHelpers.mjs.map\n","import { base64Decoder } from '../../../utils/convert/base64/base64Decoder.mjs';\nimport '../../../types/errors.mjs';\nimport '../../../errors/errorHelpers.mjs';\nimport { assert, AuthConfigurationErrorCode } from './errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction assertTokenProviderConfig(cognitoConfig) {\n let assertionValid = true; // assume valid until otherwise proveed\n if (!cognitoConfig) {\n assertionValid = false;\n }\n else {\n assertionValid =\n !!cognitoConfig.userPoolId && !!cognitoConfig.userPoolClientId;\n }\n assert(assertionValid, AuthConfigurationErrorCode.AuthUserPoolException);\n}\nfunction assertOAuthConfig(cognitoConfig) {\n const validOAuthConfig = !!cognitoConfig?.loginWith?.oauth?.domain &&\n !!cognitoConfig?.loginWith?.oauth?.redirectSignOut &&\n !!cognitoConfig?.loginWith?.oauth?.redirectSignIn &&\n !!cognitoConfig?.loginWith?.oauth?.responseType;\n assert(validOAuthConfig, AuthConfigurationErrorCode.OAuthNotConfigureException);\n}\nfunction assertIdentityPoolIdConfig(cognitoConfig) {\n const validConfig = !!cognitoConfig?.identityPoolId;\n assert(validConfig, AuthConfigurationErrorCode.InvalidIdentityPoolIdException);\n}\n/**\n * Decodes payload of JWT token\n *\n * @param {String} token A string representing a token to be decoded\n * @throws {@link Error} - Throws error when token is invalid or payload malformed.\n */\nfunction decodeJWT(token) {\n const tokenParts = token.split('.');\n if (tokenParts.length !== 3) {\n throw new Error('Invalid token');\n }\n try {\n const base64WithUrlSafe = tokenParts[1];\n const base64 = base64WithUrlSafe.replace(/-/g, '+').replace(/_/g, '/');\n const jsonStr = decodeURIComponent(base64Decoder\n .convert(base64)\n .split('')\n .map(char => `%${`00${char.charCodeAt(0).toString(16)}`.slice(-2)}`)\n .join(''));\n const payload = JSON.parse(jsonStr);\n return {\n toString: () => token,\n payload,\n };\n }\n catch (err) {\n throw new Error('Invalid token payload');\n }\n}\n\nexport { assertIdentityPoolIdConfig, assertOAuthConfig, assertTokenProviderConfig, decodeJWT };\n//# sourceMappingURL=index.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst isNonRetryableError = (obj) => {\n const key = 'nonRetryable';\n return obj && obj[key];\n};\n\nexport { isNonRetryableError };\n//# sourceMappingURL=isNonRetryableError.mjs.map\n","import { ConsoleLogger } from '../../Logger/ConsoleLogger.mjs';\nimport { isNonRetryableError } from './isNonRetryableError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('retryUtil');\n/**\n * @private\n * Internal use of Amplify only\n */\nasync function retry(functionToRetry, args, delayFn, onTerminate) {\n if (typeof functionToRetry !== 'function') {\n throw Error('functionToRetry must be a function');\n }\n // TODO(eslint): remove this linter suppression with refactoring.\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve, reject) => {\n let attempt = 0;\n let terminated = false;\n let timeout;\n let wakeUp = () => {\n // no-op\n }; // will be replaced with a resolver()\n // used after the loop if terminated while waiting for a timer.\n let lastError;\n onTerminate &&\n onTerminate.then(() => {\n // signal not to try anymore.\n terminated = true;\n // stop sleeping if we're sleeping.\n clearTimeout(timeout);\n wakeUp();\n });\n // TODO(eslint): remove this linter suppression with refactoring.\n // eslint-disable-next-line no-unmodified-loop-condition\n while (!terminated) {\n attempt++;\n logger.debug(`${functionToRetry.name} attempt #${attempt} with this vars: ${JSON.stringify(args)}`);\n try {\n resolve(await functionToRetry(...args));\n return;\n }\n catch (err) {\n lastError = err;\n logger.debug(`error on ${functionToRetry.name}`, err);\n if (isNonRetryableError(err)) {\n logger.debug(`${functionToRetry.name} non retryable error`, err);\n reject(err);\n return;\n }\n const retryIn = delayFn(attempt, args, err);\n logger.debug(`${functionToRetry.name} retrying in ${retryIn} ms`);\n // we check `terminated` again here because it could have flipped\n // in the time it took `functionToRetry` to return.\n if (retryIn === false || terminated) {\n reject(err);\n return;\n }\n else {\n await new Promise(_resolve => {\n wakeUp = _resolve; // export wakeUp for onTerminate handling\n timeout = setTimeout(wakeUp, retryIn);\n });\n }\n }\n }\n // reached if terminated while waiting for a timer.\n reject(lastError);\n });\n}\n\nexport { retry };\n//# sourceMappingURL=retry.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst deepFreeze = (object) => {\n const propNames = Reflect.ownKeys(object);\n for (const name of propNames) {\n const value = object[name];\n if ((value && typeof value === 'object') || typeof value === 'function') {\n deepFreeze(value);\n }\n }\n return Object.freeze(object);\n};\n\nexport { deepFreeze };\n//# sourceMappingURL=deepFreeze.mjs.map\n","import { ConsoleLogger } from './Logger/ConsoleLogger.mjs';\nimport { AmplifyError } from './errors/AmplifyError.mjs';\nimport './types/errors.mjs';\nimport './errors/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('parseAWSExports');\nconst authTypeMapping = {\n API_KEY: 'apiKey',\n AWS_IAM: 'iam',\n AMAZON_COGNITO_USER_POOLS: 'userPool',\n OPENID_CONNECT: 'oidc',\n NONE: 'none',\n AWS_LAMBDA: 'lambda',\n // `LAMBDA` is an incorrect value that was added during the v6 rewrite.\n // Keeping it as a valid value until v7 to prevent breaking customers who might\n // be relying on it as a workaround.\n // ref: https://github.com/aws-amplify/amplify-js/pull/12922\n // TODO: @v7 remove next line\n LAMBDA: 'lambda',\n};\n/**\n * Converts the object imported from `aws-exports.js` or `amplifyconfiguration.json` files generated by\n * the Amplify CLI into an object that conforms to the {@link ResourcesConfig}.\n *\n * @param config A configuration object imported from `aws-exports.js` or `amplifyconfiguration.json`.\n *\n * @returns An object that conforms to the {@link ResourcesConfig} .\n */\nconst parseAWSExports = (config = {}) => {\n if (!Object.prototype.hasOwnProperty.call(config, 'aws_project_region')) {\n throw new AmplifyError({\n name: 'InvalidParameterException',\n message: 'Invalid config parameter.',\n recoverySuggestion: 'Ensure passing the config object imported from `amplifyconfiguration.json`.',\n });\n }\n const { aws_appsync_apiKey, aws_appsync_authenticationType, aws_appsync_graphqlEndpoint, aws_appsync_region, aws_bots_config, aws_cognito_identity_pool_id, aws_cognito_sign_up_verification_method, aws_cognito_mfa_configuration, aws_cognito_mfa_types, aws_cognito_password_protection_settings, aws_cognito_verification_mechanisms, aws_cognito_signup_attributes, aws_cognito_social_providers, aws_cognito_username_attributes, aws_mandatory_sign_in, aws_mobile_analytics_app_id, aws_mobile_analytics_app_region, aws_user_files_s3_bucket, aws_user_files_s3_bucket_region, aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing, aws_user_pools_id, aws_user_pools_web_client_id, geo, oauth, predictions, aws_cloud_logic_custom, Notifications, modelIntrospection, } = config;\n const amplifyConfig = {};\n // Analytics\n if (aws_mobile_analytics_app_id) {\n amplifyConfig.Analytics = {\n Pinpoint: {\n appId: aws_mobile_analytics_app_id,\n region: aws_mobile_analytics_app_region,\n },\n };\n }\n // Notifications\n const { InAppMessaging, Push } = Notifications ?? {};\n if (InAppMessaging?.AWSPinpoint || Push?.AWSPinpoint) {\n if (InAppMessaging?.AWSPinpoint) {\n const { appId, region } = InAppMessaging.AWSPinpoint;\n amplifyConfig.Notifications = {\n InAppMessaging: {\n Pinpoint: {\n appId,\n region,\n },\n },\n };\n }\n if (Push?.AWSPinpoint) {\n const { appId, region } = Push.AWSPinpoint;\n amplifyConfig.Notifications = {\n ...amplifyConfig.Notifications,\n PushNotification: {\n Pinpoint: {\n appId,\n region,\n },\n },\n };\n }\n }\n // Interactions\n if (Array.isArray(aws_bots_config)) {\n amplifyConfig.Interactions = {\n LexV1: Object.fromEntries(aws_bots_config.map(bot => [bot.name, bot])),\n };\n }\n // API\n if (aws_appsync_graphqlEndpoint) {\n const defaultAuthMode = authTypeMapping[aws_appsync_authenticationType];\n if (!defaultAuthMode) {\n logger.debug(`Invalid authentication type ${aws_appsync_authenticationType}. Falling back to IAM.`);\n }\n amplifyConfig.API = {\n GraphQL: {\n endpoint: aws_appsync_graphqlEndpoint,\n apiKey: aws_appsync_apiKey,\n region: aws_appsync_region,\n defaultAuthMode: defaultAuthMode ?? 'iam',\n },\n };\n if (modelIntrospection) {\n amplifyConfig.API.GraphQL.modelIntrospection = modelIntrospection;\n }\n }\n // Auth\n const mfaConfig = aws_cognito_mfa_configuration\n ? {\n status: aws_cognito_mfa_configuration &&\n aws_cognito_mfa_configuration.toLowerCase(),\n totpEnabled: aws_cognito_mfa_types?.includes('TOTP') ?? false,\n smsEnabled: aws_cognito_mfa_types?.includes('SMS') ?? false,\n }\n : undefined;\n const passwordFormatConfig = aws_cognito_password_protection_settings\n ? {\n minLength: aws_cognito_password_protection_settings.passwordPolicyMinLength,\n requireLowercase: aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes('REQUIRES_LOWERCASE') ?? false,\n requireUppercase: aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes('REQUIRES_UPPERCASE') ?? false,\n requireNumbers: aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes('REQUIRES_NUMBERS') ?? false,\n requireSpecialCharacters: aws_cognito_password_protection_settings.passwordPolicyCharacters?.includes('REQUIRES_SYMBOLS') ?? false,\n }\n : undefined;\n const mergedUserAttributes = Array.from(new Set([\n ...(aws_cognito_verification_mechanisms ?? []),\n ...(aws_cognito_signup_attributes ?? []),\n ]));\n const userAttributes = mergedUserAttributes.reduce((attributes, key) => ({\n ...attributes,\n // All user attributes generated by the CLI are required\n [key.toLowerCase()]: { required: true },\n }), {});\n const loginWithEmailEnabled = aws_cognito_username_attributes?.includes('EMAIL') ?? false;\n const loginWithPhoneEnabled = aws_cognito_username_attributes?.includes('PHONE_NUMBER') ?? false;\n if (aws_cognito_identity_pool_id || aws_user_pools_id) {\n amplifyConfig.Auth = {\n Cognito: {\n identityPoolId: aws_cognito_identity_pool_id,\n allowGuestAccess: aws_mandatory_sign_in !== 'enable',\n signUpVerificationMethod: aws_cognito_sign_up_verification_method,\n userAttributes,\n userPoolClientId: aws_user_pools_web_client_id,\n userPoolId: aws_user_pools_id,\n mfa: mfaConfig,\n passwordFormat: passwordFormatConfig,\n loginWith: {\n username: !(loginWithEmailEnabled || loginWithPhoneEnabled),\n email: loginWithEmailEnabled,\n phone: loginWithPhoneEnabled,\n },\n },\n };\n }\n const hasOAuthConfig = oauth ? Object.keys(oauth).length > 0 : false;\n const hasSocialProviderConfig = aws_cognito_social_providers\n ? aws_cognito_social_providers.length > 0\n : false;\n if (amplifyConfig.Auth && hasOAuthConfig) {\n amplifyConfig.Auth.Cognito.loginWith = {\n ...amplifyConfig.Auth.Cognito.loginWith,\n oauth: {\n ...getOAuthConfig(oauth),\n ...(hasSocialProviderConfig && {\n providers: parseSocialProviders(aws_cognito_social_providers),\n }),\n },\n };\n }\n // Storage\n if (aws_user_files_s3_bucket) {\n amplifyConfig.Storage = {\n S3: {\n bucket: aws_user_files_s3_bucket,\n region: aws_user_files_s3_bucket_region,\n dangerouslyConnectToHttpEndpointForTesting: aws_user_files_s3_dangerously_connect_to_http_endpoint_for_testing,\n },\n };\n }\n // Geo\n if (geo) {\n const { amazon_location_service } = geo;\n amplifyConfig.Geo = {\n LocationService: {\n maps: amazon_location_service.maps,\n geofenceCollections: amazon_location_service.geofenceCollections,\n searchIndices: amazon_location_service.search_indices,\n region: amazon_location_service.region,\n },\n };\n }\n // REST API\n if (aws_cloud_logic_custom) {\n amplifyConfig.API = {\n ...amplifyConfig.API,\n REST: aws_cloud_logic_custom.reduce((acc, api) => {\n const { name, endpoint, region, service } = api;\n return {\n ...acc,\n [name]: {\n endpoint,\n ...(service ? { service } : undefined),\n ...(region ? { region } : undefined),\n },\n };\n }, {}),\n };\n }\n // Predictions\n if (predictions) {\n // map VoiceId from speechGenerator defaults to voiceId\n const { VoiceId: voiceId } = predictions?.convert?.speechGenerator?.defaults ?? {};\n amplifyConfig.Predictions = voiceId\n ? {\n ...predictions,\n convert: {\n ...predictions.convert,\n speechGenerator: {\n ...predictions.convert.speechGenerator,\n defaults: { voiceId },\n },\n },\n }\n : predictions;\n }\n return amplifyConfig;\n};\nconst getRedirectUrl = (redirectStr) => redirectStr?.split(',') ?? [];\nconst getOAuthConfig = ({ domain, scope, redirectSignIn, redirectSignOut, responseType, }) => ({\n domain,\n scopes: scope,\n redirectSignIn: getRedirectUrl(redirectSignIn),\n redirectSignOut: getRedirectUrl(redirectSignOut),\n responseType,\n});\nconst parseSocialProviders = (aws_cognito_social_providers) => {\n return aws_cognito_social_providers.map((provider) => {\n const updatedProvider = provider.toLowerCase();\n return updatedProvider.charAt(0).toUpperCase() + updatedProvider.slice(1);\n });\n};\n\nexport { parseAWSExports };\n//# sourceMappingURL=parseAWSExports.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst ADD_OAUTH_LISTENER = Symbol('oauth-listener');\n\nexport { ADD_OAUTH_LISTENER };\n//# sourceMappingURL=constants.mjs.map\n","// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nlet getRandomValues;\nconst rnds8 = new Uint8Array(16);\nexport default function rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","import validate from './validate.js';\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\n\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nexport default stringify;","const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nexport default {\n randomUUID\n};","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\n\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n\n options = options || {};\n const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return unsafeStringify(rnds);\n}\n\nexport default v4;","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction isAmplifyOutputs(config) {\n // version format initially will be '1' but is expected to be something like x.y where x is major and y minor version\n const { version } = config;\n if (!version) {\n return false;\n }\n return version.startsWith('1');\n}\nfunction parseStorage(amplifyOutputsStorageProperties) {\n if (!amplifyOutputsStorageProperties) {\n return undefined;\n }\n const { bucket_name, aws_region, buckets } = amplifyOutputsStorageProperties;\n return {\n S3: {\n bucket: bucket_name,\n region: aws_region,\n buckets: buckets && createBucketInfoMap(buckets),\n },\n };\n}\nfunction parseAuth(amplifyOutputsAuthProperties) {\n if (!amplifyOutputsAuthProperties) {\n return undefined;\n }\n const { user_pool_id, user_pool_client_id, identity_pool_id, password_policy, mfa_configuration, mfa_methods, unauthenticated_identities_enabled, oauth, username_attributes, standard_required_attributes, groups, } = amplifyOutputsAuthProperties;\n const authConfig = {\n Cognito: {\n userPoolId: user_pool_id,\n userPoolClientId: user_pool_client_id,\n groups,\n },\n };\n if (identity_pool_id) {\n authConfig.Cognito = {\n ...authConfig.Cognito,\n identityPoolId: identity_pool_id,\n };\n }\n if (password_policy) {\n authConfig.Cognito.passwordFormat = {\n requireLowercase: password_policy.require_lowercase,\n requireNumbers: password_policy.require_numbers,\n requireUppercase: password_policy.require_uppercase,\n requireSpecialCharacters: password_policy.require_symbols,\n minLength: password_policy.min_length ?? 6,\n };\n }\n if (mfa_configuration) {\n authConfig.Cognito.mfa = {\n status: getMfaStatus(mfa_configuration),\n smsEnabled: mfa_methods?.includes('SMS'),\n totpEnabled: mfa_methods?.includes('TOTP'),\n };\n }\n if (unauthenticated_identities_enabled) {\n authConfig.Cognito.allowGuestAccess = unauthenticated_identities_enabled;\n }\n if (oauth) {\n authConfig.Cognito.loginWith = {\n oauth: {\n domain: oauth.domain,\n redirectSignIn: oauth.redirect_sign_in_uri,\n redirectSignOut: oauth.redirect_sign_out_uri,\n responseType: oauth.response_type === 'token' ? 'token' : 'code',\n scopes: oauth.scopes,\n providers: getOAuthProviders(oauth.identity_providers),\n },\n };\n }\n if (username_attributes) {\n authConfig.Cognito.loginWith = {\n ...authConfig.Cognito.loginWith,\n email: username_attributes.includes('email'),\n phone: username_attributes.includes('phone_number'),\n // Signing in with a username is not currently supported in Gen2, this should always evaluate to false\n username: username_attributes.includes('username'),\n };\n }\n if (standard_required_attributes) {\n authConfig.Cognito.userAttributes = standard_required_attributes.reduce((acc, curr) => ({ ...acc, [curr]: { required: true } }), {});\n }\n return authConfig;\n}\nfunction parseAnalytics(amplifyOutputsAnalyticsProperties) {\n if (!amplifyOutputsAnalyticsProperties?.amazon_pinpoint) {\n return undefined;\n }\n const { amazon_pinpoint } = amplifyOutputsAnalyticsProperties;\n return {\n Pinpoint: {\n appId: amazon_pinpoint.app_id,\n region: amazon_pinpoint.aws_region,\n },\n };\n}\nfunction parseGeo(amplifyOutputsAnalyticsProperties) {\n if (!amplifyOutputsAnalyticsProperties) {\n return undefined;\n }\n const { aws_region, geofence_collections, maps, search_indices } = amplifyOutputsAnalyticsProperties;\n return {\n LocationService: {\n region: aws_region,\n searchIndices: search_indices,\n geofenceCollections: geofence_collections,\n maps,\n },\n };\n}\nfunction parseData(amplifyOutputsDataProperties) {\n if (!amplifyOutputsDataProperties) {\n return undefined;\n }\n const { aws_region, default_authorization_type, url, api_key, model_introspection, } = amplifyOutputsDataProperties;\n const GraphQL = {\n endpoint: url,\n defaultAuthMode: getGraphQLAuthMode(default_authorization_type),\n region: aws_region,\n apiKey: api_key,\n modelIntrospection: model_introspection,\n };\n return {\n GraphQL,\n };\n}\nfunction parseCustom(amplifyOutputsCustomProperties) {\n if (!amplifyOutputsCustomProperties?.events) {\n return undefined;\n }\n const { url, aws_region, api_key, default_authorization_type } = amplifyOutputsCustomProperties.events;\n const Events = {\n endpoint: url,\n defaultAuthMode: getGraphQLAuthMode(default_authorization_type),\n region: aws_region,\n apiKey: api_key,\n };\n return {\n Events,\n };\n}\nfunction parseNotifications(amplifyOutputsNotificationsProperties) {\n if (!amplifyOutputsNotificationsProperties) {\n return undefined;\n }\n const { aws_region, channels, amazon_pinpoint_app_id } = amplifyOutputsNotificationsProperties;\n const hasInAppMessaging = channels.includes('IN_APP_MESSAGING');\n const hasPushNotification = channels.includes('APNS') || channels.includes('FCM');\n if (!(hasInAppMessaging || hasPushNotification)) {\n return undefined;\n }\n // At this point, we know the Amplify outputs contains at least one supported channel\n const notificationsConfig = {};\n if (hasInAppMessaging) {\n notificationsConfig.InAppMessaging = {\n Pinpoint: {\n appId: amazon_pinpoint_app_id,\n region: aws_region,\n },\n };\n }\n if (hasPushNotification) {\n notificationsConfig.PushNotification = {\n Pinpoint: {\n appId: amazon_pinpoint_app_id,\n region: aws_region,\n },\n };\n }\n return notificationsConfig;\n}\nfunction parseAmplifyOutputs(amplifyOutputs) {\n const resourcesConfig = {};\n if (amplifyOutputs.storage) {\n resourcesConfig.Storage = parseStorage(amplifyOutputs.storage);\n }\n if (amplifyOutputs.auth) {\n resourcesConfig.Auth = parseAuth(amplifyOutputs.auth);\n }\n if (amplifyOutputs.analytics) {\n resourcesConfig.Analytics = parseAnalytics(amplifyOutputs.analytics);\n }\n if (amplifyOutputs.geo) {\n resourcesConfig.Geo = parseGeo(amplifyOutputs.geo);\n }\n if (amplifyOutputs.data) {\n resourcesConfig.API = parseData(amplifyOutputs.data);\n }\n if (amplifyOutputs.custom) {\n const customConfig = parseCustom(amplifyOutputs.custom);\n if (customConfig && 'Events' in customConfig) {\n resourcesConfig.API = { ...resourcesConfig.API, ...customConfig };\n }\n }\n if (amplifyOutputs.notifications) {\n resourcesConfig.Notifications = parseNotifications(amplifyOutputs.notifications);\n }\n return resourcesConfig;\n}\nconst authModeNames = {\n AMAZON_COGNITO_USER_POOLS: 'userPool',\n API_KEY: 'apiKey',\n AWS_IAM: 'iam',\n AWS_LAMBDA: 'lambda',\n OPENID_CONNECT: 'oidc',\n};\nfunction getGraphQLAuthMode(authType) {\n return authModeNames[authType];\n}\nconst providerNames = {\n GOOGLE: 'Google',\n LOGIN_WITH_AMAZON: 'Amazon',\n FACEBOOK: 'Facebook',\n SIGN_IN_WITH_APPLE: 'Apple',\n};\nfunction getOAuthProviders(providers = []) {\n return providers.reduce((oAuthProviders, provider) => {\n if (providerNames[provider] !== undefined) {\n oAuthProviders.push(providerNames[provider]);\n }\n return oAuthProviders;\n }, []);\n}\nfunction getMfaStatus(mfaConfiguration) {\n if (mfaConfiguration === 'OPTIONAL')\n return 'optional';\n if (mfaConfiguration === 'REQUIRED')\n return 'on';\n return 'off';\n}\nfunction createBucketInfoMap(buckets) {\n const mappedBuckets = {};\n buckets.forEach(({ name, bucket_name: bucketName, aws_region: region, paths }) => {\n if (name in mappedBuckets) {\n throw new Error(`Duplicate friendly name found: ${name}. Name must be unique.`);\n }\n const sanitizedPaths = paths\n ? Object.entries(paths).reduce((acc, [key, value]) => {\n if (value !== undefined) {\n acc[key] = value;\n }\n return acc;\n }, {})\n : undefined;\n mappedBuckets[name] = {\n bucketName,\n region,\n paths: sanitizedPaths,\n };\n });\n return mappedBuckets;\n}\n\nexport { isAmplifyOutputs, parseAmplifyOutputs, parseAnalytics };\n//# sourceMappingURL=parseAmplifyOutputs.mjs.map\n","import { parseAWSExports } from '../parseAWSExports.mjs';\nimport { isAmplifyOutputs, parseAmplifyOutputs } from '../parseAmplifyOutputs.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Parses the variety of configuration shapes that Amplify can accept into a ResourcesConfig.\n *\n * @param amplifyConfig An Amplify configuration object conforming to one of the supported schemas.\n * @return A ResourcesConfig for the provided configuration object.\n */\nconst parseAmplifyConfig = (amplifyConfig) => {\n if (Object.keys(amplifyConfig).some(key => key.startsWith('aws_'))) {\n return parseAWSExports(amplifyConfig);\n }\n else if (isAmplifyOutputs(amplifyConfig)) {\n return parseAmplifyOutputs(amplifyConfig);\n }\n else {\n return amplifyConfig;\n }\n};\n\nexport { parseAmplifyConfig };\n//# sourceMappingURL=parseAmplifyConfig.mjs.map\n","/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n","/**\n * @internal\n */\nexport var BLOCK_SIZE = 64;\n/**\n * @internal\n */\nexport var DIGEST_LENGTH = 32;\n/**\n * @internal\n */\nexport var KEY = new Uint32Array([\n 0x428a2f98,\n 0x71374491,\n 0xb5c0fbcf,\n 0xe9b5dba5,\n 0x3956c25b,\n 0x59f111f1,\n 0x923f82a4,\n 0xab1c5ed5,\n 0xd807aa98,\n 0x12835b01,\n 0x243185be,\n 0x550c7dc3,\n 0x72be5d74,\n 0x80deb1fe,\n 0x9bdc06a7,\n 0xc19bf174,\n 0xe49b69c1,\n 0xefbe4786,\n 0x0fc19dc6,\n 0x240ca1cc,\n 0x2de92c6f,\n 0x4a7484aa,\n 0x5cb0a9dc,\n 0x76f988da,\n 0x983e5152,\n 0xa831c66d,\n 0xb00327c8,\n 0xbf597fc7,\n 0xc6e00bf3,\n 0xd5a79147,\n 0x06ca6351,\n 0x14292967,\n 0x27b70a85,\n 0x2e1b2138,\n 0x4d2c6dfc,\n 0x53380d13,\n 0x650a7354,\n 0x766a0abb,\n 0x81c2c92e,\n 0x92722c85,\n 0xa2bfe8a1,\n 0xa81a664b,\n 0xc24b8b70,\n 0xc76c51a3,\n 0xd192e819,\n 0xd6990624,\n 0xf40e3585,\n 0x106aa070,\n 0x19a4c116,\n 0x1e376c08,\n 0x2748774c,\n 0x34b0bcb5,\n 0x391c0cb3,\n 0x4ed8aa4a,\n 0x5b9cca4f,\n 0x682e6ff3,\n 0x748f82ee,\n 0x78a5636f,\n 0x84c87814,\n 0x8cc70208,\n 0x90befffa,\n 0xa4506ceb,\n 0xbef9a3f7,\n 0xc67178f2\n]);\n/**\n * @internal\n */\nexport var INIT = [\n 0x6a09e667,\n 0xbb67ae85,\n 0x3c6ef372,\n 0xa54ff53a,\n 0x510e527f,\n 0x9b05688c,\n 0x1f83d9ab,\n 0x5be0cd19\n];\n/**\n * @internal\n */\nexport var MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1;\n//# sourceMappingURL=constants.js.map","import { BLOCK_SIZE, DIGEST_LENGTH, INIT, KEY, MAX_HASHABLE_LENGTH } from \"./constants\";\n/**\n * @internal\n */\nvar RawSha256 = /** @class */ (function () {\n function RawSha256() {\n this.state = Int32Array.from(INIT);\n this.temp = new Int32Array(64);\n this.buffer = new Uint8Array(64);\n this.bufferLength = 0;\n this.bytesHashed = 0;\n /**\n * @internal\n */\n this.finished = false;\n }\n RawSha256.prototype.update = function (data) {\n if (this.finished) {\n throw new Error(\"Attempted to update an already finished hash.\");\n }\n var position = 0;\n var byteLength = data.byteLength;\n this.bytesHashed += byteLength;\n if (this.bytesHashed * 8 > MAX_HASHABLE_LENGTH) {\n throw new Error(\"Cannot hash more than 2^53 - 1 bits\");\n }\n while (byteLength > 0) {\n this.buffer[this.bufferLength++] = data[position++];\n byteLength--;\n if (this.bufferLength === BLOCK_SIZE) {\n this.hashBuffer();\n this.bufferLength = 0;\n }\n }\n };\n RawSha256.prototype.digest = function () {\n if (!this.finished) {\n var bitsHashed = this.bytesHashed * 8;\n var bufferView = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength);\n var undecoratedLength = this.bufferLength;\n bufferView.setUint8(this.bufferLength++, 0x80);\n // Ensure the final block has enough room for the hashed length\n if (undecoratedLength % BLOCK_SIZE >= BLOCK_SIZE - 8) {\n for (var i = this.bufferLength; i < BLOCK_SIZE; i++) {\n bufferView.setUint8(i, 0);\n }\n this.hashBuffer();\n this.bufferLength = 0;\n }\n for (var i = this.bufferLength; i < BLOCK_SIZE - 8; i++) {\n bufferView.setUint8(i, 0);\n }\n bufferView.setUint32(BLOCK_SIZE - 8, Math.floor(bitsHashed / 0x100000000), true);\n bufferView.setUint32(BLOCK_SIZE - 4, bitsHashed);\n this.hashBuffer();\n this.finished = true;\n }\n // The value in state is little-endian rather than big-endian, so flip\n // each word into a new Uint8Array\n var out = new Uint8Array(DIGEST_LENGTH);\n for (var i = 0; i < 8; i++) {\n out[i * 4] = (this.state[i] >>> 24) & 0xff;\n out[i * 4 + 1] = (this.state[i] >>> 16) & 0xff;\n out[i * 4 + 2] = (this.state[i] >>> 8) & 0xff;\n out[i * 4 + 3] = (this.state[i] >>> 0) & 0xff;\n }\n return out;\n };\n RawSha256.prototype.hashBuffer = function () {\n var _a = this, buffer = _a.buffer, state = _a.state;\n var state0 = state[0], state1 = state[1], state2 = state[2], state3 = state[3], state4 = state[4], state5 = state[5], state6 = state[6], state7 = state[7];\n for (var i = 0; i < BLOCK_SIZE; i++) {\n if (i < 16) {\n this.temp[i] =\n ((buffer[i * 4] & 0xff) << 24) |\n ((buffer[i * 4 + 1] & 0xff) << 16) |\n ((buffer[i * 4 + 2] & 0xff) << 8) |\n (buffer[i * 4 + 3] & 0xff);\n }\n else {\n var u = this.temp[i - 2];\n var t1_1 = ((u >>> 17) | (u << 15)) ^ ((u >>> 19) | (u << 13)) ^ (u >>> 10);\n u = this.temp[i - 15];\n var t2_1 = ((u >>> 7) | (u << 25)) ^ ((u >>> 18) | (u << 14)) ^ (u >>> 3);\n this.temp[i] =\n ((t1_1 + this.temp[i - 7]) | 0) + ((t2_1 + this.temp[i - 16]) | 0);\n }\n var t1 = ((((((state4 >>> 6) | (state4 << 26)) ^\n ((state4 >>> 11) | (state4 << 21)) ^\n ((state4 >>> 25) | (state4 << 7))) +\n ((state4 & state5) ^ (~state4 & state6))) |\n 0) +\n ((state7 + ((KEY[i] + this.temp[i]) | 0)) | 0)) |\n 0;\n var t2 = ((((state0 >>> 2) | (state0 << 30)) ^\n ((state0 >>> 13) | (state0 << 19)) ^\n ((state0 >>> 22) | (state0 << 10))) +\n ((state0 & state1) ^ (state0 & state2) ^ (state1 & state2))) |\n 0;\n state7 = state6;\n state6 = state5;\n state5 = state4;\n state4 = (state3 + t1) | 0;\n state3 = state2;\n state2 = state1;\n state1 = state0;\n state0 = (t1 + t2) | 0;\n }\n state[0] += state0;\n state[1] += state1;\n state[2] += state2;\n state[3] += state3;\n state[4] += state4;\n state[5] += state5;\n state[6] += state6;\n state[7] += state7;\n };\n return RawSha256;\n}());\nexport { RawSha256 };\n//# sourceMappingURL=RawSha256.js.map","export const fromUtf8 = (input) => new TextEncoder().encode(input);\n","// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nimport { fromUtf8 as fromUtf8Browser } from \"@smithy/util-utf8\";\n// Quick polyfill\nvar fromUtf8 = typeof Buffer !== \"undefined\" && Buffer.from\n ? function (input) { return Buffer.from(input, \"utf8\"); }\n : fromUtf8Browser;\nexport function convertToBuffer(data) {\n // Already a Uint8, do nothing\n if (data instanceof Uint8Array)\n return data;\n if (typeof data === \"string\") {\n return fromUtf8(data);\n }\n if (ArrayBuffer.isView(data)) {\n return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT);\n }\n return new Uint8Array(data);\n}\n//# sourceMappingURL=convertToBuffer.js.map","// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport function isEmptyData(data) {\n if (typeof data === \"string\") {\n return data.length === 0;\n }\n return data.byteLength === 0;\n}\n//# sourceMappingURL=isEmptyData.js.map","// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nexport function numToUint8(num) {\n return new Uint8Array([\n (num & 0xff000000) >> 24,\n (num & 0x00ff0000) >> 16,\n (num & 0x0000ff00) >> 8,\n num & 0x000000ff,\n ]);\n}\n//# sourceMappingURL=numToUint8.js.map","// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// IE 11 does not support Array.from, so we do it manually\nexport function uint32ArrayFrom(a_lookUpTable) {\n if (!Uint32Array.from) {\n var return_array = new Uint32Array(a_lookUpTable.length);\n var a_index = 0;\n while (a_index < a_lookUpTable.length) {\n return_array[a_index] = a_lookUpTable[a_index];\n a_index += 1;\n }\n return return_array;\n }\n return Uint32Array.from(a_lookUpTable);\n}\n//# sourceMappingURL=uint32ArrayFrom.js.map","import { __awaiter, __generator } from \"tslib\";\nimport { BLOCK_SIZE } from \"./constants\";\nimport { RawSha256 } from \"./RawSha256\";\nimport { isEmptyData, convertToBuffer } from \"@aws-crypto/util\";\nvar Sha256 = /** @class */ (function () {\n function Sha256(secret) {\n this.secret = secret;\n this.hash = new RawSha256();\n this.reset();\n }\n Sha256.prototype.update = function (toHash) {\n if (isEmptyData(toHash) || this.error) {\n return;\n }\n try {\n this.hash.update(convertToBuffer(toHash));\n }\n catch (e) {\n this.error = e;\n }\n };\n /* This synchronous method keeps compatibility\n * with the v2 aws-sdk.\n */\n Sha256.prototype.digestSync = function () {\n if (this.error) {\n throw this.error;\n }\n if (this.outer) {\n if (!this.outer.finished) {\n this.outer.update(this.hash.digest());\n }\n return this.outer.digest();\n }\n return this.hash.digest();\n };\n /* The underlying digest method here is synchronous.\n * To keep the same interface with the other hash functions\n * the default is to expose this as an async method.\n * However, it can sometimes be useful to have a sync method.\n */\n Sha256.prototype.digest = function () {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n return [2 /*return*/, this.digestSync()];\n });\n });\n };\n Sha256.prototype.reset = function () {\n this.hash = new RawSha256();\n if (this.secret) {\n this.outer = new RawSha256();\n var inner = bufferFromSecret(this.secret);\n var outer = new Uint8Array(BLOCK_SIZE);\n outer.set(inner);\n for (var i = 0; i < BLOCK_SIZE; i++) {\n inner[i] ^= 0x36;\n outer[i] ^= 0x5c;\n }\n this.hash.update(inner);\n this.outer.update(outer);\n // overwrite the copied key in memory\n for (var i = 0; i < inner.byteLength; i++) {\n inner[i] = 0;\n }\n }\n };\n return Sha256;\n}());\nexport { Sha256 };\nfunction bufferFromSecret(secret) {\n var input = convertToBuffer(secret);\n if (input.byteLength > BLOCK_SIZE) {\n var bufferHash = new RawSha256();\n bufferHash.update(input);\n input = bufferHash.digest();\n }\n var buffer = new Uint8Array(BLOCK_SIZE);\n buffer.set(input);\n return buffer;\n}\n//# sourceMappingURL=jsSha256.js.map","const SHORT_TO_HEX = {};\nconst HEX_TO_SHORT = {};\nfor (let i = 0; i < 256; i++) {\n let encodedByte = i.toString(16).toLowerCase();\n if (encodedByte.length === 1) {\n encodedByte = `0${encodedByte}`;\n }\n SHORT_TO_HEX[i] = encodedByte;\n HEX_TO_SHORT[encodedByte] = i;\n}\nexport function fromHex(encoded) {\n if (encoded.length % 2 !== 0) {\n throw new Error(\"Hex encoded strings must have an even number length\");\n }\n const out = new Uint8Array(encoded.length / 2);\n for (let i = 0; i < encoded.length; i += 2) {\n const encodedByte = encoded.slice(i, i + 2).toLowerCase();\n if (encodedByte in HEX_TO_SHORT) {\n out[i / 2] = HEX_TO_SHORT[encodedByte];\n }\n else {\n throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);\n }\n }\n return out;\n}\nexport function toHex(bytes) {\n let out = \"\";\n for (let i = 0; i < bytes.byteLength; i++) {\n out += SHORT_TO_HEX[bytes[i]];\n }\n return out;\n}\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nvar Framework;\n(function (Framework) {\n // < 100 - Web frameworks\n Framework[\"WebUnknown\"] = \"0\";\n Framework[\"React\"] = \"1\";\n Framework[\"NextJs\"] = \"2\";\n Framework[\"Angular\"] = \"3\";\n Framework[\"VueJs\"] = \"4\";\n Framework[\"Nuxt\"] = \"5\";\n Framework[\"Svelte\"] = \"6\";\n // 100s - Server side frameworks\n Framework[\"ServerSideUnknown\"] = \"100\";\n Framework[\"ReactSSR\"] = \"101\";\n Framework[\"NextJsSSR\"] = \"102\";\n Framework[\"AngularSSR\"] = \"103\";\n Framework[\"VueJsSSR\"] = \"104\";\n Framework[\"NuxtSSR\"] = \"105\";\n Framework[\"SvelteSSR\"] = \"106\";\n // 200s - Mobile framework\n Framework[\"ReactNative\"] = \"201\";\n Framework[\"Expo\"] = \"202\";\n})(Framework || (Framework = {}));\nvar Category;\n(function (Category) {\n Category[\"AI\"] = \"ai\";\n Category[\"API\"] = \"api\";\n Category[\"Auth\"] = \"auth\";\n Category[\"Analytics\"] = \"analytics\";\n Category[\"DataStore\"] = \"datastore\";\n Category[\"Geo\"] = \"geo\";\n Category[\"InAppMessaging\"] = \"inappmessaging\";\n Category[\"Interactions\"] = \"interactions\";\n Category[\"Predictions\"] = \"predictions\";\n Category[\"PubSub\"] = \"pubsub\";\n Category[\"PushNotification\"] = \"pushnotification\";\n Category[\"Storage\"] = \"storage\";\n})(Category || (Category = {}));\nvar AiAction;\n(function (AiAction) {\n AiAction[\"CreateConversation\"] = \"1\";\n AiAction[\"GetConversation\"] = \"2\";\n AiAction[\"ListConversations\"] = \"3\";\n AiAction[\"DeleteConversation\"] = \"4\";\n AiAction[\"SendMessage\"] = \"5\";\n AiAction[\"ListMessages\"] = \"6\";\n AiAction[\"OnMessage\"] = \"7\";\n AiAction[\"Generation\"] = \"8\";\n AiAction[\"UpdateConversation\"] = \"9\";\n})(AiAction || (AiAction = {}));\nvar AnalyticsAction;\n(function (AnalyticsAction) {\n AnalyticsAction[\"Record\"] = \"1\";\n AnalyticsAction[\"IdentifyUser\"] = \"2\";\n})(AnalyticsAction || (AnalyticsAction = {}));\nvar ApiAction;\n(function (ApiAction) {\n ApiAction[\"GraphQl\"] = \"1\";\n ApiAction[\"Get\"] = \"2\";\n ApiAction[\"Post\"] = \"3\";\n ApiAction[\"Put\"] = \"4\";\n ApiAction[\"Patch\"] = \"5\";\n ApiAction[\"Del\"] = \"6\";\n ApiAction[\"Head\"] = \"7\";\n})(ApiAction || (ApiAction = {}));\nvar AuthAction;\n(function (AuthAction) {\n AuthAction[\"SignUp\"] = \"1\";\n AuthAction[\"ConfirmSignUp\"] = \"2\";\n AuthAction[\"ResendSignUpCode\"] = \"3\";\n AuthAction[\"SignIn\"] = \"4\";\n AuthAction[\"FetchMFAPreference\"] = \"6\";\n AuthAction[\"UpdateMFAPreference\"] = \"7\";\n AuthAction[\"SetUpTOTP\"] = \"10\";\n AuthAction[\"VerifyTOTPSetup\"] = \"11\";\n AuthAction[\"ConfirmSignIn\"] = \"12\";\n AuthAction[\"DeleteUserAttributes\"] = \"15\";\n AuthAction[\"DeleteUser\"] = \"16\";\n AuthAction[\"UpdateUserAttributes\"] = \"17\";\n AuthAction[\"FetchUserAttributes\"] = \"18\";\n AuthAction[\"ConfirmUserAttribute\"] = \"22\";\n AuthAction[\"SignOut\"] = \"26\";\n AuthAction[\"UpdatePassword\"] = \"27\";\n AuthAction[\"ResetPassword\"] = \"28\";\n AuthAction[\"ConfirmResetPassword\"] = \"29\";\n AuthAction[\"FederatedSignIn\"] = \"30\";\n AuthAction[\"RememberDevice\"] = \"32\";\n AuthAction[\"ForgetDevice\"] = \"33\";\n AuthAction[\"FetchDevices\"] = \"34\";\n AuthAction[\"SendUserAttributeVerificationCode\"] = \"35\";\n AuthAction[\"SignInWithRedirect\"] = \"36\";\n AuthAction[\"StartWebAuthnRegistration\"] = \"37\";\n AuthAction[\"CompleteWebAuthnRegistration\"] = \"38\";\n AuthAction[\"ListWebAuthnCredentials\"] = \"39\";\n AuthAction[\"DeleteWebAuthnCredential\"] = \"40\";\n})(AuthAction || (AuthAction = {}));\nvar DataStoreAction;\n(function (DataStoreAction) {\n DataStoreAction[\"Subscribe\"] = \"1\";\n DataStoreAction[\"GraphQl\"] = \"2\";\n})(DataStoreAction || (DataStoreAction = {}));\nvar GeoAction;\n(function (GeoAction) {\n GeoAction[\"SearchByText\"] = \"0\";\n GeoAction[\"SearchByCoordinates\"] = \"1\";\n GeoAction[\"SearchForSuggestions\"] = \"2\";\n GeoAction[\"SearchByPlaceId\"] = \"3\";\n GeoAction[\"SaveGeofences\"] = \"4\";\n GeoAction[\"GetGeofence\"] = \"5\";\n GeoAction[\"ListGeofences\"] = \"6\";\n GeoAction[\"DeleteGeofences\"] = \"7\";\n})(GeoAction || (GeoAction = {}));\nvar InAppMessagingAction;\n(function (InAppMessagingAction) {\n InAppMessagingAction[\"SyncMessages\"] = \"1\";\n InAppMessagingAction[\"IdentifyUser\"] = \"2\";\n InAppMessagingAction[\"NotifyMessageInteraction\"] = \"3\";\n})(InAppMessagingAction || (InAppMessagingAction = {}));\nvar InteractionsAction;\n(function (InteractionsAction) {\n InteractionsAction[\"None\"] = \"0\";\n})(InteractionsAction || (InteractionsAction = {}));\nvar PredictionsAction;\n(function (PredictionsAction) {\n PredictionsAction[\"Convert\"] = \"1\";\n PredictionsAction[\"Identify\"] = \"2\";\n PredictionsAction[\"Interpret\"] = \"3\";\n})(PredictionsAction || (PredictionsAction = {}));\nvar PubSubAction;\n(function (PubSubAction) {\n PubSubAction[\"Subscribe\"] = \"1\";\n})(PubSubAction || (PubSubAction = {}));\nvar PushNotificationAction;\n(function (PushNotificationAction) {\n PushNotificationAction[\"InitializePushNotifications\"] = \"1\";\n PushNotificationAction[\"IdentifyUser\"] = \"2\";\n})(PushNotificationAction || (PushNotificationAction = {}));\nvar StorageAction;\n(function (StorageAction) {\n StorageAction[\"UploadData\"] = \"1\";\n StorageAction[\"DownloadData\"] = \"2\";\n StorageAction[\"List\"] = \"3\";\n StorageAction[\"Copy\"] = \"4\";\n StorageAction[\"Remove\"] = \"5\";\n StorageAction[\"GetProperties\"] = \"6\";\n StorageAction[\"GetUrl\"] = \"7\";\n StorageAction[\"GetDataAccess\"] = \"8\";\n StorageAction[\"ListCallerAccessGrants\"] = \"9\";\n})(StorageAction || (StorageAction = {}));\n\nexport { AiAction, AnalyticsAction, ApiAction, AuthAction, Category, DataStoreAction, Framework, GeoAction, InAppMessagingAction, InteractionsAction, PredictionsAction, PubSubAction, PushNotificationAction, StorageAction };\n//# sourceMappingURL=types.mjs.map\n","// generated by genversion\nconst version = '6.13.3';\n\nexport { version };\n//# sourceMappingURL=version.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst globalExists = () => {\n return typeof global !== 'undefined';\n};\nconst globalThisExists = () => {\n return typeof globalThis !== 'undefined';\n};\nconst windowExists = () => {\n return typeof window !== 'undefined';\n};\nconst documentExists = () => {\n return typeof document !== 'undefined';\n};\nconst processExists = () => {\n return typeof process !== 'undefined';\n};\nconst keyPrefixMatch = (object, prefix) => {\n return !!Object.keys(object).find(key => key.startsWith(prefix));\n};\n\nexport { documentExists, globalExists, globalThisExists, keyPrefixMatch, processExists, windowExists };\n//# sourceMappingURL=helpers.mjs.map\n","import { documentExists, processExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with react 18.2 - built using Vite\nfunction reactWebDetect() {\n const elementKeyPrefixedWithReact = (key) => {\n return key.startsWith('_react') || key.startsWith('__react');\n };\n const elementIsReactEnabled = (element) => {\n return Object.keys(element).find(elementKeyPrefixedWithReact);\n };\n const allElementsWithId = () => Array.from(document.querySelectorAll('[id]'));\n return documentExists() && allElementsWithId().some(elementIsReactEnabled);\n}\nfunction reactSSRDetect() {\n return (processExists() &&\n typeof process.env !== 'undefined' &&\n !!Object.keys(process.env).find(key => key.includes('react')));\n}\n// use the some\n\nexport { reactSSRDetect, reactWebDetect };\n//# sourceMappingURL=React.mjs.map\n","import { windowExists, keyPrefixMatch, globalExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with vue 3.3.2\nfunction vueWebDetect() {\n return windowExists() && keyPrefixMatch(window, '__VUE');\n}\nfunction vueSSRDetect() {\n return globalExists() && keyPrefixMatch(global, '__VUE');\n}\n\nexport { vueSSRDetect, vueWebDetect };\n//# sourceMappingURL=Vue.mjs.map\n","import { windowExists, keyPrefixMatch, processExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with svelte 3.59\nfunction svelteWebDetect() {\n return windowExists() && keyPrefixMatch(window, '__SVELTE');\n}\nfunction svelteSSRDetect() {\n return (processExists() &&\n typeof process.env !== 'undefined' &&\n !!Object.keys(process.env).find(key => key.includes('svelte')));\n}\n\nexport { svelteSSRDetect, svelteWebDetect };\n//# sourceMappingURL=Svelte.mjs.map\n","import { windowExists, globalExists, keyPrefixMatch } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with next 13.4 / react 18.2\nfunction nextWebDetect() {\n return (windowExists() &&\n window.next &&\n typeof window.next === 'object');\n}\nfunction nextSSRDetect() {\n return (globalExists() &&\n (keyPrefixMatch(global, '__next') || keyPrefixMatch(global, '__NEXT')));\n}\n\nexport { nextSSRDetect, nextWebDetect };\n//# sourceMappingURL=Next.mjs.map\n","import { windowExists, globalExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with nuxt 2.15 / vue 2.7\nfunction nuxtWebDetect() {\n return (windowExists() &&\n (window.__NUXT__ !== undefined ||\n window.$nuxt !== undefined));\n}\nfunction nuxtSSRDetect() {\n return (globalExists() && typeof global.__NUXT_PATHS__ !== 'undefined');\n}\n\nexport { nuxtSSRDetect, nuxtWebDetect };\n//# sourceMappingURL=Nuxt.mjs.map\n","import { documentExists, processExists, windowExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with @angular/core 16.0.0\nfunction angularWebDetect() {\n const angularVersionSetInDocument = Boolean(documentExists() && document.querySelector('[ng-version]'));\n const angularContentSetInWindow = Boolean(windowExists() && typeof window.ng !== 'undefined');\n return angularVersionSetInDocument || angularContentSetInWindow;\n}\nfunction angularSSRDetect() {\n return ((processExists() &&\n typeof process.env === 'object' &&\n process.env.npm_lifecycle_script?.startsWith('ng ')) ||\n false);\n}\n\nexport { angularSSRDetect, angularWebDetect };\n//# sourceMappingURL=Angular.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with react-native 0.17.7\nfunction reactNativeDetect() {\n return (typeof navigator !== 'undefined' &&\n typeof navigator.product !== 'undefined' &&\n navigator.product === 'ReactNative');\n}\n\nexport { reactNativeDetect };\n//# sourceMappingURL=ReactNative.mjs.map\n","import { globalExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Tested with expo 48 / react-native 0.71.3\nfunction expoDetect() {\n return globalExists() && typeof global.expo !== 'undefined';\n}\n\nexport { expoDetect };\n//# sourceMappingURL=Expo.mjs.map\n","import { windowExists } from './helpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction webDetect() {\n return windowExists();\n}\n\nexport { webDetect };\n//# sourceMappingURL=Web.mjs.map\n","import { Framework } from '../types.mjs';\nimport { reactWebDetect, reactSSRDetect } from './React.mjs';\nimport { vueWebDetect, vueSSRDetect } from './Vue.mjs';\nimport { svelteWebDetect, svelteSSRDetect } from './Svelte.mjs';\nimport { nextWebDetect, nextSSRDetect } from './Next.mjs';\nimport { nuxtWebDetect, nuxtSSRDetect } from './Nuxt.mjs';\nimport { angularWebDetect, angularSSRDetect } from './Angular.mjs';\nimport { reactNativeDetect } from './ReactNative.mjs';\nimport { expoDetect } from './Expo.mjs';\nimport { webDetect } from './Web.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// These are in the order of detection where when both are detectable, the early Framework will be reported\nconst detectionMap = [\n // First, detect mobile\n { platform: Framework.Expo, detectionMethod: expoDetect },\n { platform: Framework.ReactNative, detectionMethod: reactNativeDetect },\n // Next, detect web frameworks\n { platform: Framework.NextJs, detectionMethod: nextWebDetect },\n { platform: Framework.Nuxt, detectionMethod: nuxtWebDetect },\n { platform: Framework.Angular, detectionMethod: angularWebDetect },\n { platform: Framework.React, detectionMethod: reactWebDetect },\n { platform: Framework.VueJs, detectionMethod: vueWebDetect },\n { platform: Framework.Svelte, detectionMethod: svelteWebDetect },\n { platform: Framework.WebUnknown, detectionMethod: webDetect },\n // Last, detect ssr frameworks\n { platform: Framework.NextJsSSR, detectionMethod: nextSSRDetect },\n { platform: Framework.NuxtSSR, detectionMethod: nuxtSSRDetect },\n { platform: Framework.ReactSSR, detectionMethod: reactSSRDetect },\n { platform: Framework.VueJsSSR, detectionMethod: vueSSRDetect },\n { platform: Framework.AngularSSR, detectionMethod: angularSSRDetect },\n { platform: Framework.SvelteSSR, detectionMethod: svelteSSRDetect },\n];\nfunction detect() {\n return (detectionMap.find(detectionEntry => detectionEntry.detectionMethod())\n ?.platform || Framework.ServerSideUnknown);\n}\n\nexport { detect };\n//# sourceMappingURL=index.mjs.map\n","import { Framework } from './types.mjs';\nimport { detect } from './detection/index.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// We want to cache detection since the framework won't change\nlet frameworkCache;\nconst frameworkChangeObservers = [];\n// Setup the detection reset tracking / timeout delays\nlet resetTriggered = false;\nconst SSR_RESET_TIMEOUT = 10; // ms\nconst WEB_RESET_TIMEOUT = 10; // ms\nconst PRIME_FRAMEWORK_DELAY = 1000; // ms\nconst detectFramework = () => {\n if (!frameworkCache) {\n frameworkCache = detect();\n if (resetTriggered) {\n // The final run of detectFramework:\n // Starting from this point, the `frameworkCache` becomes \"final\".\n // So we don't need to notify the observers again so the observer\n // can be removed after the final notice.\n while (frameworkChangeObservers.length) {\n frameworkChangeObservers.pop()?.();\n }\n }\n else {\n // The first run of detectFramework:\n // Every time we update the cache, call each observer function\n frameworkChangeObservers.forEach(fcn => {\n fcn();\n });\n }\n // Retry once for either Unknown type after a delay (explained below)\n resetTimeout(Framework.ServerSideUnknown, SSR_RESET_TIMEOUT);\n resetTimeout(Framework.WebUnknown, WEB_RESET_TIMEOUT);\n }\n return frameworkCache;\n};\n/**\n * @internal Setup observer callback that will be called everytime the framework changes\n */\nconst observeFrameworkChanges = (fcn) => {\n // When the `frameworkCache` won't be updated again, we ignore all incoming\n // observers.\n if (resetTriggered) {\n return;\n }\n frameworkChangeObservers.push(fcn);\n};\nfunction clearCache() {\n frameworkCache = undefined;\n}\n// For a framework type and a delay amount, setup the event to re-detect\n// During the runtime boot, it is possible that framework detection will\n// be triggered before the framework has made modifications to the\n// global/window/etc needed for detection. When no framework is detected\n// we will reset and try again to ensure we don't use a cached\n// non-framework detection result for all requests.\nfunction resetTimeout(framework, delay) {\n if (frameworkCache === framework && !resetTriggered) {\n setTimeout(() => {\n clearCache();\n resetTriggered = true;\n setTimeout(detectFramework, PRIME_FRAMEWORK_DELAY);\n }, delay);\n }\n}\n\nexport { clearCache, detectFramework, frameworkChangeObservers, observeFrameworkChanges };\n//# sourceMappingURL=detectFramework.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Maintains custom user-agent state set by external consumers.\nconst customUserAgentState = {};\n/**\n * Sets custom user agent state which will be appended to applicable requests. Returns a function that can be used to\n * clean up any custom state set with this API.\n *\n * @note\n * This API operates globally. Calling this API multiple times will result in the most recently set values for a\n * particular API being used.\n *\n * @note\n * This utility IS NOT compatible with SSR.\n *\n * @param input - SetCustomUserAgentInput that defines custom state to apply to the specified APIs.\n */\nconst setCustomUserAgent = (input) => {\n // Save custom user-agent state & increment reference counter\n // TODO Remove `any` when we upgrade to TypeScript 5.2, see: https://github.com/microsoft/TypeScript/issues/44373\n customUserAgentState[input.category] = input.apis.reduce((acc, api) => ({\n ...acc,\n [api]: {\n refCount: acc[api]?.refCount ? acc[api].refCount + 1 : 1,\n additionalDetails: input.additionalDetails,\n },\n }), customUserAgentState[input.category] ?? {});\n // Callback that cleans up state for APIs recorded by this call\n let cleanUpCallbackCalled = false;\n const cleanUpCallback = () => {\n // Only allow the cleanup callback to be called once\n if (cleanUpCallbackCalled) {\n return;\n }\n cleanUpCallbackCalled = true;\n input.apis.forEach(api => {\n const apiRefCount = customUserAgentState[input.category][api].refCount;\n if (apiRefCount > 1) {\n customUserAgentState[input.category][api].refCount = apiRefCount - 1;\n }\n else {\n delete customUserAgentState[input.category][api];\n // Clean up category if no more APIs set\n if (!Object.keys(customUserAgentState[input.category]).length) {\n delete customUserAgentState[input.category];\n }\n }\n });\n };\n return cleanUpCallback;\n};\nconst getCustomUserAgent = (category, api) => customUserAgentState[category]?.[api]?.additionalDetails;\n\nexport { getCustomUserAgent, setCustomUserAgent };\n//# sourceMappingURL=customUserAgent.mjs.map\n","import { Framework } from './types.mjs';\nimport { version } from './version.mjs';\nimport { detectFramework, observeFrameworkChanges } from './detectFramework.mjs';\nimport { getCustomUserAgent } from './customUserAgent.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst BASE_USER_AGENT = `aws-amplify`;\n/** Sanitize Amplify version string be removing special character + and character post the special character */\nconst sanitizeAmplifyVersion = (amplifyVersion) => amplifyVersion.replace(/\\+.*/, '');\nclass PlatformBuilder {\n constructor() {\n this.userAgent = `${BASE_USER_AGENT}/${sanitizeAmplifyVersion(version)}`;\n }\n get framework() {\n return detectFramework();\n }\n get isReactNative() {\n return (this.framework === Framework.ReactNative ||\n this.framework === Framework.Expo);\n }\n observeFrameworkChanges(fcn) {\n observeFrameworkChanges(fcn);\n }\n}\nconst Platform = new PlatformBuilder();\nconst getAmplifyUserAgentObject = ({ category, action, } = {}) => {\n const userAgent = [\n [BASE_USER_AGENT, sanitizeAmplifyVersion(version)],\n ];\n if (category) {\n userAgent.push([category, action]);\n }\n userAgent.push(['framework', detectFramework()]);\n if (category && action) {\n const customState = getCustomUserAgent(category, action);\n if (customState) {\n customState.forEach(state => {\n userAgent.push(state);\n });\n }\n }\n return userAgent;\n};\nconst getAmplifyUserAgent = (customUserAgentDetails) => {\n const userAgent = getAmplifyUserAgentObject(customUserAgentDetails);\n const userAgentString = userAgent\n .map(([agentKey, agentValue]) => agentKey && agentValue ? `${agentKey}/${agentValue}` : agentKey)\n .join(' ');\n return userAgentString;\n};\n\nexport { Platform, getAmplifyUserAgent, getAmplifyUserAgentObject, sanitizeAmplifyVersion };\n//# sourceMappingURL=index.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * All possible states a `BackgroundProcessManager` instance can be in.\n */\nvar BackgroundProcessManagerState;\n(function (BackgroundProcessManagerState) {\n /**\n * Accepting new jobs.\n */\n BackgroundProcessManagerState[\"Open\"] = \"Open\";\n /**\n * Not accepting new jobs. Waiting for submitted jobs to complete.\n */\n BackgroundProcessManagerState[\"Closing\"] = \"Closing\";\n /**\n * Not accepting new jobs. All submitted jobs are complete.\n */\n BackgroundProcessManagerState[\"Closed\"] = \"Closed\";\n})(BackgroundProcessManagerState || (BackgroundProcessManagerState = {}));\n\nexport { BackgroundProcessManagerState };\n//# sourceMappingURL=types.mjs.map\n","export function isFunction(value) {\n return typeof value === 'function';\n}\n//# sourceMappingURL=isFunction.js.map","export function createErrorClass(createImpl) {\n var _super = function (instance) {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n var ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n//# sourceMappingURL=createErrorClass.js.map","import { createErrorClass } from './createErrorClass';\nexport var UnsubscriptionError = createErrorClass(function (_super) {\n return function UnsubscriptionErrorImpl(errors) {\n _super(this);\n this.message = errors\n ? errors.length + \" errors occurred during unsubscription:\\n\" + errors.map(function (err, i) { return i + 1 + \") \" + err.toString(); }).join('\\n ')\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n };\n});\n//# sourceMappingURL=UnsubscriptionError.js.map","export function arrRemove(arr, item) {\n if (arr) {\n var index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n//# sourceMappingURL=arrRemove.js.map","import { __read, __spreadArray, __values } from \"tslib\";\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { arrRemove } from './util/arrRemove';\nvar Subscription = (function () {\n function Subscription(initialTeardown) {\n this.initialTeardown = initialTeardown;\n this.closed = false;\n this._parentage = null;\n this._finalizers = null;\n }\n Subscription.prototype.unsubscribe = function () {\n var e_1, _a, e_2, _b;\n var errors;\n if (!this.closed) {\n this.closed = true;\n var _parentage = this._parentage;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n try {\n for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {\n var parent_1 = _parentage_1_1.value;\n parent_1.remove(this);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n else {\n _parentage.remove(this);\n }\n }\n var initialFinalizer = this.initialTeardown;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n }\n catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n var _finalizers = this._finalizers;\n if (_finalizers) {\n this._finalizers = null;\n try {\n for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {\n var finalizer = _finalizers_1_1.value;\n try {\n execFinalizer(finalizer);\n }\n catch (err) {\n errors = errors !== null && errors !== void 0 ? errors : [];\n if (err instanceof UnsubscriptionError) {\n errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));\n }\n else {\n errors.push(err);\n }\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n };\n Subscription.prototype.add = function (teardown) {\n var _a;\n if (teardown && teardown !== this) {\n if (this.closed) {\n execFinalizer(teardown);\n }\n else {\n if (teardown instanceof Subscription) {\n if (teardown.closed || teardown._hasParent(this)) {\n return;\n }\n teardown._addParent(this);\n }\n (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);\n }\n }\n };\n Subscription.prototype._hasParent = function (parent) {\n var _parentage = this._parentage;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n };\n Subscription.prototype._addParent = function (parent) {\n var _parentage = this._parentage;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n };\n Subscription.prototype._removeParent = function (parent) {\n var _parentage = this._parentage;\n if (_parentage === parent) {\n this._parentage = null;\n }\n else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n };\n Subscription.prototype.remove = function (teardown) {\n var _finalizers = this._finalizers;\n _finalizers && arrRemove(_finalizers, teardown);\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n };\n Subscription.EMPTY = (function () {\n var empty = new Subscription();\n empty.closed = true;\n return empty;\n })();\n return Subscription;\n}());\nexport { Subscription };\nexport var EMPTY_SUBSCRIPTION = Subscription.EMPTY;\nexport function isSubscription(value) {\n return (value instanceof Subscription ||\n (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));\n}\nfunction execFinalizer(finalizer) {\n if (isFunction(finalizer)) {\n finalizer();\n }\n else {\n finalizer.unsubscribe();\n }\n}\n//# sourceMappingURL=Subscription.js.map","export var config = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n//# sourceMappingURL=config.js.map","import { __read, __spreadArray } from \"tslib\";\nexport var timeoutProvider = {\n setTimeout: function (handler, timeout) {\n var args = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n args[_i - 2] = arguments[_i];\n }\n var delegate = timeoutProvider.delegate;\n if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {\n return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));\n }\n return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));\n },\n clearTimeout: function (handle) {\n var delegate = timeoutProvider.delegate;\n return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);\n },\n delegate: undefined,\n};\n//# sourceMappingURL=timeoutProvider.js.map","import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\nexport function reportUnhandledError(err) {\n timeoutProvider.setTimeout(function () {\n var onUnhandledError = config.onUnhandledError;\n if (onUnhandledError) {\n onUnhandledError(err);\n }\n else {\n throw err;\n }\n });\n}\n//# sourceMappingURL=reportUnhandledError.js.map","export function noop() { }\n//# sourceMappingURL=noop.js.map","import { config } from '../config';\nvar context = null;\nexport function errorContext(cb) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n var isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n var _a = context, errorThrown = _a.errorThrown, error = _a.error;\n context = null;\n if (errorThrown) {\n throw error;\n }\n }\n }\n else {\n cb();\n }\n}\nexport function captureError(err) {\n if (config.useDeprecatedSynchronousErrorHandling && context) {\n context.errorThrown = true;\n context.error = err;\n }\n}\n//# sourceMappingURL=errorContext.js.map","import { __extends } from \"tslib\";\nimport { isFunction } from './util/isFunction';\nimport { isSubscription, Subscription } from './Subscription';\nimport { config } from './config';\nimport { reportUnhandledError } from './util/reportUnhandledError';\nimport { noop } from './util/noop';\nimport { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';\nimport { timeoutProvider } from './scheduler/timeoutProvider';\nimport { captureError } from './util/errorContext';\nvar Subscriber = (function (_super) {\n __extends(Subscriber, _super);\n function Subscriber(destination) {\n var _this = _super.call(this) || this;\n _this.isStopped = false;\n if (destination) {\n _this.destination = destination;\n if (isSubscription(destination)) {\n destination.add(_this);\n }\n }\n else {\n _this.destination = EMPTY_OBSERVER;\n }\n return _this;\n }\n Subscriber.create = function (next, error, complete) {\n return new SafeSubscriber(next, error, complete);\n };\n Subscriber.prototype.next = function (value) {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n }\n else {\n this._next(value);\n }\n };\n Subscriber.prototype.error = function (err) {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n }\n else {\n this.isStopped = true;\n this._error(err);\n }\n };\n Subscriber.prototype.complete = function () {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n }\n else {\n this.isStopped = true;\n this._complete();\n }\n };\n Subscriber.prototype.unsubscribe = function () {\n if (!this.closed) {\n this.isStopped = true;\n _super.prototype.unsubscribe.call(this);\n this.destination = null;\n }\n };\n Subscriber.prototype._next = function (value) {\n this.destination.next(value);\n };\n Subscriber.prototype._error = function (err) {\n try {\n this.destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n };\n Subscriber.prototype._complete = function () {\n try {\n this.destination.complete();\n }\n finally {\n this.unsubscribe();\n }\n };\n return Subscriber;\n}(Subscription));\nexport { Subscriber };\nvar _bind = Function.prototype.bind;\nfunction bind(fn, thisArg) {\n return _bind.call(fn, thisArg);\n}\nvar ConsumerObserver = (function () {\n function ConsumerObserver(partialObserver) {\n this.partialObserver = partialObserver;\n }\n ConsumerObserver.prototype.next = function (value) {\n var partialObserver = this.partialObserver;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n };\n ConsumerObserver.prototype.error = function (err) {\n var partialObserver = this.partialObserver;\n if (partialObserver.error) {\n try {\n partialObserver.error(err);\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n else {\n handleUnhandledError(err);\n }\n };\n ConsumerObserver.prototype.complete = function () {\n var partialObserver = this.partialObserver;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n };\n return ConsumerObserver;\n}());\nvar SafeSubscriber = (function (_super) {\n __extends(SafeSubscriber, _super);\n function SafeSubscriber(observerOrNext, error, complete) {\n var _this = _super.call(this) || this;\n var partialObserver;\n if (isFunction(observerOrNext) || !observerOrNext) {\n partialObserver = {\n next: (observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined),\n error: error !== null && error !== void 0 ? error : undefined,\n complete: complete !== null && complete !== void 0 ? complete : undefined,\n };\n }\n else {\n var context_1;\n if (_this && config.useDeprecatedNextContext) {\n context_1 = Object.create(observerOrNext);\n context_1.unsubscribe = function () { return _this.unsubscribe(); };\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context_1),\n error: observerOrNext.error && bind(observerOrNext.error, context_1),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),\n };\n }\n else {\n partialObserver = observerOrNext;\n }\n }\n _this.destination = new ConsumerObserver(partialObserver);\n return _this;\n }\n return SafeSubscriber;\n}(Subscriber));\nexport { SafeSubscriber };\nfunction handleUnhandledError(error) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n captureError(error);\n }\n else {\n reportUnhandledError(error);\n }\n}\nfunction defaultErrorHandler(err) {\n throw err;\n}\nfunction handleStoppedNotification(notification, subscriber) {\n var onStoppedNotification = config.onStoppedNotification;\n onStoppedNotification && timeoutProvider.setTimeout(function () { return onStoppedNotification(notification, subscriber); });\n}\nexport var EMPTY_OBSERVER = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n//# sourceMappingURL=Subscriber.js.map","export var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();\n//# sourceMappingURL=observable.js.map","export function identity(x) {\n return x;\n}\n//# sourceMappingURL=identity.js.map","import { identity } from './identity';\nexport function pipe() {\n var fns = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n fns[_i] = arguments[_i];\n }\n return pipeFromArray(fns);\n}\nexport function pipeFromArray(fns) {\n if (fns.length === 0) {\n return identity;\n }\n if (fns.length === 1) {\n return fns[0];\n }\n return function piped(input) {\n return fns.reduce(function (prev, fn) { return fn(prev); }, input);\n };\n}\n//# sourceMappingURL=pipe.js.map","import { SafeSubscriber, Subscriber } from './Subscriber';\nimport { isSubscription } from './Subscription';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nimport { isFunction } from './util/isFunction';\nimport { errorContext } from './util/errorContext';\nvar Observable = (function () {\n function Observable(subscribe) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n Observable.prototype.lift = function (operator) {\n var observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n };\n Observable.prototype.subscribe = function (observerOrNext, error, complete) {\n var _this = this;\n var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n errorContext(function () {\n var _a = _this, operator = _a.operator, source = _a.source;\n subscriber.add(operator\n ?\n operator.call(subscriber, source)\n : source\n ?\n _this._subscribe(subscriber)\n :\n _this._trySubscribe(subscriber));\n });\n return subscriber;\n };\n Observable.prototype._trySubscribe = function (sink) {\n try {\n return this._subscribe(sink);\n }\n catch (err) {\n sink.error(err);\n }\n };\n Observable.prototype.forEach = function (next, promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var subscriber = new SafeSubscriber({\n next: function (value) {\n try {\n next(value);\n }\n catch (err) {\n reject(err);\n subscriber.unsubscribe();\n }\n },\n error: reject,\n complete: resolve,\n });\n _this.subscribe(subscriber);\n });\n };\n Observable.prototype._subscribe = function (subscriber) {\n var _a;\n return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);\n };\n Observable.prototype[Symbol_observable] = function () {\n return this;\n };\n Observable.prototype.pipe = function () {\n var operations = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n operations[_i] = arguments[_i];\n }\n return pipeFromArray(operations)(this);\n };\n Observable.prototype.toPromise = function (promiseCtor) {\n var _this = this;\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor(function (resolve, reject) {\n var value;\n _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });\n });\n };\n Observable.create = function (subscribe) {\n return new Observable(subscribe);\n };\n return Observable;\n}());\nexport { Observable };\nfunction getPromiseCtor(promiseCtor) {\n var _a;\n return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;\n}\nfunction isObserver(value) {\n return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);\n}\nfunction isSubscriber(value) {\n return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));\n}\n//# sourceMappingURL=Observable.js.map","import { isFunction } from './isFunction';\nexport function hasLift(source) {\n return isFunction(source === null || source === void 0 ? void 0 : source.lift);\n}\nexport function operate(init) {\n return function (source) {\n if (hasLift(source)) {\n return source.lift(function (liftedSource) {\n try {\n return init(liftedSource, this);\n }\n catch (err) {\n this.error(err);\n }\n });\n }\n throw new TypeError('Unable to lift unknown Observable type');\n };\n}\n//# sourceMappingURL=lift.js.map","import { __extends } from \"tslib\";\nimport { Subscriber } from '../Subscriber';\nexport function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {\n return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);\n}\nvar OperatorSubscriber = (function (_super) {\n __extends(OperatorSubscriber, _super);\n function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {\n var _this = _super.call(this, destination) || this;\n _this.onFinalize = onFinalize;\n _this.shouldUnsubscribe = shouldUnsubscribe;\n _this._next = onNext\n ? function (value) {\n try {\n onNext(value);\n }\n catch (err) {\n destination.error(err);\n }\n }\n : _super.prototype._next;\n _this._error = onError\n ? function (err) {\n try {\n onError(err);\n }\n catch (err) {\n destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n }\n : _super.prototype._error;\n _this._complete = onComplete\n ? function () {\n try {\n onComplete();\n }\n catch (err) {\n destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n }\n : _super.prototype._complete;\n return _this;\n }\n OperatorSubscriber.prototype.unsubscribe = function () {\n var _a;\n if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {\n var closed_1 = this.closed;\n _super.prototype.unsubscribe.call(this);\n !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));\n }\n };\n return OperatorSubscriber;\n}(Subscriber));\nexport { OperatorSubscriber };\n//# sourceMappingURL=OperatorSubscriber.js.map","import { createErrorClass } from './createErrorClass';\nexport var ObjectUnsubscribedError = createErrorClass(function (_super) {\n return function ObjectUnsubscribedErrorImpl() {\n _super(this);\n this.name = 'ObjectUnsubscribedError';\n this.message = 'object unsubscribed';\n };\n});\n//# sourceMappingURL=ObjectUnsubscribedError.js.map","import { __extends, __values } from \"tslib\";\nimport { Observable } from './Observable';\nimport { Subscription, EMPTY_SUBSCRIPTION } from './Subscription';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { arrRemove } from './util/arrRemove';\nimport { errorContext } from './util/errorContext';\nvar Subject = (function (_super) {\n __extends(Subject, _super);\n function Subject() {\n var _this = _super.call(this) || this;\n _this.closed = false;\n _this.currentObservers = null;\n _this.observers = [];\n _this.isStopped = false;\n _this.hasError = false;\n _this.thrownError = null;\n return _this;\n }\n Subject.prototype.lift = function (operator) {\n var subject = new AnonymousSubject(this, this);\n subject.operator = operator;\n return subject;\n };\n Subject.prototype._throwIfClosed = function () {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n };\n Subject.prototype.next = function (value) {\n var _this = this;\n errorContext(function () {\n var e_1, _a;\n _this._throwIfClosed();\n if (!_this.isStopped) {\n if (!_this.currentObservers) {\n _this.currentObservers = Array.from(_this.observers);\n }\n try {\n for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {\n var observer = _c.value;\n observer.next(value);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n });\n };\n Subject.prototype.error = function (err) {\n var _this = this;\n errorContext(function () {\n _this._throwIfClosed();\n if (!_this.isStopped) {\n _this.hasError = _this.isStopped = true;\n _this.thrownError = err;\n var observers = _this.observers;\n while (observers.length) {\n observers.shift().error(err);\n }\n }\n });\n };\n Subject.prototype.complete = function () {\n var _this = this;\n errorContext(function () {\n _this._throwIfClosed();\n if (!_this.isStopped) {\n _this.isStopped = true;\n var observers = _this.observers;\n while (observers.length) {\n observers.shift().complete();\n }\n }\n });\n };\n Subject.prototype.unsubscribe = function () {\n this.isStopped = this.closed = true;\n this.observers = this.currentObservers = null;\n };\n Object.defineProperty(Subject.prototype, \"observed\", {\n get: function () {\n var _a;\n return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;\n },\n enumerable: false,\n configurable: true\n });\n Subject.prototype._trySubscribe = function (subscriber) {\n this._throwIfClosed();\n return _super.prototype._trySubscribe.call(this, subscriber);\n };\n Subject.prototype._subscribe = function (subscriber) {\n this._throwIfClosed();\n this._checkFinalizedStatuses(subscriber);\n return this._innerSubscribe(subscriber);\n };\n Subject.prototype._innerSubscribe = function (subscriber) {\n var _this = this;\n var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;\n if (hasError || isStopped) {\n return EMPTY_SUBSCRIPTION;\n }\n this.currentObservers = null;\n observers.push(subscriber);\n return new Subscription(function () {\n _this.currentObservers = null;\n arrRemove(observers, subscriber);\n });\n };\n Subject.prototype._checkFinalizedStatuses = function (subscriber) {\n var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;\n if (hasError) {\n subscriber.error(thrownError);\n }\n else if (isStopped) {\n subscriber.complete();\n }\n };\n Subject.prototype.asObservable = function () {\n var observable = new Observable();\n observable.source = this;\n return observable;\n };\n Subject.create = function (destination, source) {\n return new AnonymousSubject(destination, source);\n };\n return Subject;\n}(Observable));\nexport { Subject };\nvar AnonymousSubject = (function (_super) {\n __extends(AnonymousSubject, _super);\n function AnonymousSubject(destination, source) {\n var _this = _super.call(this) || this;\n _this.destination = destination;\n _this.source = source;\n return _this;\n }\n AnonymousSubject.prototype.next = function (value) {\n var _a, _b;\n (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);\n };\n AnonymousSubject.prototype.error = function (err) {\n var _a, _b;\n (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);\n };\n AnonymousSubject.prototype.complete = function () {\n var _a, _b;\n (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);\n };\n AnonymousSubject.prototype._subscribe = function (subscriber) {\n var _a, _b;\n return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;\n };\n return AnonymousSubject;\n}(Subject));\nexport { AnonymousSubject };\n//# sourceMappingURL=Subject.js.map","import { isFunction } from './isFunction';\nexport function isScheduler(value) {\n return value && isFunction(value.schedule);\n}\n//# sourceMappingURL=isScheduler.js.map","import { isFunction } from './isFunction';\nimport { isScheduler } from './isScheduler';\nfunction last(arr) {\n return arr[arr.length - 1];\n}\nexport function popResultSelector(args) {\n return isFunction(last(args)) ? args.pop() : undefined;\n}\nexport function popScheduler(args) {\n return isScheduler(last(args)) ? args.pop() : undefined;\n}\nexport function popNumber(args, defaultValue) {\n return typeof last(args) === 'number' ? args.pop() : defaultValue;\n}\n//# sourceMappingURL=args.js.map","export var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });\n//# sourceMappingURL=isArrayLike.js.map","import { isFunction } from \"./isFunction\";\nexport function isPromise(value) {\n return isFunction(value === null || value === void 0 ? void 0 : value.then);\n}\n//# sourceMappingURL=isPromise.js.map","import { observable as Symbol_observable } from '../symbol/observable';\nimport { isFunction } from './isFunction';\nexport function isInteropObservable(input) {\n return isFunction(input[Symbol_observable]);\n}\n//# sourceMappingURL=isInteropObservable.js.map","import { isFunction } from './isFunction';\nexport function isAsyncIterable(obj) {\n return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);\n}\n//# sourceMappingURL=isAsyncIterable.js.map","export function createInvalidObservableTypeError(input) {\n return new TypeError(\"You provided \" + (input !== null && typeof input === 'object' ? 'an invalid object' : \"'\" + input + \"'\") + \" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.\");\n}\n//# sourceMappingURL=throwUnobservableError.js.map","export function getSymbolIterator() {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator';\n }\n return Symbol.iterator;\n}\nexport var iterator = getSymbolIterator();\n//# sourceMappingURL=iterator.js.map","import { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from './isFunction';\nexport function isIterable(input) {\n return isFunction(input === null || input === void 0 ? void 0 : input[Symbol_iterator]);\n}\n//# sourceMappingURL=isIterable.js.map","import { __asyncGenerator, __await, __generator } from \"tslib\";\nimport { isFunction } from './isFunction';\nexport function readableStreamLikeToAsyncGenerator(readableStream) {\n return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {\n var reader, _a, value, done;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n reader = readableStream.getReader();\n _b.label = 1;\n case 1:\n _b.trys.push([1, , 9, 10]);\n _b.label = 2;\n case 2:\n if (!true) return [3, 8];\n return [4, __await(reader.read())];\n case 3:\n _a = _b.sent(), value = _a.value, done = _a.done;\n if (!done) return [3, 5];\n return [4, __await(void 0)];\n case 4: return [2, _b.sent()];\n case 5: return [4, __await(value)];\n case 6: return [4, _b.sent()];\n case 7:\n _b.sent();\n return [3, 2];\n case 8: return [3, 10];\n case 9:\n reader.releaseLock();\n return [7];\n case 10: return [2];\n }\n });\n });\n}\nexport function isReadableStreamLike(obj) {\n return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);\n}\n//# sourceMappingURL=isReadableStreamLike.js.map","import { __asyncValues, __awaiter, __generator, __values } from \"tslib\";\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isPromise } from '../util/isPromise';\nimport { Observable } from '../Observable';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isIterable } from '../util/isIterable';\nimport { isReadableStreamLike, readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\nimport { isFunction } from '../util/isFunction';\nimport { reportUnhandledError } from '../util/reportUnhandledError';\nimport { observable as Symbol_observable } from '../symbol/observable';\nexport function innerFrom(input) {\n if (input instanceof Observable) {\n return input;\n }\n if (input != null) {\n if (isInteropObservable(input)) {\n return fromInteropObservable(input);\n }\n if (isArrayLike(input)) {\n return fromArrayLike(input);\n }\n if (isPromise(input)) {\n return fromPromise(input);\n }\n if (isAsyncIterable(input)) {\n return fromAsyncIterable(input);\n }\n if (isIterable(input)) {\n return fromIterable(input);\n }\n if (isReadableStreamLike(input)) {\n return fromReadableStreamLike(input);\n }\n }\n throw createInvalidObservableTypeError(input);\n}\nexport function fromInteropObservable(obj) {\n return new Observable(function (subscriber) {\n var obs = obj[Symbol_observable]();\n if (isFunction(obs.subscribe)) {\n return obs.subscribe(subscriber);\n }\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n });\n}\nexport function fromArrayLike(array) {\n return new Observable(function (subscriber) {\n for (var i = 0; i < array.length && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n });\n}\nexport function fromPromise(promise) {\n return new Observable(function (subscriber) {\n promise\n .then(function (value) {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n }, function (err) { return subscriber.error(err); })\n .then(null, reportUnhandledError);\n });\n}\nexport function fromIterable(iterable) {\n return new Observable(function (subscriber) {\n var e_1, _a;\n try {\n for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {\n var value = iterable_1_1.value;\n subscriber.next(value);\n if (subscriber.closed) {\n return;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n subscriber.complete();\n });\n}\nexport function fromAsyncIterable(asyncIterable) {\n return new Observable(function (subscriber) {\n process(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); });\n });\n}\nexport function fromReadableStreamLike(readableStream) {\n return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));\n}\nfunction process(asyncIterable, subscriber) {\n var asyncIterable_1, asyncIterable_1_1;\n var e_2, _a;\n return __awaiter(this, void 0, void 0, function () {\n var value, e_2_1;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n _b.trys.push([0, 5, 6, 11]);\n asyncIterable_1 = __asyncValues(asyncIterable);\n _b.label = 1;\n case 1: return [4, asyncIterable_1.next()];\n case 2:\n if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];\n value = asyncIterable_1_1.value;\n subscriber.next(value);\n if (subscriber.closed) {\n return [2];\n }\n _b.label = 3;\n case 3: return [3, 1];\n case 4: return [3, 11];\n case 5:\n e_2_1 = _b.sent();\n e_2 = { error: e_2_1 };\n return [3, 11];\n case 6:\n _b.trys.push([6, , 9, 10]);\n if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];\n return [4, _a.call(asyncIterable_1)];\n case 7:\n _b.sent();\n _b.label = 8;\n case 8: return [3, 10];\n case 9:\n if (e_2) throw e_2.error;\n return [7];\n case 10: return [7];\n case 11:\n subscriber.complete();\n return [2];\n }\n });\n });\n}\n//# sourceMappingURL=innerFrom.js.map","export function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {\n if (delay === void 0) { delay = 0; }\n if (repeat === void 0) { repeat = false; }\n var scheduleSubscription = scheduler.schedule(function () {\n work();\n if (repeat) {\n parentSubscription.add(this.schedule(null, delay));\n }\n else {\n this.unsubscribe();\n }\n }, delay);\n parentSubscription.add(scheduleSubscription);\n if (!repeat) {\n return scheduleSubscription;\n }\n}\n//# sourceMappingURL=executeSchedule.js.map","import { executeSchedule } from '../util/executeSchedule';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function observeOn(scheduler, delay) {\n if (delay === void 0) { delay = 0; }\n return operate(function (source, subscriber) {\n source.subscribe(createOperatorSubscriber(subscriber, function (value) { return executeSchedule(subscriber, scheduler, function () { return subscriber.next(value); }, delay); }, function () { return executeSchedule(subscriber, scheduler, function () { return subscriber.complete(); }, delay); }, function (err) { return executeSchedule(subscriber, scheduler, function () { return subscriber.error(err); }, delay); }));\n });\n}\n//# sourceMappingURL=observeOn.js.map","import { operate } from '../util/lift';\nexport function subscribeOn(scheduler, delay) {\n if (delay === void 0) { delay = 0; }\n return operate(function (source, subscriber) {\n subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay));\n });\n}\n//# sourceMappingURL=subscribeOn.js.map","import { innerFrom } from '../observable/innerFrom';\nimport { observeOn } from '../operators/observeOn';\nimport { subscribeOn } from '../operators/subscribeOn';\nexport function scheduleObservable(input, scheduler) {\n return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));\n}\n//# sourceMappingURL=scheduleObservable.js.map","import { innerFrom } from '../observable/innerFrom';\nimport { observeOn } from '../operators/observeOn';\nimport { subscribeOn } from '../operators/subscribeOn';\nexport function schedulePromise(input, scheduler) {\n return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));\n}\n//# sourceMappingURL=schedulePromise.js.map","import { Observable } from '../Observable';\nexport function scheduleArray(input, scheduler) {\n return new Observable(function (subscriber) {\n var i = 0;\n return scheduler.schedule(function () {\n if (i === input.length) {\n subscriber.complete();\n }\n else {\n subscriber.next(input[i++]);\n if (!subscriber.closed) {\n this.schedule();\n }\n }\n });\n });\n}\n//# sourceMappingURL=scheduleArray.js.map","import { Observable } from '../Observable';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from '../util/isFunction';\nimport { executeSchedule } from '../util/executeSchedule';\nexport function scheduleIterable(input, scheduler) {\n return new Observable(function (subscriber) {\n var iterator;\n executeSchedule(subscriber, scheduler, function () {\n iterator = input[Symbol_iterator]();\n executeSchedule(subscriber, scheduler, function () {\n var _a;\n var value;\n var done;\n try {\n (_a = iterator.next(), value = _a.value, done = _a.done);\n }\n catch (err) {\n subscriber.error(err);\n return;\n }\n if (done) {\n subscriber.complete();\n }\n else {\n subscriber.next(value);\n }\n }, 0, true);\n });\n return function () { return isFunction(iterator === null || iterator === void 0 ? void 0 : iterator.return) && iterator.return(); };\n });\n}\n//# sourceMappingURL=scheduleIterable.js.map","import { Observable } from '../Observable';\nimport { executeSchedule } from '../util/executeSchedule';\nexport function scheduleAsyncIterable(input, scheduler) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable(function (subscriber) {\n executeSchedule(subscriber, scheduler, function () {\n var iterator = input[Symbol.asyncIterator]();\n executeSchedule(subscriber, scheduler, function () {\n iterator.next().then(function (result) {\n if (result.done) {\n subscriber.complete();\n }\n else {\n subscriber.next(result.value);\n }\n });\n }, 0, true);\n });\n });\n}\n//# sourceMappingURL=scheduleAsyncIterable.js.map","import { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\nexport function scheduleReadableStreamLike(input, scheduler) {\n return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);\n}\n//# sourceMappingURL=scheduleReadableStreamLike.js.map","import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isReadableStreamLike } from '../util/isReadableStreamLike';\nimport { scheduleReadableStreamLike } from './scheduleReadableStreamLike';\nexport function scheduled(input, scheduler) {\n if (input != null) {\n if (isInteropObservable(input)) {\n return scheduleObservable(input, scheduler);\n }\n if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n }\n if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n }\n if (isAsyncIterable(input)) {\n return scheduleAsyncIterable(input, scheduler);\n }\n if (isIterable(input)) {\n return scheduleIterable(input, scheduler);\n }\n if (isReadableStreamLike(input)) {\n return scheduleReadableStreamLike(input, scheduler);\n }\n }\n throw createInvalidObservableTypeError(input);\n}\n//# sourceMappingURL=scheduled.js.map","import { scheduled } from '../scheduled/scheduled';\nimport { innerFrom } from './innerFrom';\nexport function from(input, scheduler) {\n return scheduler ? scheduled(input, scheduler) : innerFrom(input);\n}\n//# sourceMappingURL=from.js.map","import { popScheduler } from '../util/args';\nimport { from } from './from';\nexport function of() {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var scheduler = popScheduler(args);\n return from(args, scheduler);\n}\n//# sourceMappingURL=of.js.map","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function map(project, thisArg) {\n return operate(function (source, subscriber) {\n var index = 0;\n source.subscribe(createOperatorSubscriber(subscriber, function (value) {\n subscriber.next(project.call(thisArg, value, index++));\n }));\n });\n}\n//# sourceMappingURL=map.js.map","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function filter(predicate, thisArg) {\n return operate(function (source, subscriber) {\n var index = 0;\n source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));\n });\n}\n//# sourceMappingURL=filter.js.map","import { innerFrom } from '../observable/innerFrom';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { operate } from '../util/lift';\nexport function catchError(selector) {\n return operate(function (source, subscriber) {\n var innerSub = null;\n var syncUnsub = false;\n var handledResult;\n innerSub = source.subscribe(createOperatorSubscriber(subscriber, undefined, undefined, function (err) {\n handledResult = innerFrom(selector(err, catchError(selector)(source)));\n if (innerSub) {\n innerSub.unsubscribe();\n innerSub = null;\n handledResult.subscribe(subscriber);\n }\n else {\n syncUnsub = true;\n }\n }));\n if (syncUnsub) {\n innerSub.unsubscribe();\n innerSub = null;\n handledResult.subscribe(subscriber);\n }\n });\n}\n//# sourceMappingURL=catchError.js.map","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst isWebWorker = () => {\n if (typeof self === 'undefined') {\n return false;\n }\n const selfContext = self;\n return (typeof selfContext.WorkerGlobalScope !== 'undefined' &&\n self instanceof selfContext.WorkerGlobalScope);\n};\n\nexport { isWebWorker };\n//# sourceMappingURL=isWebWorker.mjs.map\n","import { from, Observable } from 'rxjs';\nimport '../types/errors.mjs';\nimport '../errors/errorHelpers.mjs';\nimport '../utils/getClientInfo/getClientInfo.mjs';\nimport { isWebWorker } from '../utils/isWebWorker.mjs';\nimport '../utils/retry/retry.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass Reachability {\n networkMonitor(_) {\n const globalObj = isWebWorker()\n ? self\n : typeof window !== 'undefined' && window;\n if (!globalObj) {\n return from([{ online: true }]);\n }\n return new Observable(observer => {\n observer.next({ online: globalObj.navigator.onLine });\n const notifyOnline = () => {\n observer.next({ online: true });\n };\n const notifyOffline = () => {\n observer.next({ online: false });\n };\n globalObj.addEventListener('online', notifyOnline);\n globalObj.addEventListener('offline', notifyOffline);\n Reachability._observers.push(observer);\n return () => {\n globalObj.removeEventListener('online', notifyOnline);\n globalObj.removeEventListener('offline', notifyOffline);\n Reachability._observers = Reachability._observers.filter(_observer => _observer !== observer);\n };\n });\n }\n // expose observers to simulate offline mode for integration testing\n static _observerOverride(status) {\n for (const observer of this._observers) {\n if (observer.closed) {\n this._observers = this._observers.filter(_observer => _observer !== observer);\n continue;\n }\n observer?.next && observer.next(status);\n }\n }\n}\nReachability._observers = [];\n\nexport { Reachability };\n//# sourceMappingURL=Reachability.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst isBrowser = () => typeof window !== 'undefined' && typeof window.document !== 'undefined';\n\nexport { isBrowser };\n//# sourceMappingURL=isBrowser.mjs.map\n","class AuthClass {\n /**\n * Configure Auth category\n *\n * @internal\n *\n * @param authResourcesConfig - Resources configurations required by Auth providers.\n * @param authOptions - Client options used by library\n *\n * @returns void\n */\n configure(authResourcesConfig, authOptions) {\n this.authConfig = authResourcesConfig;\n this.authOptions = authOptions;\n }\n /**\n * Fetch the auth tokens, and the temporary AWS credentials and identity if they are configured. By default it\n * does not refresh the auth tokens or credentials if they are loaded in storage already. You can force a refresh\n * with `{ forceRefresh: true }` input.\n *\n * @param options - Options configuring the fetch behavior.\n *\n * @returns Promise of current auth session {@link AuthSession}.\n */\n async fetchAuthSession(options = {}) {\n let credentialsAndIdentityId;\n let userSub;\n // Get tokens will throw if session cannot be refreshed (network or service error) or return null if not available\n const tokens = await this.getTokens(options);\n if (tokens) {\n userSub = tokens.accessToken?.payload?.sub;\n // getCredentialsAndIdentityId will throw if cannot get credentials (network or service error)\n credentialsAndIdentityId =\n await this.authOptions?.credentialsProvider?.getCredentialsAndIdentityId({\n authConfig: this.authConfig,\n tokens,\n authenticated: true,\n forceRefresh: options.forceRefresh,\n });\n }\n else {\n // getCredentialsAndIdentityId will throw if cannot get credentials (network or service error)\n credentialsAndIdentityId =\n await this.authOptions?.credentialsProvider?.getCredentialsAndIdentityId({\n authConfig: this.authConfig,\n authenticated: false,\n forceRefresh: options.forceRefresh,\n });\n }\n return {\n tokens,\n credentials: credentialsAndIdentityId?.credentials,\n identityId: credentialsAndIdentityId?.identityId,\n userSub,\n };\n }\n async clearCredentials() {\n await this.authOptions?.credentialsProvider?.clearCredentialsAndIdentityId();\n }\n async getTokens(options) {\n return ((await this.authOptions?.tokenProvider?.getTokens(options)) ?? undefined);\n }\n}\n\nexport { AuthClass };\n//# sourceMappingURL=index.mjs.map\n","import { Hub, AMPLIFY_SYMBOL } from '../Hub/index.mjs';\nimport '../types/errors.mjs';\nimport '../errors/errorHelpers.mjs';\nimport '../utils/getClientInfo/getClientInfo.mjs';\nimport '../utils/retry/retry.mjs';\nimport { deepFreeze } from '../utils/deepFreeze.mjs';\nimport '../parseAWSExports.mjs';\nimport { ADD_OAUTH_LISTENER } from './constants.mjs';\nimport 'uuid';\nimport { parseAmplifyConfig } from '../utils/parseAmplifyConfig.mjs';\nimport './Auth/utils/errorHelpers.mjs';\nimport '@aws-crypto/sha256-js';\nimport '@smithy/util-hex-encoding';\nimport '../Platform/index.mjs';\nimport '../Platform/types.mjs';\nimport '../BackgroundProcessManager/types.mjs';\nimport '../Reachability/Reachability.mjs';\nimport '../utils/sessionListener/index.mjs';\nimport { AuthClass } from './Auth/index.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass AmplifyClass {\n constructor() {\n this.oAuthListener = undefined;\n this.resourcesConfig = {};\n this.libraryOptions = {};\n this.Auth = new AuthClass();\n }\n /**\n * Configures Amplify for use with your back-end resources.\n *\n * @remarks\n * This API does not perform any merging of either `resourcesConfig` or `libraryOptions`. The most recently\n * provided values will be used after configuration.\n *\n * @remarks\n * `configure` can be used to specify additional library options where available for supported categories.\n *\n * @param resourceConfig - Back-end resource configuration. Typically provided via the `aws-exports.js` file.\n * @param libraryOptions - Additional options for customizing the behavior of the library.\n */\n configure(resourcesConfig, libraryOptions) {\n const resolvedResourceConfig = parseAmplifyConfig(resourcesConfig);\n this.resourcesConfig = resolvedResourceConfig;\n if (libraryOptions) {\n this.libraryOptions = libraryOptions;\n }\n // Make resource config immutable\n this.resourcesConfig = deepFreeze(this.resourcesConfig);\n this.Auth.configure(this.resourcesConfig.Auth, this.libraryOptions.Auth);\n Hub.dispatch('core', {\n event: 'configure',\n data: this.resourcesConfig,\n }, 'Configure', AMPLIFY_SYMBOL);\n this.notifyOAuthListener();\n }\n /**\n * Provides access to the current back-end resource configuration for the Library.\n *\n * @returns Returns the immutable back-end resource configuration.\n */\n getConfig() {\n return this.resourcesConfig;\n }\n /** @internal */\n [ADD_OAUTH_LISTENER](listener) {\n if (this.resourcesConfig.Auth?.Cognito.loginWith?.oauth) {\n // when Amplify has been configured with a valid OAuth config while adding the listener, run it directly\n listener(this.resourcesConfig.Auth?.Cognito);\n }\n else {\n // otherwise register the listener and run it later when Amplify gets configured with a valid oauth config\n this.oAuthListener = listener;\n }\n }\n notifyOAuthListener() {\n if (!this.resourcesConfig.Auth?.Cognito.loginWith?.oauth ||\n !this.oAuthListener) {\n return;\n }\n this.oAuthListener(this.resourcesConfig.Auth?.Cognito);\n // the listener should only be notified once with a valid oauth config\n this.oAuthListener = undefined;\n }\n}\n/**\n * The `Amplify` utility is used to configure the library.\n *\n * @remarks\n * `Amplify` orchestrates cross-category communication within the library.\n */\nconst Amplify = new AmplifyClass();\n\nexport { Amplify, AmplifyClass };\n//# sourceMappingURL=Amplify.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst fetchAuthSession = (amplify, options) => {\n return amplify.Auth.fetchAuthSession(options);\n};\n\nexport { fetchAuthSession };\n//# sourceMappingURL=fetchAuthSession.mjs.map\n","import { Amplify } from '../Amplify.mjs';\nimport { fetchAuthSession as fetchAuthSession$1 } from './internal/fetchAuthSession.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Fetch the auth session including the tokens and credentials if they are available. By default it\n * does not refresh the auth tokens or credentials if they are loaded in storage already. You can force a refresh\n * with `{ forceRefresh: true }` input.\n *\n * @param options - Options configuring the fetch behavior.\n * @throws {@link AuthError} - Throws error when session information cannot be refreshed.\n * @returns Promise\n */\nconst fetchAuthSession = (options) => {\n return fetchAuthSession$1(Amplify, options);\n};\n\nexport { fetchAuthSession };\n//# sourceMappingURL=fetchAuthSession.mjs.map\n","import { Amplify } from '../Amplify.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction clearCredentials() {\n return Amplify.Auth.clearCredentials();\n}\n\nexport { clearCredentials };\n//# sourceMappingURL=clearCredentials.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst parseMetadata = (response) => {\n const { headers, statusCode } = response;\n return {\n ...(isMetadataBearer(response) ? response.$metadata : {}),\n httpStatusCode: statusCode,\n requestId: headers['x-amzn-requestid'] ??\n headers['x-amzn-request-id'] ??\n headers['x-amz-request-id'],\n extendedRequestId: headers['x-amz-id-2'],\n cfId: headers['x-amz-cf-id'],\n };\n};\nconst isMetadataBearer = (response) => typeof response?.$metadata === 'object';\n\nexport { parseMetadata };\n//# sourceMappingURL=responseInfo.mjs.map\n","import { parseMetadata } from './responseInfo.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Utility functions for serializing and deserializing of JSON protocol in general(including: REST-JSON, JSON-RPC, etc.)\n */\n/**\n * Error parser for AWS JSON protocol.\n */\nconst parseJsonError = async (response) => {\n if (!response || response.statusCode < 300) {\n return;\n }\n const body = await parseJsonBody(response);\n const sanitizeErrorCode = (rawValue) => {\n const [cleanValue] = rawValue.toString().split(/[,:]+/);\n if (cleanValue.includes('#')) {\n return cleanValue.split('#')[1];\n }\n return cleanValue;\n };\n const code = sanitizeErrorCode(response.headers['x-amzn-errortype'] ??\n body.code ??\n body.__type ??\n 'UnknownError');\n const message = body.message ?? body.Message ?? 'Unknown error';\n const error = new Error(message);\n return Object.assign(error, {\n name: code,\n $metadata: parseMetadata(response),\n });\n};\n/**\n * Parse JSON response body to JavaScript object.\n */\nconst parseJsonBody = async (response) => {\n if (!response.body) {\n throw new Error('Missing response payload');\n }\n const output = await response.body.json();\n return Object.assign(output, {\n $metadata: parseMetadata(response),\n });\n};\n\nexport { parseJsonBody, parseJsonError };\n//# sourceMappingURL=json.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Compose a service API handler that accepts input as defined shape and responds conforming to defined output shape.\n * A service API handler is composed with:\n * * A transfer handler\n * * A serializer function\n * * A deserializer function\n * * A default config object\n *\n * The returned service API handler, when called, will trigger the following workflow:\n * 1. When calling the service API handler function, the default config object is merged into the input config\n * object to assign the default values of some omitted configs, resulting to a resolved config object.\n * 2. The `endpointResolver` function from the default config object will be invoked with the resolved config object and\n * API input object resulting to an endpoint instance.\n * 3. The serializer function is invoked with API input object and the endpoint instance resulting to an HTTP request\n * instance.\n * 4. The HTTP request instance and the resolved config object is passed to the transfer handler function.\n * 5. The transfer handler function resolves to an HTTP response instance(can be either successful or failed status code).\n * 6. The deserializer function is invoked with the HTTP response instance resulting to the API output object, and\n * return to the caller.\n *\n *\n * @param transferHandler Async function for dispatching HTTP requests and returning HTTP response.\n * @param serializer Async function for converting object in defined input shape into HTTP request targeting a given\n * \tendpoint.\n * @param deserializer Async function for converting HTTP response into output object in defined output shape, or error\n * \tshape.\n * @param defaultConfig object containing default options to be consumed by transfer handler, serializer and\n * deserializer.\n * @returns a async service API handler function that accepts a config object and input object in defined shape, returns\n * \tan output object in defined shape. It may also throw error instance in defined shape in deserializer. The config\n * object type is composed with options type of transferHandler, endpointResolver function as well as endpointResolver\n * function's input options type, region string. The config object property will be marked as optional if it's also\n * \tdefined in defaultConfig.\n *\n * @internal\n */\nconst composeServiceApi = (transferHandler, serializer, deserializer, defaultConfig) => {\n return async (config, input) => {\n const resolvedConfig = {\n ...defaultConfig,\n ...config,\n };\n // We need to allow different endpoints based on both given config(other than region) and input.\n // However for most of non-S3 services, region is the only input for endpoint resolver.\n const endpoint = await resolvedConfig.endpointResolver(resolvedConfig, input);\n // Unlike AWS SDK clients, a serializer should NOT populate the `host` or `content-length` headers.\n // Both of these headers are prohibited per Spec(https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name).\n // They will be populated automatically by browser, or node-fetch polyfill.\n const request = await serializer(input, endpoint);\n const response = await transferHandler(request, {\n ...resolvedConfig,\n });\n return deserializer(response);\n };\n};\n\nexport { composeServiceApi };\n//# sourceMappingURL=composeServiceApi.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Default partition for AWS services. This is used when the region is not provided or the region is not recognized.\n *\n * @internal\n */\nconst defaultPartition = {\n id: 'aws',\n outputs: {\n dnsSuffix: 'amazonaws.com',\n },\n regionRegex: '^(us|eu|ap|sa|ca|me|af)\\\\-\\\\w+\\\\-\\\\d+$',\n regions: ['aws-global'],\n};\n/**\n * This data is adapted from the partition file from AWS SDK shared utilities but remove some contents for bundle size\n * concern. Information removed are `dualStackDnsSuffix`, `supportDualStack`, `supportFIPS`, restricted partitions, and\n * list of regions for each partition other than global regions.\n *\n * * Ref: https://docs.aws.amazon.com/general/latest/gr/rande.html#regional-endpoints\n * * Ref: https://github.com/aws/aws-sdk-js-v3/blob/0201baef03c2379f1f6f7150b9d401d4b230d488/packages/util-endpoints/src/lib/aws/partitions.json#L1\n *\n * @internal\n */\nconst partitionsInfo = {\n partitions: [\n defaultPartition,\n {\n id: 'aws-cn',\n outputs: {\n dnsSuffix: 'amazonaws.com.cn',\n },\n regionRegex: '^cn\\\\-\\\\w+\\\\-\\\\d+$',\n regions: ['aws-cn-global'],\n },\n ],\n};\n\nexport { defaultPartition, partitionsInfo };\n//# sourceMappingURL=partitions.mjs.map\n","import { defaultPartition, partitionsInfo } from './partitions.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Get the AWS Services endpoint URL's DNS suffix for a given region. A typical AWS regional service endpoint URL will\n * follow this pattern: {endpointPrefix}.{region}.{dnsSuffix}. For example, the endpoint URL for Cognito Identity in\n * us-east-1 will be cognito-identity.us-east-1.amazonaws.com. Here the DnsSuffix is `amazonaws.com`.\n *\n * @param region\n * @returns The DNS suffix\n *\n * @internal\n */\nconst getDnsSuffix = (region) => {\n const { partitions } = partitionsInfo;\n for (const { regions, outputs, regionRegex } of partitions) {\n const regex = new RegExp(regionRegex);\n if (regions.includes(region) || regex.test(region)) {\n return outputs.dnsSuffix;\n }\n }\n return defaultPartition.outputs.dnsSuffix;\n};\n\nexport { getDnsSuffix };\n//# sourceMappingURL=getDnsSuffix.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst DEFAULT_RETRY_ATTEMPTS = 3;\n/**\n * Retry middleware\n */\nconst retryMiddlewareFactory = ({ maxAttempts = DEFAULT_RETRY_ATTEMPTS, retryDecider, computeDelay, abortSignal, }) => {\n if (maxAttempts < 1) {\n throw new Error('maxAttempts must be greater than 0');\n }\n return (next, context) => async function retryMiddleware(request) {\n let error;\n let attemptsCount = context.attemptsCount ?? 0;\n let response;\n // When retry is not needed or max attempts is reached, either error or response will be set. This function handles either cases.\n const handleTerminalErrorOrResponse = () => {\n if (response) {\n addOrIncrementMetadataAttempts(response, attemptsCount);\n return response;\n }\n else {\n addOrIncrementMetadataAttempts(error, attemptsCount);\n throw error;\n }\n };\n while (!abortSignal?.aborted && attemptsCount < maxAttempts) {\n try {\n response = await next(request);\n error = undefined;\n }\n catch (e) {\n error = e;\n response = undefined;\n }\n // context.attemptsCount may be updated after calling next handler which may retry the request by itself.\n attemptsCount =\n (context.attemptsCount ?? 0) > attemptsCount\n ? (context.attemptsCount ?? 0)\n : attemptsCount + 1;\n context.attemptsCount = attemptsCount;\n const { isCredentialsExpiredError, retryable } = await retryDecider(response, error, context);\n if (retryable) {\n // Setting isCredentialsInvalid flag to notify signing middleware to forceRefresh credentials provider.\n context.isCredentialsExpired = !!isCredentialsExpiredError;\n if (!abortSignal?.aborted && attemptsCount < maxAttempts) {\n // prevent sleep for last attempt or cancelled request;\n const delay = computeDelay(attemptsCount);\n await cancellableSleep(delay, abortSignal);\n }\n continue;\n }\n else {\n return handleTerminalErrorOrResponse();\n }\n }\n if (abortSignal?.aborted) {\n throw new Error('Request aborted.');\n }\n else {\n return handleTerminalErrorOrResponse();\n }\n };\n};\nconst cancellableSleep = (timeoutMs, abortSignal) => {\n if (abortSignal?.aborted) {\n return Promise.resolve();\n }\n let timeoutId;\n let sleepPromiseResolveFn;\n const sleepPromise = new Promise(resolve => {\n sleepPromiseResolveFn = resolve;\n timeoutId = setTimeout(resolve, timeoutMs);\n });\n abortSignal?.addEventListener('abort', function cancelSleep(_) {\n clearTimeout(timeoutId);\n abortSignal?.removeEventListener('abort', cancelSleep);\n sleepPromiseResolveFn();\n });\n return sleepPromise;\n};\nconst addOrIncrementMetadataAttempts = (nextHandlerOutput, attempts) => {\n if (Object.prototype.toString.call(nextHandlerOutput) !== '[object Object]') {\n return;\n }\n nextHandlerOutput.$metadata = {\n ...(nextHandlerOutput.$metadata ?? {}),\n attempts,\n };\n};\n\nexport { retryMiddlewareFactory };\n//# sourceMappingURL=middleware.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Middleware injects user agent string to specified header(default to 'x-amz-user-agent'),\n * if the header is not set already.\n *\n * TODO: incorporate new user agent design\n */\nconst userAgentMiddlewareFactory = ({ userAgentHeader = 'x-amz-user-agent', userAgentValue = '', }) => next => {\n return async function userAgentMiddleware(request) {\n if (userAgentValue.trim().length === 0) {\n const result = await next(request);\n return result;\n }\n else {\n const headerName = userAgentHeader.toLowerCase();\n request.headers[headerName] = request.headers[headerName]\n ? `${request.headers[headerName]} ${userAgentValue}`\n : userAgentValue;\n const response = await next(request);\n return response;\n }\n };\n};\n\nexport { userAgentMiddlewareFactory };\n//# sourceMappingURL=middleware.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Compose a transfer handler with a core transfer handler and a list of middleware.\n * @param coreHandler Core transfer handler\n * @param middleware\tList of middleware\n * @returns A transfer handler whose option type is the union of the core\n * \ttransfer handler's option type and the middleware's option type.\n * @internal\n */\nconst composeTransferHandler = (coreHandler, middleware) => (request, options) => {\n const context = {};\n let composedHandler = (composeHandlerRequest) => coreHandler(composeHandlerRequest, options);\n for (let i = middleware.length - 1; i >= 0; i--) {\n const m = middleware[i];\n const resolvedMiddleware = m(options);\n composedHandler = resolvedMiddleware(composedHandler, context);\n }\n return composedHandler(request);\n};\n\nexport { composeTransferHandler };\n//# sourceMappingURL=composeTransferHandler.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Cache the payload of a response body. It allows multiple calls to the body,\n * for example, when reading the body in both retry decider and error deserializer.\n * Caching body is allowed here because we call the body accessor(blob(), json(),\n * etc.) when body is small or streaming implementation is not available(RN).\n *\n * @internal\n */\nconst withMemoization = (payloadAccessor) => {\n let cached;\n return () => {\n if (!cached) {\n // Explicitly not awaiting. Intermediate await would add overhead and\n // introduce a possible race in the event that this wrapper is called\n // again before the first `payloadAccessor` call resolves.\n cached = payloadAccessor();\n }\n return cached;\n };\n};\n\nexport { withMemoization };\n//# sourceMappingURL=memoization.mjs.map\n","import { AmplifyError } from '../../errors/AmplifyError.mjs';\nimport { AmplifyErrorCode } from '../../types/errors.mjs';\nimport '../../errors/errorHelpers.mjs';\nimport { withMemoization } from '../utils/memoization.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst shouldSendBody = (method) => !['HEAD', 'GET', 'DELETE'].includes(method.toUpperCase());\n// TODO[AllanZhengYP]: we need to provide isCanceledError utility\nconst fetchTransferHandler = async ({ url, method, headers, body }, { abortSignal, cache, withCrossDomainCredentials }) => {\n let resp;\n try {\n resp = await fetch(url, {\n method,\n headers,\n body: shouldSendBody(method) ? body : undefined,\n signal: abortSignal,\n cache,\n credentials: withCrossDomainCredentials ? 'include' : 'same-origin',\n });\n }\n catch (e) {\n if (e instanceof TypeError) {\n throw new AmplifyError({\n name: AmplifyErrorCode.NetworkError,\n message: 'A network error has occurred.',\n underlyingError: e,\n });\n }\n throw e;\n }\n const responseHeaders = {};\n resp.headers?.forEach((value, key) => {\n responseHeaders[key.toLowerCase()] = value;\n });\n const httpResponse = {\n statusCode: resp.status,\n headers: responseHeaders,\n body: null,\n };\n // resp.body is a ReadableStream according to Fetch API spec, but React Native\n // does not implement it.\n const bodyWithMixin = Object.assign(resp.body ?? {}, {\n text: withMemoization(() => resp.text()),\n blob: withMemoization(() => resp.blob()),\n json: withMemoization(() => resp.json()),\n });\n return {\n ...httpResponse,\n body: bodyWithMixin,\n };\n};\n\nexport { fetchTransferHandler };\n//# sourceMappingURL=fetch.mjs.map\n","import { retryMiddlewareFactory } from '../middleware/retry/middleware.mjs';\nimport '../../types/errors.mjs';\nimport '../../errors/errorHelpers.mjs';\nimport '../../utils/getClientInfo/getClientInfo.mjs';\nimport '../../utils/retry/retry.mjs';\nimport { userAgentMiddlewareFactory } from '../middleware/userAgent/middleware.mjs';\nimport { composeTransferHandler } from '../internal/composeTransferHandler.mjs';\nimport { fetchTransferHandler } from './fetch.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst unauthenticatedHandler = composeTransferHandler(fetchTransferHandler, [userAgentMiddlewareFactory, retryMiddlewareFactory]);\n\nexport { unauthenticatedHandler };\n//# sourceMappingURL=unauthenticated.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst MAX_DELAY_MS = 5 * 60 * 1000;\n\nexport { MAX_DELAY_MS };\n//# sourceMappingURL=constants.mjs.map\n","import { MAX_DELAY_MS } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @private\n * Internal use of Amplify only\n */\nfunction jitteredBackoff(maxDelayMs = MAX_DELAY_MS) {\n const BASE_TIME_MS = 100;\n const JITTER_FACTOR = 100;\n return attempt => {\n const delay = 2 ** attempt * BASE_TIME_MS + JITTER_FACTOR * Math.random();\n return delay > maxDelayMs ? false : delay;\n };\n}\n\nexport { jitteredBackoff };\n//# sourceMappingURL=jitteredBackoff.mjs.map\n","import '../../../types/errors.mjs';\nimport '../../../errors/errorHelpers.mjs';\nimport '../../../utils/getClientInfo/getClientInfo.mjs';\nimport { jitteredBackoff as jitteredBackoff$1 } from '../../../utils/retry/jitteredBackoff.mjs';\nimport '../../../utils/retry/retry.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// TODO: [v6] The separate retry utility is used by Data packages now and will replaced by retry middleware.\nconst DEFAULT_MAX_DELAY_MS = 5 * 60 * 1000;\nconst jitteredBackoff = attempt => {\n const delayFunction = jitteredBackoff$1(DEFAULT_MAX_DELAY_MS);\n const delay = delayFunction(attempt);\n // The delayFunction returns false when the delay is greater than the max delay(5 mins).\n // In this case, the retry middleware will delay 5 mins instead, as a ceiling of the delay.\n return delay === false ? DEFAULT_MAX_DELAY_MS : delay;\n};\n\nexport { jitteredBackoff };\n//# sourceMappingURL=jitteredBackoff.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// via https://github.com/aws/aws-sdk-js-v3/blob/ab0e7be36e7e7f8a0c04834357aaad643c7912c3/packages/service-error-classification/src/constants.ts#L8\nconst CLOCK_SKEW_ERROR_CODES = [\n 'AuthFailure',\n 'InvalidSignatureException',\n 'RequestExpired',\n 'RequestInTheFuture',\n 'RequestTimeTooSkewed',\n 'SignatureDoesNotMatch',\n 'BadRequestException', // API Gateway\n];\n/**\n * Given an error code, returns true if it is related to a clock skew error.\n *\n * @param errorCode String representation of some error.\n * @returns True if given error is present in `CLOCK_SKEW_ERROR_CODES`, false otherwise.\n *\n * @internal\n */\nconst isClockSkewError = (errorCode) => !!errorCode && CLOCK_SKEW_ERROR_CODES.includes(errorCode);\n\nexport { isClockSkewError };\n//# sourceMappingURL=isClockSkewError.mjs.map\n","import { AmplifyErrorCode } from '../../../types/errors.mjs';\nimport { isClockSkewError } from './isClockSkewError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Get retry decider function\n * @param errorParser Function to load JavaScript error from HTTP response\n */\nconst getRetryDecider = (errorParser) => async (response, error) => {\n const parsedError = error ??\n (await errorParser(response)) ??\n undefined;\n const errorCode = parsedError?.code || parsedError?.name;\n const statusCode = response?.statusCode;\n const isRetryable = isConnectionError(error) ||\n isThrottlingError(statusCode, errorCode) ||\n isClockSkewError(errorCode) ||\n isServerSideError(statusCode, errorCode);\n return {\n retryable: isRetryable,\n };\n};\n// reference: https://github.com/aws/aws-sdk-js-v3/blob/ab0e7be36e7e7f8a0c04834357aaad643c7912c3/packages/service-error-classification/src/constants.ts#L22-L37\nconst THROTTLING_ERROR_CODES = [\n 'BandwidthLimitExceeded',\n 'EC2ThrottledException',\n 'LimitExceededException',\n 'PriorRequestNotComplete',\n 'ProvisionedThroughputExceededException',\n 'RequestLimitExceeded',\n 'RequestThrottled',\n 'RequestThrottledException',\n 'SlowDown',\n 'ThrottledException',\n 'Throttling',\n 'ThrottlingException',\n 'TooManyRequestsException',\n];\nconst TIMEOUT_ERROR_CODES = [\n 'TimeoutError',\n 'RequestTimeout',\n 'RequestTimeoutException',\n];\nconst isThrottlingError = (statusCode, errorCode) => statusCode === 429 ||\n (!!errorCode && THROTTLING_ERROR_CODES.includes(errorCode));\nconst isConnectionError = (error) => [\n AmplifyErrorCode.NetworkError,\n // TODO(vNext): unify the error code `ERR_NETWORK` used by the Storage XHR handler\n 'ERR_NETWORK',\n].includes(error?.name);\nconst isServerSideError = (statusCode, errorCode) => (!!statusCode && [500, 502, 503, 504].includes(statusCode)) ||\n (!!errorCode && TIMEOUT_ERROR_CODES.includes(errorCode));\n\nexport { getRetryDecider };\n//# sourceMappingURL=defaultRetryDecider.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst AmplifyUrl = URL;\nconst AmplifyUrlSearchParams = URLSearchParams;\n\nexport { AmplifyUrl, AmplifyUrlSearchParams };\n//# sourceMappingURL=index.mjs.map\n","import { getDnsSuffix } from '../../clients/endpoints/getDnsSuffix.mjs';\nimport '../../types/errors.mjs';\nimport '../../errors/errorHelpers.mjs';\nimport { unauthenticatedHandler } from '../../clients/handlers/unauthenticated.mjs';\nimport { jitteredBackoff } from '../../clients/middleware/retry/jitteredBackoff.mjs';\nimport { getRetryDecider } from '../../clients/middleware/retry/defaultRetryDecider.mjs';\nimport '@aws-crypto/sha256-js';\nimport '@smithy/util-hex-encoding';\nimport { AmplifyUrl } from '../../utils/amplifyUrl/index.mjs';\nimport { composeTransferHandler } from '../../clients/internal/composeTransferHandler.mjs';\nimport { parseJsonError } from '../../clients/serde/json.mjs';\nimport { getAmplifyUserAgent } from '../../Platform/index.mjs';\nimport { observeFrameworkChanges } from '../../Platform/detectFramework.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * The service name used to sign requests if the API requires authentication.\n */\nconst SERVICE_NAME = 'cognito-identity';\n/**\n * The endpoint resolver function that returns the endpoint URL for a given region.\n */\nconst endpointResolver = ({ region }) => ({\n url: new AmplifyUrl(`https://cognito-identity.${region}.${getDnsSuffix(region)}`),\n});\n/**\n * A Cognito Identity-specific middleware that disables caching for all requests.\n */\nconst disableCacheMiddlewareFactory = () => next => async function disableCacheMiddleware(request) {\n request.headers['cache-control'] = 'no-store';\n return next(request);\n};\n/**\n * A Cognito Identity-specific transfer handler that does NOT sign requests, and\n * disables caching.\n *\n * @internal\n */\nconst cognitoIdentityTransferHandler = composeTransferHandler(unauthenticatedHandler, [disableCacheMiddlewareFactory]);\n/**\n * @internal\n */\nconst defaultConfig = {\n service: SERVICE_NAME,\n endpointResolver,\n retryDecider: getRetryDecider(parseJsonError),\n computeDelay: jitteredBackoff,\n userAgentValue: getAmplifyUserAgent(),\n cache: 'no-store',\n};\nobserveFrameworkChanges(() => {\n defaultConfig.userAgentValue = getAmplifyUserAgent();\n});\n/**\n * @internal\n */\nconst getSharedHeaders = (operation) => ({\n 'content-type': 'application/x-amz-json-1.1',\n 'x-amz-target': `AWSCognitoIdentityService.${operation}`,\n});\n/**\n * @internal\n */\nconst buildHttpRpcRequest = ({ url }, headers, body) => ({\n headers,\n url,\n body,\n method: 'POST',\n});\n\nexport { buildHttpRpcRequest, cognitoIdentityTransferHandler, defaultConfig, getSharedHeaders };\n//# sourceMappingURL=base.mjs.map\n","import '../../types/errors.mjs';\nimport '../../errors/errorHelpers.mjs';\nimport '../../utils/getClientInfo/getClientInfo.mjs';\nimport '../../utils/retry/retry.mjs';\nimport '@aws-crypto/sha256-js';\nimport '@smithy/util-hex-encoding';\nimport { parseMetadata } from '../../clients/serde/responseInfo.mjs';\nimport { parseJsonError, parseJsonBody } from '../../clients/serde/json.mjs';\nimport { composeServiceApi } from '../../clients/internal/composeServiceApi.mjs';\nimport { defaultConfig, cognitoIdentityTransferHandler, buildHttpRpcRequest, getSharedHeaders } from './base.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst getIdSerializer = (input, endpoint) => {\n const headers = getSharedHeaders('GetId');\n const body = JSON.stringify(input);\n return buildHttpRpcRequest(endpoint, headers, body);\n};\nconst getIdDeserializer = async (response) => {\n if (response.statusCode >= 300) {\n const error = await parseJsonError(response);\n throw error;\n }\n else {\n const body = await parseJsonBody(response);\n return {\n IdentityId: body.IdentityId,\n $metadata: parseMetadata(response),\n };\n }\n};\n/**\n * @internal\n */\nconst getId = composeServiceApi(cognitoIdentityTransferHandler, getIdSerializer, getIdDeserializer, defaultConfig);\n\nexport { getId };\n//# sourceMappingURL=getId.mjs.map\n","import '../../types/errors.mjs';\nimport '../../errors/errorHelpers.mjs';\nimport '../../utils/getClientInfo/getClientInfo.mjs';\nimport '../../utils/retry/retry.mjs';\nimport '@aws-crypto/sha256-js';\nimport '@smithy/util-hex-encoding';\nimport { parseMetadata } from '../../clients/serde/responseInfo.mjs';\nimport { parseJsonError, parseJsonBody } from '../../clients/serde/json.mjs';\nimport { composeServiceApi } from '../../clients/internal/composeServiceApi.mjs';\nimport { defaultConfig, cognitoIdentityTransferHandler, buildHttpRpcRequest, getSharedHeaders } from './base.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst getCredentialsForIdentitySerializer = (input, endpoint) => {\n const headers = getSharedHeaders('GetCredentialsForIdentity');\n const body = JSON.stringify(input);\n return buildHttpRpcRequest(endpoint, headers, body);\n};\nconst getCredentialsForIdentityDeserializer = async (response) => {\n if (response.statusCode >= 300) {\n const error = await parseJsonError(response);\n throw error;\n }\n else {\n const body = await parseJsonBody(response);\n return {\n IdentityId: body.IdentityId,\n Credentials: deserializeCredentials(body.Credentials),\n $metadata: parseMetadata(response),\n };\n }\n};\nconst deserializeCredentials = ({ AccessKeyId, SecretKey, SessionToken, Expiration, } = {}) => {\n return {\n AccessKeyId,\n SecretKey,\n SessionToken,\n Expiration: Expiration && new Date(Expiration * 1000),\n };\n};\n/**\n * @internal\n */\nconst getCredentialsForIdentity = composeServiceApi(cognitoIdentityTransferHandler, getCredentialsForIdentitySerializer, getCredentialsForIdentityDeserializer, defaultConfig);\n\nexport { getCredentialsForIdentity };\n//# sourceMappingURL=getCredentialsForIdentity.mjs.map\n","import { AmplifyErrorCode } from '../types/errors.mjs';\nimport { AmplifyError } from './AmplifyError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass PlatformNotSupportedError extends AmplifyError {\n constructor() {\n super({\n name: AmplifyErrorCode.PlatformNotSupported,\n message: 'Function not supported on current platform',\n });\n }\n}\n\nexport { PlatformNotSupportedError };\n//# sourceMappingURL=PlatformNotSupportedError.mjs.map\n","import { PlatformNotSupportedError } from '../errors/PlatformNotSupportedError.mjs';\nimport '../errors/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @internal\n */\nclass KeyValueStorage {\n constructor(storage) {\n this.storage = storage;\n }\n /**\n * This is used to set a specific item in storage\n * @param {string} key - the key for the item\n * @param {object} value - the value\n * @returns {string} value that was set\n */\n async setItem(key, value) {\n if (!this.storage)\n throw new PlatformNotSupportedError();\n this.storage.setItem(key, value);\n }\n /**\n * This is used to get a specific key from storage\n * @param {string} key - the key for the item\n * This is used to clear the storage\n * @returns {string} the data item\n */\n async getItem(key) {\n if (!this.storage)\n throw new PlatformNotSupportedError();\n return this.storage.getItem(key);\n }\n /**\n * This is used to remove an item from storage\n * @param {string} key - the key being set\n * @returns {string} value - value that was deleted\n */\n async removeItem(key) {\n if (!this.storage)\n throw new PlatformNotSupportedError();\n this.storage.removeItem(key);\n }\n /**\n * This is used to clear the storage\n * @returns {string} nothing\n */\n async clear() {\n if (!this.storage)\n throw new PlatformNotSupportedError();\n this.storage.clear();\n }\n}\n\nexport { KeyValueStorage };\n//# sourceMappingURL=KeyValueStorage.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @internal\n */\nclass InMemoryStorage {\n constructor() {\n this.storage = new Map();\n }\n get length() {\n return this.storage.size;\n }\n key(index) {\n if (index > this.length - 1) {\n return null;\n }\n return Array.from(this.storage.keys())[index];\n }\n setItem(key, value) {\n this.storage.set(key, value);\n }\n getItem(key) {\n return this.storage.get(key) ?? null;\n }\n removeItem(key) {\n this.storage.delete(key);\n }\n clear() {\n this.storage.clear();\n }\n}\n\nexport { InMemoryStorage };\n//# sourceMappingURL=InMemoryStorage.mjs.map\n","import { ConsoleLogger } from '../Logger/ConsoleLogger.mjs';\nimport { InMemoryStorage } from './InMemoryStorage.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @internal\n * @returns Either a reference to window.localStorage or an in-memory storage as fallback\n */\nconst logger = new ConsoleLogger('CoreStorageUtils');\nconst getLocalStorageWithFallback = () => {\n try {\n // Attempt to use localStorage directly\n if (typeof window !== 'undefined' && window.localStorage) {\n return window.localStorage;\n }\n }\n catch (e) {\n // Handle any errors related to localStorage access\n logger.info('localStorage not found. InMemoryStorage is used as a fallback.');\n }\n // Return in-memory storage as a fallback if localStorage is not accessible\n return new InMemoryStorage();\n};\n/**\n * @internal\n * @returns Either a reference to window.sessionStorage or an in-memory storage as fallback\n */\nconst getSessionStorageWithFallback = () => {\n try {\n // Attempt to use sessionStorage directly\n if (typeof window !== 'undefined' && window.sessionStorage) {\n // Verify we can actually use it by testing access\n window.sessionStorage.getItem('test');\n return window.sessionStorage;\n }\n throw new Error('sessionStorage is not defined');\n }\n catch (e) {\n // Handle any errors related to sessionStorage access\n logger.info('sessionStorage not found. InMemoryStorage is used as a fallback.');\n return new InMemoryStorage();\n }\n};\n\nexport { getLocalStorageWithFallback, getSessionStorageWithFallback };\n//# sourceMappingURL=utils.mjs.map\n","import { KeyValueStorage } from './KeyValueStorage.mjs';\nimport { getLocalStorageWithFallback } from './utils.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @internal\n */\nclass DefaultStorage extends KeyValueStorage {\n constructor() {\n super(getLocalStorageWithFallback());\n }\n}\n\nexport { DefaultStorage };\n//# sourceMappingURL=DefaultStorage.mjs.map\n","import { KeyValueStorage } from './KeyValueStorage.mjs';\nimport { getSessionStorageWithFallback } from './utils.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @internal\n */\nclass SessionStorage extends KeyValueStorage {\n constructor() {\n super(getSessionStorageWithFallback());\n }\n}\n\nexport { SessionStorage };\n//# sourceMappingURL=SessionStorage.mjs.map\n","import { PlatformNotSupportedError } from '../errors/PlatformNotSupportedError.mjs';\nimport '../errors/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @internal\n */\nclass SyncKeyValueStorage {\n constructor(storage) {\n this._storage = storage;\n }\n get storage() {\n if (!this._storage)\n throw new PlatformNotSupportedError();\n return this._storage;\n }\n /**\n * This is used to set a specific item in storage\n * @param {string} key - the key for the item\n * @param {object} value - the value\n * @returns {string} value that was set\n */\n setItem(key, value) {\n this.storage.setItem(key, value);\n }\n /**\n * This is used to get a specific key from storage\n * @param {string} key - the key for the item\n * This is used to clear the storage\n * @returns {string} the data item\n */\n getItem(key) {\n return this.storage.getItem(key);\n }\n /**\n * This is used to remove an item from storage\n * @param {string} key - the key being set\n * @returns {string} value - value that was deleted\n */\n removeItem(key) {\n this.storage.removeItem(key);\n }\n /**\n * This is used to clear the storage\n * @returns {string} nothing\n */\n clear() {\n this.storage.clear();\n }\n}\n\nexport { SyncKeyValueStorage };\n//# sourceMappingURL=SyncKeyValueStorage.mjs.map\n","import { SyncKeyValueStorage } from './SyncKeyValueStorage.mjs';\nimport { getSessionStorageWithFallback } from './utils.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @internal\n */\nclass SyncSessionStorage extends SyncKeyValueStorage {\n constructor() {\n super(getSessionStorageWithFallback());\n }\n}\n\nexport { SyncSessionStorage };\n//# sourceMappingURL=SyncSessionStorage.mjs.map\n","/*! js-cookie v3.0.5 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n function set (name, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n name = encodeURIComponent(name)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n name + '=' + converter.write(value, name) + stringifiedAttributes)\n }\n\n function get (name) {\n if (typeof document === 'undefined' || (arguments.length && !name)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var found = decodeURIComponent(parts[0]);\n jar[found] = converter.read(value, found);\n\n if (name === found) {\n break\n }\n } catch (e) {}\n }\n\n return name ? jar[name] : jar\n }\n\n return Object.create(\n {\n set,\n get,\n remove: function (name, attributes) {\n set(\n name,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n/* eslint-enable no-var */\n\nexport { api as default };\n","import JsCookie from 'js-cookie';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass CookieStorage {\n constructor(data = {}) {\n const { path, domain, expires, sameSite, secure } = data;\n this.domain = domain;\n this.path = path || '/';\n this.expires = Object.prototype.hasOwnProperty.call(data, 'expires')\n ? expires\n : 365;\n this.secure = Object.prototype.hasOwnProperty.call(data, 'secure')\n ? secure\n : true;\n if (Object.prototype.hasOwnProperty.call(data, 'sameSite')) {\n if (!sameSite || !['strict', 'lax', 'none'].includes(sameSite)) {\n throw new Error('The sameSite value of cookieStorage must be \"lax\", \"strict\" or \"none\".');\n }\n if (sameSite === 'none' && !this.secure) {\n throw new Error('sameSite = None requires the Secure attribute in latest browser versions.');\n }\n this.sameSite = sameSite;\n }\n }\n async setItem(key, value) {\n JsCookie.set(key, value, this.getData());\n }\n async getItem(key) {\n const item = JsCookie.get(key);\n return item ?? null;\n }\n async removeItem(key) {\n JsCookie.remove(key, this.getData());\n }\n async clear() {\n const cookie = JsCookie.get();\n const promises = Object.keys(cookie).map(key => this.removeItem(key));\n await Promise.all(promises);\n }\n getData() {\n return {\n path: this.path,\n expires: this.expires,\n domain: this.domain,\n secure: this.secure,\n ...(this.sameSite && { sameSite: this.sameSite }),\n };\n }\n}\n\nexport { CookieStorage };\n//# sourceMappingURL=CookieStorage.mjs.map\n","import { DefaultStorage } from './DefaultStorage.mjs';\nimport { InMemoryStorage } from './InMemoryStorage.mjs';\nimport { KeyValueStorage } from './KeyValueStorage.mjs';\nimport { SessionStorage } from './SessionStorage.mjs';\nimport { SyncSessionStorage } from './SyncSessionStorage.mjs';\nexport { CookieStorage } from './CookieStorage.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst defaultStorage = new DefaultStorage();\nconst sessionStorage = new SessionStorage();\nconst syncSessionStorage = new SyncSessionStorage();\nconst sharedInMemoryStorage = new KeyValueStorage(new InMemoryStorage());\n\nexport { defaultStorage, sessionStorage, sharedInMemoryStorage, syncSessionStorage };\n//# sourceMappingURL=index.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Default cache config\n */\nconst defaultConfig = {\n keyPrefix: 'aws-amplify-cache',\n capacityInBytes: 1048576,\n itemMaxSize: 210000,\n defaultTTL: 259200000,\n defaultPriority: 5,\n warningThreshold: 0.8,\n};\nconst currentSizeKey = 'CurSize';\n\nexport { currentSizeKey, defaultConfig };\n//# sourceMappingURL=constants.mjs.map\n","import { currentSizeKey } from '../constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * return the byte size of the string\n * @param str\n */\nfunction getByteLength(str) {\n let ret = 0;\n ret = str.length;\n for (let i = str.length; i >= 0; i -= 1) {\n const charCode = str.charCodeAt(i);\n if (charCode > 0x7f && charCode <= 0x7ff) {\n ret += 1;\n }\n else if (charCode > 0x7ff && charCode <= 0xffff) {\n ret += 2;\n }\n // trail surrogate\n if (charCode >= 0xdc00 && charCode <= 0xdfff) {\n i -= 1;\n }\n }\n return ret;\n}\n/**\n * get current time\n */\nfunction getCurrentTime() {\n const currentTime = new Date();\n return currentTime.getTime();\n}\n/**\n * check if passed value is an integer\n */\nfunction isInteger(value) {\n if (Number.isInteger) {\n return Number.isInteger(value);\n }\n return (typeof value === 'number' && isFinite(value) && Math.floor(value) === value);\n}\nconst getCurrentSizeKey = (keyPrefix) => `${keyPrefix}${currentSizeKey}`;\n\nexport { getByteLength, getCurrentSizeKey, getCurrentTime, isInteger };\n//# sourceMappingURL=cacheHelpers.mjs.map\n","import { createAssertionFunction } from '../../errors/createAssertionFunction.mjs';\nimport '../../types/errors.mjs';\nimport '../../errors/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nvar CacheErrorCode;\n(function (CacheErrorCode) {\n CacheErrorCode[\"NoCacheItem\"] = \"NoCacheItem\";\n CacheErrorCode[\"NullNextNode\"] = \"NullNextNode\";\n CacheErrorCode[\"NullPreviousNode\"] = \"NullPreviousNode\";\n})(CacheErrorCode || (CacheErrorCode = {}));\nconst cacheErrorMap = {\n [CacheErrorCode.NoCacheItem]: {\n message: 'Item not found in the cache storage.',\n },\n [CacheErrorCode.NullNextNode]: {\n message: 'Next node is null.',\n },\n [CacheErrorCode.NullPreviousNode]: {\n message: 'Previous node is null.',\n },\n};\nconst assert = createAssertionFunction(cacheErrorMap);\n\nexport { CacheErrorCode, assert };\n//# sourceMappingURL=errorHelpers.mjs.map\n","import { ConsoleLogger } from '../Logger/ConsoleLogger.mjs';\nimport { defaultConfig, currentSizeKey } from './constants.mjs';\nimport { getCurrentSizeKey, getCurrentTime, getByteLength } from './utils/cacheHelpers.mjs';\nimport { assert, CacheErrorCode } from './utils/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('StorageCache');\n/**\n * Initialization of the cache\n *\n */\nclass StorageCacheCommon {\n /**\n * Initialize the cache\n *\n * @param config - Custom configuration for this instance.\n */\n constructor({ config, keyValueStorage, }) {\n this.config = {\n ...defaultConfig,\n ...config,\n };\n this.keyValueStorage = keyValueStorage;\n this.sanitizeConfig();\n }\n getModuleName() {\n return 'Cache';\n }\n /**\n * Set custom configuration for the cache instance.\n *\n * @param config - customized configuration (without keyPrefix, which can't be changed)\n *\n * @return - the current configuration\n */\n configure(config) {\n if (config) {\n if (config.keyPrefix) {\n logger.warn('keyPrefix can not be re-configured on an existing Cache instance.');\n }\n this.config = {\n ...this.config,\n ...config,\n };\n }\n this.sanitizeConfig();\n return this.config;\n }\n /**\n * return the current size of the cache\n * @return {Promise}\n */\n async getCurrentCacheSize() {\n let size = await this.getStorage().getItem(getCurrentSizeKey(this.config.keyPrefix));\n if (!size) {\n await this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), '0');\n size = '0';\n }\n return Number(size);\n }\n /**\n * Set item into cache. You can put number, string, boolean or object.\n * The cache will first check whether has the same key.\n * If it has, it will delete the old item and then put the new item in\n * The cache will pop out items if it is full\n * You can specify the cache item options. The cache will abort and output a warning:\n * If the key is invalid\n * If the size of the item exceeds itemMaxSize.\n * If the value is undefined\n * If incorrect cache item configuration\n * If error happened with browser storage\n *\n * @param {String} key - the key of the item\n * @param {Object} value - the value of the item\n * @param {Object} [options] - optional, the specified meta-data\n *\n * @return {Promise}\n */\n async setItem(key, value, options) {\n logger.debug(`Set item: key is ${key}, value is ${value} with options: ${options}`);\n if (!key || key === currentSizeKey) {\n logger.warn(`Invalid key: should not be empty or reserved key: '${currentSizeKey}'`);\n return;\n }\n if (typeof value === 'undefined') {\n logger.warn(`The value of item should not be undefined!`);\n return;\n }\n const cacheItemOptions = {\n priority: options?.priority !== undefined\n ? options.priority\n : this.config.defaultPriority,\n expires: options?.expires !== undefined\n ? options.expires\n : this.config.defaultTTL + getCurrentTime(),\n };\n if (cacheItemOptions.priority < 1 || cacheItemOptions.priority > 5) {\n logger.warn(`Invalid parameter: priority due to out or range. It should be within 1 and 5.`);\n return;\n }\n const prefixedKey = `${this.config.keyPrefix}${key}`;\n const item = this.fillCacheItem(prefixedKey, value, cacheItemOptions);\n // check whether this item is too big;\n if (item.byteSize > this.config.itemMaxSize) {\n logger.warn(`Item with key: ${key} you are trying to put into is too big!`);\n return;\n }\n try {\n // first look into the storage, if it exists, delete it.\n const val = await this.getStorage().getItem(prefixedKey);\n if (val) {\n await this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize);\n }\n // check whether the cache is full\n if (await this.isCacheFull(item.byteSize)) {\n const validKeys = await this.clearInvalidAndGetRemainingKeys();\n if (await this.isCacheFull(item.byteSize)) {\n const sizeToPop = await this.sizeToPop(item.byteSize);\n await this.popOutItems(validKeys, sizeToPop);\n }\n }\n // put item in the cache\n return this.setCacheItem(prefixedKey, item);\n }\n catch (e) {\n logger.warn(`setItem failed! ${e}`);\n }\n }\n /**\n * Get item from cache. It will return null if item doesn’t exist or it has been expired.\n * If you specified callback function in the options,\n * then the function will be executed if no such item in the cache\n * and finally put the return value into cache.\n * Please make sure the callback function will return the value you want to put into the cache.\n * The cache will abort output a warning:\n * If the key is invalid\n * If error happened with AsyncStorage\n *\n * @param {String} key - the key of the item\n * @param {Object} [options] - the options of callback function\n *\n * @return {Promise} - return a promise resolves to be the value of the item\n */\n async getItem(key, options) {\n logger.debug(`Get item: key is ${key} with options ${options}`);\n let cached;\n if (!key || key === currentSizeKey) {\n logger.warn(`Invalid key: should not be empty or reserved key: '${currentSizeKey}'`);\n return null;\n }\n const prefixedKey = `${this.config.keyPrefix}${key}`;\n try {\n cached = await this.getStorage().getItem(prefixedKey);\n if (cached != null) {\n if (await this.isExpired(prefixedKey)) {\n // if expired, remove that item and return null\n await this.removeCacheItem(prefixedKey, JSON.parse(cached).byteSize);\n }\n else {\n // if not expired, update its visitedTime and return the value\n const item = await this.updateVisitedTime(JSON.parse(cached), prefixedKey);\n return item.data;\n }\n }\n if (options?.callback) {\n const val = options.callback();\n if (val !== null) {\n await this.setItem(key, val, options);\n }\n return val;\n }\n return null;\n }\n catch (e) {\n logger.warn(`getItem failed! ${e}`);\n return null;\n }\n }\n /**\n * remove item from the cache\n * The cache will abort output a warning:\n * If error happened with AsyncStorage\n * @param {String} key - the key of the item\n * @return {Promise}\n */\n async removeItem(key) {\n logger.debug(`Remove item: key is ${key}`);\n if (!key || key === currentSizeKey) {\n logger.warn(`Invalid key: should not be empty or reserved key: '${currentSizeKey}'`);\n return;\n }\n const prefixedKey = `${this.config.keyPrefix}${key}`;\n try {\n const val = await this.getStorage().getItem(prefixedKey);\n if (val) {\n await this.removeCacheItem(prefixedKey, JSON.parse(val).byteSize);\n }\n }\n catch (e) {\n logger.warn(`removeItem failed! ${e}`);\n }\n }\n /**\n * Return all the keys owned by this cache.\n * Will return an empty array if error occurred.\n *\n * @return {Promise}\n */\n async getAllKeys() {\n try {\n return await this.getAllCacheKeys();\n }\n catch (e) {\n logger.warn(`getAllkeys failed! ${e}`);\n return [];\n }\n }\n getStorage() {\n return this.keyValueStorage;\n }\n /**\n * check whether item is expired\n *\n * @param key - the key of the item\n *\n * @return true if the item is expired.\n */\n async isExpired(key) {\n const text = await this.getStorage().getItem(key);\n assert(text !== null, CacheErrorCode.NoCacheItem, `Key: ${key}`);\n const item = JSON.parse(text);\n if (getCurrentTime() >= item.expires) {\n return true;\n }\n return false;\n }\n /**\n * delete item from cache\n *\n * @param prefixedKey - the key of the item\n * @param size - optional, the byte size of the item\n */\n async removeCacheItem(prefixedKey, size) {\n const item = await this.getStorage().getItem(prefixedKey);\n assert(item !== null, CacheErrorCode.NoCacheItem, `Key: ${prefixedKey}`);\n const itemSize = size ?? JSON.parse(item).byteSize;\n // first try to update the current size of the cache\n await this.decreaseCurrentSizeInBytes(itemSize);\n // try to remove the item from cache\n try {\n await this.getStorage().removeItem(prefixedKey);\n }\n catch (removeItemError) {\n // if some error happened, we need to rollback the current size\n await this.increaseCurrentSizeInBytes(itemSize);\n logger.error(`Failed to remove item: ${removeItemError}`);\n }\n }\n /**\n * produce a JSON object with meta-data and data value\n * @param value - the value of the item\n * @param options - optional, the specified meta-data\n *\n * @return - the item which has the meta-data and the value\n */\n fillCacheItem(key, value, options) {\n const item = {\n key,\n data: value,\n timestamp: getCurrentTime(),\n visitedTime: getCurrentTime(),\n priority: options.priority ?? 0,\n expires: options.expires ?? 0,\n type: typeof value,\n byteSize: 0,\n };\n // calculate byte size\n item.byteSize = getByteLength(JSON.stringify(item));\n // re-calculate using cache item with updated byteSize property\n item.byteSize = getByteLength(JSON.stringify(item));\n return item;\n }\n sanitizeConfig() {\n if (this.config.itemMaxSize > this.config.capacityInBytes) {\n logger.error('Invalid parameter: itemMaxSize. It should be smaller than capacityInBytes. Setting back to default.');\n this.config.itemMaxSize = defaultConfig.itemMaxSize;\n }\n if (this.config.defaultPriority > 5 || this.config.defaultPriority < 1) {\n logger.error('Invalid parameter: defaultPriority. It should be between 1 and 5. Setting back to default.');\n this.config.defaultPriority = defaultConfig.defaultPriority;\n }\n if (Number(this.config.warningThreshold) > 1 ||\n Number(this.config.warningThreshold) < 0) {\n logger.error('Invalid parameter: warningThreshold. It should be between 0 and 1. Setting back to default.');\n this.config.warningThreshold = defaultConfig.warningThreshold;\n }\n // Set 5MB limit\n const cacheLimit = 5 * 1024 * 1024;\n if (this.config.capacityInBytes > cacheLimit) {\n logger.error('Cache Capacity should be less than 5MB. Setting back to default. Setting back to default.');\n this.config.capacityInBytes = defaultConfig.capacityInBytes;\n }\n }\n /**\n * increase current size of the cache\n *\n * @param amount - the amount of the cache szie which need to be increased\n */\n async increaseCurrentSizeInBytes(amount) {\n const size = await this.getCurrentCacheSize();\n await this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), (size + amount).toString());\n }\n /**\n * decrease current size of the cache\n *\n * @param amount - the amount of the cache size which needs to be decreased\n */\n async decreaseCurrentSizeInBytes(amount) {\n const size = await this.getCurrentCacheSize();\n await this.getStorage().setItem(getCurrentSizeKey(this.config.keyPrefix), (size - amount).toString());\n }\n /**\n * update the visited time if item has been visited\n *\n * @param item - the item which need to be updated\n * @param prefixedKey - the key of the item\n *\n * @return the updated item\n */\n async updateVisitedTime(item, prefixedKey) {\n item.visitedTime = getCurrentTime();\n await this.getStorage().setItem(prefixedKey, JSON.stringify(item));\n return item;\n }\n /**\n * put item into cache\n *\n * @param prefixedKey - the key of the item\n * @param itemData - the value of the item\n * @param itemSizeInBytes - the byte size of the item\n */\n async setCacheItem(prefixedKey, item) {\n // first try to update the current size of the cache.\n await this.increaseCurrentSizeInBytes(item.byteSize);\n // try to add the item into cache\n try {\n await this.getStorage().setItem(prefixedKey, JSON.stringify(item));\n }\n catch (setItemErr) {\n // if some error happened, we need to rollback the current size\n await this.decreaseCurrentSizeInBytes(item.byteSize);\n logger.error(`Failed to set item ${setItemErr}`);\n }\n }\n /**\n * total space needed when poping out items\n *\n * @param itemSize\n *\n * @return total space needed\n */\n async sizeToPop(itemSize) {\n const cur = await this.getCurrentCacheSize();\n const spaceItemNeed = cur + itemSize - this.config.capacityInBytes;\n const cacheThresholdSpace = (1 - this.config.warningThreshold) * this.config.capacityInBytes;\n return spaceItemNeed > cacheThresholdSpace\n ? spaceItemNeed\n : cacheThresholdSpace;\n }\n /**\n * see whether cache is full\n *\n * @param itemSize\n *\n * @return true if cache is full\n */\n async isCacheFull(itemSize) {\n const cur = await this.getCurrentCacheSize();\n return itemSize + cur > this.config.capacityInBytes;\n }\n /**\n * get all the items we have, sort them by their priority,\n * if priority is same, sort them by their last visited time\n * pop out items from the low priority (5 is the lowest)\n * @private\n * @param keys - all the keys in this cache\n * @param sizeToPop - the total size of the items which needed to be poped out\n */\n async popOutItems(keys, sizeToPop) {\n const items = [];\n let remainedSize = sizeToPop;\n for (const key of keys) {\n const val = await this.getStorage().getItem(key);\n if (val != null) {\n const item = JSON.parse(val);\n items.push(item);\n }\n }\n // first compare priority\n // then compare visited time\n items.sort((a, b) => {\n if (a.priority > b.priority) {\n return -1;\n }\n else if (a.priority < b.priority) {\n return 1;\n }\n else {\n if (a.visitedTime < b.visitedTime) {\n return -1;\n }\n else\n return 1;\n }\n });\n for (const item of items) {\n // pop out items until we have enough room for new item\n await this.removeCacheItem(item.key, item.byteSize);\n remainedSize -= item.byteSize;\n if (remainedSize <= 0) {\n return;\n }\n }\n }\n /**\n * Scan the storage and combine the following operations for efficiency\n * 1. Clear out all expired keys owned by this cache, not including the size key.\n * 2. Return the remaining keys.\n *\n * @return The remaining valid keys\n */\n async clearInvalidAndGetRemainingKeys() {\n const remainingKeys = [];\n const keys = await this.getAllCacheKeys({\n omitSizeKey: true,\n });\n for (const key of keys) {\n if (await this.isExpired(key)) {\n await this.removeCacheItem(key);\n }\n else {\n remainingKeys.push(key);\n }\n }\n return remainingKeys;\n }\n /**\n * clear the entire cache\n * The cache will abort and output a warning if error occurs\n * @return {Promise}\n */\n async clear() {\n logger.debug(`Clear Cache`);\n try {\n const keys = await this.getAllKeys();\n for (const key of keys) {\n const prefixedKey = `${this.config.keyPrefix}${key}`;\n await this.getStorage().removeItem(prefixedKey);\n }\n }\n catch (e) {\n logger.warn(`clear failed! ${e}`);\n }\n }\n}\n\nexport { StorageCacheCommon };\n//# sourceMappingURL=StorageCacheCommon.mjs.map\n","import { ConsoleLogger } from '../Logger/ConsoleLogger.mjs';\nimport { KeyValueStorage } from '../storage/KeyValueStorage.mjs';\nimport { getLocalStorageWithFallback } from '../storage/utils.mjs';\nimport { defaultConfig } from './constants.mjs';\nimport { StorageCacheCommon } from './StorageCacheCommon.mjs';\nimport { getCurrentSizeKey, getCurrentTime } from './utils/cacheHelpers.mjs';\nimport './utils/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('StorageCache');\n/**\n * Customized storage based on the SessionStorage or LocalStorage with LRU implemented\n */\nclass StorageCache extends StorageCacheCommon {\n /**\n * initialize the cache\n * @param config - the configuration of the cache\n */\n constructor(config) {\n const storage = getLocalStorageWithFallback();\n super({ config, keyValueStorage: new KeyValueStorage(storage) });\n this.storage = storage;\n this.getItem = this.getItem.bind(this);\n this.setItem = this.setItem.bind(this);\n this.removeItem = this.removeItem.bind(this);\n }\n async getAllCacheKeys(options) {\n const { omitSizeKey } = options ?? {};\n const keys = [];\n for (let i = 0; i < this.storage.length; i++) {\n const key = this.storage.key(i);\n if (omitSizeKey && key === getCurrentSizeKey(this.config.keyPrefix)) {\n continue;\n }\n if (key?.startsWith(this.config.keyPrefix)) {\n keys.push(key.substring(this.config.keyPrefix.length));\n }\n }\n return keys;\n }\n /**\n * Return a new instance of cache with customized configuration.\n * @param {Object} config - the customized configuration\n * @return {Object} - the new instance of Cache\n */\n createInstance(config) {\n if (!config.keyPrefix || config.keyPrefix === defaultConfig.keyPrefix) {\n logger.error('invalid keyPrefix, setting keyPrefix with timeStamp');\n config.keyPrefix = getCurrentTime.toString();\n }\n return new StorageCache(config);\n }\n}\n\nexport { StorageCache };\n//# sourceMappingURL=StorageCache.mjs.map\n","import { StorageCache } from './StorageCache.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst Cache = new StorageCache();\n\nexport { Cache };\n//# sourceMappingURL=index.mjs.map\n","import { ConsoleLogger } from '../Logger/ConsoleLogger.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('I18n');\n/**\n * Language translation utility.\n */\nlet I18n$1 = class I18n {\n constructor() {\n /**\n * @private\n */\n this._options = null;\n /**\n * @private\n */\n this._lang = null;\n /**\n * @private\n */\n this._dict = {};\n }\n /**\n * Sets the default language from the configuration when required.\n */\n setDefaultLanguage() {\n // Default to window language if not set in instance\n if (!this._lang &&\n typeof window !== 'undefined' &&\n window &&\n window.navigator) {\n this._lang = window.navigator.language;\n }\n logger.debug(this._lang);\n }\n /**\n * @method\n * Explicitly setting language\n * @param {String} lang\n */\n setLanguage(lang) {\n this._lang = lang;\n }\n /**\n * @method\n * Get value\n * @param {String} key\n * @param {String} defVal - Default value\n */\n get(key, defVal = undefined) {\n this.setDefaultLanguage();\n if (!this._lang) {\n return typeof defVal !== 'undefined' ? defVal : key;\n }\n const lang = this._lang;\n let val = this.getByLanguage(key, lang);\n if (val) {\n return val;\n }\n if (lang.indexOf('-') > 0) {\n val = this.getByLanguage(key, lang.split('-')[0]);\n }\n if (val) {\n return val;\n }\n return typeof defVal !== 'undefined' ? defVal : key;\n }\n /**\n * @method\n * Get value according to specified language\n * @param {String} key\n * @param {String} language - Specified langurage to be used\n * @param {String} defVal - Default value\n */\n getByLanguage(key, language, defVal = null) {\n if (!language) {\n return defVal;\n }\n const langDict = this._dict[language];\n if (!langDict) {\n return defVal;\n }\n return langDict[key];\n }\n /**\n * @method\n * Add vocabularies for one language\n * @param {String} language - Language of the dictionary\n * @param {Object} vocabularies - Object that has key-value as dictionary entry\n */\n putVocabulariesForLanguage(language, vocabularies) {\n let langDict = this._dict[language];\n if (!langDict) {\n langDict = this._dict[language] = {};\n }\n this._dict[language] = { ...langDict, ...vocabularies };\n }\n /**\n * @method\n * Add vocabularies for one language\n * @param {Object} vocabularies - Object that has language as key,\n * vocabularies of each language as value\n */\n putVocabularies(vocabularies) {\n Object.keys(vocabularies).forEach(key => {\n this.putVocabulariesForLanguage(key, vocabularies[key]);\n });\n }\n};\n\nexport { I18n$1 as I18n };\n//# sourceMappingURL=I18n.mjs.map\n","import { createAssertionFunction } from '../errors/createAssertionFunction.mjs';\nimport '../types/errors.mjs';\nimport '../errors/errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nvar I18nErrorCode;\n(function (I18nErrorCode) {\n I18nErrorCode[\"NotConfigured\"] = \"NotConfigured\";\n})(I18nErrorCode || (I18nErrorCode = {}));\nconst i18nErrorMap = {\n [I18nErrorCode.NotConfigured]: {\n message: 'i18n is not configured.',\n },\n};\nconst assert = createAssertionFunction(i18nErrorMap);\n\nexport { I18nErrorCode, assert };\n//# sourceMappingURL=errorHelpers.mjs.map\n","import { ConsoleLogger } from '../Logger/ConsoleLogger.mjs';\nimport { I18n as I18n$1 } from './I18n.mjs';\nimport { assert, I18nErrorCode } from './errorHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('I18n');\nlet _config = { language: null };\nlet _i18n = null;\n/**\n * Export I18n APIs\n */\nclass I18n {\n /**\n * @static\n * @method\n * Configure I18n part\n * @param {Object} config - Configuration of the I18n\n */\n static configure(config) {\n logger.debug('configure I18n');\n if (!config) {\n return _config;\n }\n _config = Object.assign({}, _config, config.I18n || config);\n I18n.createInstance();\n return _config;\n }\n static getModuleName() {\n return 'I18n';\n }\n /**\n * @static\n * @method\n * Create an instance of I18n for the library\n */\n static createInstance() {\n logger.debug('create I18n instance');\n if (_i18n) {\n return;\n }\n _i18n = new I18n$1();\n }\n /**\n * @static @method\n * Explicitly setting language\n * @param {String} lang\n */\n static setLanguage(lang) {\n I18n.checkConfig();\n assert(!!_i18n, I18nErrorCode.NotConfigured);\n _i18n.setLanguage(lang);\n }\n /**\n * @static @method\n * Get value\n * @param {String} key\n * @param {String} defVal - Default value\n */\n static get(key, defVal) {\n if (!I18n.checkConfig()) {\n return typeof defVal === 'undefined' ? key : defVal;\n }\n assert(!!_i18n, I18nErrorCode.NotConfigured);\n return _i18n.get(key, defVal);\n }\n /**\n * @static\n * @method\n * Add vocabularies for one language\n * @param {String} language - Language of the dictionary\n * @param {Object} vocabularies - Object that has key-value as dictionary entry\n */\n static putVocabulariesForLanguage(language, vocabularies) {\n I18n.checkConfig();\n assert(!!_i18n, I18nErrorCode.NotConfigured);\n _i18n.putVocabulariesForLanguage(language, vocabularies);\n }\n /**\n * @static\n * @method\n * Add vocabularies for one language\n * @param {Object} vocabularies - Object that has language as key,\n * vocabularies of each language as value\n */\n static putVocabularies(vocabularies) {\n I18n.checkConfig();\n assert(!!_i18n, I18nErrorCode.NotConfigured);\n _i18n.putVocabularies(vocabularies);\n }\n static checkConfig() {\n if (!_i18n) {\n I18n.createInstance();\n }\n return true;\n }\n}\n// Create an instance of I18n in the static class\nI18n.createInstance();\n\nexport { I18n };\n//# sourceMappingURL=index.mjs.map\n","import { v4 } from 'uuid';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst amplifyUuid = v4;\n\nexport { amplifyUuid };\n//# sourceMappingURL=index.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns signed headers.\n *\n * @param headers `headers` from the request.\n * @returns List of headers included in canonical headers, separated by semicolons (;). This indicates which headers\n * are part of the signing process. Header names must use lowercase characters and must appear in alphabetical order.\n *\n * @internal\n */\nconst getSignedHeaders = (headers) => Object.keys(headers)\n .map(key => key.toLowerCase())\n .sort()\n .join(';');\n\nexport { getSignedHeaders };\n//# sourceMappingURL=getSignedHeaders.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// query params\nconst ALGORITHM_QUERY_PARAM = 'X-Amz-Algorithm';\nconst AMZ_DATE_QUERY_PARAM = 'X-Amz-Date';\nconst CREDENTIAL_QUERY_PARAM = 'X-Amz-Credential';\nconst EXPIRES_QUERY_PARAM = 'X-Amz-Expires';\nconst REGION_SET_PARAM = 'X-Amz-Region-Set';\nconst SIGNATURE_QUERY_PARAM = 'X-Amz-Signature';\nconst SIGNED_HEADERS_QUERY_PARAM = 'X-Amz-SignedHeaders';\nconst TOKEN_QUERY_PARAM = 'X-Amz-Security-Token';\n// headers\nconst AUTH_HEADER = 'authorization';\nconst HOST_HEADER = 'host';\nconst AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase();\nconst TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase();\n// identifiers\nconst KEY_TYPE_IDENTIFIER = 'aws4_request';\nconst SHA256_ALGORITHM_IDENTIFIER = 'AWS4-HMAC-SHA256';\nconst SIGNATURE_IDENTIFIER = 'AWS4';\n// preset values\nconst EMPTY_HASH = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';\nconst UNSIGNED_PAYLOAD = 'UNSIGNED-PAYLOAD';\n\nexport { ALGORITHM_QUERY_PARAM, AMZ_DATE_HEADER, AMZ_DATE_QUERY_PARAM, AUTH_HEADER, CREDENTIAL_QUERY_PARAM, EMPTY_HASH, EXPIRES_QUERY_PARAM, HOST_HEADER, KEY_TYPE_IDENTIFIER, REGION_SET_PARAM, SHA256_ALGORITHM_IDENTIFIER, SIGNATURE_IDENTIFIER, SIGNATURE_QUERY_PARAM, SIGNED_HEADERS_QUERY_PARAM, TOKEN_HEADER, TOKEN_QUERY_PARAM, UNSIGNED_PAYLOAD };\n//# sourceMappingURL=constants.mjs.map\n","import { KEY_TYPE_IDENTIFIER } from '../constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns the credential scope which restricts the resulting signature to the specified region and service.\n *\n * @param date Current date in the format 'YYYYMMDD'.\n * @param region AWS region in which the service resides.\n * @param service Service to which the signed request is being sent.\n *\n * @returns A string representing the credential scope with format 'YYYYMMDD/region/service/aws4_request'.\n *\n * @internal\n */\nconst getCredentialScope = (date, region, service) => `${date}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`;\n\nexport { getCredentialScope };\n//# sourceMappingURL=getCredentialScope.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns expected date strings to be used in signing.\n *\n * @param date JavaScript `Date` object.\n * @returns `FormattedDates` object containing the following:\n * - longDate: A date string in 'YYYYMMDDThhmmssZ' format\n * - shortDate: A date string in 'YYYYMMDD' format\n *\n * @internal\n */\nconst getFormattedDates = (date) => {\n const longDate = date.toISOString().replace(/[:-]|\\.\\d{3}/g, '');\n return {\n longDate,\n shortDate: longDate.slice(0, 8),\n };\n};\n\nexport { getFormattedDates };\n//# sourceMappingURL=getFormattedDates.mjs.map\n","import { getCredentialScope } from './getCredentialScope.mjs';\nimport { getFormattedDates } from './getFormattedDates.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Extracts common values used for signing both requests and urls.\n *\n * @param options `SignRequestOptions` object containing values used to construct the signature.\n * @returns Common `SigningValues` used for signing.\n *\n * @internal\n */\nconst getSigningValues = ({ credentials, signingDate = new Date(), signingRegion, signingService, uriEscapePath = true, }) => {\n // get properties from credentials\n const { accessKeyId, secretAccessKey, sessionToken } = credentials;\n // get formatted dates for signing\n const { longDate, shortDate } = getFormattedDates(signingDate);\n // copy header and set signing properties\n const credentialScope = getCredentialScope(shortDate, signingRegion, signingService);\n return {\n accessKeyId,\n credentialScope,\n longDate,\n secretAccessKey,\n sessionToken,\n shortDate,\n signingRegion,\n signingService,\n uriEscapePath,\n };\n};\n\nexport { getSigningValues };\n//# sourceMappingURL=getSigningValues.mjs.map\n","import { Sha256 } from '@aws-crypto/sha256-js';\nimport { toHex } from '@smithy/util-hex-encoding';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// TODO: V6 update to different crypto dependency?\n/**\n * Returns the hashed data a `Uint8Array`.\n *\n * @param key `SourceData` to be used as hashing key.\n * @param data Hashable `SourceData`.\n * @returns `Uint8Array` created from the data as input to a hash function.\n */\nconst getHashedData = (key, data) => {\n const sha256 = new Sha256(key ?? undefined);\n sha256.update(data);\n // TODO: V6 flip to async digest\n const hashedData = sha256.digestSync();\n return hashedData;\n};\n/**\n * Returns the hashed data as a hex string.\n *\n * @param key `SourceData` to be used as hashing key.\n * @param data Hashable `SourceData`.\n * @returns String using lowercase hexadecimal characters created from the data as input to a hash function.\n *\n * @internal\n */\nconst getHashedDataAsHex = (key, data) => {\n const hashedData = getHashedData(key, data);\n return toHex(hashedData);\n};\n\nexport { getHashedData, getHashedDataAsHex };\n//# sourceMappingURL=dataHashHelpers.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns canonical headers.\n *\n * @param headers Headers from the request.\n * @returns Request headers that will be signed, and their values, separated by newline characters. Header names must\n * use lowercase characters, must appear in alphabetical order, and must be followed by a colon (:). For the values,\n * trim any leading or trailing spaces, convert sequential spaces to a single space, and separate the values\n * for a multi-value header using commas.\n *\n * @internal\n */\nconst getCanonicalHeaders = (headers) => Object.entries(headers)\n .map(([key, value]) => ({\n key: key.toLowerCase(),\n value: value?.trim().replace(/\\s+/g, ' ') ?? '',\n}))\n .sort((a, b) => (a.key < b.key ? -1 : 1))\n .map(entry => `${entry.key}:${entry.value}\\n`)\n .join('');\n\nexport { getCanonicalHeaders };\n//# sourceMappingURL=getCanonicalHeaders.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a canonical query string.\n *\n * @param searchParams `searchParams` from the request url.\n * @returns URL-encoded query string parameters, separated by ampersands (&). Percent-encode reserved characters,\n * including the space character. Encode names and values separately. If there are empty parameters, append the equals\n * sign to the parameter name before encoding. After encoding, sort the parameters alphabetically by key name. If there\n * is no query string, use an empty string (\"\").\n *\n * @internal\n */\nconst getCanonicalQueryString = (searchParams) => Array.from(searchParams)\n .sort(([keyA, valA], [keyB, valB]) => {\n if (keyA === keyB) {\n return valA < valB ? -1 : 1;\n }\n return keyA < keyB ? -1 : 1;\n})\n .map(([key, val]) => `${escapeUri(key)}=${escapeUri(val)}`)\n .join('&');\nconst escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode);\nconst hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`;\n\nexport { getCanonicalQueryString };\n//# sourceMappingURL=getCanonicalQueryString.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a canonical uri.\n *\n * @param pathname `pathname` from request url.\n * @param uriEscapePath Whether to uri encode the path as part of canonical uri. It's used for S3 only where the\n * pathname is already uri encoded, and the signing process is not expected to uri encode it again. Defaults to true.\n * @returns URI-encoded version of the absolute path component URL (everything between the host and the question mark\n * character (?) that starts the query string parameters). If the absolute path is empty, a forward slash character (/).\n *\n * @internal\n */\nconst getCanonicalUri = (pathname, uriEscapePath = true) => pathname\n ? uriEscapePath\n ? encodeURIComponent(pathname).replace(/%2F/g, '/')\n : pathname\n : '/';\n\nexport { getCanonicalUri };\n//# sourceMappingURL=getCanonicalUri.mjs.map\n","import { EMPTY_HASH, UNSIGNED_PAYLOAD } from '../constants.mjs';\nimport { getHashedDataAsHex } from './dataHashHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns the hashed payload.\n *\n * @param body `body` (payload) from the request.\n * @returns String created using the payload in the body of the HTTP request as input to a hash function. This string\n * uses lowercase hexadecimal characters. If the payload is empty, return precalculated result of an empty hash.\n *\n * @internal\n */\nconst getHashedPayload = (body) => {\n // return precalculated empty hash if body is undefined or null\n if (body == null) {\n return EMPTY_HASH;\n }\n if (isSourceData(body)) {\n const hashedData = getHashedDataAsHex(null, body);\n return hashedData;\n }\n // Defined body is not signable. Return unsigned payload which may or may not be accepted by the service.\n return UNSIGNED_PAYLOAD;\n};\nconst isSourceData = (body) => typeof body === 'string' || ArrayBuffer.isView(body) || isArrayBuffer(body);\nconst isArrayBuffer = (arg) => (typeof ArrayBuffer === 'function' && arg instanceof ArrayBuffer) ||\n Object.prototype.toString.call(arg) === '[object ArrayBuffer]';\n\nexport { getHashedPayload };\n//# sourceMappingURL=getHashedPayload.mjs.map\n","import { getCanonicalHeaders } from './getCanonicalHeaders.mjs';\nimport { getCanonicalQueryString } from './getCanonicalQueryString.mjs';\nimport { getCanonicalUri } from './getCanonicalUri.mjs';\nimport { getHashedPayload } from './getHashedPayload.mjs';\nimport { getSignedHeaders } from './getSignedHeaders.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a canonical request.\n *\n * @param request `HttpRequest` from which to create the canonical request from.\n * @param uriEscapePath Whether to uri encode the path as part of canonical uri. It's used for S3 only where the\n * pathname is already uri encoded, and the signing process is not expected to uri encode it again. Defaults to true.\n * @returns String created by by concatenating the following strings, separated by newline characters:\n * - HTTPMethod\n * - CanonicalUri\n * - CanonicalQueryString\n * - CanonicalHeaders\n * - SignedHeaders\n * - HashedPayload\n *\n * @internal\n */\nconst getCanonicalRequest = ({ body, headers, method, url }, uriEscapePath = true) => [\n method,\n getCanonicalUri(url.pathname, uriEscapePath),\n getCanonicalQueryString(url.searchParams),\n getCanonicalHeaders(headers),\n getSignedHeaders(headers),\n getHashedPayload(body),\n].join('\\n');\n\nexport { getCanonicalRequest };\n//# sourceMappingURL=getCanonicalRequest.mjs.map\n","import { KEY_TYPE_IDENTIFIER, SIGNATURE_IDENTIFIER } from '../constants.mjs';\nimport { getHashedData } from './dataHashHelpers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a signing key to be used for signing requests.\n *\n * @param secretAccessKey AWS secret access key from credentials.\n * @param date Current date in the format 'YYYYMMDD'.\n * @param region AWS region in which the service resides.\n * @param service Service to which the signed request is being sent.\n *\n * @returns `Uint8Array` calculated from its composite parts.\n *\n * @internal\n */\nconst getSigningKey = (secretAccessKey, date, region, service) => {\n const key = `${SIGNATURE_IDENTIFIER}${secretAccessKey}`;\n const dateKey = getHashedData(key, date);\n const regionKey = getHashedData(dateKey, region);\n const serviceKey = getHashedData(regionKey, service);\n const signingKey = getHashedData(serviceKey, KEY_TYPE_IDENTIFIER);\n return signingKey;\n};\n\nexport { getSigningKey };\n//# sourceMappingURL=getSigningKey.mjs.map\n","import { SHA256_ALGORITHM_IDENTIFIER } from '../constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a string to be signed.\n *\n * @param date Current date in the format 'YYYYMMDDThhmmssZ'.\n * @param credentialScope String representing the credential scope with format 'YYYYMMDD/region/service/aws4_request'.\n * @param hashedRequest Hashed canonical request.\n *\n * @returns A string created by by concatenating the following strings, separated by newline characters:\n * - Algorithm\n * - RequestDateTime\n * - CredentialScope\n * - HashedCanonicalRequest\n *\n * @internal\n */\nconst getStringToSign = (date, credentialScope, hashedRequest) => [SHA256_ALGORITHM_IDENTIFIER, date, credentialScope, hashedRequest].join('\\n');\n\nexport { getStringToSign };\n//# sourceMappingURL=getStringToSign.mjs.map\n","import { getHashedDataAsHex } from './dataHashHelpers.mjs';\nimport { getCanonicalRequest } from './getCanonicalRequest.mjs';\nimport { getSigningKey } from './getSigningKey.mjs';\nimport { getStringToSign } from './getStringToSign.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Calculates and returns an AWS API Signature.\n * https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html\n *\n * @param request `HttpRequest` to be signed.\n * @param signRequestOptions `SignRequestOptions` object containing values used to construct the signature.\n * @returns AWS API Signature to sign a request or url with.\n *\n * @internal\n */\nconst getSignature = (request, { credentialScope, longDate, secretAccessKey, shortDate, signingRegion, signingService, uriEscapePath, }) => {\n // step 1: create a canonical request\n const canonicalRequest = getCanonicalRequest(request, uriEscapePath);\n // step 2: create a hash of the canonical request\n const hashedRequest = getHashedDataAsHex(null, canonicalRequest);\n // step 3: create a string to sign\n const stringToSign = getStringToSign(longDate, credentialScope, hashedRequest);\n // step 4: calculate the signature\n const signature = getHashedDataAsHex(getSigningKey(secretAccessKey, shortDate, signingRegion, signingService), stringToSign);\n return signature;\n};\n\nexport { getSignature };\n//# sourceMappingURL=getSignature.mjs.map\n","import { getSignedHeaders } from './utils/getSignedHeaders.mjs';\nimport { getSigningValues } from './utils/getSigningValues.mjs';\nimport { HOST_HEADER, AMZ_DATE_HEADER, TOKEN_HEADER, AUTH_HEADER, SHA256_ALGORITHM_IDENTIFIER } from './constants.mjs';\nimport { getSignature } from './utils/getSignature.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Given a `HttpRequest`, returns a Signature Version 4 signed `HttpRequest`.\n *\n * @param request `HttpRequest` to be signed.\n * @param signRequestOptions `SignRequestOptions` object containing values used to construct the signature.\n * @returns A `HttpRequest` with authentication headers which can grant temporary access to AWS resources.\n */\nconst signRequest = (request, options) => {\n const signingValues = getSigningValues(options);\n const { accessKeyId, credentialScope, longDate, sessionToken } = signingValues;\n // create the request to sign\n const headers = { ...request.headers };\n headers[HOST_HEADER] = request.url.host;\n headers[AMZ_DATE_HEADER] = longDate;\n if (sessionToken) {\n headers[TOKEN_HEADER] = sessionToken;\n }\n const requestToSign = { ...request, headers };\n // calculate and add the signature to the request\n const signature = getSignature(requestToSign, signingValues);\n const credentialEntry = `Credential=${accessKeyId}/${credentialScope}`;\n const signedHeadersEntry = `SignedHeaders=${getSignedHeaders(headers)}`;\n const signatureEntry = `Signature=${signature}`;\n headers[AUTH_HEADER] =\n `${SHA256_ALGORITHM_IDENTIFIER} ${credentialEntry}, ${signedHeadersEntry}, ${signatureEntry}`;\n return requestToSign;\n};\n\nexport { signRequest };\n//# sourceMappingURL=signRequest.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a `Date` that is corrected for clock skew.\n *\n * @param systemClockOffset The offset of the system clock in milliseconds.\n *\n * @returns `Date` representing the current time adjusted by the system clock offset.\n *\n * @internal\n */\nconst getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset);\n\nexport { getSkewCorrectedDate };\n//# sourceMappingURL=getSkewCorrectedDate.mjs.map\n","import { getSkewCorrectedDate } from './getSkewCorrectedDate.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// 5 mins in milliseconds. Ref: https://github.com/aws/aws-sdk-js-v3/blob/6c0f44fab30a1bb2134af47362a31332abc3666b/packages/middleware-signing/src/utils/isClockSkewed.ts#L10\nconst SKEW_WINDOW = 5 * 60 * 1000;\n/**\n * Checks if the provided date is within the skew window of 5 minutes.\n *\n * @param clockTimeInMilliseconds Time to check for skew in milliseconds.\n * @param clockOffsetInMilliseconds Offset to check clock against in milliseconds.\n *\n * @returns True if skewed. False otherwise.\n *\n * @internal\n */\nconst isClockSkewed = (clockTimeInMilliseconds, clockOffsetInMilliseconds) => Math.abs(getSkewCorrectedDate(clockOffsetInMilliseconds).getTime() -\n clockTimeInMilliseconds) >= SKEW_WINDOW;\n\nexport { isClockSkewed };\n//# sourceMappingURL=isClockSkewed.mjs.map\n","import { isClockSkewed } from './isClockSkewed.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns the difference between clock time and the current system time if clock is skewed.\n *\n * @param clockTimeInMilliseconds Clock time in milliseconds.\n * @param currentSystemClockOffset Current system clock offset in milliseconds.\n *\n * @internal\n */\nconst getUpdatedSystemClockOffset = (clockTimeInMilliseconds, currentSystemClockOffset) => {\n if (isClockSkewed(clockTimeInMilliseconds, currentSystemClockOffset)) {\n return clockTimeInMilliseconds - Date.now();\n }\n return currentSystemClockOffset;\n};\n\nexport { getUpdatedSystemClockOffset };\n//# sourceMappingURL=getUpdatedSystemClockOffset.mjs.map\n","import { signRequest } from './signer/signatureV4/signRequest.mjs';\nimport '@aws-crypto/sha256-js';\nimport '@smithy/util-hex-encoding';\nimport { getSkewCorrectedDate } from './utils/getSkewCorrectedDate.mjs';\nimport { getUpdatedSystemClockOffset } from './utils/getUpdatedSystemClockOffset.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Middleware that SigV4 signs request with AWS credentials, and correct system clock offset.\n * This middleware is expected to be placed after retry middleware.\n */\nconst signingMiddlewareFactory = ({ credentials, region, service, uriEscapePath = true, }) => {\n let currentSystemClockOffset;\n return (next, context) => async function signingMiddleware(request) {\n currentSystemClockOffset = currentSystemClockOffset ?? 0;\n const signRequestOptions = {\n credentials: typeof credentials === 'function'\n ? await credentials({\n forceRefresh: !!context?.isCredentialsExpired,\n })\n : credentials,\n signingDate: getSkewCorrectedDate(currentSystemClockOffset),\n signingRegion: region,\n signingService: service,\n uriEscapePath,\n };\n const signedRequest = await signRequest(request, signRequestOptions);\n const response = await next(signedRequest);\n // Update system clock offset if response contains date header, regardless of the status code.\n // non-2xx response will still be returned from next handler instead of thrown, because it's\n // only thrown by the retry middleware.\n const dateString = getDateHeader(response);\n if (dateString) {\n currentSystemClockOffset = getUpdatedSystemClockOffset(Date.parse(dateString), currentSystemClockOffset);\n }\n return response;\n };\n};\nconst getDateHeader = ({ headers } = {}) => headers?.date ?? headers?.Date ?? headers?.['x-amz-date'];\n\nexport { signingMiddlewareFactory };\n//# sourceMappingURL=middleware.mjs.map\n","import { retryMiddlewareFactory } from '../middleware/retry/middleware.mjs';\nimport '../../types/errors.mjs';\nimport '../../errors/errorHelpers.mjs';\nimport '../../utils/getClientInfo/getClientInfo.mjs';\nimport '../../utils/retry/retry.mjs';\nimport { signingMiddlewareFactory } from '../middleware/signing/middleware.mjs';\nimport { userAgentMiddlewareFactory } from '../middleware/userAgent/middleware.mjs';\nimport { composeTransferHandler } from '../internal/composeTransferHandler.mjs';\nimport { fetchTransferHandler } from './fetch.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst authenticatedHandler = composeTransferHandler(fetchTransferHandler, [\n userAgentMiddlewareFactory,\n retryMiddlewareFactory,\n signingMiddlewareFactory,\n]);\n\nexport { authenticatedHandler };\n//# sourceMappingURL=authenticated.mjs.map\n","import { getCrypto } from './globalHelpers/index.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst generateRandomString = (length) => {\n const STATE_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n const result = [];\n const randomNums = new Uint8Array(length);\n getCrypto().getRandomValues(randomNums);\n for (const num of randomNums) {\n result.push(STATE_CHARSET[num % STATE_CHARSET.length]);\n }\n return result.join('');\n};\n\nexport { generateRandomString };\n//# sourceMappingURL=generateRandomString.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass NonRetryableError extends Error {\n constructor() {\n super(...arguments);\n this.nonRetryable = true;\n }\n}\n\nexport { NonRetryableError };\n//# sourceMappingURL=NonRetryableError.mjs.map\n","import { MAX_DELAY_MS } from './constants.mjs';\nimport { jitteredBackoff } from './jitteredBackoff.mjs';\nimport { retry } from './retry.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @private\n * Internal use of Amplify only\n */\nconst jitteredExponentialRetry = (functionToRetry, args, maxDelayMs = MAX_DELAY_MS, onTerminate) => retry(functionToRetry, args, jitteredBackoff(maxDelayMs), onTerminate);\n\nexport { jitteredExponentialRetry };\n//# sourceMappingURL=jitteredExponentialRetry.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction urlSafeDecode(hex) {\n const matchArr = hex.match(/.{2}/g) || [];\n return matchArr.map(char => String.fromCharCode(parseInt(char, 16))).join('');\n}\n\nexport { urlSafeDecode };\n//# sourceMappingURL=urlSafeDecode.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction urlSafeEncode(str) {\n return str\n .split('')\n .map(char => char.charCodeAt(0).toString(16).padStart(2, '0'))\n .join('');\n}\n\nexport { urlSafeEncode };\n//# sourceMappingURL=urlSafeEncode.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * returns in-flight promise if there is one\n *\n * @param asyncFunction - asyncFunction to be deduped.\n * @returns - the return type of the callback\n */\nconst deDupeAsyncFunction = (asyncFunction) => {\n let inflightPromise;\n return async (...args) => {\n if (inflightPromise)\n return inflightPromise;\n inflightPromise = new Promise((resolve, reject) => {\n asyncFunction(...args)\n .then(result => {\n resolve(result);\n })\n .catch(error => {\n reject(error);\n })\n .finally(() => {\n inflightPromise = undefined;\n });\n });\n return inflightPromise;\n };\n};\n\nexport { deDupeAsyncFunction };\n//# sourceMappingURL=deDupeAsyncFunction.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction isTokenExpired({ expiresAt, clockDrift, tolerance = 5000, }) {\n const currentTime = Date.now();\n return currentTime + clockDrift + tolerance > expiresAt;\n}\n\nexport { isTokenExpired };\n//# sourceMappingURL=isTokenExpired.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Retrieves the device name using the User-Agent Client Hints API if available,\n * falling back to the traditional userAgent string if not.\n *\n * @returns {Promise} A promise that resolves with a string representing the device name.\n *\n * Example Output:\n * navigator.userAgentData:\n * 'macOS 14.2.1 arm macOS Not A(Brand/99.0.0.0;Google Chrome/121.0.6167.160;Chromium/121.0.6167.160'\n * navigator.userAgent:\n * 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/115.0'\n */\nconst getDeviceName = async () => {\n const { userAgentData } = navigator;\n if (!userAgentData)\n return navigator.userAgent;\n const { platform = '', platformVersion = '', model = '', architecture = '', fullVersionList = [], } = await userAgentData.getHighEntropyValues([\n 'platform',\n 'platformVersion',\n 'architecture',\n 'model',\n 'fullVersionList',\n ]);\n const versionList = fullVersionList\n .map((v) => `${v.brand}/${v.version}`)\n .join(';');\n const deviceName = [\n platform,\n platformVersion,\n architecture,\n model,\n platform,\n versionList,\n ]\n .filter(value => value)\n .join(' ');\n return deviceName || navigator.userAgent;\n};\n\nexport { getDeviceName };\n//# sourceMappingURL=getDeviceName.mjs.map\n","import { AmplifyError } from './AmplifyError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Error class for errors that associated with unsuccessful HTTP responses.\n * It's throw by API category REST API handlers and GraphQL query handlers for now.\n */\nclass ApiError extends AmplifyError {\n /**\n * The unwrapped HTTP response causing the given API error.\n */\n get response() {\n return this._response\n ? replicateApiErrorResponse(this._response)\n : undefined;\n }\n constructor(params) {\n super(params);\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n this.constructor = ApiError;\n Object.setPrototypeOf(this, ApiError.prototype);\n if (params.response) {\n this._response = params.response;\n }\n }\n}\nconst replicateApiErrorResponse = (response) => ({\n ...response,\n headers: { ...response.headers },\n});\n\nexport { ApiError };\n//# sourceMappingURL=APIError.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass BackgroundManagerNotOpenError extends Error {\n constructor(message) {\n super(`BackgroundManagerNotOpenError: ${message}`);\n }\n}\n\nexport { BackgroundManagerNotOpenError };\n//# sourceMappingURL=BackgroundManagerNotOpenError.mjs.map\n","import { BackgroundManagerNotOpenError } from './BackgroundManagerNotOpenError.mjs';\nimport { BackgroundProcessManagerState } from './types.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @private For internal Amplify use.\n *\n * Creates a new scope for promises, observables, and other types of work or\n * processes that may be running in the background. This manager provides\n * an singular entrypoint to request termination and await completion.\n *\n * As work completes on its own prior to close, the manager removes them\n * from the registry to avoid holding references to completed jobs.\n */\nclass BackgroundProcessManager {\n constructor() {\n /**\n * A string indicating whether the manager is accepting new work (\"Open\"),\n * waiting for work to complete (\"Closing\"), or fully done with all\n * submitted work and *not* accepting new jobs (\"Closed\").\n */\n this._state = BackgroundProcessManagerState.Open;\n /**\n * The list of outstanding jobs we'll need to wait for upon `close()`\n */\n this.jobs = new Set();\n }\n add(jobOrDescription, optionalDescription) {\n let job;\n let description;\n if (typeof jobOrDescription === 'string') {\n job = undefined;\n description = jobOrDescription;\n }\n else {\n job = jobOrDescription;\n description = optionalDescription;\n }\n const error = this.closedFailure(description);\n if (error)\n return error;\n if (job === undefined) {\n return this.addHook(description);\n }\n else if (typeof job === 'function') {\n return this.addFunction(job, description);\n }\n else if (job instanceof BackgroundProcessManager) {\n this.addManager(job, description);\n }\n else {\n throw new Error('If `job` is provided, it must be an Observable, Function, or BackgroundProcessManager.');\n }\n }\n /**\n * Adds a **cleaner** function that doesn't immediately get executed.\n * Instead, the caller gets a **terminate** function back. The *cleaner* is\n * invoked only once the mananger *closes* or the returned **terminate**\n * function is called.\n *\n * @param clean The cleanup function.\n * @param description Optional description to help identify pending jobs.\n * @returns A terminate function.\n */\n addCleaner(clean, description) {\n const { resolve, onTerminate } = this.addHook(description);\n const proxy = async () => {\n await clean();\n resolve();\n };\n onTerminate.then(proxy);\n return proxy;\n }\n addFunction(job, description) {\n // the function we call when we want to try to terminate this job.\n let terminate;\n // the promise the job can opt into listening to for termination.\n const onTerminate = new Promise(resolve => {\n terminate = resolve;\n });\n // finally! start the job.\n const jobResult = job(onTerminate);\n // depending on what the job gives back, register the result\n // so we can monitor for completion.\n if (typeof jobResult?.then === 'function') {\n this.registerPromise(jobResult, terminate, description);\n }\n // At the end of the day, or you know, method call, it doesn't matter\n // what the return value is at all; we just pass it through to the\n // caller.\n return jobResult;\n }\n addManager(manager, description) {\n this.addCleaner(async () => manager.close(), description);\n }\n /**\n * Creates and registers a fabricated job for processes that need to operate\n * with callbacks/hooks. The returned `resolve` and `reject`\n * functions can be used to signal the job is done successfully or not.\n * The returned `onTerminate` is a promise that will resolve when the\n * manager is requesting the termination of the job.\n *\n * @param description Optional description to help identify pending jobs.\n * @returns `{ resolve, reject, onTerminate }`\n */\n addHook(description) {\n // the resolve/reject functions we'll provide to the caller to signal\n // the state of the job.\n let promiseResolve;\n let promiseReject;\n // the underlying promise we'll use to manage it, pretty much like\n // any other promise.\n const promise = new Promise((resolve, reject) => {\n promiseResolve = resolve;\n promiseReject = reject;\n });\n // the function we call when we want to try to terminate this job.\n let terminate;\n // the promise the job can opt into listening to for termination.\n const onTerminate = new Promise(resolve => {\n terminate = resolve;\n });\n this.registerPromise(promise, terminate, description);\n return {\n resolve: promiseResolve,\n reject: promiseReject,\n onTerminate,\n };\n }\n /**\n * Adds a Promise based job to the list of jobs for monitoring and listens\n * for either a success or failure, upon which the job is considered \"done\"\n * and removed from the registry.\n *\n * @param promise A promise that is on its way to being returned to a\n * caller, which needs to be tracked as a background job.\n * @param terminate The termination function to register, which can be\n * invoked to request the job stop.\n * @param description Optional description to help identify pending jobs.\n */\n registerPromise(promise, terminate, description) {\n const jobEntry = { promise, terminate, description };\n this.jobs.add(jobEntry);\n // in all of my testing, it is safe to multi-subscribe to a promise.\n // so, rather than create another layer of promising, we're just going\n // to hook into the promise we already have, and when it's done\n // (successfully or not), we no longer need to wait for it upon close.\n //\n // sorry this is a bit hand-wavy:\n //\n // i believe we use `.then` and `.catch` instead of `.finally` because\n // `.finally` is invoked in a different order in the sequence, and this\n // breaks assumptions throughout and causes failures.\n promise\n .then(() => {\n this.jobs.delete(jobEntry);\n })\n .catch(() => {\n this.jobs.delete(jobEntry);\n });\n }\n /**\n * The number of jobs being waited on.\n *\n * We don't use this for anything. It's just informational for the caller,\n * and can be used in logging and testing.\n *\n * @returns the number of jobs.\n */\n get length() {\n return this.jobs.size;\n }\n /**\n * The execution state of the manager. One of:\n *\n * 1. \"Open\" -> Accepting new jobs\n * 1. \"Closing\" -> Not accepting new work. Waiting for jobs to complete.\n * 1. \"Closed\" -> Not accepting new work. All submitted jobs are complete.\n */\n get state() {\n return this._state;\n }\n /**\n * The registered `description` of all still-pending jobs.\n *\n * @returns descriptions as an array.\n */\n get pending() {\n return Array.from(this.jobs).map(job => job.description);\n }\n /**\n * Whether the manager is accepting new jobs.\n */\n get isOpen() {\n return this._state === BackgroundProcessManagerState.Open;\n }\n /**\n * Whether the manager is rejecting new work, but still waiting for\n * submitted work to complete.\n */\n get isClosing() {\n return this._state === BackgroundProcessManagerState.Closing;\n }\n /**\n * Whether the manager is rejecting work and done waiting for submitted\n * work to complete.\n */\n get isClosed() {\n return this._state === BackgroundProcessManagerState.Closed;\n }\n closedFailure(description) {\n if (!this.isOpen) {\n return Promise.reject(new BackgroundManagerNotOpenError([\n `The manager is ${this.state}.`,\n `You tried to add \"${description}\".`,\n `Pending jobs: [\\n${this.pending\n .map(t => ' ' + t)\n .join(',\\n')}\\n]`,\n ].join('\\n')));\n }\n }\n /**\n * Signals jobs to stop (for those that accept interruptions) and waits\n * for confirmation that jobs have stopped.\n *\n * This immediately puts the manager into a closing state and just begins\n * to reject new work. After all work in the manager is complete, the\n * manager goes into a `Completed` state and `close()` returns.\n *\n * This call is idempotent.\n *\n * If the manager is already closing or closed, `finalCleaup` is not executed.\n *\n * @param onClosed\n * @returns The settled results of each still-running job's promise. If the\n * manager is already closed, this will contain the results as of when the\n * manager's `close()` was called in an `Open` state.\n */\n async close() {\n if (this.isOpen) {\n this._state = BackgroundProcessManagerState.Closing;\n for (const job of Array.from(this.jobs)) {\n try {\n job.terminate();\n }\n catch (error) {\n // Due to potential races with a job's natural completion, it's\n // reasonable to expect the termination call to fail. Hence,\n // not logging as an error.\n console.warn(`Failed to send termination signal to job. Error: ${error.message}`, job);\n }\n }\n // Use `allSettled()` because we want to wait for all to finish. We do\n // not want to stop waiting if there is a failure.\n this._closingPromise = Promise.allSettled(Array.from(this.jobs).map(j => j.promise));\n await this._closingPromise;\n this._state = BackgroundProcessManagerState.Closed;\n }\n return this._closingPromise;\n }\n /**\n * Signals the manager to start accepting work (again) and returns once\n * the manager is ready to do so.\n *\n * If the state is already `Open`, this call is a no-op.\n *\n * If the state is `Closed`, this call simply updates state and returns.\n *\n * If the state is `Closing`, this call waits for completion before it\n * updates the state and returns.\n */\n async open() {\n if (this.isClosing) {\n await this.close();\n }\n this._state = BackgroundProcessManagerState.Open;\n }\n}\n\nexport { BackgroundProcessManager };\n//# sourceMappingURL=BackgroundProcessManager.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/*!\n * The MIT License (MIT)\n *\n * Copyright (c) 2016 Christian Speckner \n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n */\nclass Mutex {\n constructor() {\n this._queue = [];\n this._pending = false;\n }\n isLocked() {\n return this._pending;\n }\n acquire() {\n const ticket = new Promise(resolve => this._queue.push(resolve));\n if (!this._pending) {\n this._dispatchNext();\n }\n return ticket;\n }\n runExclusive(callback) {\n return this.acquire().then(release => {\n let result;\n try {\n result = callback();\n }\n catch (e) {\n release();\n throw e;\n }\n return Promise.resolve(result).then((x) => {\n release();\n return x;\n }, e => {\n release();\n throw e;\n });\n });\n }\n _dispatchNext() {\n if (this._queue.length > 0) {\n this._pending = true;\n this._queue.shift()(this._dispatchNext.bind(this));\n }\n else {\n this._pending = false;\n }\n }\n}\n\nexport { Mutex };\n//# sourceMappingURL=Mutex.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction bytesToString(input) {\n return Array.from(input, byte => String.fromCodePoint(byte)).join('');\n}\n\nexport { bytesToString };\n//# sourceMappingURL=bytesToString.mjs.map\n","import { getBtoa } from '../../globalHelpers/index.mjs';\nimport { bytesToString } from './bytesToString.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst base64Encoder = {\n /**\n * Convert input to base64-encoded string\n * @param input - string to convert to base64\n * @param options - encoding options that can optionally produce a base64url string\n * @returns base64-encoded string\n */\n convert(input, options = {\n urlSafe: false,\n skipPadding: false,\n }) {\n const inputStr = typeof input === 'string' ? input : bytesToString(input);\n let encodedStr = getBtoa()(inputStr);\n // urlSafe char replacement and skipPadding options conform to the base64url spec\n // https://datatracker.ietf.org/doc/html/rfc4648#section-5\n if (options.urlSafe) {\n encodedStr = encodedStr.replace(/\\+/g, '-').replace(/\\//g, '_');\n }\n if (options.skipPadding) {\n encodedStr = encodedStr.replace(/=/g, '');\n }\n return encodedStr;\n },\n};\n\nexport { base64Encoder };\n//# sourceMappingURL=base64Encoder.mjs.map\n","import { getCrypto } from './globalHelpers/index.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/*\n * Cryptographically secure pseudorandom number generator\n * As Math.random() is cryptographically not safe to use\n */\nfunction cryptoSecureRandomInt() {\n const crypto = getCrypto();\n const randomResult = crypto.getRandomValues(new Uint32Array(1))[0];\n return randomResult;\n}\n\nexport { cryptoSecureRandomInt };\n//# sourceMappingURL=cryptoSecureRandomInt.mjs.map\n","import { cryptoSecureRandomInt } from './cryptoSecureRandomInt.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Hex encoding strategy.\n * Converts a word array to a hex string.\n * @param {WordArray} wordArray The word array.\n * @return {string} The hex string.\n * @static\n */\nfunction hexStringify(wordArray) {\n // Shortcuts\n const { words } = wordArray;\n const { sigBytes } = wordArray;\n // Convert\n const hexChars = [];\n for (let i = 0; i < sigBytes; i++) {\n const bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;\n hexChars.push((bite >>> 4).toString(16));\n hexChars.push((bite & 0x0f).toString(16));\n }\n return hexChars.join('');\n}\nclass WordArray {\n constructor(words, sigBytes) {\n this.words = [];\n let Words = words;\n Words = this.words = Words || [];\n if (sigBytes !== undefined) {\n this.sigBytes = sigBytes;\n }\n else {\n this.sigBytes = Words.length * 4;\n }\n }\n random(nBytes) {\n const words = [];\n for (let i = 0; i < nBytes; i += 4) {\n words.push(cryptoSecureRandomInt());\n }\n return new WordArray(words, nBytes);\n }\n toString() {\n return hexStringify(this);\n }\n}\n\nexport { WordArray };\n//# sourceMappingURL=WordArray.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nvar AuthValidationErrorCode;\n(function (AuthValidationErrorCode) {\n AuthValidationErrorCode[\"EmptySignInUsername\"] = \"EmptySignInUsername\";\n AuthValidationErrorCode[\"EmptySignInPassword\"] = \"EmptySignInPassword\";\n AuthValidationErrorCode[\"CustomAuthSignInPassword\"] = \"CustomAuthSignInPassword\";\n AuthValidationErrorCode[\"EmptySignUpUsername\"] = \"EmptySignUpUsername\";\n AuthValidationErrorCode[\"EmptySignUpPassword\"] = \"EmptySignUpPassword\";\n AuthValidationErrorCode[\"EmptyConfirmSignUpUsername\"] = \"EmptyConfirmSignUpUsername\";\n AuthValidationErrorCode[\"EmptyConfirmSignUpCode\"] = \"EmptyConfirmSignUpCode\";\n AuthValidationErrorCode[\"EmptyResendSignUpCodeUsername\"] = \"EmptyresendSignUpCodeUsername\";\n AuthValidationErrorCode[\"EmptyChallengeResponse\"] = \"EmptyChallengeResponse\";\n AuthValidationErrorCode[\"EmptyConfirmResetPasswordUsername\"] = \"EmptyConfirmResetPasswordUsername\";\n AuthValidationErrorCode[\"EmptyConfirmResetPasswordNewPassword\"] = \"EmptyConfirmResetPasswordNewPassword\";\n AuthValidationErrorCode[\"EmptyConfirmResetPasswordConfirmationCode\"] = \"EmptyConfirmResetPasswordConfirmationCode\";\n AuthValidationErrorCode[\"EmptyResetPasswordUsername\"] = \"EmptyResetPasswordUsername\";\n AuthValidationErrorCode[\"EmptyVerifyTOTPSetupCode\"] = \"EmptyVerifyTOTPSetupCode\";\n AuthValidationErrorCode[\"EmptyConfirmUserAttributeCode\"] = \"EmptyConfirmUserAttributeCode\";\n AuthValidationErrorCode[\"IncorrectMFAMethod\"] = \"IncorrectMFAMethod\";\n AuthValidationErrorCode[\"EmptyUpdatePassword\"] = \"EmptyUpdatePassword\";\n})(AuthValidationErrorCode || (AuthValidationErrorCode = {}));\n\nexport { AuthValidationErrorCode };\n//# sourceMappingURL=validation.mjs.map\n","import { AuthValidationErrorCode } from '../errors/types/validation.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst validationErrorMap = {\n [AuthValidationErrorCode.EmptyChallengeResponse]: {\n message: 'challengeResponse is required to confirmSignIn',\n },\n [AuthValidationErrorCode.EmptyConfirmResetPasswordUsername]: {\n message: 'username is required to confirmResetPassword',\n },\n [AuthValidationErrorCode.EmptyConfirmSignUpCode]: {\n message: 'code is required to confirmSignUp',\n },\n [AuthValidationErrorCode.EmptyConfirmSignUpUsername]: {\n message: 'username is required to confirmSignUp',\n },\n [AuthValidationErrorCode.EmptyConfirmResetPasswordConfirmationCode]: {\n message: 'confirmationCode is required to confirmResetPassword',\n },\n [AuthValidationErrorCode.EmptyConfirmResetPasswordNewPassword]: {\n message: 'newPassword is required to confirmResetPassword',\n },\n [AuthValidationErrorCode.EmptyResendSignUpCodeUsername]: {\n message: 'username is required to confirmSignUp',\n },\n [AuthValidationErrorCode.EmptyResetPasswordUsername]: {\n message: 'username is required to resetPassword',\n },\n [AuthValidationErrorCode.EmptySignInPassword]: {\n message: 'password is required to signIn',\n },\n [AuthValidationErrorCode.EmptySignInUsername]: {\n message: 'username is required to signIn',\n },\n [AuthValidationErrorCode.EmptySignUpPassword]: {\n message: 'password is required to signUp',\n },\n [AuthValidationErrorCode.EmptySignUpUsername]: {\n message: 'username is required to signUp',\n },\n [AuthValidationErrorCode.CustomAuthSignInPassword]: {\n message: 'A password is not needed when signing in with CUSTOM_WITHOUT_SRP',\n recoverySuggestion: 'Do not include a password in your signIn call.',\n },\n [AuthValidationErrorCode.IncorrectMFAMethod]: {\n message: 'Incorrect MFA method was chosen. It should be either SMS, TOTP, or EMAIL',\n recoverySuggestion: 'Try to pass SMS, TOTP, or EMAIL as the challengeResponse',\n },\n [AuthValidationErrorCode.EmptyVerifyTOTPSetupCode]: {\n message: 'code is required to verifyTotpSetup',\n },\n [AuthValidationErrorCode.EmptyUpdatePassword]: {\n message: 'oldPassword and newPassword are required to changePassword',\n },\n [AuthValidationErrorCode.EmptyConfirmUserAttributeCode]: {\n message: 'confirmation code is required to confirmUserAttribute',\n },\n};\n// TODO: delete this code when the Auth class is removed.\nvar AuthErrorStrings;\n(function (AuthErrorStrings) {\n AuthErrorStrings[\"DEFAULT_MSG\"] = \"Authentication Error\";\n AuthErrorStrings[\"EMPTY_EMAIL\"] = \"Email cannot be empty\";\n AuthErrorStrings[\"EMPTY_PHONE\"] = \"Phone number cannot be empty\";\n AuthErrorStrings[\"EMPTY_USERNAME\"] = \"Username cannot be empty\";\n AuthErrorStrings[\"INVALID_USERNAME\"] = \"The username should either be a string or one of the sign in types\";\n AuthErrorStrings[\"EMPTY_PASSWORD\"] = \"Password cannot be empty\";\n AuthErrorStrings[\"EMPTY_CODE\"] = \"Confirmation code cannot be empty\";\n AuthErrorStrings[\"SIGN_UP_ERROR\"] = \"Error creating account\";\n AuthErrorStrings[\"NO_MFA\"] = \"No valid MFA method provided\";\n AuthErrorStrings[\"INVALID_MFA\"] = \"Invalid MFA type\";\n AuthErrorStrings[\"EMPTY_CHALLENGE\"] = \"Challenge response cannot be empty\";\n AuthErrorStrings[\"NO_USER_SESSION\"] = \"Failed to get the session because the user is empty\";\n AuthErrorStrings[\"NETWORK_ERROR\"] = \"Network Error\";\n AuthErrorStrings[\"DEVICE_CONFIG\"] = \"Device tracking has not been configured in this User Pool\";\n AuthErrorStrings[\"AUTOSIGNIN_ERROR\"] = \"Please use your credentials to sign in\";\n AuthErrorStrings[\"OAUTH_ERROR\"] = \"Couldn't finish OAuth flow, check your User Pool HostedUI settings\";\n})(AuthErrorStrings || (AuthErrorStrings = {}));\nvar AuthErrorCodes;\n(function (AuthErrorCodes) {\n AuthErrorCodes[\"SignInException\"] = \"SignInException\";\n AuthErrorCodes[\"OAuthSignInError\"] = \"OAuthSignInException\";\n})(AuthErrorCodes || (AuthErrorCodes = {}));\n\nexport { AuthErrorCodes, AuthErrorStrings, validationErrorMap };\n//# sourceMappingURL=AuthErrorStrings.mjs.map\n","import { AmplifyError } from '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass AuthError extends AmplifyError {\n constructor(params) {\n super(params);\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n this.constructor = AuthError;\n Object.setPrototypeOf(this, AuthError.prototype);\n }\n}\n\nexport { AuthError };\n//# sourceMappingURL=AuthError.mjs.map\n","import { validationErrorMap } from '../../common/AuthErrorStrings.mjs';\nimport { AuthError } from '../AuthError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction assertValidationError(assertion, name) {\n const { message, recoverySuggestion } = validationErrorMap[name];\n if (!assertion) {\n throw new AuthError({ name, message, recoverySuggestion });\n }\n}\n\nexport { assertValidationError };\n//# sourceMappingURL=assertValidationError.mjs.map\n","import { AuthError } from '../../errors/AuthError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction getRegionFromUserPoolId(userPoolId) {\n const region = userPoolId?.split('_')[0];\n if (!userPoolId ||\n userPoolId.indexOf('_') < 0 ||\n !region ||\n typeof region !== 'string')\n throw new AuthError({\n name: 'InvalidUserPoolId',\n message: 'Invalid user pool id provided.',\n });\n return region;\n}\nfunction getRegionFromIdentityPoolId(identityPoolId) {\n if (!identityPoolId || !identityPoolId.includes(':')) {\n throw new AuthError({\n name: 'InvalidIdentityPoolIdException',\n message: 'Invalid identity pool id provided.',\n recoverySuggestion: 'Make sure a valid identityPoolId is given in the config.',\n });\n }\n return identityPoolId.split(':')[0];\n}\n\nexport { getRegionFromIdentityPoolId, getRegionFromUserPoolId };\n//# sourceMappingURL=regionParsers.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Transforms a user attributes object into an array of AttributeType objects.\n * @param attributes user attributes to be mapped to AttributeType objects.\n * @returns an array of AttributeType objects.\n */\nfunction toAttributeType(attributes) {\n return Object.entries(attributes).map(([key, value]) => ({\n Name: key,\n Value: value,\n }));\n}\n/**\n * Transforms an array of AttributeType objects into a user attributes object.\n *\n * @param attributes - an array of AttributeType objects.\n * @returns AuthUserAttributes object.\n */\nfunction toAuthUserAttribute(attributes) {\n const userAttributes = {};\n attributes?.forEach(attribute => {\n if (attribute.Name)\n userAttributes[attribute.Name] = attribute.Value;\n });\n return userAttributes;\n}\n\nexport { toAttributeType, toAuthUserAttribute };\n//# sourceMappingURL=apiHelpers.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nvar AssociateSoftwareTokenException;\n(function (AssociateSoftwareTokenException) {\n AssociateSoftwareTokenException[\"ConcurrentModificationException\"] = \"ConcurrentModificationException\";\n AssociateSoftwareTokenException[\"ForbiddenException\"] = \"ForbiddenException\";\n AssociateSoftwareTokenException[\"InternalErrorException\"] = \"InternalErrorException\";\n AssociateSoftwareTokenException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n AssociateSoftwareTokenException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n AssociateSoftwareTokenException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n AssociateSoftwareTokenException[\"SoftwareTokenMFANotFoundException\"] = \"SoftwareTokenMFANotFoundException\";\n})(AssociateSoftwareTokenException || (AssociateSoftwareTokenException = {}));\nvar ChangePasswordException;\n(function (ChangePasswordException) {\n ChangePasswordException[\"ForbiddenException\"] = \"ForbiddenException\";\n ChangePasswordException[\"InternalErrorException\"] = \"InternalErrorException\";\n ChangePasswordException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ChangePasswordException[\"InvalidPasswordException\"] = \"InvalidPasswordException\";\n ChangePasswordException[\"LimitExceededException\"] = \"LimitExceededException\";\n ChangePasswordException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ChangePasswordException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n ChangePasswordException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ChangePasswordException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ChangePasswordException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n ChangePasswordException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ChangePasswordException || (ChangePasswordException = {}));\nvar ConfirmDeviceException;\n(function (ConfirmDeviceException) {\n ConfirmDeviceException[\"ForbiddenException\"] = \"ForbiddenException\";\n ConfirmDeviceException[\"InternalErrorException\"] = \"InternalErrorException\";\n ConfirmDeviceException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n ConfirmDeviceException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ConfirmDeviceException[\"InvalidPasswordException\"] = \"InvalidPasswordException\";\n ConfirmDeviceException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n ConfirmDeviceException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ConfirmDeviceException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n ConfirmDeviceException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ConfirmDeviceException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ConfirmDeviceException[\"UsernameExistsException\"] = \"UsernameExistsException\";\n ConfirmDeviceException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n ConfirmDeviceException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ConfirmDeviceException || (ConfirmDeviceException = {}));\nvar ConfirmForgotPasswordException;\n(function (ConfirmForgotPasswordException) {\n ConfirmForgotPasswordException[\"CodeMismatchException\"] = \"CodeMismatchException\";\n ConfirmForgotPasswordException[\"ExpiredCodeException\"] = \"ExpiredCodeException\";\n ConfirmForgotPasswordException[\"ForbiddenException\"] = \"ForbiddenException\";\n ConfirmForgotPasswordException[\"InternalErrorException\"] = \"InternalErrorException\";\n ConfirmForgotPasswordException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n ConfirmForgotPasswordException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ConfirmForgotPasswordException[\"InvalidPasswordException\"] = \"InvalidPasswordException\";\n ConfirmForgotPasswordException[\"LimitExceededException\"] = \"LimitExceededException\";\n ConfirmForgotPasswordException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ConfirmForgotPasswordException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ConfirmForgotPasswordException[\"TooManyFailedAttemptsException\"] = \"TooManyFailedAttemptsException\";\n ConfirmForgotPasswordException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ConfirmForgotPasswordException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n ConfirmForgotPasswordException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n ConfirmForgotPasswordException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n ConfirmForgotPasswordException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ConfirmForgotPasswordException || (ConfirmForgotPasswordException = {}));\nvar ConfirmSignUpException;\n(function (ConfirmSignUpException) {\n ConfirmSignUpException[\"AliasExistsException\"] = \"AliasExistsException\";\n ConfirmSignUpException[\"CodeMismatchException\"] = \"CodeMismatchException\";\n ConfirmSignUpException[\"ExpiredCodeException\"] = \"ExpiredCodeException\";\n ConfirmSignUpException[\"ForbiddenException\"] = \"ForbiddenException\";\n ConfirmSignUpException[\"InternalErrorException\"] = \"InternalErrorException\";\n ConfirmSignUpException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n ConfirmSignUpException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ConfirmSignUpException[\"LimitExceededException\"] = \"LimitExceededException\";\n ConfirmSignUpException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ConfirmSignUpException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ConfirmSignUpException[\"TooManyFailedAttemptsException\"] = \"TooManyFailedAttemptsException\";\n ConfirmSignUpException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ConfirmSignUpException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n ConfirmSignUpException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n ConfirmSignUpException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ConfirmSignUpException || (ConfirmSignUpException = {}));\nvar DeleteUserAttributesException;\n(function (DeleteUserAttributesException) {\n DeleteUserAttributesException[\"ForbiddenException\"] = \"ForbiddenException\";\n DeleteUserAttributesException[\"InternalErrorException\"] = \"InternalErrorException\";\n DeleteUserAttributesException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n DeleteUserAttributesException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n DeleteUserAttributesException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n DeleteUserAttributesException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n DeleteUserAttributesException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n DeleteUserAttributesException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n DeleteUserAttributesException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(DeleteUserAttributesException || (DeleteUserAttributesException = {}));\nvar DeleteUserException;\n(function (DeleteUserException) {\n DeleteUserException[\"ForbiddenException\"] = \"ForbiddenException\";\n DeleteUserException[\"InternalErrorException\"] = \"InternalErrorException\";\n DeleteUserException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n DeleteUserException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n DeleteUserException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n DeleteUserException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n DeleteUserException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n DeleteUserException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n DeleteUserException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(DeleteUserException || (DeleteUserException = {}));\nvar ForgetDeviceException;\n(function (ForgetDeviceException) {\n ForgetDeviceException[\"ForbiddenException\"] = \"ForbiddenException\";\n ForgetDeviceException[\"InternalErrorException\"] = \"InternalErrorException\";\n ForgetDeviceException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ForgetDeviceException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n ForgetDeviceException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ForgetDeviceException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n ForgetDeviceException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ForgetDeviceException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ForgetDeviceException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n ForgetDeviceException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ForgetDeviceException || (ForgetDeviceException = {}));\nvar ForgotPasswordException;\n(function (ForgotPasswordException) {\n ForgotPasswordException[\"CodeDeliveryFailureException\"] = \"CodeDeliveryFailureException\";\n ForgotPasswordException[\"ForbiddenException\"] = \"ForbiddenException\";\n ForgotPasswordException[\"InternalErrorException\"] = \"InternalErrorException\";\n ForgotPasswordException[\"InvalidEmailRoleAccessPolicyException\"] = \"InvalidEmailRoleAccessPolicyException\";\n ForgotPasswordException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n ForgotPasswordException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ForgotPasswordException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n ForgotPasswordException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n ForgotPasswordException[\"LimitExceededException\"] = \"LimitExceededException\";\n ForgotPasswordException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ForgotPasswordException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ForgotPasswordException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ForgotPasswordException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n ForgotPasswordException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n ForgotPasswordException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ForgotPasswordException || (ForgotPasswordException = {}));\nvar GetUserException;\n(function (GetUserException) {\n GetUserException[\"ForbiddenException\"] = \"ForbiddenException\";\n GetUserException[\"InternalErrorException\"] = \"InternalErrorException\";\n GetUserException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n GetUserException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n GetUserException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n GetUserException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n GetUserException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n GetUserException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n GetUserException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(GetUserException || (GetUserException = {}));\nvar GetIdException;\n(function (GetIdException) {\n GetIdException[\"ExternalServiceException\"] = \"ExternalServiceException\";\n GetIdException[\"InternalErrorException\"] = \"InternalErrorException\";\n GetIdException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n GetIdException[\"LimitExceededException\"] = \"LimitExceededException\";\n GetIdException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n GetIdException[\"ResourceConflictException\"] = \"ResourceConflictException\";\n GetIdException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n GetIdException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n})(GetIdException || (GetIdException = {}));\nvar GetCredentialsForIdentityException;\n(function (GetCredentialsForIdentityException) {\n GetCredentialsForIdentityException[\"ExternalServiceException\"] = \"ExternalServiceException\";\n GetCredentialsForIdentityException[\"InternalErrorException\"] = \"InternalErrorException\";\n GetCredentialsForIdentityException[\"InvalidIdentityPoolConfigurationException\"] = \"InvalidIdentityPoolConfigurationException\";\n GetCredentialsForIdentityException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n GetCredentialsForIdentityException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n GetCredentialsForIdentityException[\"ResourceConflictException\"] = \"ResourceConflictException\";\n GetCredentialsForIdentityException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n GetCredentialsForIdentityException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n})(GetCredentialsForIdentityException || (GetCredentialsForIdentityException = {}));\nvar GetUserAttributeVerificationException;\n(function (GetUserAttributeVerificationException) {\n GetUserAttributeVerificationException[\"CodeDeliveryFailureException\"] = \"CodeDeliveryFailureException\";\n GetUserAttributeVerificationException[\"ForbiddenException\"] = \"ForbiddenException\";\n GetUserAttributeVerificationException[\"InternalErrorException\"] = \"InternalErrorException\";\n GetUserAttributeVerificationException[\"InvalidEmailRoleAccessPolicyException\"] = \"InvalidEmailRoleAccessPolicyException\";\n GetUserAttributeVerificationException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n GetUserAttributeVerificationException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n GetUserAttributeVerificationException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n GetUserAttributeVerificationException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n GetUserAttributeVerificationException[\"LimitExceededException\"] = \"LimitExceededException\";\n GetUserAttributeVerificationException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n GetUserAttributeVerificationException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n GetUserAttributeVerificationException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n GetUserAttributeVerificationException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n GetUserAttributeVerificationException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n GetUserAttributeVerificationException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n GetUserAttributeVerificationException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n GetUserAttributeVerificationException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(GetUserAttributeVerificationException || (GetUserAttributeVerificationException = {}));\nvar GlobalSignOutException;\n(function (GlobalSignOutException) {\n GlobalSignOutException[\"ForbiddenException\"] = \"ForbiddenException\";\n GlobalSignOutException[\"InternalErrorException\"] = \"InternalErrorException\";\n GlobalSignOutException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n GlobalSignOutException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n GlobalSignOutException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n GlobalSignOutException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n GlobalSignOutException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n GlobalSignOutException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n})(GlobalSignOutException || (GlobalSignOutException = {}));\nvar InitiateAuthException;\n(function (InitiateAuthException) {\n InitiateAuthException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n InitiateAuthException[\"ForbiddenException\"] = \"ForbiddenException\";\n InitiateAuthException[\"InternalErrorException\"] = \"InternalErrorException\";\n InitiateAuthException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n InitiateAuthException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n InitiateAuthException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n InitiateAuthException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n InitiateAuthException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n InitiateAuthException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n InitiateAuthException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n InitiateAuthException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n InitiateAuthException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n InitiateAuthException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n InitiateAuthException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n InitiateAuthException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(InitiateAuthException || (InitiateAuthException = {}));\nvar ResendConfirmationException;\n(function (ResendConfirmationException) {\n ResendConfirmationException[\"CodeDeliveryFailureException\"] = \"CodeDeliveryFailureException\";\n ResendConfirmationException[\"ForbiddenException\"] = \"ForbiddenException\";\n ResendConfirmationException[\"InternalErrorException\"] = \"InternalErrorException\";\n ResendConfirmationException[\"InvalidEmailRoleAccessPolicyException\"] = \"InvalidEmailRoleAccessPolicyException\";\n ResendConfirmationException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n ResendConfirmationException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ResendConfirmationException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n ResendConfirmationException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n ResendConfirmationException[\"LimitExceededException\"] = \"LimitExceededException\";\n ResendConfirmationException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ResendConfirmationException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ResendConfirmationException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ResendConfirmationException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n ResendConfirmationException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n ResendConfirmationException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ResendConfirmationException || (ResendConfirmationException = {}));\nvar RespondToAuthChallengeException;\n(function (RespondToAuthChallengeException) {\n RespondToAuthChallengeException[\"AliasExistsException\"] = \"AliasExistsException\";\n RespondToAuthChallengeException[\"CodeMismatchException\"] = \"CodeMismatchException\";\n RespondToAuthChallengeException[\"ExpiredCodeException\"] = \"ExpiredCodeException\";\n RespondToAuthChallengeException[\"ForbiddenException\"] = \"ForbiddenException\";\n RespondToAuthChallengeException[\"InternalErrorException\"] = \"InternalErrorException\";\n RespondToAuthChallengeException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n RespondToAuthChallengeException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n RespondToAuthChallengeException[\"InvalidPasswordException\"] = \"InvalidPasswordException\";\n RespondToAuthChallengeException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n RespondToAuthChallengeException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n RespondToAuthChallengeException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n RespondToAuthChallengeException[\"MFAMethodNotFoundException\"] = \"MFAMethodNotFoundException\";\n RespondToAuthChallengeException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n RespondToAuthChallengeException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n RespondToAuthChallengeException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n RespondToAuthChallengeException[\"SoftwareTokenMFANotFoundException\"] = \"SoftwareTokenMFANotFoundException\";\n RespondToAuthChallengeException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n RespondToAuthChallengeException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n RespondToAuthChallengeException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n RespondToAuthChallengeException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n RespondToAuthChallengeException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(RespondToAuthChallengeException || (RespondToAuthChallengeException = {}));\nvar SetUserMFAPreferenceException;\n(function (SetUserMFAPreferenceException) {\n SetUserMFAPreferenceException[\"ForbiddenException\"] = \"ForbiddenException\";\n SetUserMFAPreferenceException[\"InternalErrorException\"] = \"InternalErrorException\";\n SetUserMFAPreferenceException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n SetUserMFAPreferenceException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n SetUserMFAPreferenceException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n SetUserMFAPreferenceException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n SetUserMFAPreferenceException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n SetUserMFAPreferenceException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(SetUserMFAPreferenceException || (SetUserMFAPreferenceException = {}));\nvar SignUpException;\n(function (SignUpException) {\n SignUpException[\"CodeDeliveryFailureException\"] = \"CodeDeliveryFailureException\";\n SignUpException[\"InternalErrorException\"] = \"InternalErrorException\";\n SignUpException[\"InvalidEmailRoleAccessPolicyException\"] = \"InvalidEmailRoleAccessPolicyException\";\n SignUpException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n SignUpException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n SignUpException[\"InvalidPasswordException\"] = \"InvalidPasswordException\";\n SignUpException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n SignUpException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n SignUpException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n SignUpException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n SignUpException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n SignUpException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n SignUpException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n SignUpException[\"UsernameExistsException\"] = \"UsernameExistsException\";\n})(SignUpException || (SignUpException = {}));\nvar UpdateUserAttributesException;\n(function (UpdateUserAttributesException) {\n UpdateUserAttributesException[\"AliasExistsException\"] = \"AliasExistsException\";\n UpdateUserAttributesException[\"CodeDeliveryFailureException\"] = \"CodeDeliveryFailureException\";\n UpdateUserAttributesException[\"CodeMismatchException\"] = \"CodeMismatchException\";\n UpdateUserAttributesException[\"ExpiredCodeException\"] = \"ExpiredCodeException\";\n UpdateUserAttributesException[\"ForbiddenException\"] = \"ForbiddenException\";\n UpdateUserAttributesException[\"InternalErrorException\"] = \"InternalErrorException\";\n UpdateUserAttributesException[\"InvalidEmailRoleAccessPolicyException\"] = \"InvalidEmailRoleAccessPolicyException\";\n UpdateUserAttributesException[\"InvalidLambdaResponseException\"] = \"InvalidLambdaResponseException\";\n UpdateUserAttributesException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n UpdateUserAttributesException[\"InvalidSmsRoleAccessPolicyException\"] = \"InvalidSmsRoleAccessPolicyException\";\n UpdateUserAttributesException[\"InvalidSmsRoleTrustRelationshipException\"] = \"InvalidSmsRoleTrustRelationshipException\";\n UpdateUserAttributesException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n UpdateUserAttributesException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n UpdateUserAttributesException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n UpdateUserAttributesException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n UpdateUserAttributesException[\"UnexpectedLambdaException\"] = \"UnexpectedLambdaException\";\n UpdateUserAttributesException[\"UserLambdaValidationException\"] = \"UserLambdaValidationException\";\n UpdateUserAttributesException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n UpdateUserAttributesException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(UpdateUserAttributesException || (UpdateUserAttributesException = {}));\nvar VerifySoftwareTokenException;\n(function (VerifySoftwareTokenException) {\n VerifySoftwareTokenException[\"CodeMismatchException\"] = \"CodeMismatchException\";\n VerifySoftwareTokenException[\"EnableSoftwareTokenMFAException\"] = \"EnableSoftwareTokenMFAException\";\n VerifySoftwareTokenException[\"ForbiddenException\"] = \"ForbiddenException\";\n VerifySoftwareTokenException[\"InternalErrorException\"] = \"InternalErrorException\";\n VerifySoftwareTokenException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n VerifySoftwareTokenException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n VerifySoftwareTokenException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n VerifySoftwareTokenException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n VerifySoftwareTokenException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n VerifySoftwareTokenException[\"SoftwareTokenMFANotFoundException\"] = \"SoftwareTokenMFANotFoundException\";\n VerifySoftwareTokenException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n VerifySoftwareTokenException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n VerifySoftwareTokenException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(VerifySoftwareTokenException || (VerifySoftwareTokenException = {}));\nvar VerifyUserAttributeException;\n(function (VerifyUserAttributeException) {\n VerifyUserAttributeException[\"AliasExistsException\"] = \"AliasExistsException\";\n VerifyUserAttributeException[\"CodeMismatchException\"] = \"CodeMismatchException\";\n VerifyUserAttributeException[\"ExpiredCodeException\"] = \"ExpiredCodeException\";\n VerifyUserAttributeException[\"ForbiddenException\"] = \"ForbiddenException\";\n VerifyUserAttributeException[\"InternalErrorException\"] = \"InternalErrorException\";\n VerifyUserAttributeException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n VerifyUserAttributeException[\"LimitExceededException\"] = \"LimitExceededException\";\n VerifyUserAttributeException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n VerifyUserAttributeException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n VerifyUserAttributeException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n VerifyUserAttributeException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n VerifyUserAttributeException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n VerifyUserAttributeException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(VerifyUserAttributeException || (VerifyUserAttributeException = {}));\nvar UpdateDeviceStatusException;\n(function (UpdateDeviceStatusException) {\n UpdateDeviceStatusException[\"ForbiddenException\"] = \"ForbiddenException\";\n UpdateDeviceStatusException[\"InternalErrorException\"] = \"InternalErrorException\";\n UpdateDeviceStatusException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n UpdateDeviceStatusException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n UpdateDeviceStatusException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n UpdateDeviceStatusException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n UpdateDeviceStatusException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n UpdateDeviceStatusException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n UpdateDeviceStatusException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n UpdateDeviceStatusException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(UpdateDeviceStatusException || (UpdateDeviceStatusException = {}));\nvar ListDevicesException;\n(function (ListDevicesException) {\n ListDevicesException[\"ForbiddenException\"] = \"ForbiddenException\";\n ListDevicesException[\"InternalErrorException\"] = \"InternalErrorException\";\n ListDevicesException[\"InvalidParameterException\"] = \"InvalidParameterException\";\n ListDevicesException[\"InvalidUserPoolConfigurationException\"] = \"InvalidUserPoolConfigurationException\";\n ListDevicesException[\"NotAuthorizedException\"] = \"NotAuthorizedException\";\n ListDevicesException[\"PasswordResetRequiredException\"] = \"PasswordResetRequiredException\";\n ListDevicesException[\"ResourceNotFoundException\"] = \"ResourceNotFoundException\";\n ListDevicesException[\"TooManyRequestsException\"] = \"TooManyRequestsException\";\n ListDevicesException[\"UserNotConfirmedException\"] = \"UserNotConfirmedException\";\n ListDevicesException[\"UserNotFoundException\"] = \"UserNotFoundException\";\n})(ListDevicesException || (ListDevicesException = {}));\nconst SETUP_TOTP_EXCEPTION = 'SetUpTOTPException';\n\nexport { AssociateSoftwareTokenException, ChangePasswordException, ConfirmDeviceException, ConfirmForgotPasswordException, ConfirmSignUpException, DeleteUserAttributesException, DeleteUserException, ForgetDeviceException, ForgotPasswordException, GetCredentialsForIdentityException, GetIdException, GetUserAttributeVerificationException, GetUserException, GlobalSignOutException, InitiateAuthException, ListDevicesException, ResendConfirmationException, RespondToAuthChallengeException, SETUP_TOTP_EXCEPTION, SetUserMFAPreferenceException, SignUpException, UpdateDeviceStatusException, UpdateUserAttributesException, VerifySoftwareTokenException, VerifyUserAttributeException };\n//# sourceMappingURL=errors.mjs.map\n","import { AuthError } from './AuthError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst USER_UNAUTHENTICATED_EXCEPTION = 'UserUnAuthenticatedException';\nconst USER_ALREADY_AUTHENTICATED_EXCEPTION = 'UserAlreadyAuthenticatedException';\nconst DEVICE_METADATA_NOT_FOUND_EXCEPTION = 'DeviceMetadataNotFoundException';\nconst AUTO_SIGN_IN_EXCEPTION = 'AutoSignInException';\nconst INVALID_REDIRECT_EXCEPTION = 'InvalidRedirectException';\nconst INVALID_APP_SCHEME_EXCEPTION = 'InvalidAppSchemeException';\nconst INVALID_PREFERRED_REDIRECT_EXCEPTION = 'InvalidPreferredRedirectUrlException';\nconst invalidRedirectException = new AuthError({\n name: INVALID_REDIRECT_EXCEPTION,\n message: 'signInRedirect or signOutRedirect had an invalid format or was not found.',\n recoverySuggestion: 'Please make sure the signIn/Out redirect in your oauth config is valid.',\n});\nconst invalidAppSchemeException = new AuthError({\n name: INVALID_APP_SCHEME_EXCEPTION,\n message: 'A valid non-http app scheme was not found in the config.',\n recoverySuggestion: 'Please make sure a valid custom app scheme is present in the config.',\n});\nconst invalidPreferredRedirectUrlException = new AuthError({\n name: INVALID_PREFERRED_REDIRECT_EXCEPTION,\n message: 'The given preferredRedirectUrl does not match any items in the redirectSignOutUrls array from the config.',\n recoverySuggestion: 'Please make sure a matching preferredRedirectUrl is provided.',\n});\nconst INVALID_ORIGIN_EXCEPTION = 'InvalidOriginException';\nconst invalidOriginException = new AuthError({\n name: INVALID_ORIGIN_EXCEPTION,\n message: 'redirect is coming from a different origin. The oauth flow needs to be initiated from the same origin',\n recoverySuggestion: 'Please call signInWithRedirect from the same origin.',\n});\nconst OAUTH_SIGNOUT_EXCEPTION = 'OAuthSignOutException';\nconst TOKEN_REFRESH_EXCEPTION = 'TokenRefreshException';\nconst UNEXPECTED_SIGN_IN_INTERRUPTION_EXCEPTION = 'UnexpectedSignInInterruptionException';\n\nexport { AUTO_SIGN_IN_EXCEPTION, DEVICE_METADATA_NOT_FOUND_EXCEPTION, INVALID_APP_SCHEME_EXCEPTION, INVALID_ORIGIN_EXCEPTION, INVALID_PREFERRED_REDIRECT_EXCEPTION, INVALID_REDIRECT_EXCEPTION, OAUTH_SIGNOUT_EXCEPTION, TOKEN_REFRESH_EXCEPTION, UNEXPECTED_SIGN_IN_INTERRUPTION_EXCEPTION, USER_ALREADY_AUTHENTICATED_EXCEPTION, USER_UNAUTHENTICATED_EXCEPTION, invalidAppSchemeException, invalidOriginException, invalidPreferredRedirectUrlException, invalidRedirectException };\n//# sourceMappingURL=constants.mjs.map\n","import { AuthError } from '../../../errors/AuthError.mjs';\nimport { TOKEN_REFRESH_EXCEPTION, USER_UNAUTHENTICATED_EXCEPTION, DEVICE_METADATA_NOT_FOUND_EXCEPTION } from '../../../errors/constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction isTypeUserPoolConfig(authConfig) {\n if (authConfig &&\n authConfig.Cognito.userPoolId &&\n authConfig.Cognito.userPoolClientId) {\n return true;\n }\n return false;\n}\nfunction assertAuthTokens(tokens) {\n if (!tokens || !tokens.accessToken) {\n throw new AuthError({\n name: USER_UNAUTHENTICATED_EXCEPTION,\n message: 'User needs to be authenticated to call this API.',\n recoverySuggestion: 'Sign in before calling this API again.',\n });\n }\n}\nfunction assertIdTokenInAuthTokens(tokens) {\n if (!tokens || !tokens.idToken) {\n throw new AuthError({\n name: USER_UNAUTHENTICATED_EXCEPTION,\n message: 'User needs to be authenticated to call this API.',\n recoverySuggestion: 'Sign in before calling this API again.',\n });\n }\n}\nconst oAuthTokenRefreshException = new AuthError({\n name: TOKEN_REFRESH_EXCEPTION,\n message: `Token refresh is not supported when authenticated with the 'implicit grant' (token) oauth flow. \n\tPlease change your oauth configuration to use 'code grant' flow.`,\n recoverySuggestion: `Please logout and change your Amplify configuration to use \"code grant\" flow. \n\tE.g { responseType: 'code' }`,\n});\nconst tokenRefreshException = new AuthError({\n name: USER_UNAUTHENTICATED_EXCEPTION,\n message: 'User needs to be authenticated to call this API.',\n recoverySuggestion: 'Sign in before calling this API again.',\n});\nfunction assertAuthTokensWithRefreshToken(tokens) {\n if (isAuthenticatedWithImplicitOauthFlow(tokens)) {\n throw oAuthTokenRefreshException;\n }\n if (!isAuthenticatedWithRefreshToken(tokens)) {\n throw tokenRefreshException;\n }\n}\nfunction assertDeviceMetadata(deviceMetadata) {\n if (!deviceMetadata ||\n !deviceMetadata.deviceKey ||\n !deviceMetadata.deviceGroupKey ||\n !deviceMetadata.randomPassword) {\n throw new AuthError({\n name: DEVICE_METADATA_NOT_FOUND_EXCEPTION,\n message: 'Either deviceKey, deviceGroupKey or secretPassword were not found during the sign-in process.',\n recoverySuggestion: 'Make sure to not clear storage after calling the signIn API.',\n });\n }\n}\nconst OAuthStorageKeys = {\n inflightOAuth: 'inflightOAuth',\n oauthSignIn: 'oauthSignIn',\n oauthPKCE: 'oauthPKCE',\n oauthState: 'oauthState',\n};\nfunction isAuthenticated(tokens) {\n return tokens?.accessToken || tokens?.idToken;\n}\nfunction isAuthenticatedWithRefreshToken(tokens) {\n return isAuthenticated(tokens) && tokens?.refreshToken;\n}\nfunction isAuthenticatedWithImplicitOauthFlow(tokens) {\n return isAuthenticated(tokens) && !tokens?.refreshToken;\n}\n\nexport { OAuthStorageKeys, assertAuthTokens, assertAuthTokensWithRefreshToken, assertDeviceMetadata, assertIdTokenInAuthTokens, isTypeUserPoolConfig, oAuthTokenRefreshException, tokenRefreshException };\n//# sourceMappingURL=types.mjs.map\n","import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { assertAuthTokens } from '../../utils/types.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst getCurrentUser = async (amplify) => {\n const authConfig = amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const tokens = await amplify.Auth.getTokens({ forceRefresh: false });\n assertAuthTokens(tokens);\n const { 'cognito:username': username, sub } = tokens.idToken?.payload ?? {};\n const authUser = {\n username: username,\n userId: sub,\n };\n const signInDetails = getSignInDetailsFromTokens(tokens);\n if (signInDetails) {\n authUser.signInDetails = signInDetails;\n }\n return authUser;\n};\nfunction getSignInDetailsFromTokens(tokens) {\n return tokens?.signInDetails;\n}\n\nexport { getCurrentUser };\n//# sourceMappingURL=getCurrentUser.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { getCurrentUser as getCurrentUser$1 } from './internal/getCurrentUser.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Gets the current user from the idToken.\n *\n * @param input - The GetCurrentUserInput object.\n * @returns GetCurrentUserOutput\n * @throws - {@link InitiateAuthException} - Thrown when the service fails to refresh the tokens.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nconst getCurrentUser = async () => {\n return getCurrentUser$1(Amplify);\n};\n\nexport { getCurrentUser };\n//# sourceMappingURL=getCurrentUser.mjs.map\n","import { getAmplifyUserAgent, Category } from '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst getAuthUserAgentValue = (action, customUserAgentDetails) => getAmplifyUserAgent({\n category: Category.Auth,\n action,\n ...customUserAgentDetails,\n});\n\nexport { getAuthUserAgentValue };\n//# sourceMappingURL=getAuthUserAgentValue.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createUserPoolSerializer = (operation) => (input, endpoint) => {\n const headers = getSharedHeaders(operation);\n const body = JSON.stringify(input);\n return buildHttpRpcRequest(endpoint, headers, body);\n};\nconst getSharedHeaders = (operation) => ({\n 'content-type': 'application/x-amz-json-1.1',\n 'x-amz-target': `AWSCognitoIdentityProviderService.${operation}`,\n});\nconst buildHttpRpcRequest = ({ url }, headers, body) => ({\n headers,\n url,\n body,\n method: 'POST',\n});\n\nexport { createUserPoolSerializer };\n//# sourceMappingURL=createUserPoolSerializer.mjs.map\n","import { AmplifyErrorCode } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../AuthError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction assertServiceError(error) {\n if (!error ||\n error.name === 'Error' ||\n error instanceof TypeError) {\n throw new AuthError({\n name: AmplifyErrorCode.Unknown,\n message: 'An unknown error has occurred.',\n underlyingError: error,\n });\n }\n}\n\nexport { assertServiceError };\n//# sourceMappingURL=assertServiceError.mjs.map\n","import { parseJsonError, parseJsonBody } from '@aws-amplify/core/internals/aws-client-utils';\nimport { assertServiceError } from '../../../../../../errors/utils/assertServiceError.mjs';\nimport { AuthError } from '../../../../../../errors/AuthError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createUserPoolDeserializer = () => async (response) => {\n if (response.statusCode >= 300) {\n const error = await parseJsonError(response);\n assertServiceError(error);\n throw new AuthError({ name: error.name, message: error.message });\n }\n return parseJsonBody(response);\n};\n\nexport { createUserPoolDeserializer };\n//# sourceMappingURL=createUserPoolDeserializer.mjs.map\n","import { composeTransferHandler } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { unauthenticatedHandler } from '@aws-amplify/core/internals/aws-client-utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * A Cognito Identity-specific middleware that disables caching for all requests.\n */\nconst disableCacheMiddlewareFactory = () => (next, _) => async function disableCacheMiddleware(request) {\n request.headers['cache-control'] = 'no-store';\n return next(request);\n};\n/**\n * A Cognito Identity-specific transfer handler that does NOT sign requests, and\n * disables caching.\n *\n * @internal\n */\nconst cognitoUserPoolTransferHandler = composeTransferHandler(unauthenticatedHandler, [disableCacheMiddlewareFactory]);\n\nexport { cognitoUserPoolTransferHandler };\n//# sourceMappingURL=cognitoUserPoolTransferHandler.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * The service name used to sign requests if the API requires authentication.\n */\nconst COGNITO_IDP_SERVICE_NAME = 'cognito-idp';\n\nexport { COGNITO_IDP_SERVICE_NAME };\n//# sourceMappingURL=constants.mjs.map\n","import { getRetryDecider, parseJsonError, jitteredBackoff } from '@aws-amplify/core/internals/aws-client-utils';\nimport { getAmplifyUserAgent } from '@aws-amplify/core/internals/utils';\nimport { COGNITO_IDP_SERVICE_NAME } from '../../../constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst DEFAULT_SERVICE_CLIENT_API_CONFIG = {\n service: COGNITO_IDP_SERVICE_NAME,\n retryDecider: getRetryDecider(parseJsonError),\n computeDelay: jitteredBackoff,\n userAgentValue: getAmplifyUserAgent(),\n cache: 'no-store',\n};\n\nexport { DEFAULT_SERVICE_CLIENT_API_CONFIG };\n//# sourceMappingURL=constants.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createInitiateAuthClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('InitiateAuth'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createInitiateAuthClient };\n//# sourceMappingURL=createInitiateAuthClient.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createRespondToAuthChallengeClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('RespondToAuthChallenge'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createRespondToAuthChallengeClient };\n//# sourceMappingURL=createRespondToAuthChallengeClient.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createVerifySoftwareTokenClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('VerifySoftwareToken'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createVerifySoftwareTokenClient };\n//# sourceMappingURL=createVerifySoftwareTokenClient.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createAssociateSoftwareTokenClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('AssociateSoftwareToken'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createAssociateSoftwareTokenClient };\n//# sourceMappingURL=createAssociateSoftwareTokenClient.mjs.map\n","import { getDnsSuffix } from '@aws-amplify/core/internals/aws-client-utils';\nimport { AmplifyUrl } from '@aws-amplify/core/internals/utils';\nimport { COGNITO_IDP_SERVICE_NAME } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst cognitoUserPoolEndpointResolver = ({ region, }) => ({\n url: new AmplifyUrl(`https://${COGNITO_IDP_SERVICE_NAME}.${region}.${getDnsSuffix(region)}`),\n});\n\nexport { cognitoUserPoolEndpointResolver };\n//# sourceMappingURL=cognitoUserPoolEndpointResolver.mjs.map\n","import { AmplifyUrl } from '@aws-amplify/core/internals/utils';\nimport { cognitoUserPoolEndpointResolver } from '../../../foundation/cognitoUserPoolEndpointResolver.mjs';\n\nconst createCognitoUserPoolEndpointResolver = ({ endpointOverride }) => (input) => {\n if (endpointOverride) {\n return { url: new AmplifyUrl(endpointOverride) };\n }\n return cognitoUserPoolEndpointResolver(input);\n};\n\nexport { createCognitoUserPoolEndpointResolver };\n//# sourceMappingURL=createCognitoUserPoolEndpointResolver.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction getUserContextData({ username, userPoolId, userPoolClientId, }) {\n if (typeof window === 'undefined') {\n return undefined;\n }\n const amazonCognitoAdvancedSecurityData = window\n .AmazonCognitoAdvancedSecurityData;\n if (typeof amazonCognitoAdvancedSecurityData === 'undefined') {\n return undefined;\n }\n const advancedSecurityData = amazonCognitoAdvancedSecurityData.getData(username, userPoolId, userPoolClientId);\n if (advancedSecurityData) {\n const userContextData = {\n EncodedData: advancedSecurityData,\n };\n return userContextData;\n }\n return {};\n}\n\nexport { getUserContextData };\n//# sourceMappingURL=userContextData.mjs.map\n","import { deDupeAsyncFunction, assertTokenProviderConfig, decodeJWT } from '@aws-amplify/core/internals/utils';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { assertAuthTokensWithRefreshToken } from './types.mjs';\nimport { AuthError } from '../../../errors/AuthError.mjs';\nimport { createInitiateAuthClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../../../errors/types/validation.mjs';\nimport '../types/errors.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { getUserContextData } from './userContextData.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst refreshAuthTokensFunction = async ({ tokens, authConfig, username, }) => {\n assertTokenProviderConfig(authConfig?.Cognito);\n const { userPoolId, userPoolClientId, userPoolEndpoint } = authConfig.Cognito;\n const region = getRegionFromUserPoolId(userPoolId);\n assertAuthTokensWithRefreshToken(tokens);\n const refreshTokenString = tokens.refreshToken;\n const AuthParameters = {\n REFRESH_TOKEN: refreshTokenString,\n };\n if (tokens.deviceMetadata?.deviceKey) {\n AuthParameters.DEVICE_KEY = tokens.deviceMetadata.deviceKey;\n }\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const initiateAuth = createInitiateAuthClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { AuthenticationResult } = await initiateAuth({ region }, {\n ClientId: userPoolClientId,\n AuthFlow: 'REFRESH_TOKEN_AUTH',\n AuthParameters,\n UserContextData,\n });\n const accessToken = decodeJWT(AuthenticationResult?.AccessToken ?? '');\n const idToken = AuthenticationResult?.IdToken\n ? decodeJWT(AuthenticationResult.IdToken)\n : undefined;\n const { iat } = accessToken.payload;\n // This should never happen. If it does, it's a bug from the service.\n if (!iat) {\n throw new AuthError({\n name: 'iatNotFoundException',\n message: 'iat not found in access token',\n });\n }\n const clockDrift = iat * 1000 - new Date().getTime();\n return {\n accessToken,\n idToken,\n clockDrift,\n refreshToken: refreshTokenString,\n username,\n };\n};\nconst refreshAuthTokens = deDupeAsyncFunction(refreshAuthTokensFunction);\nconst refreshAuthTokensWithoutDedupe = refreshAuthTokensFunction;\n\nexport { refreshAuthTokens, refreshAuthTokensWithoutDedupe };\n//# sourceMappingURL=refreshAuthTokens.mjs.map\n","const AuthTokenStorageKeys = {\n accessToken: 'accessToken',\n idToken: 'idToken',\n oidcProvider: 'oidcProvider',\n clockDrift: 'clockDrift',\n refreshToken: 'refreshToken',\n deviceKey: 'deviceKey',\n randomPasswordKey: 'randomPasswordKey',\n deviceGroupKey: 'deviceGroupKey',\n signInDetails: 'signInDetails',\n oauthMetadata: 'oauthMetadata',\n};\n\nexport { AuthTokenStorageKeys };\n//# sourceMappingURL=types.mjs.map\n","import { createAssertionFunction } from '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nvar TokenProviderErrorCode;\n(function (TokenProviderErrorCode) {\n TokenProviderErrorCode[\"InvalidAuthTokens\"] = \"InvalidAuthTokens\";\n})(TokenProviderErrorCode || (TokenProviderErrorCode = {}));\nconst tokenValidationErrorMap = {\n [TokenProviderErrorCode.InvalidAuthTokens]: {\n message: 'Invalid tokens.',\n recoverySuggestion: 'Make sure the tokens are valid.',\n },\n};\nconst assert = createAssertionFunction(tokenValidationErrorMap);\n\nexport { TokenProviderErrorCode, assert };\n//# sourceMappingURL=errorHelpers.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst AUTH_KEY_PREFIX = 'CognitoIdentityServiceProvider';\n\nexport { AUTH_KEY_PREFIX };\n//# sourceMappingURL=constants.mjs.map\n","import { decodeJWT, assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError.mjs';\nimport { AuthTokenStorageKeys } from './types.mjs';\nimport { assert, TokenProviderErrorCode } from './errorHelpers.mjs';\nimport { AUTH_KEY_PREFIX } from './constants.mjs';\n\nclass DefaultTokenStore {\n getKeyValueStorage() {\n if (!this.keyValueStorage) {\n throw new AuthError({\n name: 'KeyValueStorageNotFoundException',\n message: 'KeyValueStorage was not found in TokenStore',\n });\n }\n return this.keyValueStorage;\n }\n setKeyValueStorage(keyValueStorage) {\n this.keyValueStorage = keyValueStorage;\n }\n setAuthConfig(authConfig) {\n this.authConfig = authConfig;\n }\n async loadTokens() {\n // TODO(v6): migration logic should be here\n // Reading V5 tokens old format\n try {\n const authKeys = await this.getAuthKeys();\n const accessTokenString = await this.getKeyValueStorage().getItem(authKeys.accessToken);\n if (!accessTokenString) {\n throw new AuthError({\n name: 'NoSessionFoundException',\n message: 'Auth session was not found. Make sure to call signIn.',\n });\n }\n const accessToken = decodeJWT(accessTokenString);\n const itString = await this.getKeyValueStorage().getItem(authKeys.idToken);\n const idToken = itString ? decodeJWT(itString) : undefined;\n const refreshToken = (await this.getKeyValueStorage().getItem(authKeys.refreshToken)) ??\n undefined;\n const clockDriftString = (await this.getKeyValueStorage().getItem(authKeys.clockDrift)) ?? '0';\n const clockDrift = Number.parseInt(clockDriftString);\n const signInDetails = await this.getKeyValueStorage().getItem(authKeys.signInDetails);\n const tokens = {\n accessToken,\n idToken,\n refreshToken,\n deviceMetadata: (await this.getDeviceMetadata()) ?? undefined,\n clockDrift,\n username: await this.getLastAuthUser(),\n };\n if (signInDetails) {\n tokens.signInDetails = JSON.parse(signInDetails);\n }\n return tokens;\n }\n catch (err) {\n return null;\n }\n }\n async storeTokens(tokens) {\n assert(tokens !== undefined, TokenProviderErrorCode.InvalidAuthTokens);\n const lastAuthUser = tokens.username;\n await this.getKeyValueStorage().setItem(this.getLastAuthUserKey(), lastAuthUser);\n const authKeys = await this.getAuthKeys();\n await this.getKeyValueStorage().setItem(authKeys.accessToken, tokens.accessToken.toString());\n if (tokens.idToken) {\n await this.getKeyValueStorage().setItem(authKeys.idToken, tokens.idToken.toString());\n }\n else {\n await this.getKeyValueStorage().removeItem(authKeys.idToken);\n }\n if (tokens.refreshToken) {\n await this.getKeyValueStorage().setItem(authKeys.refreshToken, tokens.refreshToken);\n }\n else {\n await this.getKeyValueStorage().removeItem(authKeys.refreshToken);\n }\n if (tokens.deviceMetadata) {\n if (tokens.deviceMetadata.deviceKey) {\n await this.getKeyValueStorage().setItem(authKeys.deviceKey, tokens.deviceMetadata.deviceKey);\n }\n if (tokens.deviceMetadata.deviceGroupKey) {\n await this.getKeyValueStorage().setItem(authKeys.deviceGroupKey, tokens.deviceMetadata.deviceGroupKey);\n }\n await this.getKeyValueStorage().setItem(authKeys.randomPasswordKey, tokens.deviceMetadata.randomPassword);\n }\n if (tokens.signInDetails) {\n await this.getKeyValueStorage().setItem(authKeys.signInDetails, JSON.stringify(tokens.signInDetails));\n }\n else {\n await this.getKeyValueStorage().removeItem(authKeys.signInDetails);\n }\n await this.getKeyValueStorage().setItem(authKeys.clockDrift, `${tokens.clockDrift}`);\n }\n async clearTokens() {\n const authKeys = await this.getAuthKeys();\n // Not calling clear because it can remove data that is not managed by AuthTokenStore\n await Promise.all([\n this.getKeyValueStorage().removeItem(authKeys.accessToken),\n this.getKeyValueStorage().removeItem(authKeys.idToken),\n this.getKeyValueStorage().removeItem(authKeys.clockDrift),\n this.getKeyValueStorage().removeItem(authKeys.refreshToken),\n this.getKeyValueStorage().removeItem(authKeys.signInDetails),\n this.getKeyValueStorage().removeItem(this.getLastAuthUserKey()),\n this.getKeyValueStorage().removeItem(authKeys.oauthMetadata),\n ]);\n }\n async getDeviceMetadata(username) {\n const authKeys = await this.getAuthKeys(username);\n const deviceKey = await this.getKeyValueStorage().getItem(authKeys.deviceKey);\n const deviceGroupKey = await this.getKeyValueStorage().getItem(authKeys.deviceGroupKey);\n const randomPassword = await this.getKeyValueStorage().getItem(authKeys.randomPasswordKey);\n return randomPassword && deviceGroupKey && deviceKey\n ? {\n deviceKey,\n deviceGroupKey,\n randomPassword,\n }\n : null;\n }\n async clearDeviceMetadata(username) {\n const authKeys = await this.getAuthKeys(username);\n await Promise.all([\n this.getKeyValueStorage().removeItem(authKeys.deviceKey),\n this.getKeyValueStorage().removeItem(authKeys.deviceGroupKey),\n this.getKeyValueStorage().removeItem(authKeys.randomPasswordKey),\n ]);\n }\n async getAuthKeys(username) {\n assertTokenProviderConfig(this.authConfig?.Cognito);\n const lastAuthUser = username ?? (await this.getLastAuthUser());\n return createKeysForAuthStorage(AUTH_KEY_PREFIX, `${this.authConfig.Cognito.userPoolClientId}.${lastAuthUser}`);\n }\n getLastAuthUserKey() {\n assertTokenProviderConfig(this.authConfig?.Cognito);\n const identifier = this.authConfig.Cognito.userPoolClientId;\n return `${AUTH_KEY_PREFIX}.${identifier}.LastAuthUser`;\n }\n async getLastAuthUser() {\n const lastAuthUser = (await this.getKeyValueStorage().getItem(this.getLastAuthUserKey())) ??\n 'username';\n return lastAuthUser;\n }\n async setOAuthMetadata(metadata) {\n const { oauthMetadata: oauthMetadataKey } = await this.getAuthKeys();\n await this.getKeyValueStorage().setItem(oauthMetadataKey, JSON.stringify(metadata));\n }\n async getOAuthMetadata() {\n const { oauthMetadata: oauthMetadataKey } = await this.getAuthKeys();\n const oauthMetadata = await this.getKeyValueStorage().getItem(oauthMetadataKey);\n return oauthMetadata && JSON.parse(oauthMetadata);\n }\n}\nconst createKeysForAuthStorage = (provider, identifier) => {\n return getAuthStorageKeys(AuthTokenStorageKeys)(`${provider}`, identifier);\n};\nfunction getAuthStorageKeys(authKeys) {\n const keys = Object.values({ ...authKeys });\n return (prefix, identifier) => keys.reduce((acc, authKey) => ({\n ...acc,\n [authKey]: `${prefix}.${identifier}.${authKey}`,\n }), {});\n}\n\nexport { DefaultTokenStore, createKeysForAuthStorage, getAuthStorageKeys };\n//# sourceMappingURL=TokenStore.mjs.map\n","import { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { getAuthStorageKeys } from '../tokenProvider/TokenStore.mjs';\nimport { OAuthStorageKeys } from './types.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst V5_HOSTED_UI_KEY = 'amplify-signin-with-hostedUI';\nconst name = 'CognitoIdentityServiceProvider';\nclass DefaultOAuthStore {\n constructor(keyValueStorage) {\n this.keyValueStorage = keyValueStorage;\n }\n async clearOAuthInflightData() {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n await Promise.all([\n this.keyValueStorage.removeItem(authKeys.inflightOAuth),\n this.keyValueStorage.removeItem(authKeys.oauthPKCE),\n this.keyValueStorage.removeItem(authKeys.oauthState),\n ]);\n }\n async clearOAuthData() {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n await this.clearOAuthInflightData();\n await this.keyValueStorage.removeItem(V5_HOSTED_UI_KEY); // remove in case a customer migrated an App from v5 to v6\n return this.keyValueStorage.removeItem(authKeys.oauthSignIn);\n }\n loadOAuthState() {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n return this.keyValueStorage.getItem(authKeys.oauthState);\n }\n storeOAuthState(state) {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n return this.keyValueStorage.setItem(authKeys.oauthState, state);\n }\n loadPKCE() {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n return this.keyValueStorage.getItem(authKeys.oauthPKCE);\n }\n storePKCE(pkce) {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n return this.keyValueStorage.setItem(authKeys.oauthPKCE, pkce);\n }\n setAuthConfig(authConfigParam) {\n this.cognitoConfig = authConfigParam;\n }\n async loadOAuthInFlight() {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n return ((await this.keyValueStorage.getItem(authKeys.inflightOAuth)) === 'true');\n }\n async storeOAuthInFlight(inflight) {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n await this.keyValueStorage.setItem(authKeys.inflightOAuth, `${inflight}`);\n }\n async loadOAuthSignIn() {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n const isLegacyHostedUISignIn = await this.keyValueStorage.getItem(V5_HOSTED_UI_KEY);\n const [isOAuthSignIn, preferPrivateSession] = (await this.keyValueStorage.getItem(authKeys.oauthSignIn))?.split(',') ??\n [];\n return {\n isOAuthSignIn: isOAuthSignIn === 'true' || isLegacyHostedUISignIn === 'true',\n preferPrivateSession: preferPrivateSession === 'true',\n };\n }\n async storeOAuthSignIn(oauthSignIn, preferPrivateSession = false) {\n assertTokenProviderConfig(this.cognitoConfig);\n const authKeys = createKeysForAuthStorage(name, this.cognitoConfig.userPoolClientId);\n await this.keyValueStorage.setItem(authKeys.oauthSignIn, `${oauthSignIn},${preferPrivateSession}`);\n }\n}\nconst createKeysForAuthStorage = (provider, identifier) => {\n return getAuthStorageKeys(OAuthStorageKeys)(provider, identifier);\n};\n\nexport { DefaultOAuthStore };\n//# sourceMappingURL=signInWithRedirectStore.mjs.map\n","import { defaultStorage } from '@aws-amplify/core';\nimport { DefaultOAuthStore } from '../signInWithRedirectStore.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst oAuthStore = new DefaultOAuthStore(defaultStorage);\n\nexport { oAuthStore };\n//# sourceMappingURL=oAuthStore.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst inflightPromises = [];\nconst addInflightPromise = (resolver) => {\n inflightPromises.push(resolver);\n};\nconst resolveAndClearInflightPromises = () => {\n while (inflightPromises.length) {\n inflightPromises.pop()?.();\n }\n};\n\nexport { addInflightPromise, resolveAndClearInflightPromises };\n//# sourceMappingURL=inflightPromise.mjs.map\n","import { Hub } from '@aws-amplify/core';\nimport { isBrowser, assertTokenProviderConfig, isTokenExpired, AMPLIFY_SYMBOL, AmplifyErrorCode } from '@aws-amplify/core/internals/utils';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError.mjs';\nimport { AuthError } from '../../../errors/AuthError.mjs';\nimport { oAuthStore } from '../utils/oauth/oAuthStore.mjs';\nimport { addInflightPromise } from '../utils/oauth/inflightPromise.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass TokenOrchestrator {\n constructor() {\n this.waitForInflightOAuth = isBrowser()\n ? async () => {\n if (!(await oAuthStore.loadOAuthInFlight())) {\n return;\n }\n if (this.inflightPromise) {\n return this.inflightPromise;\n }\n // when there is valid oauth config and there is an inflight oauth flow, try\n // to block async calls that require fetching tokens before the oauth flow completes\n // e.g. getCurrentUser, fetchAuthSession etc.\n this.inflightPromise = new Promise((resolve, _reject) => {\n addInflightPromise(resolve);\n });\n return this.inflightPromise;\n }\n : async () => {\n // no-op for non-browser environments\n };\n }\n setAuthConfig(authConfig) {\n oAuthStore.setAuthConfig(authConfig.Cognito);\n this.authConfig = authConfig;\n }\n setTokenRefresher(tokenRefresher) {\n this.tokenRefresher = tokenRefresher;\n }\n setAuthTokenStore(tokenStore) {\n this.tokenStore = tokenStore;\n }\n getTokenStore() {\n if (!this.tokenStore) {\n throw new AuthError({\n name: 'EmptyTokenStoreException',\n message: 'TokenStore not set',\n });\n }\n return this.tokenStore;\n }\n getTokenRefresher() {\n if (!this.tokenRefresher) {\n throw new AuthError({\n name: 'EmptyTokenRefresherException',\n message: 'TokenRefresher not set',\n });\n }\n return this.tokenRefresher;\n }\n async getTokens(options) {\n let tokens;\n try {\n assertTokenProviderConfig(this.authConfig?.Cognito);\n }\n catch (_err) {\n // Token provider not configured\n return null;\n }\n await this.waitForInflightOAuth();\n this.inflightPromise = undefined;\n tokens = await this.getTokenStore().loadTokens();\n const username = await this.getTokenStore().getLastAuthUser();\n if (tokens === null) {\n return null;\n }\n const idTokenExpired = !!tokens?.idToken &&\n isTokenExpired({\n expiresAt: (tokens.idToken?.payload?.exp ?? 0) * 1000,\n clockDrift: tokens.clockDrift ?? 0,\n });\n const accessTokenExpired = isTokenExpired({\n expiresAt: (tokens.accessToken?.payload?.exp ?? 0) * 1000,\n clockDrift: tokens.clockDrift ?? 0,\n });\n if (options?.forceRefresh || idTokenExpired || accessTokenExpired) {\n tokens = await this.refreshTokens({\n tokens,\n username,\n });\n if (tokens === null) {\n return null;\n }\n }\n return {\n accessToken: tokens?.accessToken,\n idToken: tokens?.idToken,\n signInDetails: tokens?.signInDetails,\n };\n }\n async refreshTokens({ tokens, username, }) {\n try {\n const { signInDetails } = tokens;\n const newTokens = await this.getTokenRefresher()({\n tokens,\n authConfig: this.authConfig,\n username,\n });\n newTokens.signInDetails = signInDetails;\n await this.setTokens({ tokens: newTokens });\n Hub.dispatch('auth', { event: 'tokenRefresh' }, 'Auth', AMPLIFY_SYMBOL);\n return newTokens;\n }\n catch (err) {\n return this.handleErrors(err);\n }\n }\n handleErrors(err) {\n assertServiceError(err);\n if (err.name !== AmplifyErrorCode.NetworkError) {\n // TODO(v6): Check errors on client\n this.clearTokens();\n }\n Hub.dispatch('auth', {\n event: 'tokenRefresh_failure',\n data: { error: err },\n }, 'Auth', AMPLIFY_SYMBOL);\n if (err.name.startsWith('NotAuthorizedException')) {\n return null;\n }\n throw err;\n }\n async setTokens({ tokens }) {\n return this.getTokenStore().storeTokens(tokens);\n }\n async clearTokens() {\n return this.getTokenStore().clearTokens();\n }\n getDeviceMetadata(username) {\n return this.getTokenStore().getDeviceMetadata(username);\n }\n clearDeviceMetadata(username) {\n return this.getTokenStore().clearDeviceMetadata(username);\n }\n setOAuthMetadata(metadata) {\n return this.getTokenStore().setOAuthMetadata(metadata);\n }\n getOAuthMetadata() {\n return this.getTokenStore().getOAuthMetadata();\n }\n}\n\nexport { TokenOrchestrator };\n//# sourceMappingURL=TokenOrchestrator.mjs.map\n","import { defaultStorage } from '@aws-amplify/core';\nimport { refreshAuthTokens } from '../utils/refreshAuthTokens.mjs';\nimport { DefaultTokenStore } from './TokenStore.mjs';\nimport { TokenOrchestrator } from './TokenOrchestrator.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass CognitoUserPoolsTokenProvider {\n constructor() {\n this.authTokenStore = new DefaultTokenStore();\n this.authTokenStore.setKeyValueStorage(defaultStorage);\n this.tokenOrchestrator = new TokenOrchestrator();\n this.tokenOrchestrator.setAuthTokenStore(this.authTokenStore);\n this.tokenOrchestrator.setTokenRefresher(refreshAuthTokens);\n }\n getTokens({ forceRefresh } = { forceRefresh: false }) {\n return this.tokenOrchestrator.getTokens({ forceRefresh });\n }\n setKeyValueStorage(keyValueStorage) {\n this.authTokenStore.setKeyValueStorage(keyValueStorage);\n }\n setAuthConfig(authConfig) {\n this.authTokenStore.setAuthConfig(authConfig);\n this.tokenOrchestrator.setAuthConfig(authConfig);\n }\n}\n\nexport { CognitoUserPoolsTokenProvider };\n//# sourceMappingURL=CognitoUserPoolsTokenProvider.mjs.map\n","import { CognitoUserPoolsTokenProvider } from './CognitoUserPoolsTokenProvider.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * The default provider for the JWT access token and ID token issued from the configured Cognito user pool. It manages\n * the refresh and storage of the tokens. It stores the tokens in `window.localStorage` if available, and falls back to\n * in-memory storage if not.\n */\nconst cognitoUserPoolsTokenProvider = new CognitoUserPoolsTokenProvider();\nconst { tokenOrchestrator } = cognitoUserPoolsTokenProvider;\n\nexport { cognitoUserPoolsTokenProvider, tokenOrchestrator };\n//# sourceMappingURL=tokenProvider.mjs.map\n","import { decodeJWT, AmplifyError } from '@aws-amplify/core/internals/utils';\nimport { tokenOrchestrator } from './tokenProvider.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nasync function cacheCognitoTokens(AuthenticationResult) {\n if (AuthenticationResult.AccessToken) {\n const accessToken = decodeJWT(AuthenticationResult.AccessToken);\n const accessTokenIssuedAtInMillis = (accessToken.payload.iat || 0) * 1000;\n const currentTime = new Date().getTime();\n const clockDrift = accessTokenIssuedAtInMillis > 0\n ? accessTokenIssuedAtInMillis - currentTime\n : 0;\n let idToken;\n let refreshToken;\n let deviceMetadata;\n if (AuthenticationResult.RefreshToken) {\n refreshToken = AuthenticationResult.RefreshToken;\n }\n if (AuthenticationResult.IdToken) {\n idToken = decodeJWT(AuthenticationResult.IdToken);\n }\n if (AuthenticationResult?.NewDeviceMetadata) {\n deviceMetadata = AuthenticationResult.NewDeviceMetadata;\n }\n const tokens = {\n accessToken,\n idToken,\n refreshToken,\n clockDrift,\n deviceMetadata,\n username: AuthenticationResult.username,\n };\n if (AuthenticationResult?.signInDetails) {\n tokens.signInDetails = AuthenticationResult.signInDetails;\n }\n await tokenOrchestrator.setTokens({\n tokens,\n });\n }\n else {\n // This would be a service error\n throw new AmplifyError({\n message: 'Invalid tokens',\n name: 'InvalidTokens',\n recoverySuggestion: 'Check Cognito UserPool settings',\n });\n }\n}\n\nexport { cacheCognitoTokens };\n//# sourceMappingURL=cacheTokens.mjs.map\n","import { Hub } from '@aws-amplify/core';\nimport { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';\nimport { getCurrentUser } from '../apis/getCurrentUser.mjs';\nimport { USER_UNAUTHENTICATED_EXCEPTION, UNEXPECTED_SIGN_IN_INTERRUPTION_EXCEPTION } from '../../../errors/constants.mjs';\nimport { AuthError } from '../../../errors/AuthError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst ERROR_MESSAGE = 'Unable to get user session following successful sign-in.';\nconst dispatchSignedInHubEvent = async () => {\n try {\n Hub.dispatch('auth', {\n event: 'signedIn',\n data: await getCurrentUser(),\n }, 'Auth', AMPLIFY_SYMBOL);\n }\n catch (error) {\n if (error.name === USER_UNAUTHENTICATED_EXCEPTION) {\n throw new AuthError({\n name: UNEXPECTED_SIGN_IN_INTERRUPTION_EXCEPTION,\n message: ERROR_MESSAGE,\n recoverySuggestion: 'This most likely is due to auth tokens not being persisted. If you are using cookie store, please ensure cookies can be correctly set from your server.',\n });\n }\n throw error;\n }\n};\n\nexport { ERROR_MESSAGE, dispatchSignedInHubEvent };\n//# sourceMappingURL=dispatchSignedInHubEvent.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction defaultState() {\n return {\n active: false,\n };\n}\nconst autoSignInReducer = (state, action) => {\n switch (action.type) {\n case 'SET_USERNAME':\n return {\n ...state,\n username: action.value,\n };\n case 'SET_SESSION':\n return {\n ...state,\n session: action.value,\n };\n case 'START':\n return {\n ...state,\n active: true,\n };\n case 'RESET':\n return defaultState();\n default:\n return state;\n }\n};\nconst createAutoSignInStore = (reducer) => {\n let currentState = reducer(defaultState(), { type: 'RESET' });\n return {\n getState: () => currentState,\n dispatch: action => {\n currentState = reducer(currentState, action);\n },\n };\n};\nconst autoSignInStore = createAutoSignInStore(autoSignInReducer);\n\nexport { autoSignInStore };\n//# sourceMappingURL=autoSignInStore.mjs.map\n","import { syncSessionStorage } from '@aws-amplify/core';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// Minutes until stored session invalidates is defaulted to 3 minutes\n// to maintain parity with Amazon Cognito user pools API behavior\nconst MS_TO_EXPIRY = 3 * 60 * 1000;\nconst TGT_STATE = 'CognitoSignInState';\nconst SIGN_IN_STATE_KEYS = {\n username: `${TGT_STATE}.username`,\n challengeName: `${TGT_STATE}.challengeName`,\n signInSession: `${TGT_STATE}.signInSession`,\n expiry: `${TGT_STATE}.expiry`,\n};\nconst signInReducer = (state, action) => {\n switch (action.type) {\n case 'SET_SIGN_IN_SESSION':\n persistSignInState({ signInSession: action.value });\n return {\n ...state,\n signInSession: action.value,\n };\n case 'SET_SIGN_IN_STATE':\n persistSignInState(action.value);\n return {\n ...action.value,\n };\n case 'SET_CHALLENGE_NAME':\n persistSignInState({ challengeName: action.value });\n return {\n ...state,\n challengeName: action.value,\n };\n case 'SET_USERNAME':\n persistSignInState({ username: action.value });\n return {\n ...state,\n username: action.value,\n };\n case 'SET_INITIAL_STATE':\n return getInitialState();\n case 'RESET_STATE':\n clearPersistedSignInState();\n return getDefaultState();\n // this state is never reachable\n default:\n return state;\n }\n};\nconst isExpired = (expiryDate) => {\n const expiryTimestamp = Number(expiryDate);\n const currentTimestamp = Date.now();\n return expiryTimestamp <= currentTimestamp;\n};\nconst resetActiveSignInState = () => {\n signInStore.dispatch({ type: 'RESET_STATE' });\n};\nconst clearPersistedSignInState = () => {\n for (const stateKey of Object.values(SIGN_IN_STATE_KEYS)) {\n syncSessionStorage.removeItem(stateKey);\n }\n};\nconst getDefaultState = () => ({\n username: undefined,\n challengeName: undefined,\n signInSession: undefined,\n});\n// Hydrate signInStore from syncSessionStorage if the session has not expired\nconst getInitialState = () => {\n const expiry = syncSessionStorage.getItem(SIGN_IN_STATE_KEYS.expiry);\n if (!expiry || isExpired(expiry)) {\n clearPersistedSignInState();\n return getDefaultState();\n }\n const username = syncSessionStorage.getItem(SIGN_IN_STATE_KEYS.username) ?? undefined;\n const challengeName = (syncSessionStorage.getItem(SIGN_IN_STATE_KEYS.challengeName) ?? undefined);\n const signInSession = syncSessionStorage.getItem(SIGN_IN_STATE_KEYS.signInSession) ?? undefined;\n return {\n username,\n challengeName,\n signInSession,\n };\n};\nconst createStore = reducer => {\n let currentState = reducer(getDefaultState(), { type: 'SET_INITIAL_STATE' });\n return {\n getState: () => currentState,\n dispatch: action => {\n currentState = reducer(currentState, action);\n },\n };\n};\nconst signInStore = createStore(signInReducer);\nfunction setActiveSignInState(state) {\n signInStore.dispatch({\n type: 'SET_SIGN_IN_STATE',\n value: state,\n });\n}\n// Save local state into Session Storage\nconst persistSignInState = ({ challengeName, signInSession, username, }) => {\n username && syncSessionStorage.setItem(SIGN_IN_STATE_KEYS.username, username);\n challengeName &&\n syncSessionStorage.setItem(SIGN_IN_STATE_KEYS.challengeName, challengeName);\n if (signInSession) {\n syncSessionStorage.setItem(SIGN_IN_STATE_KEYS.signInSession, signInSession);\n // Updates expiry when session is passed\n syncSessionStorage.setItem(SIGN_IN_STATE_KEYS.expiry, String(Date.now() + MS_TO_EXPIRY));\n }\n};\n\nexport { persistSignInState, resetActiveSignInState, setActiveSignInState, signInStore };\n//# sourceMappingURL=signInStore.mjs.map\n","import { createAssertionFunction, AmplifyError, AmplifyErrorCode } from '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nclass PasskeyError extends AmplifyError {\n constructor(params) {\n super(params);\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n this.constructor = PasskeyError;\n Object.setPrototypeOf(this, PasskeyError.prototype);\n }\n}\nvar PasskeyErrorCode;\n(function (PasskeyErrorCode) {\n // not supported\n PasskeyErrorCode[\"PasskeyNotSupported\"] = \"PasskeyNotSupported\";\n // duplicate passkey\n PasskeyErrorCode[\"PasskeyAlreadyExists\"] = \"PasskeyAlreadyExists\";\n // misconfigurations\n PasskeyErrorCode[\"InvalidPasskeyRegistrationOptions\"] = \"InvalidPasskeyRegistrationOptions\";\n PasskeyErrorCode[\"InvalidPasskeyAuthenticationOptions\"] = \"InvalidPasskeyAuthenticationOptions\";\n PasskeyErrorCode[\"RelyingPartyMismatch\"] = \"RelyingPartyMismatch\";\n // failed credential creation / retrieval\n PasskeyErrorCode[\"PasskeyRegistrationFailed\"] = \"PasskeyRegistrationFailed\";\n PasskeyErrorCode[\"PasskeyRetrievalFailed\"] = \"PasskeyRetrievalFailed\";\n // cancel / aborts\n PasskeyErrorCode[\"PasskeyRegistrationCanceled\"] = \"PasskeyRegistrationCanceled\";\n PasskeyErrorCode[\"PasskeyAuthenticationCanceled\"] = \"PasskeyAuthenticationCanceled\";\n PasskeyErrorCode[\"PasskeyOperationAborted\"] = \"PasskeyOperationAborted\";\n})(PasskeyErrorCode || (PasskeyErrorCode = {}));\nconst notSupportedRecoverySuggestion = 'Passkeys may not be supported on this device. Ensure your application is running in a secure context (HTTPS) and Web Authentication API is supported.';\nconst abortOrCancelRecoverySuggestion = 'User may have canceled the ceremony or another interruption has occurred. Check underlying error for details.';\nconst misconfigurationRecoverySuggestion = 'Ensure your user pool is configured to support the WEB_AUTHN as an authentication factor.';\nconst passkeyErrorMap = {\n [PasskeyErrorCode.PasskeyNotSupported]: {\n message: 'Passkeys may not be supported on this device.',\n recoverySuggestion: notSupportedRecoverySuggestion,\n },\n [PasskeyErrorCode.InvalidPasskeyRegistrationOptions]: {\n message: 'Invalid passkey registration options.',\n recoverySuggestion: misconfigurationRecoverySuggestion,\n },\n [PasskeyErrorCode.InvalidPasskeyAuthenticationOptions]: {\n message: 'Invalid passkey authentication options.',\n recoverySuggestion: misconfigurationRecoverySuggestion,\n },\n [PasskeyErrorCode.PasskeyRegistrationFailed]: {\n message: 'Device failed to create passkey.',\n recoverySuggestion: notSupportedRecoverySuggestion,\n },\n [PasskeyErrorCode.PasskeyRetrievalFailed]: {\n message: 'Device failed to retrieve passkey.',\n recoverySuggestion: 'Passkeys may not be available on this device. Try an alternative authentication factor like PASSWORD, EMAIL_OTP, or SMS_OTP.',\n },\n [PasskeyErrorCode.PasskeyAlreadyExists]: {\n message: 'Passkey already exists in authenticator.',\n recoverySuggestion: 'Proceed with existing passkey or try again after deleting the credential.',\n },\n [PasskeyErrorCode.PasskeyRegistrationCanceled]: {\n message: 'Passkey registration ceremony has been canceled.',\n recoverySuggestion: abortOrCancelRecoverySuggestion,\n },\n [PasskeyErrorCode.PasskeyAuthenticationCanceled]: {\n message: 'Passkey authentication ceremony has been canceled.',\n recoverySuggestion: abortOrCancelRecoverySuggestion,\n },\n [PasskeyErrorCode.PasskeyOperationAborted]: {\n message: 'Passkey operation has been aborted.',\n recoverySuggestion: abortOrCancelRecoverySuggestion,\n },\n [PasskeyErrorCode.RelyingPartyMismatch]: {\n message: 'Relying party does not match current domain.',\n recoverySuggestion: 'Ensure relying party identifier matches current domain.',\n },\n};\nconst assertPasskeyError = createAssertionFunction(passkeyErrorMap, PasskeyError);\n/**\n * Handle Passkey Authentication Errors\n * https://w3c.github.io/webauthn/#sctn-get-request-exceptions\n *\n * @param err unknown\n * @returns PasskeyError\n */\nconst handlePasskeyAuthenticationError = (err) => {\n if (err instanceof PasskeyError) {\n return err;\n }\n if (err instanceof Error) {\n if (err.name === 'NotAllowedError') {\n const { message, recoverySuggestion } = passkeyErrorMap[PasskeyErrorCode.PasskeyAuthenticationCanceled];\n return new PasskeyError({\n name: PasskeyErrorCode.PasskeyAuthenticationCanceled,\n message,\n recoverySuggestion,\n underlyingError: err,\n });\n }\n }\n return handlePasskeyError(err);\n};\n/**\n * Handle Passkey Registration Errors\n * https://w3c.github.io/webauthn/#sctn-create-request-exceptions\n *\n * @param err unknown\n * @returns PasskeyError\n */\nconst handlePasskeyRegistrationError = (err) => {\n if (err instanceof PasskeyError) {\n return err;\n }\n if (err instanceof Error) {\n // Duplicate Passkey\n if (err.name === 'InvalidStateError') {\n const { message, recoverySuggestion } = passkeyErrorMap[PasskeyErrorCode.PasskeyAlreadyExists];\n return new PasskeyError({\n name: PasskeyErrorCode.PasskeyAlreadyExists,\n message,\n recoverySuggestion,\n underlyingError: err,\n });\n }\n // User Cancels Ceremony / Generic Catch All\n if (err.name === 'NotAllowedError') {\n const { message, recoverySuggestion } = passkeyErrorMap[PasskeyErrorCode.PasskeyRegistrationCanceled];\n return new PasskeyError({\n name: PasskeyErrorCode.PasskeyRegistrationCanceled,\n message,\n recoverySuggestion,\n underlyingError: err,\n });\n }\n }\n return handlePasskeyError(err);\n};\n/**\n * Handles Overlapping Passkey Errors Between Registration & Authentication\n * https://w3c.github.io/webauthn/#sctn-create-request-exceptions\n * https://w3c.github.io/webauthn/#sctn-get-request-exceptions\n *\n * @param err unknown\n * @returns PasskeyError\n */\nconst handlePasskeyError = (err) => {\n if (err instanceof Error) {\n // Passkey Operation Aborted\n if (err.name === 'AbortError') {\n const { message, recoverySuggestion } = passkeyErrorMap[PasskeyErrorCode.PasskeyOperationAborted];\n return new PasskeyError({\n name: PasskeyErrorCode.PasskeyOperationAborted,\n message,\n recoverySuggestion,\n underlyingError: err,\n });\n }\n // Relying Party / Domain Mismatch\n if (err.name === 'SecurityError') {\n const { message, recoverySuggestion } = passkeyErrorMap[PasskeyErrorCode.RelyingPartyMismatch];\n return new PasskeyError({\n name: PasskeyErrorCode.RelyingPartyMismatch,\n message,\n recoverySuggestion,\n underlyingError: err,\n });\n }\n }\n return new PasskeyError({\n name: AmplifyErrorCode.Unknown,\n message: 'An unknown error has occurred.',\n underlyingError: err,\n });\n};\n\nexport { PasskeyError, PasskeyErrorCode, assertPasskeyError, handlePasskeyAuthenticationError, handlePasskeyRegistrationError };\n//# sourceMappingURL=errors.mjs.map\n","import { isBrowser } from '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Determines if passkey is supported in current context\n * Will return false if executed in non-secure context\n * @returns boolean\n */\nconst getIsPasskeySupported = () => {\n return (isBrowser() &&\n window.isSecureContext &&\n 'credentials' in navigator &&\n typeof window.PublicKeyCredential === 'function');\n};\n\nexport { getIsPasskeySupported };\n//# sourceMappingURL=getIsPasskeySupported.mjs.map\n","import { base64Encoder } from '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// https://datatracker.ietf.org/doc/html/rfc4648#page-7\n/**\n * Converts an ArrayBuffer to a base64url encoded string\n * @param buffer - the ArrayBuffer instance of a Uint8Array\n * @returns string - a base64url encoded string\n */\nconst convertArrayBufferToBase64Url = (buffer) => {\n return base64Encoder.convert(new Uint8Array(buffer), {\n urlSafe: true,\n skipPadding: true,\n });\n};\n\nexport { convertArrayBufferToBase64Url };\n//# sourceMappingURL=convertArrayBufferToBase64Url.mjs.map\n","import { base64Decoder } from '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Converts a base64url encoded string to an ArrayBuffer\n * @param base64url - a base64url encoded string\n * @returns ArrayBuffer\n */\nconst convertBase64UrlToArrayBuffer = (base64url) => {\n return Uint8Array.from(base64Decoder.convert(base64url, { urlSafe: true }), x => x.charCodeAt(0)).buffer;\n};\n\nexport { convertBase64UrlToArrayBuffer };\n//# sourceMappingURL=convertBase64UrlToArrayBuffer.mjs.map\n","import { convertArrayBufferToBase64Url } from '../../../foundation/convert/base64url/convertArrayBufferToBase64Url.mjs';\nimport { convertBase64UrlToArrayBuffer } from '../../../foundation/convert/base64url/convertBase64UrlToArrayBuffer.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Deserializes Public Key Credential Creation Options JSON\n * @param input PasskeyCreateOptionsJson\n * @returns PublicKeyCredentialCreationOptions\n */\nconst deserializeJsonToPkcCreationOptions = (input) => {\n const userIdBuffer = convertBase64UrlToArrayBuffer(input.user.id);\n const challengeBuffer = convertBase64UrlToArrayBuffer(input.challenge);\n const excludeCredentialsWithBuffer = (input.excludeCredentials || []).map(excludeCred => ({\n ...excludeCred,\n id: convertBase64UrlToArrayBuffer(excludeCred.id),\n }));\n return {\n ...input,\n excludeCredentials: excludeCredentialsWithBuffer,\n challenge: challengeBuffer,\n user: {\n ...input.user,\n id: userIdBuffer,\n },\n };\n};\n/**\n * Serializes a Public Key Credential With Attestation to JSON\n * @param input PasskeyCreateResult\n * @returns PasskeyCreateResultJson\n */\nconst serializePkcWithAttestationToJson = (input) => {\n const response = {\n clientDataJSON: convertArrayBufferToBase64Url(input.response.clientDataJSON),\n attestationObject: convertArrayBufferToBase64Url(input.response.attestationObject),\n transports: input.response.getTransports(),\n publicKeyAlgorithm: input.response.getPublicKeyAlgorithm(),\n authenticatorData: convertArrayBufferToBase64Url(input.response.getAuthenticatorData()),\n };\n const publicKey = input.response.getPublicKey();\n if (publicKey) {\n response.publicKey = convertArrayBufferToBase64Url(publicKey);\n }\n const resultJson = {\n type: input.type,\n id: input.id,\n rawId: convertArrayBufferToBase64Url(input.rawId),\n clientExtensionResults: input.getClientExtensionResults(),\n response,\n };\n if (input.authenticatorAttachment) {\n resultJson.authenticatorAttachment = input.authenticatorAttachment;\n }\n return resultJson;\n};\n/**\n * Deserializes Public Key Credential Get Options JSON\n * @param input PasskeyGetOptionsJson\n * @returns PublicKeyCredentialRequestOptions\n */\nconst deserializeJsonToPkcGetOptions = (input) => {\n const challengeBuffer = convertBase64UrlToArrayBuffer(input.challenge);\n const allowedCredentialsWithBuffer = (input.allowCredentials || []).map(allowedCred => ({\n ...allowedCred,\n id: convertBase64UrlToArrayBuffer(allowedCred.id),\n }));\n return {\n ...input,\n challenge: challengeBuffer,\n allowCredentials: allowedCredentialsWithBuffer,\n };\n};\n/**\n * Serializes a Public Key Credential With Attestation to JSON\n * @param input PasskeyGetResult\n * @returns PasskeyGetResultJson\n */\nconst serializePkcWithAssertionToJson = (input) => {\n const response = {\n clientDataJSON: convertArrayBufferToBase64Url(input.response.clientDataJSON),\n authenticatorData: convertArrayBufferToBase64Url(input.response.authenticatorData),\n signature: convertArrayBufferToBase64Url(input.response.signature),\n };\n if (input.response.userHandle) {\n response.userHandle = convertArrayBufferToBase64Url(input.response.userHandle);\n }\n const resultJson = {\n id: input.id,\n rawId: convertArrayBufferToBase64Url(input.rawId),\n type: input.type,\n clientExtensionResults: input.getClientExtensionResults(),\n response,\n };\n if (input.authenticatorAttachment) {\n resultJson.authenticatorAttachment = input.authenticatorAttachment;\n }\n return resultJson;\n};\n\nexport { deserializeJsonToPkcCreationOptions, deserializeJsonToPkcGetOptions, serializePkcWithAssertionToJson, serializePkcWithAttestationToJson };\n//# sourceMappingURL=serde.mjs.map\n","import { assertPasskeyError, PasskeyErrorCode } from '../errors.mjs';\nexport { assertValidCredentialCreationOptions } from './shared.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction assertCredentialIsPkcWithAuthenticatorAttestationResponse(credential) {\n assertPasskeyError(credential &&\n credential instanceof PublicKeyCredential &&\n credential.response instanceof AuthenticatorAttestationResponse, PasskeyErrorCode.PasskeyRegistrationFailed);\n}\nfunction assertCredentialIsPkcWithAuthenticatorAssertionResponse(credential) {\n assertPasskeyError(credential &&\n credential instanceof PublicKeyCredential &&\n credential.response instanceof AuthenticatorAssertionResponse, PasskeyErrorCode.PasskeyRetrievalFailed);\n}\n\nexport { assertCredentialIsPkcWithAuthenticatorAssertionResponse, assertCredentialIsPkcWithAuthenticatorAttestationResponse };\n//# sourceMappingURL=index.mjs.map\n","import { assertPasskeyError, PasskeyErrorCode, handlePasskeyAuthenticationError } from './errors.mjs';\nimport { getIsPasskeySupported } from './getIsPasskeySupported.mjs';\nimport { deserializeJsonToPkcGetOptions, serializePkcWithAssertionToJson } from './serde.mjs';\nimport { assertCredentialIsPkcWithAuthenticatorAssertionResponse } from './types/index.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst getPasskey = async (input) => {\n try {\n const isPasskeySupported = getIsPasskeySupported();\n assertPasskeyError(isPasskeySupported, PasskeyErrorCode.PasskeyNotSupported);\n const passkeyGetOptions = deserializeJsonToPkcGetOptions(input);\n const credential = await navigator.credentials.get({\n publicKey: passkeyGetOptions,\n });\n assertCredentialIsPkcWithAuthenticatorAssertionResponse(credential);\n return serializePkcWithAssertionToJson(credential);\n }\n catch (err) {\n throw handlePasskeyAuthenticationError(err);\n }\n};\n\nexport { getPasskey };\n//# sourceMappingURL=getPasskey.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createConfirmDeviceClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ConfirmDevice'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createConfirmDeviceClient };\n//# sourceMappingURL=createConfirmDeviceClient.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst textEncoder = {\n convert(input) {\n return new TextEncoder().encode(input);\n },\n};\n\nexport { textEncoder };\n//# sourceMappingURL=index.mjs.map\n","/* eslint-disable */\n// @ts-nocheck -> BigInteger is already a vended utility\n// A small implementation of BigInteger based on http://www-cs-students.stanford.edu/~tjw/jsbn/\n//\n// All public methods have been removed except the following:\n// new BigInteger(a, b) (only radix 2, 4, 8, 16 and 32 supported)\n// toString (only radix 2, 4, 8, 16 and 32 supported)\n// negate\n// abs\n// compareTo\n// bitLength\n// mod\n// equals\n// add\n// subtract\n// multiply\n// divide\n// modPow\n/*\n * Copyright (c) 2003-2005 Tom Wu\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS-IS\" AND WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY\n * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.\n *\n * IN NO EVENT SHALL TOM WU BE LIABLE FOR ANY SPECIAL, INCIDENTAL,\n * INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER\n * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF\n * THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT\n * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\n * In addition, the following condition applies:\n *\n * All redistributions must retain an intact copy of this copyright notice\n * and disclaimer.\n */\n// (public) Constructor\nfunction BigInteger(a, b) {\n if (a != null)\n this.fromString(a, b);\n}\n// return new, unset BigInteger\nfunction nbi() {\n return new BigInteger(null, null);\n}\n// Bits per digit\nlet dbits;\n// JavaScript engine analysis\nconst canary = 0xdeadbeefcafe;\nconst j_lm = (canary & 0xffffff) === 0xefcafe;\n// am: Compute w_j += (x*this_i), propagate carries,\n// c is initial carry, returns final carry.\n// c < 3*dvalue, x < 2*dvalue, this_i < dvalue\n// We need to select the fastest one that works in this environment.\n// am1: use a single mult and divide to get the high bits,\n// max digit bits should be 26 because\n// max internal value = 2*dvalue^2-2*dvalue (< 2^53)\nfunction am1(i, x, w, j, c, n) {\n while (--n >= 0) {\n const v = x * this[i++] + w[j] + c;\n c = Math.floor(v / 0x4000000);\n w[j++] = v & 0x3ffffff;\n }\n return c;\n}\n// am2 avoids a big mult-and-extract completely.\n// Max digit bits should be <= 30 because we do bitwise ops\n// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)\nfunction am2(i, x, w, j, c, n) {\n const xl = x & 0x7fff;\n const xh = x >> 15;\n while (--n >= 0) {\n let l = this[i] & 0x7fff;\n const h = this[i++] >> 15;\n const m = xh * l + h * xl;\n l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff);\n c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30);\n w[j++] = l & 0x3fffffff;\n }\n return c;\n}\n// Alternately, set max digit bits to 28 since some\n// browsers slow down when dealing with 32-bit numbers.\nfunction am3(i, x, w, j, c, n) {\n const xl = x & 0x3fff;\n const xh = x >> 14;\n while (--n >= 0) {\n let l = this[i] & 0x3fff;\n const h = this[i++] >> 14;\n const m = xh * l + h * xl;\n l = xl * l + ((m & 0x3fff) << 14) + w[j] + c;\n c = (l >> 28) + (m >> 14) + xh * h;\n w[j++] = l & 0xfffffff;\n }\n return c;\n}\nconst inBrowser = typeof navigator !== 'undefined';\nif (inBrowser && j_lm && navigator.appName === 'Microsoft Internet Explorer') {\n BigInteger.prototype.am = am2;\n dbits = 30;\n}\nelse if (inBrowser && j_lm && navigator.appName !== 'Netscape') {\n BigInteger.prototype.am = am1;\n dbits = 26;\n}\nelse {\n // Mozilla/Netscape seems to prefer am3\n BigInteger.prototype.am = am3;\n dbits = 28;\n}\nBigInteger.prototype.DB = dbits;\nBigInteger.prototype.DM = (1 << dbits) - 1;\nBigInteger.prototype.DV = 1 << dbits;\nconst BI_FP = 52;\nBigInteger.prototype.FV = Math.pow(2, BI_FP);\nBigInteger.prototype.F1 = BI_FP - dbits;\nBigInteger.prototype.F2 = 2 * dbits - BI_FP;\n// Digit conversions\nconst BI_RM = '0123456789abcdefghijklmnopqrstuvwxyz';\nconst BI_RC = [];\nlet rr, vv;\nrr = '0'.charCodeAt(0);\nfor (vv = 0; vv <= 9; ++vv)\n BI_RC[rr++] = vv;\nrr = 'a'.charCodeAt(0);\nfor (vv = 10; vv < 36; ++vv)\n BI_RC[rr++] = vv;\nrr = 'A'.charCodeAt(0);\nfor (vv = 10; vv < 36; ++vv)\n BI_RC[rr++] = vv;\nfunction int2char(n) {\n return BI_RM.charAt(n);\n}\nfunction intAt(s, i) {\n const c = BI_RC[s.charCodeAt(i)];\n return c == null ? -1 : c;\n}\n// (protected) copy this to r\nfunction bnpCopyTo(r) {\n for (let i = this.t - 1; i >= 0; --i)\n r[i] = this[i];\n r.t = this.t;\n r.s = this.s;\n}\n// (protected) set from integer value x, -DV <= x < DV\nfunction bnpFromInt(x) {\n this.t = 1;\n this.s = x < 0 ? -1 : 0;\n if (x > 0)\n this[0] = x;\n else if (x < -1)\n this[0] = x + this.DV;\n else\n this.t = 0;\n}\n// return bigint initialized to value\nfunction nbv(i) {\n const r = nbi();\n r.fromInt(i);\n return r;\n}\n// (protected) set from string and radix\nfunction bnpFromString(s, b) {\n let k;\n if (b === 16)\n k = 4;\n else if (b === 8)\n k = 3;\n else if (b === 2)\n k = 1;\n else if (b === 32)\n k = 5;\n else if (b === 4)\n k = 2;\n else\n throw new Error('Only radix 2, 4, 8, 16, 32 are supported');\n this.t = 0;\n this.s = 0;\n let i = s.length;\n let mi = false;\n let sh = 0;\n while (--i >= 0) {\n const x = intAt(s, i);\n if (x < 0) {\n if (s.charAt(i) === '-')\n mi = true;\n continue;\n }\n mi = false;\n if (sh === 0)\n this[this.t++] = x;\n else if (sh + k > this.DB) {\n this[this.t - 1] |= (x & ((1 << (this.DB - sh)) - 1)) << sh;\n this[this.t++] = x >> (this.DB - sh);\n }\n else\n this[this.t - 1] |= x << sh;\n sh += k;\n if (sh >= this.DB)\n sh -= this.DB;\n }\n this.clamp();\n if (mi)\n BigInteger.ZERO.subTo(this, this);\n}\n// (protected) clamp off excess high words\nfunction bnpClamp() {\n const c = this.s & this.DM;\n while (this.t > 0 && this[this.t - 1] == c)\n --this.t;\n}\n// (public) return string representation in given radix\nfunction bnToString(b) {\n if (this.s < 0)\n return '-' + this.negate().toString(b);\n let k;\n if (b == 16)\n k = 4;\n else if (b === 8)\n k = 3;\n else if (b === 2)\n k = 1;\n else if (b === 32)\n k = 5;\n else if (b === 4)\n k = 2;\n else\n throw new Error('Only radix 2, 4, 8, 16, 32 are supported');\n const km = (1 << k) - 1;\n let d;\n let m = false;\n let r = '';\n let i = this.t;\n let p = this.DB - ((i * this.DB) % k);\n if (i-- > 0) {\n if (p < this.DB && (d = this[i] >> p) > 0) {\n m = true;\n r = int2char(d);\n }\n while (i >= 0) {\n if (p < k) {\n d = (this[i] & ((1 << p) - 1)) << (k - p);\n d |= this[--i] >> (p += this.DB - k);\n }\n else {\n d = (this[i] >> (p -= k)) & km;\n if (p <= 0) {\n p += this.DB;\n --i;\n }\n }\n if (d > 0)\n m = true;\n if (m)\n r += int2char(d);\n }\n }\n return m ? r : '0';\n}\n// (public) -this\nfunction bnNegate() {\n const r = nbi();\n BigInteger.ZERO.subTo(this, r);\n return r;\n}\n// (public) |this|\nfunction bnAbs() {\n return this.s < 0 ? this.negate() : this;\n}\n// (public) return + if this > a, - if this < a, 0 if equal\nfunction bnCompareTo(a) {\n let r = this.s - a.s;\n if (r != 0)\n return r;\n let i = this.t;\n r = i - a.t;\n if (r != 0)\n return this.s < 0 ? -r : r;\n while (--i >= 0)\n if ((r = this[i] - a[i]) != 0)\n return r;\n return 0;\n}\n// returns bit length of the integer x\nfunction nbits(x) {\n let r = 1;\n let t;\n if ((t = x >>> 16) !== 0) {\n x = t;\n r += 16;\n }\n if ((t = x >> 8) !== 0) {\n x = t;\n r += 8;\n }\n if ((t = x >> 4) !== 0) {\n x = t;\n r += 4;\n }\n if ((t = x >> 2) !== 0) {\n x = t;\n r += 2;\n }\n if ((t = x >> 1) !== 0) {\n x = t;\n r += 1;\n }\n return r;\n}\n// (public) return the number of bits in \"this\"\nfunction bnBitLength() {\n if (this.t <= 0)\n return 0;\n return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM));\n}\n// (protected) r = this << n*DB\nfunction bnpDLShiftTo(n, r) {\n let i;\n for (i = this.t - 1; i >= 0; --i)\n r[i + n] = this[i];\n for (i = n - 1; i >= 0; --i)\n r[i] = 0;\n r.t = this.t + n;\n r.s = this.s;\n}\n// (protected) r = this >> n*DB\nfunction bnpDRShiftTo(n, r) {\n for (let i = n; i < this.t; ++i)\n r[i - n] = this[i];\n r.t = Math.max(this.t - n, 0);\n r.s = this.s;\n}\n// (protected) r = this << n\nfunction bnpLShiftTo(n, r) {\n const bs = n % this.DB;\n const cbs = this.DB - bs;\n const bm = (1 << cbs) - 1;\n const ds = Math.floor(n / this.DB);\n let c = (this.s << bs) & this.DM;\n let i;\n for (i = this.t - 1; i >= 0; --i) {\n r[i + ds + 1] = (this[i] >> cbs) | c;\n c = (this[i] & bm) << bs;\n }\n for (i = ds - 1; i >= 0; --i)\n r[i] = 0;\n r[ds] = c;\n r.t = this.t + ds + 1;\n r.s = this.s;\n r.clamp();\n}\n// (protected) r = this >> n\nfunction bnpRShiftTo(n, r) {\n r.s = this.s;\n const ds = Math.floor(n / this.DB);\n if (ds >= this.t) {\n r.t = 0;\n return;\n }\n const bs = n % this.DB;\n const cbs = this.DB - bs;\n const bm = (1 << bs) - 1;\n r[0] = this[ds] >> bs;\n for (let i = ds + 1; i < this.t; ++i) {\n r[i - ds - 1] |= (this[i] & bm) << cbs;\n r[i - ds] = this[i] >> bs;\n }\n if (bs > 0)\n r[this.t - ds - 1] |= (this.s & bm) << cbs;\n r.t = this.t - ds;\n r.clamp();\n}\n// (protected) r = this - a\nfunction bnpSubTo(a, r) {\n let i = 0;\n let c = 0;\n const m = Math.min(a.t, this.t);\n while (i < m) {\n c += this[i] - a[i];\n r[i++] = c & this.DM;\n c >>= this.DB;\n }\n if (a.t < this.t) {\n c -= a.s;\n while (i < this.t) {\n c += this[i];\n r[i++] = c & this.DM;\n c >>= this.DB;\n }\n c += this.s;\n }\n else {\n c += this.s;\n while (i < a.t) {\n c -= a[i];\n r[i++] = c & this.DM;\n c >>= this.DB;\n }\n c -= a.s;\n }\n r.s = c < 0 ? -1 : 0;\n if (c < -1)\n r[i++] = this.DV + c;\n else if (c > 0)\n r[i++] = c;\n r.t = i;\n r.clamp();\n}\n// (protected) r = this * a, r != this,a (HAC 14.12)\n// \"this\" should be the larger one if appropriate.\nfunction bnpMultiplyTo(a, r) {\n const x = this.abs();\n const y = a.abs();\n let i = x.t;\n r.t = i + y.t;\n while (--i >= 0)\n r[i] = 0;\n for (i = 0; i < y.t; ++i)\n r[i + x.t] = x.am(0, y[i], r, i, 0, x.t);\n r.s = 0;\n r.clamp();\n if (this.s !== a.s)\n BigInteger.ZERO.subTo(r, r);\n}\n// (protected) r = this^2, r != this (HAC 14.16)\nfunction bnpSquareTo(r) {\n const x = this.abs();\n let i = (r.t = 2 * x.t);\n while (--i >= 0)\n r[i] = 0;\n for (i = 0; i < x.t - 1; ++i) {\n const c = x.am(i, x[i], r, 2 * i, 0, 1);\n if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >=\n x.DV) {\n r[i + x.t] -= x.DV;\n r[i + x.t + 1] = 1;\n }\n }\n if (r.t > 0)\n r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1);\n r.s = 0;\n r.clamp();\n}\n// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)\n// r != q, this != m. q or r may be null.\nfunction bnpDivRemTo(m, q, r) {\n const pm = m.abs();\n if (pm.t <= 0)\n return;\n const pt = this.abs();\n if (pt.t < pm.t) {\n if (q != null)\n q.fromInt(0);\n if (r != null)\n this.copyTo(r);\n return;\n }\n if (r === null)\n r = nbi();\n const y = nbi();\n const ts = this.s;\n const ms = m.s;\n const nsh = this.DB - nbits(pm[pm.t - 1]);\n // normalize modulus\n if (nsh > 0) {\n pm.lShiftTo(nsh, y);\n pt.lShiftTo(nsh, r);\n }\n else {\n pm.copyTo(y);\n pt.copyTo(r);\n }\n const ys = y.t;\n const y0 = y[ys - 1];\n if (y0 === 0)\n return;\n const yt = y0 * (1 << this.F1) + (ys > 1 ? y[ys - 2] >> this.F2 : 0);\n const d1 = this.FV / yt;\n const d2 = (1 << this.F1) / yt;\n const e = 1 << this.F2;\n let i = r.t;\n let j = i - ys;\n const t = q === null ? nbi() : q;\n y.dlShiftTo(j, t);\n if (r.compareTo(t) >= 0) {\n r[r.t++] = 1;\n r.subTo(t, r);\n }\n BigInteger.ONE.dlShiftTo(ys, t);\n t.subTo(y, y);\n // \"negative\" y so we can replace sub with am later\n while (y.t < ys)\n y[y.t++] = 0;\n while (--j >= 0) {\n // Estimate quotient digit\n let qd = r[--i] === y0 ? this.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2);\n if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) {\n // Try it out\n y.dlShiftTo(j, t);\n r.subTo(t, r);\n while (r[i] < --qd)\n r.subTo(t, r);\n }\n }\n if (q !== null) {\n r.drShiftTo(ys, q);\n if (ts !== ms)\n BigInteger.ZERO.subTo(q, q);\n }\n r.t = ys;\n r.clamp();\n if (nsh > 0)\n r.rShiftTo(nsh, r);\n // Denormalize remainder\n if (ts < 0)\n BigInteger.ZERO.subTo(r, r);\n}\n// (public) this mod a\nfunction bnMod(a) {\n const r = nbi();\n this.abs().divRemTo(a, null, r);\n if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0)\n a.subTo(r, r);\n return r;\n}\n// (protected) return \"-1/this % 2^DB\"; useful for Mont. reduction\n// justification:\n// xy == 1 (mod m)\n// xy = 1+km\n// xy(2-xy) = (1+km)(1-km)\n// x[y(2-xy)] = 1-k^2m^2\n// x[y(2-xy)] == 1 (mod m^2)\n// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2\n// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.\n// JS multiply \"overflows\" differently from C/C++, so care is needed here.\nfunction bnpInvDigit() {\n if (this.t < 1)\n return 0;\n const x = this[0];\n if ((x & 1) === 0)\n return 0;\n let y = x & 3;\n // y == 1/x mod 2^2\n y = (y * (2 - (x & 0xf) * y)) & 0xf;\n // y == 1/x mod 2^4\n y = (y * (2 - (x & 0xff) * y)) & 0xff;\n // y == 1/x mod 2^8\n y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff;\n // y == 1/x mod 2^16\n // last step - calculate inverse mod DV directly;\n // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints\n y = (y * (2 - ((x * y) % this.DV))) % this.DV;\n // y == 1/x mod 2^dbits\n // we really want the negative inverse, and -DV < y < DV\n return y > 0 ? this.DV - y : -y;\n}\nfunction bnEquals(a) {\n return this.compareTo(a) === 0;\n}\n// (protected) r = this + a\nfunction bnpAddTo(a, r) {\n let i = 0;\n let c = 0;\n const m = Math.min(a.t, this.t);\n while (i < m) {\n c += this[i] + a[i];\n r[i++] = c & this.DM;\n c >>= this.DB;\n }\n if (a.t < this.t) {\n c += a.s;\n while (i < this.t) {\n c += this[i];\n r[i++] = c & this.DM;\n c >>= this.DB;\n }\n c += this.s;\n }\n else {\n c += this.s;\n while (i < a.t) {\n c += a[i];\n r[i++] = c & this.DM;\n c >>= this.DB;\n }\n c += a.s;\n }\n r.s = c < 0 ? -1 : 0;\n if (c > 0)\n r[i++] = c;\n else if (c < -1)\n r[i++] = this.DV + c;\n r.t = i;\n r.clamp();\n}\n// (public) this + a\nfunction bnAdd(a) {\n const r = nbi();\n this.addTo(a, r);\n return r;\n}\n// (public) this - a\nfunction bnSubtract(a) {\n const r = nbi();\n this.subTo(a, r);\n return r;\n}\n// (public) this * a\nfunction bnMultiply(a) {\n const r = nbi();\n this.multiplyTo(a, r);\n return r;\n}\n// (public) this / a\nfunction bnDivide(a) {\n const r = nbi();\n this.divRemTo(a, r, null);\n return r;\n}\n// Montgomery reduction\nfunction Montgomery(m) {\n this.m = m;\n this.mp = m.invDigit();\n this.mpl = this.mp & 0x7fff;\n this.mph = this.mp >> 15;\n this.um = (1 << (m.DB - 15)) - 1;\n this.mt2 = 2 * m.t;\n}\n// xR mod m\nfunction montConvert(x) {\n const r = nbi();\n x.abs().dlShiftTo(this.m.t, r);\n r.divRemTo(this.m, null, r);\n if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0)\n this.m.subTo(r, r);\n return r;\n}\n// x/R mod m\nfunction montRevert(x) {\n const r = nbi();\n x.copyTo(r);\n this.reduce(r);\n return r;\n}\n// x = x/R mod m (HAC 14.32)\nfunction montReduce(x) {\n while (x.t <= this.mt2)\n // pad x so am has enough room later\n x[x.t++] = 0;\n for (let i = 0; i < this.m.t; ++i) {\n // faster way of calculating u0 = x[i]*mp mod DV\n let j = x[i] & 0x7fff;\n const u0 = (j * this.mpl +\n (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) &\n x.DM;\n // use am to combine the multiply-shift-add into one call\n j = i + this.m.t;\n x[j] += this.m.am(0, u0, x, i, 0, this.m.t);\n // propagate carry\n while (x[j] >= x.DV) {\n x[j] -= x.DV;\n x[++j]++;\n }\n }\n x.clamp();\n x.drShiftTo(this.m.t, x);\n if (x.compareTo(this.m) >= 0)\n x.subTo(this.m, x);\n}\n// r = \"x^2/R mod m\"; x != r\nfunction montSqrTo(x, r) {\n x.squareTo(r);\n this.reduce(r);\n}\n// r = \"xy/R mod m\"; x,y != r\nfunction montMulTo(x, y, r) {\n x.multiplyTo(y, r);\n this.reduce(r);\n}\nMontgomery.prototype.convert = montConvert;\nMontgomery.prototype.revert = montRevert;\nMontgomery.prototype.reduce = montReduce;\nMontgomery.prototype.mulTo = montMulTo;\nMontgomery.prototype.sqrTo = montSqrTo;\n// (public) this^e % m (HAC 14.85)\nfunction bnModPow(e, m, callback) {\n let i = e.bitLength();\n let k;\n let r = nbv(1);\n const z = new Montgomery(m);\n if (i <= 0)\n return r;\n else if (i < 18)\n k = 1;\n else if (i < 48)\n k = 3;\n else if (i < 144)\n k = 4;\n else if (i < 768)\n k = 5;\n else\n k = 6;\n // precomputation\n const g = [];\n let n = 3;\n const k1 = k - 1;\n const km = (1 << k) - 1;\n g[1] = z.convert(this);\n if (k > 1) {\n const g2 = nbi();\n z.sqrTo(g[1], g2);\n while (n <= km) {\n g[n] = nbi();\n z.mulTo(g2, g[n - 2], g[n]);\n n += 2;\n }\n }\n let j = e.t - 1;\n let w;\n let is1 = true;\n let r2 = nbi();\n let t;\n i = nbits(e[j]) - 1;\n while (j >= 0) {\n if (i >= k1)\n w = (e[j] >> (i - k1)) & km;\n else {\n w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i);\n if (j > 0)\n w |= e[j - 1] >> (this.DB + i - k1);\n }\n n = k;\n while ((w & 1) === 0) {\n w >>= 1;\n --n;\n }\n if ((i -= n) < 0) {\n i += this.DB;\n --j;\n }\n if (is1) {\n // ret == 1, don't bother squaring or multiplying it\n g[w].copyTo(r);\n is1 = false;\n }\n else {\n while (n > 1) {\n z.sqrTo(r, r2);\n z.sqrTo(r2, r);\n n -= 2;\n }\n if (n > 0)\n z.sqrTo(r, r2);\n else {\n t = r;\n r = r2;\n r2 = t;\n }\n z.mulTo(r2, g[w], r);\n }\n while (j >= 0 && (e[j] & (1 << i)) === 0) {\n z.sqrTo(r, r2);\n t = r;\n r = r2;\n r2 = t;\n if (--i < 0) {\n i = this.DB - 1;\n --j;\n }\n }\n }\n const result = z.revert(r);\n callback(null, result);\n return result;\n}\n// protected\nBigInteger.prototype.copyTo = bnpCopyTo;\nBigInteger.prototype.fromInt = bnpFromInt;\nBigInteger.prototype.fromString = bnpFromString;\nBigInteger.prototype.clamp = bnpClamp;\nBigInteger.prototype.dlShiftTo = bnpDLShiftTo;\nBigInteger.prototype.drShiftTo = bnpDRShiftTo;\nBigInteger.prototype.lShiftTo = bnpLShiftTo;\nBigInteger.prototype.rShiftTo = bnpRShiftTo;\nBigInteger.prototype.subTo = bnpSubTo;\nBigInteger.prototype.multiplyTo = bnpMultiplyTo;\nBigInteger.prototype.squareTo = bnpSquareTo;\nBigInteger.prototype.divRemTo = bnpDivRemTo;\nBigInteger.prototype.invDigit = bnpInvDigit;\nBigInteger.prototype.addTo = bnpAddTo;\n// public\nBigInteger.prototype.toString = bnToString;\nBigInteger.prototype.negate = bnNegate;\nBigInteger.prototype.abs = bnAbs;\nBigInteger.prototype.compareTo = bnCompareTo;\nBigInteger.prototype.bitLength = bnBitLength;\nBigInteger.prototype.mod = bnMod;\nBigInteger.prototype.equals = bnEquals;\nBigInteger.prototype.add = bnAdd;\nBigInteger.prototype.subtract = bnSubtract;\nBigInteger.prototype.multiply = bnMultiply;\nBigInteger.prototype.divide = bnDivide;\nBigInteger.prototype.modPow = bnModPow;\n// \"constants\"\nBigInteger.ZERO = nbv(0);\nBigInteger.ONE = nbv(1);\n\nexport { BigInteger as default };\n//# sourceMappingURL=BigInteger.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @internal\n */\nconst calculateS = async ({ a, g, k, x, B, N, U, }) => {\n return new Promise((resolve, reject) => {\n g.modPow(x, N, (outerErr, outerResult) => {\n if (outerErr) {\n reject(outerErr);\n return;\n }\n B.subtract(k.multiply(outerResult)).modPow(a.add(U.multiply(x)), N, (innerErr, innerResult) => {\n if (innerErr) {\n reject(innerErr);\n return;\n }\n resolve(innerResult.mod(N));\n });\n });\n });\n};\n\nexport { calculateS };\n//# sourceMappingURL=calculateS.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst INIT_N = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1' +\n '29024E088A67CC74020BBEA63B139B22514A08798E3404DD' +\n 'EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245' +\n 'E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' +\n 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D' +\n 'C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F' +\n '83655D23DCA3AD961C62F356208552BB9ED529077096966D' +\n '670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' +\n 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9' +\n 'DE2BCBF6955817183995497CEA956AE515D2261898FA0510' +\n '15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64' +\n 'ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7' +\n 'ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B' +\n 'F12FFA06D98A0864D87602733EC86A64521F2B18177B200C' +\n 'BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31' +\n '43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF';\nconst SHORT_TO_HEX = {};\nconst HEX_TO_SHORT = {};\nfor (let i = 0; i < 256; i++) {\n let encodedByte = i.toString(16).toLowerCase();\n if (encodedByte.length === 1) {\n encodedByte = `0${encodedByte}`;\n }\n SHORT_TO_HEX[i] = encodedByte;\n HEX_TO_SHORT[encodedByte] = i;\n}\n\nexport { HEX_TO_SHORT, INIT_N, SHORT_TO_HEX };\n//# sourceMappingURL=constants.mjs.map\n","import { HEX_TO_SHORT } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Converts a hexadecimal encoded string to a Uint8Array of bytes.\n *\n * @param encoded The hexadecimal encoded string\n */\nconst getBytesFromHex = (encoded) => {\n if (encoded.length % 2 !== 0) {\n throw new Error('Hex encoded strings must have an even number length');\n }\n const out = new Uint8Array(encoded.length / 2);\n for (let i = 0; i < encoded.length; i += 2) {\n const encodedByte = encoded.slice(i, i + 2).toLowerCase();\n if (encodedByte in HEX_TO_SHORT) {\n out[i / 2] = HEX_TO_SHORT[encodedByte];\n }\n else {\n throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);\n }\n }\n return out;\n};\n\nexport { getBytesFromHex };\n//# sourceMappingURL=getBytesFromHex.mjs.map\n","import { SHORT_TO_HEX } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Converts a Uint8Array of binary data to a hexadecimal encoded string.\n *\n * @param bytes The binary data to encode\n */\nconst getHexFromBytes = (bytes) => {\n let out = '';\n for (let i = 0; i < bytes.byteLength; i++) {\n out += SHORT_TO_HEX[bytes[i]];\n }\n return out;\n};\n\nexport { getHexFromBytes };\n//# sourceMappingURL=getHexFromBytes.mjs.map\n","import { Sha256 } from '@aws-crypto/sha256-js';\nimport { getHexFromBytes } from './getHexFromBytes.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Calculate a hash from a `SourceData`\n * @param {SourceData} data Value to hash.\n * @returns {string} Hex-encoded hash.\n * @private\n */\nconst getHashFromData = (data) => {\n const sha256 = new Sha256();\n sha256.update(data);\n const hashedData = sha256.digestSync();\n const hashHexFromUint8 = getHexFromBytes(hashedData);\n return new Array(64 - hashHexFromUint8.length).join('0') + hashHexFromUint8;\n};\n\nexport { getHashFromData };\n//# sourceMappingURL=getHashFromData.mjs.map\n","import { getBytesFromHex } from './getBytesFromHex.mjs';\nimport { getHashFromData } from './getHashFromData.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Calculate a hash from a hex string\n * @param {string} hexStr Value to hash.\n * @returns {string} Hex-encoded hash.\n * @private\n */\nconst getHashFromHex = (hexStr) => getHashFromData(getBytesFromHex(hexStr));\n\nexport { getHashFromHex };\n//# sourceMappingURL=getHashFromHex.mjs.map\n","import BigInteger from './BigInteger/BigInteger.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Tests if a hex string has it most significant bit set (case-insensitive regex)\n */\nconst HEX_MSB_REGEX = /^[89a-f]/i;\n/**\n * Returns an unambiguous, even-length hex string of the two's complement encoding of an integer.\n *\n * It is compatible with the hex encoding of Java's BigInteger's toByteArray(), wich returns a\n * byte array containing the two's-complement representation of a BigInteger. The array contains\n * the minimum number of bytes required to represent the BigInteger, including at least one sign bit.\n *\n * Examples showing how ambiguity is avoided by left padding with:\n * \t\"00\" (for positive values where the most-significant-bit is set)\n * \"FF\" (for negative values where the most-significant-bit is set)\n *\n * padHex(bigInteger.fromInt(-236)) === \"FF14\"\n * padHex(bigInteger.fromInt(20)) === \"14\"\n *\n * padHex(bigInteger.fromInt(-200)) === \"FF38\"\n * padHex(bigInteger.fromInt(56)) === \"38\"\n *\n * padHex(bigInteger.fromInt(-20)) === \"EC\"\n * padHex(bigInteger.fromInt(236)) === \"00EC\"\n *\n * padHex(bigInteger.fromInt(-56)) === \"C8\"\n * padHex(bigInteger.fromInt(200)) === \"00C8\"\n *\n * @param {AuthBigInteger} bigInt Number to encode.\n * @returns {String} even-length hex string of the two's complement encoding.\n */\nconst getPaddedHex = (bigInt) => {\n if (!(bigInt instanceof BigInteger)) {\n throw new Error('Not a BigInteger');\n }\n const isNegative = bigInt.compareTo(BigInteger.ZERO) < 0;\n /* Get a hex string for abs(bigInt) */\n let hexStr = bigInt.abs().toString(16);\n /* Pad hex to even length if needed */\n hexStr = hexStr.length % 2 !== 0 ? `0${hexStr}` : hexStr;\n /* Prepend \"00\" if the most significant bit is set */\n hexStr = HEX_MSB_REGEX.test(hexStr) ? `00${hexStr}` : hexStr;\n if (isNegative) {\n /* Flip the bits of the representation */\n const invertedNibbles = hexStr\n .split('')\n .map((x) => {\n const invertedNibble = ~parseInt(x, 16) & 0xf;\n return '0123456789ABCDEF'.charAt(invertedNibble);\n })\n .join('');\n /* After flipping the bits, add one to get the 2's complement representation */\n const flippedBitsBI = new BigInteger(invertedNibbles, 16).add(BigInteger.ONE);\n hexStr = flippedBitsBI.toString(16);\n /*\n For hex strings starting with 'FF8', 'FF' can be dropped, e.g. 0xFFFF80=0xFF80=0x80=-128\n\n Any sequence of '1' bits on the left can always be substituted with a single '1' bit\n without changing the represented value.\n\n This only happens in the case when the input is 80...00\n */\n if (hexStr.toUpperCase().startsWith('FF8')) {\n hexStr = hexStr.substring(2);\n }\n }\n return hexStr;\n};\n\nexport { getPaddedHex };\n//# sourceMappingURL=getPaddedHex.mjs.map\n","import BigInteger from '../BigInteger/BigInteger.mjs';\nimport { getHashFromHex } from '../getHashFromHex.mjs';\nimport { getPaddedHex } from '../getPaddedHex.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @internal\n */\nconst calculateU = ({ A, B, }) => {\n const U = new BigInteger(getHashFromHex(getPaddedHex(A) + getPaddedHex(B)), 16);\n if (U.equals(BigInteger.ZERO)) {\n throw new Error('U cannot be zero.');\n }\n return U;\n};\n\nexport { calculateU };\n//# sourceMappingURL=calculateU.mjs.map\n","import { Sha256 } from '@aws-crypto/sha256-js';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Standard HKDF algorithm.\n *\n * @param {Uint8Array} ikm Input key material.\n * @param {Uint8Array} salt Salt value.\n * @param {Uint8Array} info Context and application specific info.\n *\n * @returns {Uint8Array} Strong key material.\n *\n * @internal\n */\nconst getHkdfKey = (ikm, salt, info) => {\n const awsCryptoHash = new Sha256(salt);\n awsCryptoHash.update(ikm);\n const resultFromAWSCryptoPrk = awsCryptoHash.digestSync();\n const awsCryptoHashHmac = new Sha256(resultFromAWSCryptoPrk);\n awsCryptoHashHmac.update(info);\n const resultFromAWSCryptoHmac = awsCryptoHashHmac.digestSync();\n const hashHexFromAWSCrypto = resultFromAWSCryptoHmac;\n return hashHexFromAWSCrypto.slice(0, 16);\n};\n\nexport { getHkdfKey };\n//# sourceMappingURL=getHkdfKey.mjs.map\n","import { WordArray } from '@aws-amplify/core/internals/utils';\nimport { getBytesFromHex } from './getBytesFromHex.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a Uint8Array with a sequence of random nBytes\n *\n * @param {number} nBytes\n * @returns {Uint8Array} fixed-length sequence of random bytes\n */\nconst getRandomBytes = (nBytes) => {\n const str = new WordArray().random(nBytes).toString();\n return getBytesFromHex(str);\n};\n\nexport { getRandomBytes };\n//# sourceMappingURL=getRandomBytes.mjs.map\n","import { base64Encoder } from '@aws-amplify/core/internals/utils';\nimport { getRandomBytes } from './getRandomBytes.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Helper function to generate a random string\n * @returns {string} a random value.\n *\n * @internal\n */\nconst getRandomString = () => base64Encoder.convert(getRandomBytes(40));\n\nexport { getRandomString };\n//# sourceMappingURL=getRandomString.mjs.map\n","import { AuthError } from '../../../../../errors/AuthError.mjs';\nimport { textEncoder } from '../../textEncoder/index.mjs';\nimport BigInteger from '../BigInteger/BigInteger.mjs';\nimport { calculateS } from '../calculate/calculateS.mjs';\nimport { calculateU } from '../calculate/calculateU.mjs';\nimport { getBytesFromHex } from '../getBytesFromHex.mjs';\nimport { getHashFromData } from '../getHashFromData.mjs';\nimport { getHashFromHex } from '../getHashFromHex.mjs';\nimport { getHexFromBytes } from '../getHexFromBytes.mjs';\nimport { getHkdfKey } from '../getHkdfKey.mjs';\nimport { getPaddedHex } from '../getPaddedHex.mjs';\nimport { getRandomBytes } from '../getRandomBytes.mjs';\nimport { getRandomString } from '../getRandomString.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/** @class */\nclass AuthenticationHelper {\n constructor({ userPoolName, a, g, A, N, }) {\n this.encoder = textEncoder;\n this.userPoolName = userPoolName;\n this.a = a;\n this.g = g;\n this.A = A;\n this.N = N;\n this.k = new BigInteger(getHashFromHex(`${getPaddedHex(N)}${getPaddedHex(g)}`), 16);\n }\n /**\n * @returns {string} Generated random value included in password hash.\n */\n getRandomPassword() {\n if (!this.randomPassword) {\n throw new AuthError({\n name: 'EmptyBigIntegerRandomPassword',\n message: 'random password is empty',\n });\n }\n return this.randomPassword;\n }\n /**\n * @returns {string} Generated random value included in devices hash.\n */\n getSaltToHashDevices() {\n if (!this.saltToHashDevices) {\n throw new AuthError({\n name: 'EmptyBigIntegersaltToHashDevices',\n message: 'saltToHashDevices is empty',\n });\n }\n return this.saltToHashDevices;\n }\n /**\n * @returns {string} Value used to verify devices.\n */\n getVerifierDevices() {\n if (!this.verifierDevices) {\n throw new AuthError({\n name: 'EmptyBigIntegerVerifierDevices',\n message: 'verifyDevices is empty',\n });\n }\n return this.verifierDevices;\n }\n /**\n * Generate salts and compute verifier.\n *\n * @param {string} deviceGroupKey Devices to generate verifier for.\n * @param {string} username User to generate verifier for.\n *\n * @returns {Promise}\n */\n async generateHashDevice(deviceGroupKey, username) {\n this.randomPassword = getRandomString();\n const combinedString = `${deviceGroupKey}${username}:${this.randomPassword}`;\n const hashedString = getHashFromData(combinedString);\n const hexRandom = getHexFromBytes(getRandomBytes(16));\n // The random hex will be unambiguously represented as a postive integer\n this.saltToHashDevices = getPaddedHex(new BigInteger(hexRandom, 16));\n return new Promise((resolve, reject) => {\n this.g.modPow(new BigInteger(getHashFromHex(this.saltToHashDevices + hashedString), 16), this.N, (err, result) => {\n if (err) {\n reject(err);\n return;\n }\n this.verifierDevices = getPaddedHex(result);\n resolve();\n });\n });\n }\n /**\n * Calculates the final HKDF key based on computed S value, computed U value and the key\n *\n * @param {String} username Username.\n * @param {String} password Password.\n * @param {AuthBigInteger} B Server B value.\n * @param {AuthBigInteger} salt Generated salt.\n */\n async getPasswordAuthenticationKey({ username, password, serverBValue, salt, }) {\n if (serverBValue.mod(this.N).equals(BigInteger.ZERO)) {\n throw new Error('B cannot be zero.');\n }\n const U = calculateU({\n A: this.A,\n B: serverBValue,\n });\n const usernamePassword = `${this.userPoolName}${username}:${password}`;\n const usernamePasswordHash = getHashFromData(usernamePassword);\n const x = new BigInteger(getHashFromHex(getPaddedHex(salt) + usernamePasswordHash), 16);\n const S = await calculateS({\n a: this.a,\n g: this.g,\n k: this.k,\n x,\n B: serverBValue,\n N: this.N,\n U,\n });\n const context = this.encoder.convert('Caldera Derived Key');\n const spacer = this.encoder.convert(String.fromCharCode(1));\n const info = new Uint8Array(context.byteLength + spacer.byteLength);\n info.set(context, 0);\n info.set(spacer, context.byteLength);\n const hkdfKey = getHkdfKey(getBytesFromHex(getPaddedHex(S)), getBytesFromHex(getPaddedHex(U)), info);\n return hkdfKey;\n }\n}\n\nexport { AuthenticationHelper as default };\n//# sourceMappingURL=AuthenticationHelper.mjs.map\n","import BigInteger from '../BigInteger/BigInteger.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * @internal\n */\nconst calculateA = async ({ a, g, N, }) => {\n return new Promise((resolve, reject) => {\n g.modPow(a, N, (err, A) => {\n if (err) {\n reject(err);\n return;\n }\n if (A.mod(N).equals(BigInteger.ZERO)) {\n reject(new Error('Illegal parameter. A mod N cannot be 0.'));\n return;\n }\n resolve(A);\n });\n });\n};\n\nexport { calculateA };\n//# sourceMappingURL=calculateA.mjs.map\n","import AuthenticationHelper from './AuthenticationHelper/AuthenticationHelper.mjs';\nimport BigInteger from './BigInteger/BigInteger.mjs';\nimport { calculateA } from './calculate/calculateA.mjs';\nimport { INIT_N } from './constants.mjs';\nimport '@aws-crypto/sha256-js';\nimport { getHexFromBytes } from './getHexFromBytes.mjs';\nimport { getRandomBytes } from './getRandomBytes.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Returns a new {@link AuthenticationHelper} instance with randomly generated BigInteger seed\n *\n * @param userPoolName Cognito user pool name.\n * @returns An {@link AuthenticationHelper} instance.\n *\n * @internal\n */\nconst getAuthenticationHelper = async (userPoolName) => {\n const N = new BigInteger(INIT_N, 16);\n const g = new BigInteger('2', 16);\n const a = generateRandomBigInteger();\n const A = await calculateA({ a, g, N });\n return new AuthenticationHelper({ userPoolName, a, g, A, N });\n};\n/**\n * Generates a random BigInteger.\n *\n * @returns {BigInteger} a random value.\n */\nconst generateRandomBigInteger = () => {\n // This will be interpreted as a postive 128-bit integer\n const hexRandom = getHexFromBytes(getRandomBytes(128));\n // There is no need to do randomBigInt.mod(this.N - 1) as N (3072-bit) is > 128 bytes (1024-bit)\n return new BigInteger(hexRandom, 16);\n};\n\nexport { getAuthenticationHelper };\n//# sourceMappingURL=getAuthenticationHelper.mjs.map\n","import { base64Encoder, getDeviceName } from '@aws-amplify/core/internals/utils';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../../../errors/types/validation.mjs';\nimport '../types/errors.mjs';\nimport { createConfirmDeviceClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmDeviceClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { getAuthenticationHelper } from './srp/getAuthenticationHelper.mjs';\nimport { getBytesFromHex } from './srp/getBytesFromHex.mjs';\nimport '@aws-crypto/sha256-js';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * This function is used to kick off the device management flow.\n *\n * If an error is thrown while generating a hash device or calling the `ConfirmDevice`\n * client, then this API will ignore the error and return undefined. Otherwise the authentication\n * flow will not complete and the user won't be able to be signed in.\n *\n * @returns DeviceMetadata | undefined\n */\nasync function getNewDeviceMetadata({ userPoolId, userPoolEndpoint, newDeviceMetadata, accessToken, }) {\n if (!newDeviceMetadata)\n return undefined;\n const userPoolName = userPoolId.split('_')[1] || '';\n const authenticationHelper = await getAuthenticationHelper(userPoolName);\n const deviceKey = newDeviceMetadata?.DeviceKey;\n const deviceGroupKey = newDeviceMetadata?.DeviceGroupKey;\n try {\n await authenticationHelper.generateHashDevice(deviceGroupKey ?? '', deviceKey ?? '');\n }\n catch (errGenHash) {\n // TODO: log error here\n return undefined;\n }\n const deviceSecretVerifierConfig = {\n Salt: base64Encoder.convert(getBytesFromHex(authenticationHelper.getSaltToHashDevices())),\n PasswordVerifier: base64Encoder.convert(getBytesFromHex(authenticationHelper.getVerifierDevices())),\n };\n const randomPassword = authenticationHelper.getRandomPassword();\n try {\n const confirmDevice = createConfirmDeviceClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await confirmDevice({ region: getRegionFromUserPoolId(userPoolId) }, {\n AccessToken: accessToken,\n DeviceName: await getDeviceName(),\n DeviceKey: newDeviceMetadata?.DeviceKey,\n DeviceSecretVerifierConfig: deviceSecretVerifierConfig,\n });\n return {\n deviceKey,\n deviceGroupKey,\n randomPassword,\n };\n }\n catch (error) {\n // TODO: log error here\n return undefined;\n }\n}\n\nexport { getNewDeviceMetadata };\n//# sourceMappingURL=getNewDeviceMetadata.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils';\nimport { AuthErrorCodes } from '../../../common/AuthErrorStrings.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport { AuthError } from '../../../errors/AuthError.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../errors/types/validation.mjs';\nimport '../../../providers/cognito/types/errors.mjs';\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../../../providers/cognito/factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { cacheCognitoTokens } from '../../../providers/cognito/tokenProvider/cacheTokens.mjs';\nimport { dispatchSignedInHubEvent } from '../../../providers/cognito/utils/dispatchSignedInHubEvent.mjs';\nimport '../../utils/store/autoSignInStore.mjs';\nimport { signInStore, setActiveSignInState } from '../../utils/store/signInStore.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport { assertPasskeyError, PasskeyErrorCode } from '../../utils/passkey/errors.mjs';\nimport { getPasskey } from '../../utils/passkey/getPasskey.mjs';\nimport { getNewDeviceMetadata } from '../../../providers/cognito/utils/getNewDeviceMetadata.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nasync function handleWebAuthnSignInResult(challengeParameters) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { username, signInSession, signInDetails, challengeName } = signInStore.getState();\n if (challengeName !== 'WEB_AUTHN' || !username) {\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: 'Unable to proceed due to invalid sign in state.',\n });\n }\n const { CREDENTIAL_REQUEST_OPTIONS: credentialRequestOptions } = challengeParameters;\n assertPasskeyError(!!credentialRequestOptions, PasskeyErrorCode.InvalidPasskeyAuthenticationOptions);\n const cred = await getPasskey(JSON.parse(credentialRequestOptions));\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: authConfig.userPoolEndpoint,\n }),\n });\n const { ChallengeName: nextChallengeName, ChallengeParameters: nextChallengeParameters, AuthenticationResult: authenticationResult, Session: nextSession, } = await respondToAuthChallenge({\n region: getRegionFromUserPoolId(authConfig.userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, {\n ChallengeName: 'WEB_AUTHN',\n ChallengeResponses: {\n USERNAME: username,\n CREDENTIAL: JSON.stringify(cred),\n },\n ClientId: authConfig.userPoolClientId,\n Session: signInSession,\n });\n setActiveSignInState({\n signInSession: nextSession,\n username,\n challengeName: nextChallengeName,\n signInDetails,\n });\n if (authenticationResult) {\n await cacheCognitoTokens({\n ...authenticationResult,\n username,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: authenticationResult.NewDeviceMetadata,\n accessToken: authenticationResult.AccessToken,\n }),\n signInDetails,\n });\n signInStore.dispatch({ type: 'RESET_STATE' });\n await dispatchSignedInHubEvent();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n if (nextChallengeName === 'WEB_AUTHN') {\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: 'Sequential WEB_AUTHN challenges returned from underlying service cannot be handled.',\n });\n }\n return {\n challengeName: nextChallengeName,\n challengeParameters: nextChallengeParameters,\n };\n}\n\nexport { handleWebAuthnSignInResult };\n//# sourceMappingURL=handleWebAuthnSignInResult.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst MONTH_NAMES = [\n 'Jan',\n 'Feb',\n 'Mar',\n 'Apr',\n 'May',\n 'Jun',\n 'Jul',\n 'Aug',\n 'Sep',\n 'Oct',\n 'Nov',\n 'Dec',\n];\nconst WEEK_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];\nconst getNowString = () => {\n const now = new Date();\n const weekDay = WEEK_NAMES[now.getUTCDay()];\n const month = MONTH_NAMES[now.getUTCMonth()];\n const day = now.getUTCDate();\n let hours = now.getUTCHours();\n if (hours < 10) {\n hours = `0${hours}`;\n }\n let minutes = now.getUTCMinutes();\n if (minutes < 10) {\n minutes = `0${minutes}`;\n }\n let seconds = now.getUTCSeconds();\n if (seconds < 10) {\n seconds = `0${seconds}`;\n }\n const year = now.getUTCFullYear();\n // ddd MMM D HH:mm:ss UTC YYYY\n const dateNow = `${weekDay} ${month} ${day} ${hours}:${minutes}:${seconds} UTC ${year}`;\n return dateNow;\n};\n\nexport { getNowString };\n//# sourceMappingURL=getNowString.mjs.map\n","import { Sha256 } from '@aws-crypto/sha256-js';\nimport { base64Encoder, base64Decoder } from '@aws-amplify/core/internals/utils';\nimport { textEncoder } from '../textEncoder/index.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst getSignatureString = ({ userPoolName, username, challengeParameters, dateNow, hkdf, }) => {\n const bufUPIDaToB = textEncoder.convert(userPoolName);\n const bufUNaToB = textEncoder.convert(username);\n const bufSBaToB = urlB64ToUint8Array(challengeParameters.SECRET_BLOCK);\n const bufDNaToB = textEncoder.convert(dateNow);\n const bufConcat = new Uint8Array(bufUPIDaToB.byteLength +\n bufUNaToB.byteLength +\n bufSBaToB.byteLength +\n bufDNaToB.byteLength);\n bufConcat.set(bufUPIDaToB, 0);\n bufConcat.set(bufUNaToB, bufUPIDaToB.byteLength);\n bufConcat.set(bufSBaToB, bufUPIDaToB.byteLength + bufUNaToB.byteLength);\n bufConcat.set(bufDNaToB, bufUPIDaToB.byteLength + bufUNaToB.byteLength + bufSBaToB.byteLength);\n const awsCryptoHash = new Sha256(hkdf);\n awsCryptoHash.update(bufConcat);\n const resultFromAWSCrypto = awsCryptoHash.digestSync();\n const signatureString = base64Encoder.convert(resultFromAWSCrypto);\n return signatureString;\n};\nconst urlB64ToUint8Array = (base64String) => {\n const padding = '='.repeat((4 - (base64String.length % 4)) % 4);\n const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');\n const rawData = base64Decoder.convert(base64);\n const outputArray = new Uint8Array(rawData.length);\n for (let i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i);\n }\n return outputArray;\n};\n\nexport { getSignatureString };\n//# sourceMappingURL=getSignatureString.mjs.map\n","import '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../../../errors/types/validation.mjs';\nimport '../types/errors.mjs';\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { assertDeviceMetadata } from './types.mjs';\nimport { getAuthenticationHelper } from './srp/getAuthenticationHelper.mjs';\nimport './srp/constants.mjs';\nimport { getNowString } from './srp/getNowString.mjs';\nimport { getSignatureString } from './srp/getSignatureString.mjs';\nimport BigInteger from './srp/BigInteger/BigInteger.mjs';\nimport { getUserContextData } from './userContextData.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nasync function handleDeviceSRPAuth({ username, config, clientMetadata, session, tokenOrchestrator, }) {\n const { userPoolId, userPoolEndpoint } = config;\n const clientId = config.userPoolClientId;\n const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username);\n assertDeviceMetadata(deviceMetadata);\n const authenticationHelper = await getAuthenticationHelper(deviceMetadata.deviceGroupKey);\n const challengeResponses = {\n USERNAME: username,\n SRP_A: authenticationHelper.A.toString(16),\n DEVICE_KEY: deviceMetadata.deviceKey,\n };\n const jsonReqResponseChallenge = {\n ChallengeName: 'DEVICE_SRP_AUTH',\n ClientId: clientId,\n ChallengeResponses: challengeResponses,\n ClientMetadata: clientMetadata,\n Session: session,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { ChallengeParameters: respondedChallengeParameters, Session } = await respondToAuthChallenge({ region: getRegionFromUserPoolId(userPoolId) }, jsonReqResponseChallenge);\n return handleDevicePasswordVerifier(username, respondedChallengeParameters, clientMetadata, Session, authenticationHelper, config, tokenOrchestrator);\n}\nasync function handleDevicePasswordVerifier(username, challengeParameters, clientMetadata, session, authenticationHelper, { userPoolId, userPoolClientId, userPoolEndpoint }, tokenOrchestrator) {\n const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username);\n assertDeviceMetadata(deviceMetadata);\n const serverBValue = new BigInteger(challengeParameters?.SRP_B, 16);\n const salt = new BigInteger(challengeParameters?.SALT, 16);\n const { deviceKey } = deviceMetadata;\n const { deviceGroupKey } = deviceMetadata;\n const hkdf = await authenticationHelper.getPasswordAuthenticationKey({\n username: deviceMetadata.deviceKey,\n password: deviceMetadata.randomPassword,\n serverBValue,\n salt,\n });\n const dateNow = getNowString();\n const challengeResponses = {\n USERNAME: challengeParameters?.USERNAME ?? username,\n PASSWORD_CLAIM_SECRET_BLOCK: challengeParameters?.SECRET_BLOCK,\n TIMESTAMP: dateNow,\n PASSWORD_CLAIM_SIGNATURE: getSignatureString({\n username: deviceKey,\n userPoolName: deviceGroupKey,\n challengeParameters,\n dateNow,\n hkdf,\n }),\n DEVICE_KEY: deviceKey,\n };\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReqResponseChallenge = {\n ChallengeName: 'DEVICE_PASSWORD_VERIFIER',\n ClientId: userPoolClientId,\n ChallengeResponses: challengeResponses,\n Session: session,\n ClientMetadata: clientMetadata,\n UserContextData,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({ region: getRegionFromUserPoolId(userPoolId) }, jsonReqResponseChallenge);\n}\n\nexport { handleDeviceSRPAuth };\n//# sourceMappingURL=handleDeviceSRPAuth.mjs.map\n","import { AuthError } from '../../../errors/AuthError.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../../../errors/types/validation.mjs';\nimport '../types/errors.mjs';\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport BigInteger from './srp/BigInteger/BigInteger.mjs';\nimport './srp/constants.mjs';\nimport '@aws-crypto/sha256-js';\nimport { getNowString } from './srp/getNowString.mjs';\nimport { getSignatureString } from './srp/getSignatureString.mjs';\nimport { getUserContextData } from './userContextData.mjs';\nimport { handleDeviceSRPAuth } from './handleDeviceSRPAuth.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nasync function handlePasswordVerifierChallenge(password, challengeParameters, clientMetadata, session, authenticationHelper, config, tokenOrchestrator) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const userPoolName = userPoolId?.split('_')[1] || '';\n const serverBValue = new BigInteger(challengeParameters?.SRP_B, 16);\n const salt = new BigInteger(challengeParameters?.SALT, 16);\n const username = challengeParameters?.USER_ID_FOR_SRP;\n if (!username)\n throw new AuthError({\n name: 'EmptyUserIdForSRPException',\n message: 'USER_ID_FOR_SRP was not found in challengeParameters',\n });\n const hkdf = await authenticationHelper.getPasswordAuthenticationKey({\n username,\n password,\n serverBValue,\n salt,\n });\n const dateNow = getNowString();\n const challengeResponses = {\n USERNAME: username,\n PASSWORD_CLAIM_SECRET_BLOCK: challengeParameters?.SECRET_BLOCK,\n TIMESTAMP: dateNow,\n PASSWORD_CLAIM_SIGNATURE: getSignatureString({\n username,\n userPoolName,\n challengeParameters,\n dateNow,\n hkdf,\n }),\n };\n const deviceMetadata = await tokenOrchestrator.getDeviceMetadata(username);\n if (deviceMetadata && deviceMetadata.deviceKey) {\n challengeResponses.DEVICE_KEY = deviceMetadata.deviceKey;\n }\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReqResponseChallenge = {\n ChallengeName: 'PASSWORD_VERIFIER',\n ChallengeResponses: challengeResponses,\n ClientMetadata: clientMetadata,\n Session: session,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await respondToAuthChallenge({ region: getRegionFromUserPoolId(userPoolId) }, jsonReqResponseChallenge);\n if (response.ChallengeName === 'DEVICE_SRP_AUTH')\n return handleDeviceSRPAuth({\n username,\n config,\n clientMetadata,\n session: response.Session,\n tokenOrchestrator,\n });\n return response;\n}\n\nexport { handlePasswordVerifierChallenge };\n//# sourceMappingURL=handlePasswordVerifierChallenge.mjs.map\n","import { AuthError } from '../../../errors/AuthError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * It will retry the function if the error is a `ResourceNotFoundException` and\n * will clean the device keys stored in the storage mechanism.\n *\n */\nasync function retryOnResourceNotFoundException(func, args, username, tokenOrchestrator) {\n try {\n return await func(...args);\n }\n catch (error) {\n if (error instanceof AuthError &&\n error.name === 'ResourceNotFoundException' &&\n error.message.includes('Device does not exist.')) {\n await tokenOrchestrator.clearDeviceMetadata(username);\n return func(...args);\n }\n throw error;\n }\n}\n\nexport { retryOnResourceNotFoundException };\n//# sourceMappingURL=retryOnResourceNotFoundException.mjs.map\n","import '../../../client/utils/store/autoSignInStore.mjs';\nimport { signInStore } from '../../../client/utils/store/signInStore.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction setActiveSignInUsername(username) {\n const { dispatch } = signInStore;\n dispatch({ type: 'SET_USERNAME', value: username });\n}\n\nexport { setActiveSignInUsername };\n//# sourceMappingURL=setActiveSignInUsername.mjs.map\n","import { AuthAction } from '@aws-amplify/core/internals/utils';\nimport { getUserContextData } from '../../../providers/cognito/utils/userContextData.mjs';\nimport { getAuthenticationHelper } from '../../../providers/cognito/utils/srp/getAuthenticationHelper.mjs';\nimport '../../../providers/cognito/utils/srp/constants.mjs';\nimport '@aws-crypto/sha256-js';\nimport { createInitiateAuthClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../../../errors/types/validation.mjs';\nimport '../../../providers/cognito/types/errors.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../../../providers/cognito/factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport { handlePasswordVerifierChallenge } from '../../../providers/cognito/utils/handlePasswordVerifierChallenge.mjs';\nimport { retryOnResourceNotFoundException } from '../../../providers/cognito/utils/retryOnResourceNotFoundException.mjs';\nimport { setActiveSignInUsername } from '../../../providers/cognito/utils/setActiveSignInUsername.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Handles the Password SRP (Secure Remote Password) authentication flow.\n * This function can be used with both USER_SRP_AUTH and USER_AUTH flows.\n *\n * @param {Object} params - The parameters for the Password SRP authentication\n * @param {string} params.username - The username for authentication\n * @param {string} params.password - The user's password\n * @param {ClientMetadata} [params.clientMetadata] - Optional metadata to be sent with auth requests\n * @param {CognitoUserPoolConfig} params.config - Cognito User Pool configuration\n * @param {AuthTokenOrchestrator} params.tokenOrchestrator - Token orchestrator for managing auth tokens\n * @param {AuthFlowType} params.authFlow - The type of authentication flow ('USER_SRP_AUTH' or 'USER_AUTH')\n * @param {AuthFactorType} [params.preferredChallenge] - Optional preferred challenge type when using USER_AUTH flow\n *\n * @returns {Promise} The authentication response\n */\nasync function handlePasswordSRP({ username, password, clientMetadata, config, tokenOrchestrator, authFlow, preferredChallenge, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const userPoolName = userPoolId?.split('_')[1] || '';\n const authenticationHelper = await getAuthenticationHelper(userPoolName);\n const authParameters = {\n USERNAME: username,\n SRP_A: authenticationHelper.A.toString(16),\n };\n if (authFlow === 'USER_AUTH' && preferredChallenge) {\n authParameters.PREFERRED_CHALLENGE = preferredChallenge;\n }\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n AuthFlow: authFlow,\n AuthParameters: authParameters,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const initiateAuth = createInitiateAuthClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const resp = await initiateAuth({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignIn),\n }, jsonReq);\n const { ChallengeParameters: challengeParameters, Session: session } = resp;\n const activeUsername = challengeParameters?.USERNAME ?? username;\n setActiveSignInUsername(activeUsername);\n if (resp.ChallengeName === 'PASSWORD_VERIFIER') {\n return retryOnResourceNotFoundException(handlePasswordVerifierChallenge, [\n password,\n challengeParameters,\n clientMetadata,\n session,\n authenticationHelper,\n config,\n tokenOrchestrator,\n ], activeUsername, tokenOrchestrator);\n }\n return resp;\n}\n\nexport { handlePasswordSRP };\n//# sourceMappingURL=handlePasswordSRP.mjs.map\n","import { AuthAction } from '@aws-amplify/core/internals/utils';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../../../errors/types/validation.mjs';\nimport '../../../providers/cognito/types/errors.mjs';\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../../../providers/cognito/factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Handles the SELECT_CHALLENGE response for authentication.\n * Initiates the selected authentication challenge based on user choice.\n *\n * @param {Object} params - The parameters for handling the selected challenge\n * @param {string} params.username - The username for authentication\n * @param {string} params.session - The current authentication session token\n * @param {string} params.selectedChallenge - The challenge type selected by the user\n * @param {CognitoUserPoolConfig} params.config - Cognito User Pool configuration\n * @param {ClientMetadata} [params.clientMetadata] - Optional metadata to be sent with auth requests\n *\n * @returns {Promise} The challenge response\n */\nasync function initiateSelectedChallenge({ username, session, selectedChallenge, config, clientMetadata, }) {\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: config.userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({\n region: getRegionFromUserPoolId(config.userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, {\n ChallengeName: 'SELECT_CHALLENGE',\n ChallengeResponses: {\n USERNAME: username,\n ANSWER: selectedChallenge,\n },\n ClientId: config.userPoolClientId,\n Session: session,\n ClientMetadata: clientMetadata,\n });\n}\n\nexport { initiateSelectedChallenge };\n//# sourceMappingURL=handleSelectChallenge.mjs.map\n","import { AuthAction } from '@aws-amplify/core/internals/utils';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../../../errors/types/validation.mjs';\nimport '../../../providers/cognito/types/errors.mjs';\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../../../providers/cognito/factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport { getUserContextData } from '../../../providers/cognito/utils/userContextData.mjs';\nimport { setActiveSignInUsername } from '../../../providers/cognito/utils/setActiveSignInUsername.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Handles the SELECT_CHALLENGE response specifically for Password authentication.\n * This function combines the SELECT_CHALLENGE flow with standard password authentication.\n *\n * @param {string} username - The username for authentication\n * @param {string} password - The user's password\n * @param {ClientMetadata} [clientMetadata] - Optional metadata to be sent with auth requests\n * @param {CognitoUserPoolConfig} config - Cognito User Pool configuration\n * @param {string} session - The current authentication session token\n *\n * @returns {Promise} The challenge response\n */\nasync function handleSelectChallengeWithPassword(username, password, clientMetadata, config, session) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const authParameters = {\n ANSWER: 'PASSWORD',\n USERNAME: username,\n PASSWORD: password,\n };\n const userContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, {\n ChallengeName: 'SELECT_CHALLENGE',\n ChallengeResponses: authParameters,\n ClientId: userPoolClientId,\n ClientMetadata: clientMetadata,\n Session: session,\n UserContextData: userContextData,\n });\n const activeUsername = response.ChallengeParameters?.USERNAME ?? username;\n setActiveSignInUsername(activeUsername);\n return response;\n}\n\nexport { handleSelectChallengeWithPassword };\n//# sourceMappingURL=handleSelectChallengeWithPassword.mjs.map\n","import { AuthAction } from '@aws-amplify/core/internals/utils';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../../../errors/types/validation.mjs';\nimport '../../../providers/cognito/types/errors.mjs';\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../../../providers/cognito/factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport { getAuthenticationHelper } from '../../../providers/cognito/utils/srp/getAuthenticationHelper.mjs';\nimport '../../../providers/cognito/utils/srp/constants.mjs';\nimport '@aws-crypto/sha256-js';\nimport { getUserContextData } from '../../../providers/cognito/utils/userContextData.mjs';\nimport { setActiveSignInUsername } from '../../../providers/cognito/utils/setActiveSignInUsername.mjs';\nimport { retryOnResourceNotFoundException } from '../../../providers/cognito/utils/retryOnResourceNotFoundException.mjs';\nimport { handlePasswordVerifierChallenge } from '../../../providers/cognito/utils/handlePasswordVerifierChallenge.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Handles the SELECT_CHALLENGE response specifically for Password SRP authentication.\n * This function combines the SELECT_CHALLENGE flow with Password SRP protocol.\n *\n * @param {string} username - The username for authentication\n * @param {string} password - The user's password\n * @param {ClientMetadata} [clientMetadata] - Optional metadata to be sent with auth requests\n * @param {CognitoUserPoolConfig} config - Cognito User Pool configuration\n * @param {string} session - The current authentication session token\n * @param {AuthTokenOrchestrator} tokenOrchestrator - Token orchestrator for managing auth tokens\n *\n * @returns {Promise} The challenge response\n */\nasync function handleSelectChallengeWithPasswordSRP(username, password, clientMetadata, config, session, tokenOrchestrator) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const userPoolName = userPoolId.split('_')[1] || '';\n const authenticationHelper = await getAuthenticationHelper(userPoolName);\n const authParameters = {\n ANSWER: 'PASSWORD_SRP',\n USERNAME: username,\n SRP_A: authenticationHelper.A.toString(16),\n };\n const userContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, {\n ChallengeName: 'SELECT_CHALLENGE',\n ChallengeResponses: authParameters,\n ClientId: userPoolClientId,\n ClientMetadata: clientMetadata,\n Session: session,\n UserContextData: userContextData,\n });\n const activeUsername = response.ChallengeParameters?.USERNAME ?? username;\n setActiveSignInUsername(activeUsername);\n if (response.ChallengeName === 'PASSWORD_VERIFIER') {\n return retryOnResourceNotFoundException(handlePasswordVerifierChallenge, [\n password,\n response.ChallengeParameters,\n clientMetadata,\n response.Session,\n authenticationHelper,\n config,\n tokenOrchestrator,\n ], activeUsername, tokenOrchestrator);\n }\n return response;\n}\n\nexport { handleSelectChallengeWithPasswordSRP };\n//# sourceMappingURL=handleSelectChallengeWithPasswordSRP.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { AuthAction, assertTokenProviderConfig, AmplifyUrl } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError.mjs';\nimport { InitiateAuthException } from '../types/errors.mjs';\nimport { AuthErrorCodes } from '../../../common/AuthErrorStrings.mjs';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { USER_ALREADY_AUTHENTICATED_EXCEPTION } from '../../../errors/constants.mjs';\nimport { getCurrentUser } from '../apis/getCurrentUser.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport { createInitiateAuthClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport { createRespondToAuthChallengeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createRespondToAuthChallengeClient.mjs';\nimport { createVerifySoftwareTokenClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createVerifySoftwareTokenClient.mjs';\nimport { createAssociateSoftwareTokenClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createAssociateSoftwareTokenClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { handleWebAuthnSignInResult } from '../../../client/flows/userAuth/handleWebAuthnSignInResult.mjs';\nimport { handlePasswordSRP } from '../../../client/flows/shared/handlePasswordSRP.mjs';\nimport { initiateSelectedChallenge } from '../../../client/flows/userAuth/handleSelectChallenge.mjs';\nimport { handleSelectChallengeWithPassword } from '../../../client/flows/userAuth/handleSelectChallengeWithPassword.mjs';\nimport { handleSelectChallengeWithPasswordSRP } from '../../../client/flows/userAuth/handleSelectChallengeWithPasswordSRP.mjs';\nimport '../../../client/utils/store/autoSignInStore.mjs';\nimport { signInStore } from '../../../client/utils/store/signInStore.mjs';\nimport { getAuthenticationHelper } from './srp/getAuthenticationHelper.mjs';\nimport './srp/constants.mjs';\nimport '@aws-crypto/sha256-js';\nimport { getUserContextData } from './userContextData.mjs';\nimport { handlePasswordVerifierChallenge } from './handlePasswordVerifierChallenge.mjs';\nimport { handleDeviceSRPAuth } from './handleDeviceSRPAuth.mjs';\nimport { retryOnResourceNotFoundException } from './retryOnResourceNotFoundException.mjs';\nimport { setActiveSignInUsername } from './setActiveSignInUsername.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst USER_ATTRIBUTES = 'userAttributes.';\nfunction isWebAuthnResultAuthSignInOutput(result) {\n return 'isSignedIn' in result && 'nextStep' in result;\n}\nasync function handleCustomChallenge({ challengeResponse, clientMetadata, session, username, config, tokenOrchestrator, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const challengeResponses = {\n USERNAME: username,\n ANSWER: challengeResponse,\n };\n const deviceMetadata = await tokenOrchestrator?.getDeviceMetadata(username);\n if (deviceMetadata && deviceMetadata.deviceKey) {\n challengeResponses.DEVICE_KEY = deviceMetadata.deviceKey;\n }\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n ChallengeName: 'CUSTOM_CHALLENGE',\n ChallengeResponses: challengeResponses,\n Session: session,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, jsonReq);\n if (response.ChallengeName === 'DEVICE_SRP_AUTH') {\n return handleDeviceSRPAuth({\n username,\n config,\n clientMetadata,\n session: response.Session,\n tokenOrchestrator,\n });\n }\n return response;\n}\nasync function handleMFASetupChallenge({ challengeResponse, username, clientMetadata, session, deviceName, config, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n if (challengeResponse === 'EMAIL') {\n return {\n ChallengeName: 'MFA_SETUP',\n Session: session,\n ChallengeParameters: {\n MFAS_CAN_SETUP: '[\"EMAIL_OTP\"]',\n },\n $metadata: {},\n };\n }\n if (challengeResponse === 'TOTP') {\n return {\n ChallengeName: 'MFA_SETUP',\n Session: session,\n ChallengeParameters: {\n MFAS_CAN_SETUP: '[\"SOFTWARE_TOKEN_MFA\"]',\n },\n $metadata: {},\n };\n }\n const challengeResponses = {\n USERNAME: username,\n };\n const isTOTPCode = /^\\d+$/.test(challengeResponse);\n if (isTOTPCode) {\n const verifySoftwareToken = createVerifySoftwareTokenClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { Session } = await verifySoftwareToken({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, {\n UserCode: challengeResponse,\n Session: session,\n FriendlyDeviceName: deviceName,\n });\n signInStore.dispatch({\n type: 'SET_SIGN_IN_SESSION',\n value: Session,\n });\n const jsonReq = {\n ChallengeName: 'MFA_SETUP',\n ChallengeResponses: challengeResponses,\n Session,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, jsonReq);\n }\n const isEmail = challengeResponse.includes('@');\n if (isEmail) {\n challengeResponses.EMAIL = challengeResponse;\n const jsonReq = {\n ChallengeName: 'MFA_SETUP',\n ChallengeResponses: challengeResponses,\n Session: session,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, jsonReq);\n }\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: `Cannot proceed with MFA setup using challengeResponse: ${challengeResponse}`,\n recoverySuggestion: 'Try passing \"EMAIL\", \"TOTP\", a valid email, or OTP code as the challengeResponse.',\n });\n}\nasync function handleSelectMFATypeChallenge({ challengeResponse, username, clientMetadata, session, config, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n assertValidationError(challengeResponse === 'TOTP' ||\n challengeResponse === 'SMS' ||\n challengeResponse === 'EMAIL', AuthValidationErrorCode.IncorrectMFAMethod);\n const challengeResponses = {\n USERNAME: username,\n ANSWER: mapMfaType(challengeResponse),\n };\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n ChallengeName: 'SELECT_MFA_TYPE',\n ChallengeResponses: challengeResponses,\n Session: session,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, jsonReq);\n}\nasync function handleCompleteNewPasswordChallenge({ challengeResponse, clientMetadata, session, username, requiredAttributes, config, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const challengeResponses = {\n ...createAttributes(requiredAttributes),\n NEW_PASSWORD: challengeResponse,\n USERNAME: username,\n };\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n ChallengeName: 'NEW_PASSWORD_REQUIRED',\n ChallengeResponses: challengeResponses,\n ClientMetadata: clientMetadata,\n Session: session,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, jsonReq);\n}\nasync function handleUserPasswordAuthFlow(username, password, clientMetadata, config, tokenOrchestrator) {\n const { userPoolClientId, userPoolId, userPoolEndpoint } = config;\n const authParameters = {\n USERNAME: username,\n PASSWORD: password,\n };\n const deviceMetadata = await tokenOrchestrator.getDeviceMetadata(username);\n if (deviceMetadata && deviceMetadata.deviceKey) {\n authParameters.DEVICE_KEY = deviceMetadata.deviceKey;\n }\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n AuthFlow: 'USER_PASSWORD_AUTH',\n AuthParameters: authParameters,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const initiateAuth = createInitiateAuthClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await initiateAuth({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignIn),\n }, jsonReq);\n const activeUsername = response.ChallengeParameters?.USERNAME ??\n response.ChallengeParameters?.USER_ID_FOR_SRP ??\n username;\n setActiveSignInUsername(activeUsername);\n if (response.ChallengeName === 'DEVICE_SRP_AUTH')\n return handleDeviceSRPAuth({\n username: activeUsername,\n config,\n clientMetadata,\n session: response.Session,\n tokenOrchestrator,\n });\n return response;\n}\nasync function handleUserSRPAuthFlow(username, password, clientMetadata, config, tokenOrchestrator) {\n return handlePasswordSRP({\n username,\n password,\n clientMetadata,\n config,\n tokenOrchestrator,\n authFlow: 'USER_SRP_AUTH',\n });\n}\nasync function handleCustomAuthFlowWithoutSRP(username, clientMetadata, config, tokenOrchestrator) {\n const { userPoolClientId, userPoolId, userPoolEndpoint } = config;\n const authParameters = {\n USERNAME: username,\n };\n const deviceMetadata = await tokenOrchestrator.getDeviceMetadata(username);\n if (deviceMetadata && deviceMetadata.deviceKey) {\n authParameters.DEVICE_KEY = deviceMetadata.deviceKey;\n }\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n AuthFlow: 'CUSTOM_AUTH',\n AuthParameters: authParameters,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const initiateAuth = createInitiateAuthClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await initiateAuth({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignIn),\n }, jsonReq);\n const activeUsername = response.ChallengeParameters?.USERNAME ?? username;\n setActiveSignInUsername(activeUsername);\n if (response.ChallengeName === 'DEVICE_SRP_AUTH')\n return handleDeviceSRPAuth({\n username: activeUsername,\n config,\n clientMetadata,\n session: response.Session,\n tokenOrchestrator,\n });\n return response;\n}\nasync function handleCustomSRPAuthFlow(username, password, clientMetadata, config, tokenOrchestrator) {\n assertTokenProviderConfig(config);\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const userPoolName = userPoolId?.split('_')[1] || '';\n const authenticationHelper = await getAuthenticationHelper(userPoolName);\n const authParameters = {\n USERNAME: username,\n SRP_A: authenticationHelper.A.toString(16),\n CHALLENGE_NAME: 'SRP_A',\n };\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n AuthFlow: 'CUSTOM_AUTH',\n AuthParameters: authParameters,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n const initiateAuth = createInitiateAuthClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { ChallengeParameters: challengeParameters, Session: session } = await initiateAuth({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignIn),\n }, jsonReq);\n const activeUsername = challengeParameters?.USERNAME ?? username;\n setActiveSignInUsername(activeUsername);\n return retryOnResourceNotFoundException(handlePasswordVerifierChallenge, [\n password,\n challengeParameters,\n clientMetadata,\n session,\n authenticationHelper,\n config,\n tokenOrchestrator,\n ], activeUsername, tokenOrchestrator);\n}\nasync function getSignInResult(params) {\n const { challengeName, challengeParameters, availableChallenges } = params;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n switch (challengeName) {\n case 'CUSTOM_CHALLENGE':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONFIRM_SIGN_IN_WITH_CUSTOM_CHALLENGE',\n additionalInfo: challengeParameters,\n },\n };\n case 'MFA_SETUP': {\n const { signInSession, username } = signInStore.getState();\n const mfaSetupTypes = getMFATypes(parseMFATypes(challengeParameters.MFAS_CAN_SETUP)) || [];\n const allowedMfaSetupTypes = getAllowedMfaSetupTypes(mfaSetupTypes);\n const isTotpMfaSetupAvailable = allowedMfaSetupTypes.includes('TOTP');\n const isEmailMfaSetupAvailable = allowedMfaSetupTypes.includes('EMAIL');\n if (isTotpMfaSetupAvailable && isEmailMfaSetupAvailable) {\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONTINUE_SIGN_IN_WITH_MFA_SETUP_SELECTION',\n allowedMFATypes: allowedMfaSetupTypes,\n },\n };\n }\n if (isEmailMfaSetupAvailable) {\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONTINUE_SIGN_IN_WITH_EMAIL_SETUP',\n },\n };\n }\n if (isTotpMfaSetupAvailable) {\n const associateSoftwareToken = createAssociateSoftwareTokenClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: authConfig.userPoolEndpoint,\n }),\n });\n const { Session, SecretCode: secretCode } = await associateSoftwareToken({ region: getRegionFromUserPoolId(authConfig.userPoolId) }, {\n Session: signInSession,\n });\n signInStore.dispatch({\n type: 'SET_SIGN_IN_SESSION',\n value: Session,\n });\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONTINUE_SIGN_IN_WITH_TOTP_SETUP',\n totpSetupDetails: getTOTPSetupDetails(secretCode, username),\n },\n };\n }\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: `Cannot initiate MFA setup from available types: ${mfaSetupTypes}`,\n });\n }\n case 'NEW_PASSWORD_REQUIRED':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED',\n missingAttributes: parseAttributes(challengeParameters.requiredAttributes),\n },\n };\n case 'SELECT_MFA_TYPE':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONTINUE_SIGN_IN_WITH_MFA_SELECTION',\n allowedMFATypes: getMFATypes(parseMFATypes(challengeParameters.MFAS_CAN_CHOOSE)),\n },\n };\n case 'SMS_OTP':\n case 'SMS_MFA':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONFIRM_SIGN_IN_WITH_SMS_CODE',\n codeDeliveryDetails: {\n deliveryMedium: challengeParameters.CODE_DELIVERY_DELIVERY_MEDIUM,\n destination: challengeParameters.CODE_DELIVERY_DESTINATION,\n },\n },\n };\n case 'SOFTWARE_TOKEN_MFA':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONFIRM_SIGN_IN_WITH_TOTP_CODE',\n },\n };\n case 'EMAIL_OTP':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONFIRM_SIGN_IN_WITH_EMAIL_CODE',\n codeDeliveryDetails: {\n deliveryMedium: challengeParameters.CODE_DELIVERY_DELIVERY_MEDIUM,\n destination: challengeParameters.CODE_DELIVERY_DESTINATION,\n },\n },\n };\n case 'WEB_AUTHN': {\n const result = await handleWebAuthnSignInResult(challengeParameters);\n if (isWebAuthnResultAuthSignInOutput(result)) {\n return result;\n }\n return getSignInResult(result);\n }\n case 'PASSWORD':\n case 'PASSWORD_SRP':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONFIRM_SIGN_IN_WITH_PASSWORD',\n },\n };\n case 'SELECT_CHALLENGE':\n return {\n isSignedIn: false,\n nextStep: {\n signInStep: 'CONTINUE_SIGN_IN_WITH_FIRST_FACTOR_SELECTION',\n availableChallenges,\n },\n };\n }\n // TODO: remove this error message for production apps\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: 'An error occurred during the sign in process. ' +\n `${challengeName} challengeName returned by the underlying service was not addressed.`,\n });\n}\nfunction getTOTPSetupDetails(secretCode, username) {\n return {\n sharedSecret: secretCode,\n getSetupUri: (appName, accountName) => {\n const totpUri = `otpauth://totp/${appName}:${accountName ?? username}?secret=${secretCode}&issuer=${appName}`;\n return new AmplifyUrl(totpUri);\n },\n };\n}\nfunction getSignInResultFromError(errorName) {\n if (errorName === InitiateAuthException.PasswordResetRequiredException) {\n return {\n isSignedIn: false,\n nextStep: { signInStep: 'RESET_PASSWORD' },\n };\n }\n else if (errorName === InitiateAuthException.UserNotConfirmedException) {\n return {\n isSignedIn: false,\n nextStep: { signInStep: 'CONFIRM_SIGN_UP' },\n };\n }\n}\nfunction parseAttributes(attributes) {\n if (!attributes)\n return [];\n const parsedAttributes = JSON.parse(attributes).map(att => att.includes(USER_ATTRIBUTES) ? att.replace(USER_ATTRIBUTES, '') : att);\n return parsedAttributes;\n}\nfunction createAttributes(attributes) {\n if (!attributes)\n return {};\n const newAttributes = {};\n Object.entries(attributes).forEach(([key, value]) => {\n if (value)\n newAttributes[`${USER_ATTRIBUTES}${key}`] = value;\n });\n return newAttributes;\n}\nasync function handleChallengeName(username, challengeName, session, challengeResponse, config, tokenOrchestrator, clientMetadata, options) {\n const userAttributes = options?.userAttributes;\n const deviceName = options?.friendlyDeviceName;\n switch (challengeName) {\n case 'WEB_AUTHN':\n case 'SELECT_CHALLENGE':\n if (challengeResponse === 'PASSWORD_SRP' ||\n challengeResponse === 'PASSWORD') {\n return {\n ChallengeName: challengeResponse,\n Session: session,\n $metadata: {},\n };\n }\n return initiateSelectedChallenge({\n username,\n session,\n selectedChallenge: challengeResponse,\n config,\n clientMetadata,\n });\n case 'SELECT_MFA_TYPE':\n return handleSelectMFATypeChallenge({\n challengeResponse,\n clientMetadata,\n session,\n username,\n config,\n });\n case 'MFA_SETUP':\n return handleMFASetupChallenge({\n challengeResponse,\n clientMetadata,\n session,\n username,\n deviceName,\n config,\n });\n case 'NEW_PASSWORD_REQUIRED':\n return handleCompleteNewPasswordChallenge({\n challengeResponse,\n clientMetadata,\n session,\n username,\n requiredAttributes: userAttributes,\n config,\n });\n case 'CUSTOM_CHALLENGE':\n return retryOnResourceNotFoundException(handleCustomChallenge, [\n {\n challengeResponse,\n clientMetadata,\n session,\n username,\n config,\n tokenOrchestrator,\n },\n ], username, tokenOrchestrator);\n case 'SMS_MFA':\n case 'SOFTWARE_TOKEN_MFA':\n case 'SMS_OTP':\n case 'EMAIL_OTP':\n return handleMFAChallenge({\n challengeName,\n challengeResponse,\n clientMetadata,\n session,\n username,\n config,\n });\n case 'PASSWORD':\n return handleSelectChallengeWithPassword(username, challengeResponse, clientMetadata, config, session);\n case 'PASSWORD_SRP':\n return handleSelectChallengeWithPasswordSRP(username, challengeResponse, // This is the actual password\n clientMetadata, config, session, tokenOrchestrator);\n }\n // TODO: remove this error message for production apps\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: `An error occurred during the sign in process.\n\t\t${challengeName} challengeName returned by the underlying service was not addressed.`,\n });\n}\nfunction mapMfaType(mfa) {\n let mfaType = 'SMS_MFA';\n if (mfa === 'TOTP')\n mfaType = 'SOFTWARE_TOKEN_MFA';\n if (mfa === 'EMAIL')\n mfaType = 'EMAIL_OTP';\n return mfaType;\n}\nfunction getMFAType(type) {\n if (type === 'SMS_MFA')\n return 'SMS';\n if (type === 'SOFTWARE_TOKEN_MFA')\n return 'TOTP';\n if (type === 'EMAIL_OTP')\n return 'EMAIL';\n // TODO: log warning for unknown MFA type\n}\nfunction getMFATypes(types) {\n if (!types)\n return undefined;\n return types.map(getMFAType).filter(Boolean);\n}\nfunction parseMFATypes(mfa) {\n if (!mfa)\n return [];\n return JSON.parse(mfa);\n}\nfunction getAllowedMfaSetupTypes(availableMfaSetupTypes) {\n return availableMfaSetupTypes.filter(authMfaType => authMfaType === 'EMAIL' || authMfaType === 'TOTP');\n}\nasync function assertUserNotAuthenticated() {\n let authUser;\n try {\n authUser = await getCurrentUser();\n }\n catch (error) { }\n if (authUser && authUser.userId && authUser.username) {\n throw new AuthError({\n name: USER_ALREADY_AUTHENTICATED_EXCEPTION,\n message: 'There is already a signed in user.',\n recoverySuggestion: 'Call signOut before calling signIn again.',\n });\n }\n}\nfunction getActiveSignInUsername(username) {\n const state = signInStore.getState();\n return state.username ?? username;\n}\nasync function handleMFAChallenge({ challengeName, challengeResponse, clientMetadata, session, username, config, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const challengeResponses = {\n USERNAME: username,\n };\n if (challengeName === 'EMAIL_OTP') {\n challengeResponses.EMAIL_OTP_CODE = challengeResponse;\n }\n if (challengeName === 'SMS_MFA') {\n challengeResponses.SMS_MFA_CODE = challengeResponse;\n }\n if (challengeName === 'SMS_OTP') {\n challengeResponses.SMS_OTP_CODE = challengeResponse;\n }\n if (challengeName === 'SOFTWARE_TOKEN_MFA') {\n challengeResponses.SOFTWARE_TOKEN_MFA_CODE = challengeResponse;\n }\n const userContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const jsonReq = {\n ChallengeName: challengeName,\n ChallengeResponses: challengeResponses,\n Session: session,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData: userContextData,\n };\n const respondToAuthChallenge = createRespondToAuthChallengeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n return respondToAuthChallenge({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignIn),\n }, jsonReq);\n}\n\nexport { assertUserNotAuthenticated, createAttributes, getActiveSignInUsername, getAllowedMfaSetupTypes, getMFAType, getMFATypes, getSignInResult, getSignInResultFromError, getTOTPSetupDetails, handleChallengeName, handleCompleteNewPasswordChallenge, handleCustomAuthFlowWithoutSRP, handleCustomChallenge, handleCustomSRPAuthFlow, handleMFAChallenge, handleMFASetupChallenge, handleSelectMFATypeChallenge, handleUserPasswordAuthFlow, handleUserSRPAuthFlow, mapMfaType, parseAttributes, parseMFATypes };\n//# sourceMappingURL=signInHelpers.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError.mjs';\nimport { handleCustomAuthFlowWithoutSRP, getActiveSignInUsername, getSignInResult, getSignInResultFromError } from '../utils/signInHelpers.mjs';\nimport { setActiveSignInState, resetActiveSignInState } from '../../../client/utils/store/signInStore.mjs';\nimport { cacheCognitoTokens } from '../tokenProvider/cacheTokens.mjs';\nimport '../utils/refreshAuthTokens.mjs';\nimport '../tokenProvider/errorHelpers.mjs';\nimport '../utils/types.mjs';\nimport { tokenOrchestrator } from '../tokenProvider/tokenProvider.mjs';\nimport { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent.mjs';\nimport { retryOnResourceNotFoundException } from '../utils/retryOnResourceNotFoundException.mjs';\nimport { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Signs a user in using a custom authentication flow without password\n *\n * @param input - The SignInWithCustomAuthInput object\n * @returns AuthSignInResult\n * @throws service: {@link InitiateAuthException } - Cognito service errors thrown during the sign-in process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password\n * are not defined.\n * @throws SignInWithCustomAuthOutput - Thrown when the token provider config is invalid.\n */\nasync function signInWithCustomAuth(input) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { username, password, options } = input;\n const signInDetails = {\n loginId: username,\n authFlowType: 'CUSTOM_WITHOUT_SRP',\n };\n const metadata = options?.clientMetadata;\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignInUsername);\n assertValidationError(!password, AuthValidationErrorCode.CustomAuthSignInPassword);\n try {\n const { ChallengeName: retriedChallengeName, ChallengeParameters: retiredChallengeParameters, AuthenticationResult, Session, } = await retryOnResourceNotFoundException(handleCustomAuthFlowWithoutSRP, [username, metadata, authConfig, tokenOrchestrator], username, tokenOrchestrator);\n const activeUsername = getActiveSignInUsername(username);\n // sets up local state used during the sign-in process\n setActiveSignInState({\n signInSession: Session,\n username: activeUsername,\n challengeName: retriedChallengeName,\n signInDetails,\n });\n if (AuthenticationResult) {\n await cacheCognitoTokens({\n username: activeUsername,\n ...AuthenticationResult,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: AuthenticationResult.NewDeviceMetadata,\n accessToken: AuthenticationResult.AccessToken,\n }),\n signInDetails,\n });\n resetActiveSignInState();\n await dispatchSignedInHubEvent();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n return getSignInResult({\n challengeName: retriedChallengeName,\n challengeParameters: retiredChallengeParameters,\n });\n }\n catch (error) {\n resetActiveSignInState();\n assertServiceError(error);\n const result = getSignInResultFromError(error.name);\n if (result)\n return result;\n throw error;\n }\n}\n\nexport { signInWithCustomAuth };\n//# sourceMappingURL=signInWithCustomAuth.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError.mjs';\nimport { handleCustomSRPAuthFlow, getActiveSignInUsername, getSignInResult, getSignInResultFromError } from '../utils/signInHelpers.mjs';\nimport { setActiveSignInState, resetActiveSignInState } from '../../../client/utils/store/signInStore.mjs';\nimport { cacheCognitoTokens } from '../tokenProvider/cacheTokens.mjs';\nimport '../utils/refreshAuthTokens.mjs';\nimport '../tokenProvider/errorHelpers.mjs';\nimport '../utils/types.mjs';\nimport { tokenOrchestrator } from '../tokenProvider/tokenProvider.mjs';\nimport { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent.mjs';\nimport { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Signs a user in using a custom authentication flow with SRP\n *\n * @param input - The SignInWithCustomSRPAuthInput object\n * @returns SignInWithCustomSRPAuthOutput\n * @throws service: {@link InitiateAuthException }, {@link RespondToAuthChallengeException } - Cognito\n * service errors thrown during the sign-in process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password\n * are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nasync function signInWithCustomSRPAuth(input) {\n const { username, password, options } = input;\n const signInDetails = {\n loginId: username,\n authFlowType: 'CUSTOM_WITH_SRP',\n };\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const metadata = options?.clientMetadata;\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignInUsername);\n assertValidationError(!!password, AuthValidationErrorCode.EmptySignInPassword);\n try {\n const { ChallengeName: handledChallengeName, ChallengeParameters: handledChallengeParameters, AuthenticationResult, Session, } = await handleCustomSRPAuthFlow(username, password, metadata, authConfig, tokenOrchestrator);\n const activeUsername = getActiveSignInUsername(username);\n // sets up local state used during the sign-in process\n setActiveSignInState({\n signInSession: Session,\n username: activeUsername,\n challengeName: handledChallengeName,\n signInDetails,\n });\n if (AuthenticationResult) {\n await cacheCognitoTokens({\n username: activeUsername,\n ...AuthenticationResult,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: AuthenticationResult.NewDeviceMetadata,\n accessToken: AuthenticationResult.AccessToken,\n }),\n signInDetails,\n });\n resetActiveSignInState();\n await dispatchSignedInHubEvent();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n return getSignInResult({\n challengeName: handledChallengeName,\n challengeParameters: handledChallengeParameters,\n });\n }\n catch (error) {\n resetActiveSignInState();\n assertServiceError(error);\n const result = getSignInResultFromError(error.name);\n if (result)\n return result;\n throw error;\n }\n}\n\nexport { signInWithCustomSRPAuth };\n//# sourceMappingURL=signInWithCustomSRPAuth.mjs.map\n","import { autoSignInStore } from '../../../client/utils/store/autoSignInStore.mjs';\nimport '../../../client/utils/store/signInStore.mjs';\nimport { AuthError } from '../../../errors/AuthError.mjs';\nimport { AUTO_SIGN_IN_EXCEPTION } from '../../../errors/constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst initialAutoSignIn = async () => {\n throw new AuthError({\n name: AUTO_SIGN_IN_EXCEPTION,\n message: 'The autoSignIn flow has not started, or has been cancelled/completed.',\n recoverySuggestion: 'Please try to use the signIn API or log out before starting a new autoSignIn flow.',\n });\n};\n/**\n * Signs a user in automatically after finishing the sign-up process.\n *\n * This API will automatically sign a user in if the autoSignIn flow has been completed in the following cases:\n * - User confirmed their account with a verification code sent to their phone or email (default option).\n * - User confirmed their account with a verification link sent to their phone or email. In order to\n * enable this option you need to go to the Amazon Cognito [console](https://aws.amazon.com/pm/cognito),\n * look for your userpool, then go to the `Messaging` tab and enable `link` mode inside the `Verification message` option.\n * Finally you need to define the `signUpVerificationMethod` in your `Auth` config.\n *\n * @example\n * ```typescript\n * Amplify.configure({\n * Auth: {\n * Cognito: {\n * ...cognitoConfig,\n * signUpVerificationMethod: \"link\" // the default value is \"code\"\n * }\n *\t}});\n * ```\n *\n * @throws AutoSignInException - Thrown when the autoSignIn flow has not started, or has been cancelled/completed.\n * @returns The signInOutput.\n *\n * @example\n * ```typescript\n * // handleSignUp.ts\n * async function handleSignUp(\n * username:string,\n * password:string\n * ){\n * try {\n * const { nextStep } = await signUp({\n * username,\n * password,\n * options: {\n * userAttributes:{ email:'email@email.com'},\n * autoSignIn: true // This enables the auto sign-in flow.\n * },\n * });\n *\n * handleSignUpStep(nextStep);\n *\n * } catch (error) {\n * console.log(error);\n * }\n * }\n *\n * // handleConfirmSignUp.ts\n * async function handleConfirmSignUp(username:string, confirmationCode:string) {\n * try {\n * const { nextStep } = await confirmSignUp({\n * username,\n * confirmationCode,\n * });\n *\n * handleSignUpStep(nextStep);\n * } catch (error) {\n * console.log(error);\n * }\n * }\n *\n * // signUpUtils.ts\n * async function handleSignUpStep( step: SignUpOutput[\"nextStep\"]) {\n * switch (step.signUpStep) {\n * case \"CONFIRM_SIGN_UP\":\n *\n * // Redirect end-user to confirm-sign up screen.\n *\n * case \"COMPLETE_AUTO_SIGN_IN\":\n *\t const codeDeliveryDetails = step.codeDeliveryDetails;\n * if (codeDeliveryDetails) {\n * // Redirect user to confirm-sign-up with link screen.\n * }\n * const signInOutput = await autoSignIn();\n * // handle sign-in steps\n * }\n *\n * ```\n */\n// TODO(Eslint): can this be refactored not using `let` on exported member?\n// eslint-disable-next-line import/no-mutable-exports\nlet autoSignIn = initialAutoSignIn;\n/**\n * Sets the context of autoSignIn at run time.\n * @internal\n */\nfunction setAutoSignIn(callback) {\n autoSignIn = callback;\n}\n/**\n * Resets the context\n *\n * @internal\n */\nfunction resetAutoSignIn(resetCallback = true) {\n if (resetCallback) {\n autoSignIn = initialAutoSignIn;\n }\n autoSignInStore.dispatch({ type: 'RESET' });\n}\n\nexport { autoSignIn, resetAutoSignIn, setAutoSignIn };\n//# sourceMappingURL=autoSignIn.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError.mjs';\nimport { handleUserSRPAuthFlow, getActiveSignInUsername, getSignInResult, getSignInResultFromError } from '../utils/signInHelpers.mjs';\nimport { setActiveSignInState, resetActiveSignInState } from '../../../client/utils/store/signInStore.mjs';\nimport { cacheCognitoTokens } from '../tokenProvider/cacheTokens.mjs';\nimport '../utils/refreshAuthTokens.mjs';\nimport '../tokenProvider/errorHelpers.mjs';\nimport '../utils/types.mjs';\nimport { tokenOrchestrator } from '../tokenProvider/tokenProvider.mjs';\nimport { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent.mjs';\nimport { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata.mjs';\nimport { resetAutoSignIn } from './autoSignIn.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Signs a user in\n *\n * @param input - The SignInWithSRPInput object\n * @returns SignInWithSRPOutput\n * @throws service: {@link InitiateAuthException }, {@link RespondToAuthChallengeException } - Cognito service errors\n * thrown during the sign-in process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password\n * are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nasync function signInWithSRP(input) {\n const { username, password } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n const signInDetails = {\n loginId: username,\n authFlowType: 'USER_SRP_AUTH',\n };\n assertTokenProviderConfig(authConfig);\n const clientMetaData = input.options?.clientMetadata;\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignInUsername);\n assertValidationError(!!password, AuthValidationErrorCode.EmptySignInPassword);\n try {\n const { ChallengeName: handledChallengeName, ChallengeParameters: handledChallengeParameters, AuthenticationResult, Session, } = await handleUserSRPAuthFlow(username, password, clientMetaData, authConfig, tokenOrchestrator);\n const activeUsername = getActiveSignInUsername(username);\n // sets up local state used during the sign-in process\n setActiveSignInState({\n signInSession: Session,\n username: activeUsername,\n challengeName: handledChallengeName,\n signInDetails,\n });\n if (AuthenticationResult) {\n await cacheCognitoTokens({\n username: activeUsername,\n ...AuthenticationResult,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: AuthenticationResult.NewDeviceMetadata,\n accessToken: AuthenticationResult.AccessToken,\n }),\n signInDetails,\n });\n resetActiveSignInState();\n await dispatchSignedInHubEvent();\n resetAutoSignIn();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n return getSignInResult({\n challengeName: handledChallengeName,\n challengeParameters: handledChallengeParameters,\n });\n }\n catch (error) {\n resetActiveSignInState();\n resetAutoSignIn();\n assertServiceError(error);\n const result = getSignInResultFromError(error.name);\n if (result)\n return result;\n throw error;\n }\n}\n\nexport { signInWithSRP };\n//# sourceMappingURL=signInWithSRP.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError.mjs';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { handleUserPasswordAuthFlow, getActiveSignInUsername, getSignInResult, getSignInResultFromError } from '../utils/signInHelpers.mjs';\nimport { setActiveSignInState, resetActiveSignInState } from '../../../client/utils/store/signInStore.mjs';\nimport { cacheCognitoTokens } from '../tokenProvider/cacheTokens.mjs';\nimport '../utils/refreshAuthTokens.mjs';\nimport '../tokenProvider/errorHelpers.mjs';\nimport '../utils/types.mjs';\nimport { tokenOrchestrator } from '../tokenProvider/tokenProvider.mjs';\nimport { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent.mjs';\nimport { retryOnResourceNotFoundException } from '../utils/retryOnResourceNotFoundException.mjs';\nimport { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata.mjs';\nimport { resetAutoSignIn } from './autoSignIn.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Signs a user in using USER_PASSWORD_AUTH AuthFlowType\n *\n * @param input - The SignInWithUserPasswordInput object\n * @returns SignInWithUserPasswordOutput\n * @throws service: {@link InitiateAuthException } - Cognito service error thrown during the sign-in process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password\n * are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nasync function signInWithUserPassword(input) {\n const { username, password, options } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n const signInDetails = {\n loginId: username,\n authFlowType: 'USER_PASSWORD_AUTH',\n };\n assertTokenProviderConfig(authConfig);\n const metadata = options?.clientMetadata;\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignInUsername);\n assertValidationError(!!password, AuthValidationErrorCode.EmptySignInPassword);\n try {\n const { ChallengeName: retiredChallengeName, ChallengeParameters: retriedChallengeParameters, AuthenticationResult, Session, } = await retryOnResourceNotFoundException(handleUserPasswordAuthFlow, [username, password, metadata, authConfig, tokenOrchestrator], username, tokenOrchestrator);\n const activeUsername = getActiveSignInUsername(username);\n // sets up local state used during the sign-in process\n setActiveSignInState({\n signInSession: Session,\n username: activeUsername,\n challengeName: retiredChallengeName,\n signInDetails,\n });\n if (AuthenticationResult) {\n await cacheCognitoTokens({\n ...AuthenticationResult,\n username: activeUsername,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: AuthenticationResult.NewDeviceMetadata,\n accessToken: AuthenticationResult.AccessToken,\n }),\n signInDetails,\n });\n resetActiveSignInState();\n await dispatchSignedInHubEvent();\n resetAutoSignIn();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n return getSignInResult({\n challengeName: retiredChallengeName,\n challengeParameters: retriedChallengeParameters,\n });\n }\n catch (error) {\n resetActiveSignInState();\n resetAutoSignIn();\n assertServiceError(error);\n const result = getSignInResultFromError(error.name);\n if (result)\n return result;\n throw error;\n }\n}\n\nexport { signInWithUserPassword };\n//# sourceMappingURL=signInWithUserPassword.mjs.map\n","import { AuthAction } from '@aws-amplify/core/internals/utils';\nimport { getUserContextData } from '../../../providers/cognito/utils/userContextData.mjs';\nimport { createInitiateAuthClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createInitiateAuthClient.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport '../../../providers/cognito/types/errors.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../../../providers/cognito/factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport { handlePasswordSRP } from '../shared/handlePasswordSRP.mjs';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { setActiveSignInUsername } from '../../../providers/cognito/utils/setActiveSignInUsername.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Handles user authentication flow with configurable challenge preferences.\n * Supports AuthFactorType challenges through the USER_AUTH flow.\n *\n * @param {HandleUserAuthFlowInput} params - Authentication flow parameters\n * @param {string} params.username - The username for authentication\n * @param {Record} [params.clientMetadata] - Optional metadata to pass to authentication service\n * @param {CognitoUserPoolConfig} params.config - Cognito User Pool configuration\n * @param {AuthTokenOrchestrator} params.tokenOrchestrator - Manages authentication tokens and device tracking\n * @param {AuthFactorType} [params.preferredChallenge] - Optional preferred authentication method\n * @param {string} [params.password] - Required when preferredChallenge is 'PASSWORD' or 'PASSWORD_SRP'\n *\n * @returns {Promise} The authentication response from Cognito\n */\nasync function handleUserAuthFlow({ username, clientMetadata, config, tokenOrchestrator, preferredChallenge, password, session, }) {\n const { userPoolId, userPoolClientId, userPoolEndpoint } = config;\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const authParameters = { USERNAME: username };\n if (preferredChallenge) {\n if (preferredChallenge === 'PASSWORD_SRP') {\n assertValidationError(!!password, AuthValidationErrorCode.EmptySignInPassword);\n return handlePasswordSRP({\n username,\n password,\n clientMetadata,\n config,\n tokenOrchestrator,\n authFlow: 'USER_AUTH',\n preferredChallenge,\n });\n }\n if (preferredChallenge === 'PASSWORD') {\n assertValidationError(!!password, AuthValidationErrorCode.EmptySignInPassword);\n authParameters.PASSWORD = password;\n }\n authParameters.PREFERRED_CHALLENGE = preferredChallenge;\n }\n const jsonReq = {\n AuthFlow: 'USER_AUTH',\n AuthParameters: authParameters,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n };\n if (session) {\n jsonReq.Session = session;\n }\n const initiateAuth = createInitiateAuthClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const response = await initiateAuth({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignIn),\n }, jsonReq);\n // Set the active username immediately after successful authentication attempt\n // If a user starts a new sign-in while another sign-in is incomplete,\n // this ensures we're tracking the correct user for subsequent auth challenges.\n setActiveSignInUsername(username);\n return response;\n}\n\nexport { handleUserAuthFlow };\n//# sourceMappingURL=handleUserAuthFlow.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError.mjs';\nimport { getActiveSignInUsername, getSignInResult, getSignInResultFromError } from '../utils/signInHelpers.mjs';\nimport { autoSignInStore } from '../../../client/utils/store/autoSignInStore.mjs';\nimport { setActiveSignInState, resetActiveSignInState } from '../../../client/utils/store/signInStore.mjs';\nimport { cacheCognitoTokens } from '../tokenProvider/cacheTokens.mjs';\nimport { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent.mjs';\nimport '../utils/refreshAuthTokens.mjs';\nimport '../tokenProvider/errorHelpers.mjs';\nimport '../utils/types.mjs';\nimport { tokenOrchestrator } from '../tokenProvider/tokenProvider.mjs';\nimport { handleUserAuthFlow } from '../../../client/flows/userAuth/handleUserAuthFlow.mjs';\nimport { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata.mjs';\nimport { resetAutoSignIn } from './autoSignIn.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Signs a user in through a registered email or phone number without a password by by receiving and entering an OTP.\n *\n * @param input - The SignInWithUserAuthInput object\n * @returns SignInWithUserAuthOutput\n * @throws service: {@link InitiateAuthException }, {@link RespondToAuthChallengeException } - Cognito service errors\n * thrown during the sign-in process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password -- needs to change\n * are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nasync function signInWithUserAuth(input) {\n const { username, password, options } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n const signInDetails = {\n loginId: username,\n authFlowType: 'USER_AUTH',\n };\n assertTokenProviderConfig(authConfig);\n const clientMetaData = options?.clientMetadata;\n const preferredChallenge = options?.preferredChallenge;\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignInUsername);\n try {\n const handleUserAuthFlowInput = {\n username,\n config: authConfig,\n tokenOrchestrator,\n clientMetadata: clientMetaData,\n preferredChallenge,\n password,\n };\n const autoSignInStoreState = autoSignInStore.getState();\n if (autoSignInStoreState.active &&\n autoSignInStoreState.username === username) {\n handleUserAuthFlowInput.session = autoSignInStoreState.session;\n }\n const response = await handleUserAuthFlow(handleUserAuthFlowInput);\n const activeUsername = getActiveSignInUsername(username);\n setActiveSignInState({\n signInSession: response.Session,\n username: activeUsername,\n challengeName: response.ChallengeName,\n signInDetails,\n });\n if (response.AuthenticationResult) {\n await cacheCognitoTokens({\n username: activeUsername,\n ...response.AuthenticationResult,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: response.AuthenticationResult.NewDeviceMetadata,\n accessToken: response.AuthenticationResult.AccessToken,\n }),\n signInDetails,\n });\n resetActiveSignInState();\n await dispatchSignedInHubEvent();\n resetAutoSignIn();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n return getSignInResult({\n challengeName: response.ChallengeName,\n challengeParameters: response.ChallengeParameters,\n availableChallenges: 'AvailableChallenges' in response\n ? response.AvailableChallenges\n : undefined,\n });\n }\n catch (error) {\n resetActiveSignInState();\n resetAutoSignIn();\n assertServiceError(error);\n const result = getSignInResultFromError(error.name);\n if (result)\n return result;\n throw error;\n }\n}\n\nexport { signInWithUserAuth };\n//# sourceMappingURL=signInWithUserAuth.mjs.map\n","import { assertUserNotAuthenticated } from '../utils/signInHelpers.mjs';\nimport { signInWithCustomAuth } from './signInWithCustomAuth.mjs';\nimport { signInWithCustomSRPAuth } from './signInWithCustomSRPAuth.mjs';\nimport { signInWithSRP } from './signInWithSRP.mjs';\nimport { signInWithUserPassword } from './signInWithUserPassword.mjs';\nimport { signInWithUserAuth } from './signInWithUserAuth.mjs';\nimport { resetAutoSignIn } from './autoSignIn.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Signs a user in\n *\n * @param input - The SignInInput object\n * @returns SignInOutput\n * @throws service: {@link InitiateAuthException }, {@link RespondToAuthChallengeException }\n * - Cognito service errors thrown during the sign-in process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown when either username or password\n * are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nasync function signIn(input) {\n // Here we want to reset the store but not reassign the callback.\n // The callback is reset when the underlying promise resolves or rejects.\n // With the advent of session based sign in, this guarantees that the signIn API initiates a new auth flow,\n // regardless of whether it is called for a user currently engaged in an active auto sign in session.\n resetAutoSignIn(false);\n const authFlowType = input.options?.authFlowType;\n await assertUserNotAuthenticated();\n switch (authFlowType) {\n case 'USER_SRP_AUTH':\n return signInWithSRP(input);\n case 'USER_PASSWORD_AUTH':\n return signInWithUserPassword(input);\n case 'CUSTOM_WITHOUT_SRP':\n return signInWithCustomAuth(input);\n case 'CUSTOM_WITH_SRP':\n return signInWithCustomSRPAuth(input);\n case 'USER_AUTH':\n return signInWithUserAuth(input);\n default:\n return signInWithSRP(input);\n }\n}\n\nexport { signIn };\n//# sourceMappingURL=signIn.mjs.map\n","import { HubInternal } from '@aws-amplify/core/internals/utils';\nimport { signIn } from '../apis/signIn.mjs';\nimport { AuthError } from '../../../errors/AuthError.mjs';\nimport { setAutoSignIn, resetAutoSignIn } from '../apis/autoSignIn.mjs';\nimport { AUTO_SIGN_IN_EXCEPTION } from '../../../errors/constants.mjs';\nimport { signInWithUserAuth } from '../apis/signInWithUserAuth.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst MAX_AUTOSIGNIN_POLLING_MS = 3 * 60 * 1000;\nfunction handleCodeAutoSignIn(signInInput) {\n const stopHubListener = HubInternal.listen('auth-internal', async ({ payload }) => {\n switch (payload.event) {\n case 'confirmSignUp': {\n const response = payload.data;\n if (response?.isSignUpComplete) {\n HubInternal.dispatch('auth-internal', {\n event: 'autoSignIn',\n });\n setAutoSignIn(autoSignInWithCode(signInInput));\n stopHubListener();\n }\n }\n }\n });\n // This will stop the listener if confirmSignUp is not resolved.\n const timeOutId = setTimeout(() => {\n stopHubListener();\n clearTimeout(timeOutId);\n resetAutoSignIn();\n }, MAX_AUTOSIGNIN_POLLING_MS);\n}\nfunction debounce(fun, delay) {\n let timer;\n return (args) => {\n if (!timer) {\n fun(...args);\n }\n clearTimeout(timer);\n timer = setTimeout(() => {\n timer = undefined;\n }, delay);\n };\n}\nfunction handleAutoSignInWithLink(signInInput, resolve, reject) {\n const start = Date.now();\n const autoSignInPollingIntervalId = setInterval(async () => {\n const elapsedTime = Date.now() - start;\n const maxTime = MAX_AUTOSIGNIN_POLLING_MS;\n if (elapsedTime > maxTime) {\n clearInterval(autoSignInPollingIntervalId);\n reject(new AuthError({\n name: AUTO_SIGN_IN_EXCEPTION,\n message: 'The account was not confirmed on time.',\n recoverySuggestion: 'Try to verify your account by clicking the link sent your email or phone and then login manually.',\n }));\n resetAutoSignIn();\n }\n else {\n try {\n const signInOutput = await signIn(signInInput);\n if (signInOutput.nextStep.signInStep !== 'CONFIRM_SIGN_UP') {\n resolve(signInOutput);\n clearInterval(autoSignInPollingIntervalId);\n resetAutoSignIn();\n }\n }\n catch (error) {\n clearInterval(autoSignInPollingIntervalId);\n reject(error);\n resetAutoSignIn();\n }\n }\n }, 5000);\n}\nconst debouncedAutoSignInWithLink = debounce(handleAutoSignInWithLink, 300);\nconst debouncedAutoSignWithCodeOrUserConfirmed = debounce(handleAutoSignInWithCodeOrUserConfirmed, 300);\nfunction autoSignInWhenUserIsConfirmedWithLink(signInInput) {\n return async () => {\n return new Promise((resolve, reject) => {\n debouncedAutoSignInWithLink([signInInput, resolve, reject]);\n });\n };\n}\nasync function handleAutoSignInWithCodeOrUserConfirmed(signInInput, resolve, reject) {\n try {\n const output = signInInput?.options?.authFlowType === 'USER_AUTH'\n ? await signInWithUserAuth(signInInput)\n : await signIn(signInInput);\n resolve(output);\n resetAutoSignIn();\n }\n catch (error) {\n reject(error);\n resetAutoSignIn();\n }\n}\nfunction autoSignInWithCode(signInInput) {\n return async () => {\n return new Promise((resolve, reject) => {\n debouncedAutoSignWithCodeOrUserConfirmed([signInInput, resolve, reject]);\n });\n };\n}\nconst autoSignInUserConfirmed = autoSignInWithCode;\n\nexport { autoSignInUserConfirmed, autoSignInWhenUserIsConfirmedWithLink, handleCodeAutoSignIn };\n//# sourceMappingURL=signUpHelpers.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { parseJsonError, parseJsonBody } from '@aws-amplify/core/internals/aws-client-utils';\nimport { validationErrorMap } from '../../../../common/AuthErrorStrings.mjs';\nimport { AuthError } from '../../../../errors/AuthError.mjs';\nimport { AuthValidationErrorCode } from '../../../../errors/types/validation.mjs';\nimport { assertServiceError } from '../../../../errors/utils/assertServiceError.mjs';\nimport { SignUpException } from '../../../../providers/cognito/types/errors.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createSignUpClientDeserializer = () => async (response) => {\n if (response.statusCode >= 300) {\n const error = await parseJsonError(response);\n assertServiceError(error);\n if (\n // Missing Password Error\n // 1 validation error detected: Value at 'password'failed to satisfy constraint: Member must not be null\n error.name === SignUpException.InvalidParameterException &&\n /'password'/.test(error.message) &&\n /Member must not be null/.test(error.message)) {\n const name = AuthValidationErrorCode.EmptySignUpPassword;\n const { message, recoverySuggestion } = validationErrorMap[name];\n throw new AuthError({\n name,\n message,\n recoverySuggestion,\n });\n }\n throw new AuthError({ name: error.name, message: error.message });\n }\n return parseJsonBody(response);\n};\nconst createSignUpClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('SignUp'), createSignUpClientDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createSignUpClient, createSignUpClientDeserializer };\n//# sourceMappingURL=createSignUpClient.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { toAttributeType } from '../utils/apiHelpers.mjs';\nimport { autoSignInUserConfirmed, autoSignInWhenUserIsConfirmedWithLink, handleCodeAutoSignIn } from '../utils/signUpHelpers.mjs';\nimport { getUserContextData } from '../utils/userContextData.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport { createSignUpClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createSignUpClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { autoSignInStore } from '../../../client/utils/store/autoSignInStore.mjs';\nimport '../../../client/utils/store/signInStore.mjs';\nimport { setAutoSignIn } from './autoSignIn.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Creates a user\n *\n * @param input - The SignUpInput object\n * @returns SignUpOutput\n * @throws service: {@link SignUpException } - Cognito service errors thrown during the sign-up process.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown either username or password\n * are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nasync function signUp(input) {\n const { username, password, options } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n const signUpVerificationMethod = authConfig?.signUpVerificationMethod ?? 'code';\n const { clientMetadata, validationData, autoSignIn } = input.options ?? {};\n assertTokenProviderConfig(authConfig);\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignUpUsername);\n const signInServiceOptions = typeof autoSignIn !== 'boolean' ? autoSignIn : undefined;\n const signInInput = {\n username,\n options: signInServiceOptions,\n };\n // if the authFlowType is 'CUSTOM_WITHOUT_SRP' then we don't include the password\n if (signInServiceOptions?.authFlowType !== 'CUSTOM_WITHOUT_SRP') {\n signInInput.password = password;\n }\n const { userPoolId, userPoolClientId, userPoolEndpoint } = authConfig;\n const signUpClient = createSignUpClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const signUpClientInput = {\n Username: username,\n Password: undefined,\n UserAttributes: options?.userAttributes && toAttributeType(options?.userAttributes),\n ClientMetadata: clientMetadata,\n ValidationData: validationData && toAttributeType(validationData),\n ClientId: userPoolClientId,\n UserContextData: getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n }),\n };\n if (password) {\n signUpClientInput.Password = password;\n }\n const { UserSub: userId, CodeDeliveryDetails: cdd, UserConfirmed: userConfirmed, Session: session, } = await signUpClient({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignUp),\n }, signUpClientInput);\n if (signInServiceOptions || autoSignIn === true) {\n autoSignInStore.dispatch({ type: 'START' });\n autoSignInStore.dispatch({ type: 'SET_USERNAME', value: username });\n autoSignInStore.dispatch({ type: 'SET_SESSION', value: session });\n }\n const codeDeliveryDetails = {\n destination: cdd?.Destination,\n deliveryMedium: cdd?.DeliveryMedium,\n attributeName: cdd?.AttributeName,\n };\n const isSignUpComplete = !!userConfirmed;\n const isAutoSignInStarted = autoSignInStore.getState().active;\n // Sign Up Complete\n // No Confirm Sign In Step Required\n if (isSignUpComplete) {\n if (isAutoSignInStarted) {\n setAutoSignIn(autoSignInUserConfirmed(signInInput));\n return {\n isSignUpComplete: true,\n nextStep: {\n signUpStep: 'COMPLETE_AUTO_SIGN_IN',\n },\n userId,\n };\n }\n return {\n isSignUpComplete: true,\n nextStep: {\n signUpStep: 'DONE',\n },\n userId,\n };\n }\n // Sign Up Not Complete\n // Confirm Sign Up Step Required\n if (isAutoSignInStarted) {\n // Confirmation Via Link Occurs In Separate Context\n // AutoSignIn Fn Will Initiate Polling Once Executed\n if (signUpVerificationMethod === 'link') {\n setAutoSignIn(autoSignInWhenUserIsConfirmedWithLink(signInInput));\n return {\n isSignUpComplete: false,\n nextStep: {\n signUpStep: 'COMPLETE_AUTO_SIGN_IN',\n codeDeliveryDetails,\n },\n userId,\n };\n }\n // Confirmation Via Code Occurs In Same Context\n // AutoSignIn Next Step Will Be Returned From Confirm Sign Up\n handleCodeAutoSignIn(signInInput);\n }\n return {\n isSignUpComplete: false,\n nextStep: {\n signUpStep: 'CONFIRM_SIGN_UP',\n codeDeliveryDetails,\n },\n userId,\n };\n}\n\nexport { signUp };\n//# sourceMappingURL=signUp.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createForgotPasswordClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ForgotPassword'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createForgotPasswordClient };\n//# sourceMappingURL=createForgotPasswordClient.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport { getUserContextData } from '../utils/userContextData.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../types/errors.mjs';\nimport { createForgotPasswordClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createForgotPasswordClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Resets a user's password.\n *\n * @param input - The ResetPasswordInput object.\n * @returns ResetPasswordOutput\n * @throws -{@link ForgotPasswordException }\n * Thrown due to an invalid confirmation code or password.\n * @throws -{@link AuthValidationErrorCode }\n * Thrown due to an empty username.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n **/\nasync function resetPassword(input) {\n const { username } = input;\n assertValidationError(!!username, AuthValidationErrorCode.EmptyResetPasswordUsername);\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolClientId, userPoolId, userPoolEndpoint } = authConfig;\n const clientMetadata = input.options?.clientMetadata;\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const forgotPassword = createForgotPasswordClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const res = await forgotPassword({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ResetPassword),\n }, {\n Username: username,\n ClientMetadata: clientMetadata,\n ClientId: userPoolClientId,\n UserContextData,\n });\n const codeDeliveryDetails = res.CodeDeliveryDetails;\n return {\n isPasswordReset: false,\n nextStep: {\n resetPasswordStep: 'CONFIRM_RESET_PASSWORD_WITH_CODE',\n codeDeliveryDetails: {\n deliveryMedium: codeDeliveryDetails?.DeliveryMedium,\n destination: codeDeliveryDetails?.Destination,\n attributeName: codeDeliveryDetails?.AttributeName,\n },\n },\n };\n}\n\nexport { resetPassword };\n//# sourceMappingURL=resetPassword.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createConfirmForgotPasswordClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ConfirmForgotPassword'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createConfirmForgotPasswordClient };\n//# sourceMappingURL=createConfirmForgotPasswordClient.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport { getUserContextData } from '../utils/userContextData.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../types/errors.mjs';\nimport { createConfirmForgotPasswordClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmForgotPasswordClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Confirms the new password and verification code to reset the password.\n *\n * @param input - The ConfirmResetPasswordInput object.\n * @throws -{@link ConfirmForgotPasswordException }\n * Thrown due to an invalid confirmation code or password.\n * @throws -{@link AuthValidationErrorCode }\n * Thrown due to an empty confirmation code, password or username.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nasync function confirmResetPassword(input) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolClientId, userPoolId, userPoolEndpoint } = authConfig;\n const { username, newPassword } = input;\n assertValidationError(!!username, AuthValidationErrorCode.EmptyConfirmResetPasswordUsername);\n assertValidationError(!!newPassword, AuthValidationErrorCode.EmptyConfirmResetPasswordNewPassword);\n const code = input.confirmationCode;\n assertValidationError(!!code, AuthValidationErrorCode.EmptyConfirmResetPasswordConfirmationCode);\n const metadata = input.options?.clientMetadata;\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const confirmForgotPassword = createConfirmForgotPasswordClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await confirmForgotPassword({\n region: getRegionFromUserPoolId(authConfig.userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmResetPassword),\n }, {\n Username: username,\n ConfirmationCode: code,\n Password: newPassword,\n ClientMetadata: metadata,\n ClientId: authConfig.userPoolClientId,\n UserContextData,\n });\n}\n\nexport { confirmResetPassword };\n//# sourceMappingURL=confirmResetPassword.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createResendConfirmationCodeClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ResendConfirmationCode'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createResendConfirmationCodeClient };\n//# sourceMappingURL=createResendConfirmationCodeClient.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport { getUserContextData } from '../utils/userContextData.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../types/errors.mjs';\nimport { createResendConfirmationCodeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createResendConfirmationCodeClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Resend the confirmation code while signing up\n *\n * @param input - The ResendSignUpCodeInput object\n * @returns ResendSignUpCodeOutput\n * @throws service: {@link ResendConfirmationException } - Cognito service errors thrown when resending the code.\n * @throws validation: {@link AuthValidationErrorCode } - Validation errors thrown either username are not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nasync function resendSignUpCode(input) {\n const { username } = input;\n assertValidationError(!!username, AuthValidationErrorCode.EmptySignUpUsername);\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolClientId, userPoolId, userPoolEndpoint } = authConfig;\n const clientMetadata = input.options?.clientMetadata;\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const resendConfirmationCode = createResendConfirmationCodeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { CodeDeliveryDetails } = await resendConfirmationCode({\n region: getRegionFromUserPoolId(authConfig.userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ResendSignUpCode),\n }, {\n Username: username,\n ClientMetadata: clientMetadata,\n ClientId: authConfig.userPoolClientId,\n UserContextData,\n });\n const { DeliveryMedium, AttributeName, Destination } = {\n ...CodeDeliveryDetails,\n };\n return {\n destination: Destination,\n deliveryMedium: DeliveryMedium,\n attributeName: AttributeName\n ? AttributeName\n : undefined,\n };\n}\n\nexport { resendSignUpCode };\n//# sourceMappingURL=resendSignUpCode.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createConfirmSignUpClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('ConfirmSignUp'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createConfirmSignUpClient };\n//# sourceMappingURL=createConfirmSignUpClient.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig, AuthAction, HubInternal } from '@aws-amplify/core/internals/utils';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport { getUserContextData } from '../utils/userContextData.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../types/errors.mjs';\nimport { createConfirmSignUpClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createConfirmSignUpClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\nimport { autoSignInStore } from '../../../client/utils/store/autoSignInStore.mjs';\nimport '../../../client/utils/store/signInStore.mjs';\nimport { resetAutoSignIn } from './autoSignIn.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Confirms a new user account.\n *\n * @param input - The ConfirmSignUpInput object.\n * @returns ConfirmSignUpOutput\n * @throws -{@link ConfirmSignUpException }\n * Thrown due to an invalid confirmation code.\n * @throws -{@link AuthValidationErrorCode }\n * Thrown due to an empty confirmation code\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nasync function confirmSignUp(input) {\n const { username, confirmationCode, options } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolId, userPoolClientId, userPoolEndpoint } = authConfig;\n const clientMetadata = options?.clientMetadata;\n assertValidationError(!!username, AuthValidationErrorCode.EmptyConfirmSignUpUsername);\n assertValidationError(!!confirmationCode, AuthValidationErrorCode.EmptyConfirmSignUpCode);\n const UserContextData = getUserContextData({\n username,\n userPoolId,\n userPoolClientId,\n });\n const confirmSignUpClient = createConfirmSignUpClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { Session: session } = await confirmSignUpClient({\n region: getRegionFromUserPoolId(authConfig.userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmSignUp),\n }, {\n Username: username,\n ConfirmationCode: confirmationCode,\n ClientMetadata: clientMetadata,\n ForceAliasCreation: options?.forceAliasCreation,\n ClientId: authConfig.userPoolClientId,\n UserContextData,\n });\n return new Promise((resolve, reject) => {\n try {\n const signUpOut = {\n isSignUpComplete: true,\n nextStep: {\n signUpStep: 'DONE',\n },\n };\n const autoSignInStoreState = autoSignInStore.getState();\n if (!autoSignInStoreState.active ||\n autoSignInStoreState.username !== username) {\n resolve(signUpOut);\n resetAutoSignIn();\n return;\n }\n autoSignInStore.dispatch({ type: 'SET_SESSION', value: session });\n const stopListener = HubInternal.listen('auth-internal', ({ payload }) => {\n switch (payload.event) {\n case 'autoSignIn':\n resolve({\n isSignUpComplete: true,\n nextStep: {\n signUpStep: 'COMPLETE_AUTO_SIGN_IN',\n },\n });\n stopListener();\n }\n });\n HubInternal.dispatch('auth-internal', {\n event: 'confirmSignUp',\n data: signUpOut,\n });\n }\n catch (error) {\n reject(error);\n }\n });\n}\n\nexport { confirmSignUp };\n//# sourceMappingURL=confirmSignUp.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig } from '@aws-amplify/core/internals/utils';\nimport '../../../client/utils/store/autoSignInStore.mjs';\nimport { signInStore, setActiveSignInState, resetActiveSignInState } from '../../../client/utils/store/signInStore.mjs';\nimport { AuthError } from '../../../errors/AuthError.mjs';\nimport { handleChallengeName, getSignInResult, getSignInResultFromError } from '../utils/signInHelpers.mjs';\nimport { assertServiceError } from '../../../errors/utils/assertServiceError.mjs';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { AuthErrorCodes } from '../../../common/AuthErrorStrings.mjs';\nimport { cacheCognitoTokens } from '../tokenProvider/cacheTokens.mjs';\nimport '../utils/refreshAuthTokens.mjs';\nimport '../tokenProvider/errorHelpers.mjs';\nimport '../utils/types.mjs';\nimport { tokenOrchestrator } from '../tokenProvider/tokenProvider.mjs';\nimport { dispatchSignedInHubEvent } from '../utils/dispatchSignedInHubEvent.mjs';\nimport { getNewDeviceMetadata } from '../utils/getNewDeviceMetadata.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Continues or completes the sign in process when required by the initial call to `signIn`.\n *\n * @param input - The ConfirmSignInInput object\n * @returns ConfirmSignInOutput\n * @throws -{@link VerifySoftwareTokenException }:\n * Thrown due to an invalid MFA token.\n * @throws -{@link RespondToAuthChallengeException }:\n * Thrown due to an invalid auth challenge response.\n * @throws -{@link AssociateSoftwareTokenException}:\n * Thrown due to a service error during the MFA setup process.\n * @throws -{@link AuthValidationErrorCode }:\n * Thrown when `challengeResponse` is not defined.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nasync function confirmSignIn(input) {\n const { challengeResponse, options } = input;\n const { username, challengeName, signInSession, signInDetails } = signInStore.getState();\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const clientMetaData = options?.clientMetadata;\n assertValidationError(!!challengeResponse, AuthValidationErrorCode.EmptyChallengeResponse);\n if (!username || !challengeName || !signInSession)\n // TODO: remove this error message for production apps\n throw new AuthError({\n name: AuthErrorCodes.SignInException,\n message: `\n\t\t\tAn error occurred during the sign in process.\n\n\t\t\tThis most likely occurred due to:\n\t\t\t1. signIn was not called before confirmSignIn.\n\t\t\t2. signIn threw an exception.\n\t\t\t3. page was refreshed during the sign in flow and session has expired.\n\t\t\t`,\n recoverySuggestion: 'Make sure a successful call to signIn is made before calling confirmSignIn' +\n 'and that the session has not expired.',\n });\n try {\n const { Session, ChallengeName: handledChallengeName, AuthenticationResult, ChallengeParameters: handledChallengeParameters, } = await handleChallengeName(username, challengeName, signInSession, challengeResponse, authConfig, tokenOrchestrator, clientMetaData, options);\n // sets up local state used during the sign-in process\n setActiveSignInState({\n signInSession: Session,\n username,\n challengeName: handledChallengeName,\n signInDetails,\n });\n if (AuthenticationResult) {\n await cacheCognitoTokens({\n username,\n ...AuthenticationResult,\n NewDeviceMetadata: await getNewDeviceMetadata({\n userPoolId: authConfig.userPoolId,\n userPoolEndpoint: authConfig.userPoolEndpoint,\n newDeviceMetadata: AuthenticationResult.NewDeviceMetadata,\n accessToken: AuthenticationResult.AccessToken,\n }),\n signInDetails,\n });\n resetActiveSignInState();\n await dispatchSignedInHubEvent();\n return {\n isSignedIn: true,\n nextStep: { signInStep: 'DONE' },\n };\n }\n return getSignInResult({\n challengeName: handledChallengeName,\n challengeParameters: handledChallengeParameters,\n });\n }\n catch (error) {\n assertServiceError(error);\n const result = getSignInResultFromError(error.name);\n if (result)\n return result;\n throw error;\n }\n}\n\nexport { confirmSignIn };\n//# sourceMappingURL=confirmSignIn.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createGetUserClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('GetUser'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createGetUserClient };\n//# sourceMappingURL=createGetUserClient.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createVerifyUserAttributeClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('VerifyUserAttribute'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createVerifyUserAttributeClient };\n//# sourceMappingURL=createVerifyUserAttributeClient.mjs.map\n","import { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils';\nimport { AuthValidationErrorCode } from '../../../errors/types/validation.mjs';\nimport { assertValidationError } from '../../../errors/utils/assertValidationError.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { assertAuthTokens } from '../utils/types.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../types/errors.mjs';\nimport { createVerifyUserAttributeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createVerifyUserAttributeClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Confirms a user attribute with the confirmation code.\n *\n * @param input - The ConfirmUserAttributeInput object\n * @throws -{@link AuthValidationErrorCode } -\n * Thrown when `confirmationCode` is not defined.\n * @throws -{@link VerifyUserAttributeException } - Thrown due to an invalid confirmation code or attribute.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nasync function confirmUserAttribute(input) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { confirmationCode, userAttributeKey } = input;\n assertValidationError(!!confirmationCode, AuthValidationErrorCode.EmptyConfirmUserAttributeCode);\n const { tokens } = await fetchAuthSession({ forceRefresh: false });\n assertAuthTokens(tokens);\n const verifyUserAttribute = createVerifyUserAttributeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await verifyUserAttribute({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.ConfirmUserAttribute),\n }, {\n AccessToken: tokens.accessToken.toString(),\n AttributeName: userAttributeKey,\n Code: confirmationCode,\n });\n}\n\nexport { confirmUserAttribute };\n//# sourceMappingURL=confirmUserAttribute.mjs.map\n","import { ConsoleLogger } from '@aws-amplify/core';\nimport { AuthErrorStrings } from './common/AuthErrorStrings.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// TODO: delete this module when the Auth class is removed.\nconst logger = new ConsoleLogger('AuthError');\nclass AuthError extends Error {\n constructor(type) {\n const { message, log } = authErrorMessages[type];\n super(message);\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n this.constructor = AuthError;\n Object.setPrototypeOf(this, AuthError.prototype);\n this.name = 'AuthError';\n this.log = log || message;\n logger.error(this.log);\n }\n}\nclass NoUserPoolError extends AuthError {\n constructor(type) {\n super(type);\n // Hack for making the custom error class work when transpiled to es5\n // TODO: Delete the following 2 lines after we change the build target to >= es2015\n this.constructor = NoUserPoolError;\n Object.setPrototypeOf(this, NoUserPoolError.prototype);\n this.name = 'NoUserPoolError';\n }\n}\nconst authErrorMessages = {\n oauthSignInError: {\n message: AuthErrorStrings.OAUTH_ERROR,\n log: 'Make sure Cognito Hosted UI has been configured correctly',\n },\n noConfig: {\n message: AuthErrorStrings.DEFAULT_MSG,\n log: `\n Error: Amplify has not been configured correctly.\n This error is typically caused by one of the following scenarios:\n\n 1. Make sure you're passing the awsconfig object to Amplify.configure() in your app's entry point\n See https://aws-amplify.github.io/docs/js/authentication#configure-your-app for more information\n \n 2. There might be multiple conflicting versions of amplify packages in your node_modules.\n\t\t\t\tRefer to our docs site for help upgrading Amplify packages (https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js)\n `,\n },\n missingAuthConfig: {\n message: AuthErrorStrings.DEFAULT_MSG,\n log: `\n Error: Amplify has not been configured correctly. \n The configuration object is missing required auth properties.\n This error is typically caused by one of the following scenarios:\n\n 1. Did you run \\`amplify push\\` after adding auth via \\`amplify add auth\\`?\n See https://aws-amplify.github.io/docs/js/authentication#amplify-project-setup for more information\n\n 2. This could also be caused by multiple conflicting versions of amplify packages, see (https://docs.amplify.aws/lib/troubleshooting/upgrading/q/platform/js) for help upgrading Amplify packages.\n `,\n },\n emptyUsername: {\n message: AuthErrorStrings.EMPTY_USERNAME,\n },\n // TODO: should include a list of valid sign-in types\n invalidUsername: {\n message: AuthErrorStrings.INVALID_USERNAME,\n },\n emptyPassword: {\n message: AuthErrorStrings.EMPTY_PASSWORD,\n },\n emptyCode: {\n message: AuthErrorStrings.EMPTY_CODE,\n },\n signUpError: {\n message: AuthErrorStrings.SIGN_UP_ERROR,\n log: 'The first parameter should either be non-null string or object',\n },\n noMFA: {\n message: AuthErrorStrings.NO_MFA,\n },\n invalidMFA: {\n message: AuthErrorStrings.INVALID_MFA,\n },\n emptyChallengeResponse: {\n message: AuthErrorStrings.EMPTY_CHALLENGE,\n },\n noUserSession: {\n message: AuthErrorStrings.NO_USER_SESSION,\n },\n deviceConfig: {\n message: AuthErrorStrings.DEVICE_CONFIG,\n },\n networkError: {\n message: AuthErrorStrings.NETWORK_ERROR,\n },\n autoSignInError: {\n message: AuthErrorStrings.AUTOSIGNIN_ERROR,\n },\n default: {\n message: AuthErrorStrings.DEFAULT_MSG,\n },\n};\n\nexport { AuthError, NoUserPoolError, authErrorMessages };\n//# sourceMappingURL=Errors.mjs.map\n","import { authErrorMessages } from '../../../../Errors.mjs';\nimport { AuthErrorCodes } from '../../../../common/AuthErrorStrings.mjs';\nimport { AuthError } from '../../../../errors/AuthError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createOAuthError = (message, recoverySuggestion) => new AuthError({\n message: message ?? 'An error has occurred during the oauth process.',\n name: AuthErrorCodes.OAuthSignInError,\n recoverySuggestion: recoverySuggestion ?? authErrorMessages.oauthSignInError.log,\n});\n\nexport { createOAuthError };\n//# sourceMappingURL=createOAuthError.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nvar AuthErrorTypes;\n(function (AuthErrorTypes) {\n AuthErrorTypes[\"NoConfig\"] = \"noConfig\";\n AuthErrorTypes[\"MissingAuthConfig\"] = \"missingAuthConfig\";\n AuthErrorTypes[\"EmptyUsername\"] = \"emptyUsername\";\n AuthErrorTypes[\"InvalidUsername\"] = \"invalidUsername\";\n AuthErrorTypes[\"EmptyPassword\"] = \"emptyPassword\";\n AuthErrorTypes[\"EmptyCode\"] = \"emptyCode\";\n AuthErrorTypes[\"SignUpError\"] = \"signUpError\";\n AuthErrorTypes[\"NoMFA\"] = \"noMFA\";\n AuthErrorTypes[\"InvalidMFA\"] = \"invalidMFA\";\n AuthErrorTypes[\"EmptyChallengeResponse\"] = \"emptyChallengeResponse\";\n AuthErrorTypes[\"NoUserSession\"] = \"noUserSession\";\n AuthErrorTypes[\"Default\"] = \"default\";\n AuthErrorTypes[\"DeviceConfig\"] = \"deviceConfig\";\n AuthErrorTypes[\"NetworkError\"] = \"networkError\";\n AuthErrorTypes[\"AutoSignInError\"] = \"autoSignInError\";\n AuthErrorTypes[\"OAuthSignInError\"] = \"oauthSignInError\";\n})(AuthErrorTypes || (AuthErrorTypes = {}));\n\nexport { AuthErrorTypes };\n//# sourceMappingURL=Auth.mjs.map\n","import { AuthError } from '../../../../errors/AuthError.mjs';\nimport { AuthErrorTypes } from '../../../../types/Auth.mjs';\nimport { oAuthStore } from './oAuthStore.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst flowCancelledMessage = '`signInWithRedirect` has been canceled.';\nconst validationFailedMessage = 'An error occurred while validating the state.';\nconst validationRecoverySuggestion = 'Try to initiate an OAuth flow from Amplify';\nconst validateState = async (state) => {\n const savedState = await oAuthStore.loadOAuthState();\n // This is because savedState only exists if the flow was initiated by Amplify\n const validatedState = state === savedState ? savedState : undefined;\n if (!validatedState) {\n throw new AuthError({\n name: AuthErrorTypes.OAuthSignInError,\n message: state === null ? flowCancelledMessage : validationFailedMessage,\n recoverySuggestion: state === null ? undefined : validationRecoverySuggestion,\n });\n }\n return validatedState;\n};\n\nexport { flowCancelledMessage, validateState, validationFailedMessage, validationRecoverySuggestion };\n//# sourceMappingURL=validateState.mjs.map\n","import { AmplifyUrl, USER_AGENT_HEADER, urlSafeDecode, AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';\nimport { decodeJWT, Hub } from '@aws-amplify/core';\nimport { cacheCognitoTokens } from '../../tokenProvider/cacheTokens.mjs';\nimport { dispatchSignedInHubEvent } from '../dispatchSignedInHubEvent.mjs';\nimport '../refreshAuthTokens.mjs';\nimport '../../tokenProvider/errorHelpers.mjs';\nimport { oAuthStore } from './oAuthStore.mjs';\nimport { resolveAndClearInflightPromises } from './inflightPromise.mjs';\nimport { tokenOrchestrator } from '../../tokenProvider/tokenProvider.mjs';\nimport { createOAuthError } from './createOAuthError.mjs';\nimport { validateState } from './validateState.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst completeOAuthFlow = async ({ currentUrl, userAgentValue, clientId, redirectUri, responseType, domain, preferPrivateSession, }) => {\n const urlParams = new AmplifyUrl(currentUrl);\n const error = urlParams.searchParams.get('error');\n const errorMessage = urlParams.searchParams.get('error_description');\n if (error) {\n throw createOAuthError(errorMessage ?? error);\n }\n if (responseType === 'code') {\n return handleCodeFlow({\n currentUrl,\n userAgentValue,\n clientId,\n redirectUri,\n domain,\n preferPrivateSession,\n });\n }\n return handleImplicitFlow({\n currentUrl,\n redirectUri,\n preferPrivateSession,\n });\n};\nconst handleCodeFlow = async ({ currentUrl, userAgentValue, clientId, redirectUri, domain, preferPrivateSession, }) => {\n /* Convert URL into an object with parameters as keys\n{ redirect_uri: 'http://localhost:3000/', response_type: 'code', ...} */\n const url = new AmplifyUrl(currentUrl);\n const code = url.searchParams.get('code');\n const state = url.searchParams.get('state');\n // if `code` or `state` is not presented in the redirect url, most likely\n // that the end user cancelled the inflight oauth flow by:\n // 1. clicking the back button of browser\n // 2. closing the provider hosted UI page and coming back to the app\n if (!code || !state) {\n throw createOAuthError('User cancelled OAuth flow.');\n }\n // may throw error is being caught in attemptCompleteOAuthFlow.ts\n const validatedState = await validateState(state);\n const oAuthTokenEndpoint = 'https://' + domain + '/oauth2/token';\n // TODO(v6): check hub events\n // dispatchAuthEvent(\n // \t'codeFlow',\n // \t{},\n // \t`Retrieving tokens from ${oAuthTokenEndpoint}`\n // );\n const codeVerifier = await oAuthStore.loadPKCE();\n const oAuthTokenBody = {\n grant_type: 'authorization_code',\n code,\n client_id: clientId,\n redirect_uri: redirectUri,\n ...(codeVerifier ? { code_verifier: codeVerifier } : {}),\n };\n const body = Object.entries(oAuthTokenBody)\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join('&');\n const { access_token, refresh_token: refreshToken, id_token, error, error_message: errorMessage, token_type, expires_in, } = await (await fetch(oAuthTokenEndpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/x-www-form-urlencoded',\n [USER_AGENT_HEADER]: userAgentValue,\n },\n body,\n })).json();\n if (error) {\n // error is being caught in attemptCompleteOAuthFlow.ts\n throw createOAuthError(errorMessage ?? error);\n }\n const username = (access_token && decodeJWT(access_token).payload.username) ?? 'username';\n await cacheCognitoTokens({\n username,\n AccessToken: access_token,\n IdToken: id_token,\n RefreshToken: refreshToken,\n TokenType: token_type,\n ExpiresIn: expires_in,\n });\n return completeFlow({\n redirectUri,\n state: validatedState,\n preferPrivateSession,\n });\n};\nconst handleImplicitFlow = async ({ currentUrl, redirectUri, preferPrivateSession, }) => {\n // hash is `null` if `#` doesn't exist on URL\n const url = new AmplifyUrl(currentUrl);\n const { id_token, access_token, state, token_type, expires_in, error_description, error, } = (url.hash ?? '#')\n .substring(1) // Remove # from returned code\n .split('&')\n .map(pairings => pairings.split('='))\n .reduce((accum, [k, v]) => ({ ...accum, [k]: v }), {\n id_token: undefined,\n access_token: undefined,\n state: undefined,\n token_type: undefined,\n expires_in: undefined,\n error_description: undefined,\n error: undefined,\n });\n if (error) {\n throw createOAuthError(error_description ?? error);\n }\n if (!access_token) {\n // error is being caught in attemptCompleteOAuthFlow.ts\n throw createOAuthError('No access token returned from OAuth flow.');\n }\n const validatedState = await validateState(state);\n const username = (access_token && decodeJWT(access_token).payload.username) ?? 'username';\n await cacheCognitoTokens({\n username,\n AccessToken: access_token,\n IdToken: id_token,\n TokenType: token_type,\n ExpiresIn: expires_in,\n });\n return completeFlow({\n redirectUri,\n state: validatedState,\n preferPrivateSession,\n });\n};\nconst completeFlow = async ({ redirectUri, state, preferPrivateSession, }) => {\n await tokenOrchestrator.setOAuthMetadata({\n oauthSignIn: true,\n });\n await oAuthStore.clearOAuthData();\n await oAuthStore.storeOAuthSignIn(true, preferPrivateSession);\n // this should be called before any call that involves `fetchAuthSession`\n // e.g. `getCurrentUser()` below, so it allows every inflight async calls to\n // `fetchAuthSession` can be resolved\n resolveAndClearInflightPromises();\n if (isCustomState(state)) {\n Hub.dispatch('auth', {\n event: 'customOAuthState',\n data: urlSafeDecode(getCustomState(state)),\n }, 'Auth', AMPLIFY_SYMBOL);\n }\n Hub.dispatch('auth', { event: 'signInWithRedirect' }, 'Auth', AMPLIFY_SYMBOL);\n await dispatchSignedInHubEvent();\n clearHistory(redirectUri);\n};\nconst isCustomState = (state) => {\n return /-/.test(state);\n};\nconst getCustomState = (state) => {\n return state.split('-').splice(1).join('-');\n};\nconst clearHistory = (redirectUri) => {\n if (typeof window !== 'undefined' && typeof window.history !== 'undefined') {\n window.history.replaceState(window.history.state, '', redirectUri);\n }\n};\n\nexport { completeOAuthFlow };\n//# sourceMappingURL=completeOAuthFlow.mjs.map\n","import { invalidPreferredRedirectUrlException, invalidOriginException, invalidRedirectException } from '../../../../errors/constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/** @internal */\nfunction getRedirectUrl(redirects, preferredRedirectUrl) {\n if (preferredRedirectUrl) {\n const redirectUrl = redirects?.find(redirect => redirect === preferredRedirectUrl);\n if (!redirectUrl) {\n throw invalidPreferredRedirectUrlException;\n }\n return redirectUrl;\n }\n else {\n const redirectUrlFromTheSameOrigin = redirects?.find(isSameOriginAndPathName) ??\n redirects?.find(isTheSameDomain);\n const redirectUrlFromDifferentOrigin = redirects?.find(isHttps) ?? redirects?.find(isHttp);\n if (redirectUrlFromTheSameOrigin) {\n return redirectUrlFromTheSameOrigin;\n }\n else if (redirectUrlFromDifferentOrigin) {\n throw invalidOriginException;\n }\n throw invalidRedirectException;\n }\n}\n// origin + pathname => https://example.com/app\nconst isSameOriginAndPathName = (redirect) => redirect.startsWith(\n// eslint-disable-next-line no-constant-binary-expression\nString(window.location.origin + window.location.pathname ?? '/'));\n// domain => outlook.live.com, github.com\nconst isTheSameDomain = (redirect) => redirect.includes(String(window.location.hostname));\nconst isHttp = (redirect) => redirect.startsWith('http://');\nconst isHttps = (redirect) => redirect.startsWith('https://');\n\nexport { getRedirectUrl };\n//# sourceMappingURL=getRedirectUrl.mjs.map\n","import { Hub } from '@aws-amplify/core';\nimport { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';\nimport { oAuthStore } from './oAuthStore.mjs';\nimport { resolveAndClearInflightPromises } from './inflightPromise.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst handleFailure = async (error) => {\n resolveAndClearInflightPromises();\n await oAuthStore.clearOAuthInflightData();\n Hub.dispatch('auth', { event: 'signInWithRedirect_failure', data: { error } }, 'Auth', AMPLIFY_SYMBOL);\n};\n\nexport { handleFailure };\n//# sourceMappingURL=handleFailure.mjs.map\n","import { assertTokenProviderConfig, assertOAuthConfig, AuthAction } from '@aws-amplify/core/internals/utils';\nimport { getAuthUserAgentValue } from '../../../../utils/getAuthUserAgentValue.mjs';\nimport { oAuthStore } from './oAuthStore.mjs';\nimport { completeOAuthFlow } from './completeOAuthFlow.mjs';\nimport { getRedirectUrl } from './getRedirectUrl.mjs';\nimport { handleFailure } from './handleFailure.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst attemptCompleteOAuthFlow = async (authConfig) => {\n try {\n assertTokenProviderConfig(authConfig);\n assertOAuthConfig(authConfig);\n oAuthStore.setAuthConfig(authConfig);\n }\n catch (_) {\n // no-op\n // This should not happen as Amplify singleton checks the oauth config key\n // unless the oauth config object doesn't contain required properties\n return;\n }\n // No inflight OAuth\n if (!(await oAuthStore.loadOAuthInFlight())) {\n return;\n }\n try {\n const currentUrl = window.location.href;\n const { loginWith, userPoolClientId } = authConfig;\n const { domain, redirectSignIn, responseType } = loginWith.oauth;\n const redirectUri = getRedirectUrl(redirectSignIn);\n await completeOAuthFlow({\n currentUrl,\n clientId: userPoolClientId,\n domain,\n redirectUri,\n responseType,\n userAgentValue: getAuthUserAgentValue(AuthAction.SignInWithRedirect),\n });\n }\n catch (err) {\n await handleFailure(err);\n }\n};\n\nexport { attemptCompleteOAuthFlow };\n//# sourceMappingURL=attemptCompleteOAuthFlow.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { isBrowser, ADD_OAUTH_LISTENER } from '@aws-amplify/core/internals/utils';\nimport { attemptCompleteOAuthFlow } from './attemptCompleteOAuthFlow.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n// attach the side effect for handling the completion of an inflight oauth flow\n// this side effect works only on Web\nisBrowser() &&\n (() => {\n // add the listener to the singleton for triggering\n Amplify[ADD_OAUTH_LISTENER](attemptCompleteOAuthFlow);\n })();\n//# sourceMappingURL=enableOAuthListener.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst cognitoHostedUIIdentityProviderMap = {\n Google: 'Google',\n Facebook: 'Facebook',\n Amazon: 'LoginWithAmazon',\n Apple: 'SignInWithApple',\n};\n\nexport { cognitoHostedUIIdentityProviderMap };\n//# sourceMappingURL=models.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst openAuthSession = async (url) => {\n if (!window?.location) {\n return;\n }\n // enforce HTTPS\n window.location.href = url.replace('http://', 'https://');\n};\n\nexport { openAuthSession };\n//# sourceMappingURL=openAuthSession.mjs.map\n","import { Sha256 } from '@aws-crypto/sha256-js';\nimport { getCrypto, base64Encoder } from '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst CODE_VERIFIER_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n/**\n *\n * @param length Desired length of the code verifier.\n *\n * **NOTE:** According to the [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636#section-4.1)\n * A code verifier must be with a length >= 43 and <= 128.\n *\n * @returns An object that contains the generated `codeVerifier` and a method\n * `toCodeChallenge` to generate the code challenge from the `codeVerifier`\n * following the spec of [RFC 7636](https://datatracker.ietf.org/doc/html/rfc7636#section-4.2).\n */\nconst generateCodeVerifier = (length) => {\n const randomBytes = new Uint8Array(length);\n getCrypto().getRandomValues(randomBytes);\n let value = '';\n let codeChallenge;\n for (const byte of randomBytes) {\n value += CODE_VERIFIER_CHARSET.charAt(byte % CODE_VERIFIER_CHARSET.length);\n }\n return {\n value,\n method: 'S256',\n toCodeChallenge() {\n if (codeChallenge) {\n return codeChallenge;\n }\n codeChallenge = generateCodeChallenge(value);\n return codeChallenge;\n },\n };\n};\nfunction generateCodeChallenge(codeVerifier) {\n const awsCryptoHash = new Sha256();\n awsCryptoHash.update(codeVerifier);\n const codeChallenge = removePaddingChar(base64Encoder.convert(awsCryptoHash.digestSync(), { urlSafe: true }));\n return codeChallenge;\n}\nfunction removePaddingChar(base64Encoded) {\n return base64Encoded.replace(/=/g, '');\n}\n\nexport { generateCodeVerifier };\n//# sourceMappingURL=generateCodeVerifier.mjs.map\n","import { generateRandomString } from '@aws-amplify/core/internals/utils';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst generateState = () => {\n return generateRandomString(32);\n};\n\nexport { generateState };\n//# sourceMappingURL=generateState.mjs.map\n","import { createOAuthError } from './createOAuthError.mjs';\nimport { handleFailure } from './handleFailure.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst listenForOAuthFlowCancellation = (store) => {\n async function handleCancelOAuthFlow(event) {\n const isBfcache = event.persisted;\n if (isBfcache && (await store.loadOAuthInFlight())) {\n const error = createOAuthError('User cancelled OAuth flow.');\n await handleFailure(error);\n }\n window.removeEventListener('pageshow', handleCancelOAuthFlow);\n }\n window.addEventListener('pageshow', handleCancelOAuthFlow);\n};\n\nexport { listenForOAuthFlowCancellation };\n//# sourceMappingURL=cancelOAuthFlow.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { assertTokenProviderConfig, assertOAuthConfig, urlSafeEncode, isBrowser, AuthAction } from '@aws-amplify/core/internals/utils';\nimport '../utils/oauth/enableOAuthListener.mjs';\nimport { cognitoHostedUIIdentityProviderMap } from '../types/models.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport { openAuthSession } from '../../../utils/openAuthSession.mjs';\nimport { assertUserNotAuthenticated } from '../utils/signInHelpers.mjs';\nimport { generateCodeVerifier } from '../utils/oauth/generateCodeVerifier.mjs';\nimport { generateState } from '../utils/oauth/generateState.mjs';\nimport '../utils/refreshAuthTokens.mjs';\nimport '../tokenProvider/errorHelpers.mjs';\nimport { oAuthStore } from '../utils/oauth/oAuthStore.mjs';\nimport '../tokenProvider/tokenProvider.mjs';\nimport { getRedirectUrl } from '../utils/oauth/getRedirectUrl.mjs';\nimport { handleFailure } from '../utils/oauth/handleFailure.mjs';\nimport { completeOAuthFlow } from '../utils/oauth/completeOAuthFlow.mjs';\nimport '../../../types/Auth.mjs';\nimport { createOAuthError } from '../utils/oauth/createOAuthError.mjs';\nimport { listenForOAuthFlowCancellation } from '../utils/oauth/cancelOAuthFlow.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Signs in a user with OAuth. Redirects the application to an Identity Provider.\n *\n * @param input - The SignInWithRedirectInput object, if empty it will redirect to Cognito HostedUI\n *\n * @throws AuthTokenConfigException - Thrown when the user pool config is invalid.\n * @throws OAuthNotConfigureException - Thrown when the oauth config is invalid.\n */\nasync function signInWithRedirect(input) {\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n assertOAuthConfig(authConfig);\n oAuthStore.setAuthConfig(authConfig);\n await assertUserNotAuthenticated();\n let provider = 'COGNITO'; // Default\n if (typeof input?.provider === 'string') {\n provider = cognitoHostedUIIdentityProviderMap[input.provider];\n }\n else if (input?.provider?.custom) {\n provider = input.provider.custom;\n }\n return oauthSignIn({\n oauthConfig: authConfig.loginWith.oauth,\n clientId: authConfig.userPoolClientId,\n provider,\n customState: input?.customState,\n preferPrivateSession: input?.options?.preferPrivateSession,\n options: {\n loginHint: input?.options?.loginHint,\n lang: input?.options?.lang,\n nonce: input?.options?.nonce,\n },\n });\n}\nconst oauthSignIn = async ({ oauthConfig, provider, clientId, customState, preferPrivateSession, options, }) => {\n const { domain, redirectSignIn, responseType, scopes } = oauthConfig;\n const { loginHint, lang, nonce } = options ?? {};\n const randomState = generateState();\n /* encodeURIComponent is not URL safe, use urlSafeEncode instead. Cognito\n single-encodes/decodes url on first sign in and double-encodes/decodes url\n when user already signed in. Using encodeURIComponent, Base32, Base64 add\n characters % or = which on further encoding becomes unsafe. '=' create issue\n for parsing query params.\n Refer: https://github.com/aws-amplify/amplify-js/issues/5218 */\n const state = customState\n ? `${randomState}-${urlSafeEncode(customState)}`\n : randomState;\n const { value, method, toCodeChallenge } = generateCodeVerifier(128);\n const redirectUri = getRedirectUrl(oauthConfig.redirectSignIn);\n if (isBrowser())\n oAuthStore.storeOAuthInFlight(true);\n oAuthStore.storeOAuthState(state);\n oAuthStore.storePKCE(value);\n const queryString = Object.entries({\n redirect_uri: redirectUri,\n response_type: responseType,\n client_id: clientId,\n identity_provider: provider,\n scope: scopes.join(' '),\n // eslint-disable-next-line camelcase\n ...(loginHint && { login_hint: loginHint }),\n ...(lang && { lang }),\n ...(nonce && { nonce }),\n state,\n ...(responseType === 'code' && {\n code_challenge: toCodeChallenge(),\n code_challenge_method: method,\n }),\n })\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join('&');\n // TODO(v6): use URL object instead\n const oAuthUrl = `https://${domain}/oauth2/authorize?${queryString}`;\n // this will only take effect in the following scenarios:\n // 1. the user cancels the OAuth flow on web via back button, and\n // 2. when bfcache is enabled\n listenForOAuthFlowCancellation(oAuthStore);\n // the following is effective only in react-native as openAuthSession resolves only in react-native\n const { type, error, url } = (await openAuthSession(oAuthUrl)) ??\n {};\n try {\n if (type === 'error') {\n throw createOAuthError(String(error));\n }\n if (type === 'success' && url) {\n await completeOAuthFlow({\n currentUrl: url,\n clientId,\n domain,\n redirectUri,\n responseType,\n userAgentValue: getAuthUserAgentValue(AuthAction.SignInWithRedirect),\n preferPrivateSession,\n });\n }\n }\n catch (err) {\n await handleFailure(err);\n // rethrow the error so it can be caught by `await signInWithRedirect()` in react-native\n throw err;\n }\n};\n\nexport { signInWithRedirect };\n//# sourceMappingURL=signInWithRedirect.mjs.map\n","import { assertTokenProviderConfig, fetchAuthSession, AuthAction } from '@aws-amplify/core/internals/utils';\nimport { getRegionFromUserPoolId } from '../../../../foundation/parsers/regionParsers.mjs';\nimport { assertAuthTokens } from '../../utils/types.mjs';\nimport { toAuthUserAttribute } from '../../utils/apiHelpers.mjs';\nimport { getAuthUserAgentValue } from '../../../../utils/getAuthUserAgentValue.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../../common/AuthErrorStrings.mjs';\nimport '../../../../errors/types/validation.mjs';\nimport '../../types/errors.mjs';\nimport { createGetUserClient } from '../../../../foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../../factories/createCognitoUserPoolEndpointResolver.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst fetchUserAttributes = async (amplify) => {\n const authConfig = amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession(amplify, {\n forceRefresh: false,\n });\n assertAuthTokens(tokens);\n const getUser = createGetUserClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { UserAttributes } = await getUser({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.FetchUserAttributes),\n }, {\n AccessToken: tokens.accessToken.toString(),\n });\n return toAuthUserAttribute(UserAttributes);\n};\n\nexport { fetchUserAttributes };\n//# sourceMappingURL=fetchUserAttributes.mjs.map\n","import { Amplify } from '@aws-amplify/core';\nimport { fetchUserAttributes as fetchUserAttributes$1 } from './internal/fetchUserAttributes.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Fetches the current user attributes while authenticated.\n *\n * @throws - {@link GetUserException} - Cognito service errors thrown when the service is not able to get the user.\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nconst fetchUserAttributes = () => {\n return fetchUserAttributes$1(Amplify);\n};\n\nexport { fetchUserAttributes };\n//# sourceMappingURL=fetchUserAttributes.mjs.map\n","import { clearCredentials, Hub } from '@aws-amplify/core';\nimport { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';\nimport '../refreshAuthTokens.mjs';\nimport '../../tokenProvider/errorHelpers.mjs';\nimport '../types.mjs';\nimport { tokenOrchestrator } from '../../tokenProvider/tokenProvider.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst completeOAuthSignOut = async (store) => {\n await store.clearOAuthData();\n tokenOrchestrator.clearTokens();\n await clearCredentials();\n Hub.dispatch('auth', { event: 'signedOut' }, 'Auth', AMPLIFY_SYMBOL);\n};\n\nexport { completeOAuthSignOut };\n//# sourceMappingURL=completeOAuthSignOut.mjs.map\n","import { assertOAuthConfig } from '@aws-amplify/core/internals/utils';\nimport { openAuthSession } from '../../../../utils/openAuthSession.mjs';\nimport { getRedirectUrl } from './getRedirectUrl.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst oAuthSignOutRedirect = async (authConfig, preferPrivateSession = false, redirectUrl) => {\n assertOAuthConfig(authConfig);\n const { loginWith, userPoolClientId } = authConfig;\n const { domain, redirectSignOut } = loginWith.oauth;\n const signoutUri = getRedirectUrl(redirectSignOut, redirectUrl);\n const oAuthLogoutEndpoint = `https://${domain}/logout?${Object.entries({\n client_id: userPoolClientId,\n logout_uri: encodeURIComponent(signoutUri),\n })\n .map(([k, v]) => `${k}=${v}`)\n .join('&')}`;\n return openAuthSession(oAuthLogoutEndpoint);\n};\n\nexport { oAuthSignOutRedirect };\n//# sourceMappingURL=oAuthSignOutRedirect.mjs.map\n","import { completeOAuthSignOut } from './completeOAuthSignOut.mjs';\nimport { oAuthSignOutRedirect } from './oAuthSignOutRedirect.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst handleOAuthSignOut = async (cognitoConfig, store, tokenOrchestrator, redirectUrl) => {\n const { isOAuthSignIn } = await store.loadOAuthSignIn();\n const oauthMetadata = await tokenOrchestrator.getOAuthMetadata();\n // Clear everything before attempting to visted logout endpoint since the current application\n // state could be wiped away on redirect\n await completeOAuthSignOut(store);\n // The isOAuthSignIn flag is propagated by the oAuthToken store which manages oauth keys in local storage only.\n // These keys are used to determine if a user is in an inflight or signedIn oauth states.\n // However, this behavior represents an issue when 2 apps share the same set of tokens in Cookie storage because the app that didn't\n // start the OAuth will not have access to the oauth keys.\n // A heuristic solution is to add oauth metadata to the tokenOrchestrator which will have access to the underlying\n // storage mechanism that is used by Amplify.\n if (isOAuthSignIn || oauthMetadata?.oauthSignIn) {\n // On web, this will always end up being a void action\n return oAuthSignOutRedirect(cognitoConfig, false, redirectUrl);\n }\n};\n\nexport { handleOAuthSignOut };\n//# sourceMappingURL=handleOAuthSignOut.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createRevokeTokenClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('RevokeToken'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createRevokeTokenClient };\n//# sourceMappingURL=createRevokeTokenClient.mjs.map\n","import { ConsoleLogger, Amplify, clearCredentials, Hub, defaultStorage } from '@aws-amplify/core';\nimport { assertTokenProviderConfig, assertOAuthConfig, AMPLIFY_SYMBOL, AuthAction } from '@aws-amplify/core/internals/utils';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport '../utils/refreshAuthTokens.mjs';\nimport { AuthError } from '../../../errors/AuthError.mjs';\nimport '../tokenProvider/errorHelpers.mjs';\nimport { DefaultOAuthStore } from '../utils/signInWithRedirectStore.mjs';\nimport { tokenOrchestrator } from '../tokenProvider/tokenProvider.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { assertAuthTokensWithRefreshToken, assertAuthTokens } from '../utils/types.mjs';\nimport '@aws-crypto/sha256-js';\nimport { handleOAuthSignOut } from '../utils/oauth/handleOAuthSignOut.mjs';\nimport { OAUTH_SIGNOUT_EXCEPTION } from '../../../errors/constants.mjs';\nimport '../../../Errors.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../../../types/Auth.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport { createRevokeTokenClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createRevokeTokenClient.mjs';\nimport '../../../errors/types/validation.mjs';\nimport '../types/errors.mjs';\nimport { createGlobalSignOutClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createGlobalSignOutClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('Auth');\n/**\n * Signs a user out\n *\n * @param input - The SignOutInput object\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nasync function signOut(input) {\n const cognitoConfig = Amplify.getConfig().Auth?.Cognito;\n assertTokenProviderConfig(cognitoConfig);\n if (input?.global) {\n await globalSignOut(cognitoConfig);\n }\n else {\n await clientSignOut(cognitoConfig);\n }\n let hasOAuthConfig;\n try {\n assertOAuthConfig(cognitoConfig);\n hasOAuthConfig = true;\n }\n catch (err) {\n hasOAuthConfig = false;\n }\n if (hasOAuthConfig) {\n const oAuthStore = new DefaultOAuthStore(defaultStorage);\n oAuthStore.setAuthConfig(cognitoConfig);\n const { type } = (await handleOAuthSignOut(cognitoConfig, oAuthStore, tokenOrchestrator, input?.oauth?.redirectUrl)) ?? {};\n if (type === 'error') {\n throw new AuthError({\n name: OAUTH_SIGNOUT_EXCEPTION,\n message: `An error occurred when attempting to log out from OAuth provider.`,\n });\n }\n }\n else {\n // complete sign out\n tokenOrchestrator.clearTokens();\n await clearCredentials();\n Hub.dispatch('auth', { event: 'signedOut' }, 'Auth', AMPLIFY_SYMBOL);\n }\n}\nasync function clientSignOut(cognitoConfig) {\n try {\n const { userPoolEndpoint, userPoolId, userPoolClientId } = cognitoConfig;\n const authTokens = await tokenOrchestrator.getTokenStore().loadTokens();\n assertAuthTokensWithRefreshToken(authTokens);\n if (isSessionRevocable(authTokens.accessToken)) {\n const revokeToken = createRevokeTokenClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await revokeToken({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignOut),\n }, {\n ClientId: userPoolClientId,\n Token: authTokens.refreshToken,\n });\n }\n }\n catch (err) {\n // this shouldn't throw\n logger.debug('Client signOut error caught but will proceed with token removal');\n }\n}\nasync function globalSignOut(cognitoConfig) {\n try {\n const { userPoolEndpoint, userPoolId } = cognitoConfig;\n const authTokens = await tokenOrchestrator.getTokenStore().loadTokens();\n assertAuthTokens(authTokens);\n const globalSignOutClient = createGlobalSignOutClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n await globalSignOutClient({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SignOut),\n }, {\n AccessToken: authTokens.accessToken.toString(),\n });\n }\n catch (err) {\n // it should not throw\n logger.debug('Global signOut error caught but will proceed with token removal');\n }\n}\nconst isSessionRevocable = (token) => !!token?.payload?.origin_jti;\n\nexport { signOut };\n//# sourceMappingURL=signOut.mjs.map\n","import { composeServiceApi } from '@aws-amplify/core/internals/aws-client-utils/composers';\nimport { cognitoUserPoolTransferHandler } from './shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport { createUserPoolSerializer } from './shared/serde/createUserPoolSerializer.mjs';\nimport { createUserPoolDeserializer } from './shared/serde/createUserPoolDeserializer.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '@aws-amplify/core/internals/utils';\nimport { DEFAULT_SERVICE_CLIENT_API_CONFIG } from './constants.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst createGetUserAttributeVerificationCodeClient = (config) => composeServiceApi(cognitoUserPoolTransferHandler, createUserPoolSerializer('GetUserAttributeVerificationCode'), createUserPoolDeserializer(), {\n ...DEFAULT_SERVICE_CLIENT_API_CONFIG,\n ...config,\n});\n\nexport { createGetUserAttributeVerificationCodeClient };\n//# sourceMappingURL=createGetUserAttributeVerificationCodeClient.mjs.map\n","import { Amplify, fetchAuthSession } from '@aws-amplify/core';\nimport { assertTokenProviderConfig, AuthAction } from '@aws-amplify/core/internals/utils';\nimport { assertAuthTokens } from '../utils/types.mjs';\nimport { getRegionFromUserPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { getAuthUserAgentValue } from '../../../utils/getAuthUserAgentValue.mjs';\nimport '@aws-amplify/core/internals/aws-client-utils/composers';\nimport '@aws-amplify/core/internals/aws-client-utils';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/shared/handler/cognitoUserPoolTransferHandler.mjs';\nimport '../../../foundation/factories/serviceClients/cognitoIdentityProvider/constants.mjs';\nimport '../../../common/AuthErrorStrings.mjs';\nimport '../../../errors/types/validation.mjs';\nimport '../types/errors.mjs';\nimport { createGetUserAttributeVerificationCodeClient } from '../../../foundation/factories/serviceClients/cognitoIdentityProvider/createGetUserAttributeVerificationCodeClient.mjs';\nimport { createCognitoUserPoolEndpointResolver } from '../factories/createCognitoUserPoolEndpointResolver.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Resends user's confirmation code when updating attributes while authenticated.\n *\n * @param input - The SendUserAttributeVerificationCodeInput object\n * @returns SendUserAttributeVerificationCodeOutput\n * @throws - {@link GetUserAttributeVerificationException}\n * @throws AuthTokenConfigException - Thrown when the token provider config is invalid.\n */\nconst sendUserAttributeVerificationCode = async (input) => {\n const { userAttributeKey, options } = input;\n const authConfig = Amplify.getConfig().Auth?.Cognito;\n const clientMetadata = options?.clientMetadata;\n assertTokenProviderConfig(authConfig);\n const { userPoolEndpoint, userPoolId } = authConfig;\n const { tokens } = await fetchAuthSession({ forceRefresh: false });\n assertAuthTokens(tokens);\n const getUserAttributeVerificationCode = createGetUserAttributeVerificationCodeClient({\n endpointResolver: createCognitoUserPoolEndpointResolver({\n endpointOverride: userPoolEndpoint,\n }),\n });\n const { CodeDeliveryDetails } = await getUserAttributeVerificationCode({\n region: getRegionFromUserPoolId(userPoolId),\n userAgentValue: getAuthUserAgentValue(AuthAction.SendUserAttributeVerificationCode),\n }, {\n AccessToken: tokens.accessToken.toString(),\n ClientMetadata: clientMetadata,\n AttributeName: userAttributeKey,\n });\n const { DeliveryMedium, AttributeName, Destination } = {\n ...CodeDeliveryDetails,\n };\n return {\n destination: Destination,\n deliveryMedium: DeliveryMedium,\n attributeName: AttributeName,\n };\n};\n\nexport { sendUserAttributeVerificationCode };\n//# sourceMappingURL=sendUserAttributeVerificationCode.mjs.map\n","// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst IdentityIdStorageKeys = {\n identityId: 'identityId',\n};\n\nexport { IdentityIdStorageKeys };\n//# sourceMappingURL=types.mjs.map\n","import { ConsoleLogger } from '@aws-amplify/core';\nimport { assertIdentityPoolIdConfig } from '@aws-amplify/core/internals/utils';\nimport { getAuthStorageKeys } from '../tokenProvider/TokenStore.mjs';\nimport { IdentityIdStorageKeys } from './types.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('DefaultIdentityIdStore');\nclass DefaultIdentityIdStore {\n setAuthConfig(authConfigParam) {\n assertIdentityPoolIdConfig(authConfigParam.Cognito);\n this.authConfig = authConfigParam;\n this._authKeys = createKeysForAuthStorage('Cognito', authConfigParam.Cognito.identityPoolId);\n }\n constructor(keyValueStorage) {\n this._authKeys = {};\n this._hasGuestIdentityId = false;\n this.keyValueStorage = keyValueStorage;\n }\n async loadIdentityId() {\n assertIdentityPoolIdConfig(this.authConfig?.Cognito);\n try {\n if (this._primaryIdentityId) {\n return {\n id: this._primaryIdentityId,\n type: 'primary',\n };\n }\n else {\n const storedIdentityId = await this.keyValueStorage.getItem(this._authKeys.identityId);\n if (storedIdentityId) {\n this._hasGuestIdentityId = true;\n return {\n id: storedIdentityId,\n type: 'guest',\n };\n }\n return null;\n }\n }\n catch (err) {\n logger.log('Error getting stored IdentityId.', err);\n return null;\n }\n }\n async storeIdentityId(identity) {\n assertIdentityPoolIdConfig(this.authConfig?.Cognito);\n if (identity.type === 'guest') {\n this.keyValueStorage.setItem(this._authKeys.identityId, identity.id);\n // Clear in-memory storage of primary identityId\n this._primaryIdentityId = undefined;\n this._hasGuestIdentityId = true;\n }\n else {\n this._primaryIdentityId = identity.id;\n // Clear locally stored guest id\n if (this._hasGuestIdentityId) {\n this.keyValueStorage.removeItem(this._authKeys.identityId);\n this._hasGuestIdentityId = false;\n }\n }\n }\n async clearIdentityId() {\n this._primaryIdentityId = undefined;\n await this.keyValueStorage.removeItem(this._authKeys.identityId);\n }\n}\nconst createKeysForAuthStorage = (provider, identifier) => {\n return getAuthStorageKeys(IdentityIdStorageKeys)(`com.amplify.${provider}`, identifier);\n};\n\nexport { DefaultIdentityIdStore };\n//# sourceMappingURL=IdentityIdStore.mjs.map\n","import { decodeJWT } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nfunction formLoginsMap(idToken) {\n const issuer = decodeJWT(idToken).payload.iss;\n const res = {};\n if (!issuer) {\n throw new AuthError({\n name: 'InvalidIdTokenException',\n message: 'Invalid Idtoken.',\n });\n }\n const domainName = issuer.replace(/(^\\w+:|^)\\/\\//, '');\n res[domainName] = idToken;\n return res;\n}\n\nexport { formLoginsMap };\n//# sourceMappingURL=utils.mjs.map\n","import { ConsoleLogger, getId } from '@aws-amplify/core';\nimport { AuthError } from '../../../errors/AuthError.mjs';\nimport { getRegionFromIdentityPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { formLoginsMap } from './utils.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('CognitoIdentityIdProvider');\n/**\n * Provides a Cognito identityId\n *\n * @param tokens - The AuthTokens received after SignIn\n * @returns string\n * @throws configuration exceptions: `InvalidIdentityPoolIdException`\n * - Auth errors that may arise from misconfiguration.\n * @throws service exceptions: {@link GetIdException }\n */\nasync function cognitoIdentityIdProvider({ tokens, authConfig, identityIdStore, }) {\n identityIdStore.setAuthConfig({ Cognito: authConfig });\n // will return null only if there is no identityId cached or if there is an error retrieving it\n let identityId = await identityIdStore.loadIdentityId();\n // Tokens are available so return primary identityId\n if (tokens) {\n // If there is existing primary identityId in-memory return that\n if (identityId && identityId.type === 'primary') {\n return identityId.id;\n }\n else {\n const logins = tokens.idToken\n ? formLoginsMap(tokens.idToken.toString())\n : {};\n const generatedIdentityId = await generateIdentityId(logins, authConfig);\n if (identityId && identityId.id === generatedIdentityId) {\n logger.debug(`The guest identity ${identityId.id} has become the primary identity.`);\n }\n identityId = {\n id: generatedIdentityId,\n type: 'primary',\n };\n }\n }\n else {\n // If there is existing guest identityId cached return that\n if (identityId && identityId.type === 'guest') {\n return identityId.id;\n }\n else {\n identityId = {\n id: await generateIdentityId({}, authConfig),\n type: 'guest',\n };\n }\n }\n // Store in-memory or local storage depending on guest or primary identityId\n identityIdStore.storeIdentityId(identityId);\n return identityId.id;\n}\nasync function generateIdentityId(logins, authConfig) {\n const identityPoolId = authConfig?.identityPoolId;\n const region = getRegionFromIdentityPoolId(identityPoolId);\n // IdentityId is absent so get it using IdentityPoolId with Cognito's GetId API\n const idResult = \n // for a first-time user, this will return a brand new identity\n // for a returning user, this will retrieve the previous identity assocaited with the logins\n (await getId({\n region,\n }, {\n IdentityPoolId: identityPoolId,\n Logins: logins,\n })).IdentityId;\n if (!idResult) {\n throw new AuthError({\n name: 'GetIdResponseException',\n message: 'Received undefined response from getId operation',\n recoverySuggestion: 'Make sure to pass a valid identityPoolId in the configuration.',\n });\n }\n return idResult;\n}\n\nexport { cognitoIdentityIdProvider };\n//# sourceMappingURL=IdentityIdProvider.mjs.map\n","import { ConsoleLogger, getCredentialsForIdentity } from '@aws-amplify/core';\nimport { assertIdentityPoolIdConfig } from '@aws-amplify/core/internals/utils';\nimport { AuthError } from '../../../errors/AuthError.mjs';\nimport { getRegionFromIdentityPoolId } from '../../../foundation/parsers/regionParsers.mjs';\nimport { assertIdTokenInAuthTokens } from '../utils/types.mjs';\nimport { cognitoIdentityIdProvider } from './IdentityIdProvider.mjs';\nimport { formLoginsMap } from './utils.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst logger = new ConsoleLogger('CognitoCredentialsProvider');\nconst CREDENTIALS_TTL = 50 * 60 * 1000; // 50 min, can be modified on config if required in the future\nclass CognitoAWSCredentialsAndIdentityIdProvider {\n constructor(identityIdStore) {\n this._nextCredentialsRefresh = 0;\n this._identityIdStore = identityIdStore;\n }\n async clearCredentialsAndIdentityId() {\n logger.debug('Clearing out credentials and identityId');\n this._credentialsAndIdentityId = undefined;\n await this._identityIdStore.clearIdentityId();\n }\n async clearCredentials() {\n logger.debug('Clearing out in-memory credentials');\n this._credentialsAndIdentityId = undefined;\n }\n async getCredentialsAndIdentityId(getCredentialsOptions) {\n const isAuthenticated = getCredentialsOptions.authenticated;\n const { tokens } = getCredentialsOptions;\n const { authConfig } = getCredentialsOptions;\n try {\n assertIdentityPoolIdConfig(authConfig?.Cognito);\n }\n catch {\n // No identity pool configured, skipping\n return;\n }\n if (!isAuthenticated && !authConfig.Cognito.allowGuestAccess) {\n // TODO(V6): return partial result like Native platforms\n return;\n }\n const { forceRefresh } = getCredentialsOptions;\n const tokenHasChanged = this.hasTokenChanged(tokens);\n const identityId = await cognitoIdentityIdProvider({\n tokens,\n authConfig: authConfig.Cognito,\n identityIdStore: this._identityIdStore,\n });\n // Clear cached credentials when forceRefresh is true OR the cache token has changed\n if (forceRefresh || tokenHasChanged) {\n this.clearCredentials();\n }\n if (!isAuthenticated) {\n return this.getGuestCredentials(identityId, authConfig.Cognito);\n }\n else {\n assertIdTokenInAuthTokens(tokens);\n return this.credsForOIDCTokens(authConfig.Cognito, tokens, identityId);\n }\n }\n async getGuestCredentials(identityId, authConfig) {\n // Return existing in-memory cached credentials only if it exists, is not past it's lifetime and is unauthenticated credentials\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === false) {\n logger.info('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any authenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const region = getRegionFromIdentityPoolId(authConfig.identityPoolId);\n // use identityId to obtain guest credentials\n // save credentials in-memory\n // No logins params should be passed for guest creds:\n // https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html\n const clientResult = await getCredentialsForIdentity({ region }, {\n IdentityId: identityId,\n });\n if (clientResult.Credentials &&\n clientResult.Credentials.AccessKeyId &&\n clientResult.Credentials.SecretKey) {\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n const identityIdRes = clientResult.IdentityId;\n if (identityIdRes) {\n res.identityId = identityIdRes;\n this._identityIdStore.storeIdentityId({\n id: identityIdRes,\n type: 'guest',\n });\n }\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: false,\n };\n return res;\n }\n else {\n throw new AuthError({\n name: 'CredentialsNotFoundException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n async credsForOIDCTokens(authConfig, authTokens, identityId) {\n if (this._credentialsAndIdentityId &&\n !this.isPastTTL() &&\n this._credentialsAndIdentityId.isAuthenticatedCreds === true) {\n logger.debug('returning stored credentials as they neither past TTL nor expired.');\n return this._credentialsAndIdentityId;\n }\n // Clear to discard if any unauthenticated credentials are set and start with a clean slate\n this.clearCredentials();\n const logins = authTokens.idToken\n ? formLoginsMap(authTokens.idToken.toString())\n : {};\n const region = getRegionFromIdentityPoolId(authConfig.identityPoolId);\n const clientResult = await getCredentialsForIdentity({ region }, {\n IdentityId: identityId,\n Logins: logins,\n });\n if (clientResult.Credentials &&\n clientResult.Credentials.AccessKeyId &&\n clientResult.Credentials.SecretKey) {\n const res = {\n credentials: {\n accessKeyId: clientResult.Credentials.AccessKeyId,\n secretAccessKey: clientResult.Credentials.SecretKey,\n sessionToken: clientResult.Credentials.SessionToken,\n expiration: clientResult.Credentials.Expiration,\n },\n identityId,\n };\n // Store the credentials in-memory along with the expiration\n this._credentialsAndIdentityId = {\n ...res,\n isAuthenticatedCreds: true,\n associatedIdToken: authTokens.idToken?.toString(),\n };\n this._nextCredentialsRefresh = new Date().getTime() + CREDENTIALS_TTL;\n const identityIdRes = clientResult.IdentityId;\n if (identityIdRes) {\n res.identityId = identityIdRes;\n this._identityIdStore.storeIdentityId({\n id: identityIdRes,\n type: 'primary',\n });\n }\n return res;\n }\n else {\n throw new AuthError({\n name: 'CredentialsException',\n message: `Cognito did not respond with either Credentials, AccessKeyId or SecretKey.`,\n });\n }\n }\n isPastTTL() {\n return this._nextCredentialsRefresh === undefined\n ? true\n : this._nextCredentialsRefresh <= Date.now();\n }\n hasTokenChanged(tokens) {\n return (!!tokens &&\n !!this._credentialsAndIdentityId?.associatedIdToken &&\n tokens.idToken?.toString() !==\n this._credentialsAndIdentityId.associatedIdToken);\n }\n}\n\nexport { CognitoAWSCredentialsAndIdentityIdProvider };\n//# sourceMappingURL=credentialsProvider.mjs.map\n","import { defaultStorage } from '@aws-amplify/core';\nimport { DefaultIdentityIdStore } from './IdentityIdStore.mjs';\nimport { CognitoAWSCredentialsAndIdentityIdProvider } from './credentialsProvider.mjs';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n/**\n * Cognito specific implmentation of the CredentialsProvider interface\n * that manages setting and getting of AWS Credentials.\n *\n * @throws configuration expections: `InvalidIdentityPoolIdException`\n * - Auth errors that may arise from misconfiguration.\n * @throws service expections: {@link GetCredentialsForIdentityException}, {@link GetIdException}\n *\n */\nconst cognitoCredentialsProvider = new CognitoAWSCredentialsAndIdentityIdProvider(new DefaultIdentityIdStore(defaultStorage));\n\nexport { CognitoAWSCredentialsAndIdentityIdProvider, DefaultIdentityIdStore, cognitoCredentialsProvider };\n//# sourceMappingURL=index.mjs.map\n","import { Amplify, CookieStorage, defaultStorage } from '@aws-amplify/core';\nimport { parseAmplifyConfig } from '@aws-amplify/core/internals/utils';\nimport { cognitoUserPoolsTokenProvider, cognitoCredentialsProvider } from '@aws-amplify/auth/cognito';\n\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nconst DefaultAmplify = {\n /**\n * Configures Amplify with the {@link resourceConfig} and {@link libraryOptions}.\n *\n * @param resourceConfig The {@link ResourcesConfig} object that is typically imported from the\n * `amplifyconfiguration.json` file. It can also be an object literal created inline when calling `Amplify.configure`.\n * @param libraryOptions The {@link LibraryOptions} additional options for the library.\n *\n * @example\n * import config from './amplifyconfiguration.json';\n *\n * Amplify.configure(config);\n */\n configure(resourceConfig, libraryOptions) {\n const resolvedResourceConfig = parseAmplifyConfig(resourceConfig);\n // If no Auth config is provided, no special handling will be required, configure as is.\n // Otherwise, we can assume an Auth config is provided from here on.\n if (!resolvedResourceConfig.Auth) {\n Amplify.configure(resolvedResourceConfig, libraryOptions);\n return;\n }\n // If Auth options are provided, always just configure as is.\n // Otherwise, we can assume no Auth libraryOptions were provided from here on.\n if (libraryOptions?.Auth) {\n Amplify.configure(resolvedResourceConfig, libraryOptions);\n return;\n }\n // If no Auth libraryOptions were previously configured, then always add default providers.\n if (!Amplify.libraryOptions.Auth) {\n cognitoUserPoolsTokenProvider.setAuthConfig(resolvedResourceConfig.Auth);\n cognitoUserPoolsTokenProvider.setKeyValueStorage(\n // TODO: allow configure with a public interface\n libraryOptions?.ssr\n ? new CookieStorage({ sameSite: 'lax' })\n : defaultStorage);\n Amplify.configure(resolvedResourceConfig, {\n ...libraryOptions,\n Auth: {\n tokenProvider: cognitoUserPoolsTokenProvider,\n credentialsProvider: cognitoCredentialsProvider,\n },\n });\n return;\n }\n // At this point, Auth libraryOptions would have been previously configured and no overriding\n // Auth options were given, so we should preserve the currently configured Auth libraryOptions.\n if (libraryOptions) {\n // If ssr is provided through libraryOptions, we should respect the intentional reconfiguration.\n if (libraryOptions.ssr !== undefined) {\n cognitoUserPoolsTokenProvider.setKeyValueStorage(\n // TODO: allow configure with a public interface\n libraryOptions.ssr\n ? new CookieStorage({ sameSite: 'lax' })\n : defaultStorage);\n }\n Amplify.configure(resolvedResourceConfig, {\n Auth: Amplify.libraryOptions.Auth,\n ...libraryOptions,\n });\n return;\n }\n // Finally, if there were no libraryOptions given at all, we should simply not touch the currently\n // configured libraryOptions.\n Amplify.configure(resolvedResourceConfig);\n },\n /**\n * Returns the {@link ResourcesConfig} object passed in as the `resourceConfig` parameter when calling\n * `Amplify.configure`.\n *\n * @returns An {@link ResourcesConfig} object.\n */\n getConfig() {\n return Amplify.getConfig();\n },\n};\n\nexport { DefaultAmplify };\n//# sourceMappingURL=initSingleton.mjs.map\n","/**\n * @license React\n * scheduler.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';function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","/**\n * @license React\n * react-dom.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/*\n Modernizr 3.0.0pre (Custom Build) | MIT\n*/\n'use strict';var aa=require(\"react\"),ca=require(\"scheduler\");function p(a){for(var b=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+a,c=1;cb}return!1}function v(a,b,c,d,e,f,g){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f;this.removeEmptyString=g}var z={};\n\"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style\".split(\" \").forEach(function(a){z[a]=new v(a,0,!1,a,null,!1,!1)});[[\"acceptCharset\",\"accept-charset\"],[\"className\",\"class\"],[\"htmlFor\",\"for\"],[\"httpEquiv\",\"http-equiv\"]].forEach(function(a){var b=a[0];z[b]=new v(b,1,!1,a[1],null,!1,!1)});[\"contentEditable\",\"draggable\",\"spellCheck\",\"value\"].forEach(function(a){z[a]=new v(a,2,!1,a.toLowerCase(),null,!1,!1)});\n[\"autoReverse\",\"externalResourcesRequired\",\"focusable\",\"preserveAlpha\"].forEach(function(a){z[a]=new v(a,2,!1,a,null,!1,!1)});\"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope\".split(\" \").forEach(function(a){z[a]=new v(a,3,!1,a.toLowerCase(),null,!1,!1)});\n[\"checked\",\"multiple\",\"muted\",\"selected\"].forEach(function(a){z[a]=new v(a,3,!0,a,null,!1,!1)});[\"capture\",\"download\"].forEach(function(a){z[a]=new v(a,4,!1,a,null,!1,!1)});[\"cols\",\"rows\",\"size\",\"span\"].forEach(function(a){z[a]=new v(a,6,!1,a,null,!1,!1)});[\"rowSpan\",\"start\"].forEach(function(a){z[a]=new v(a,5,!1,a.toLowerCase(),null,!1,!1)});var ra=/[\\-:]([a-z])/g;function sa(a){return a[1].toUpperCase()}\n\"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height\".split(\" \").forEach(function(a){var b=a.replace(ra,\nsa);z[b]=new v(b,1,!1,a,null,!1,!1)});\"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type\".split(\" \").forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/1999/xlink\",!1,!1)});[\"xml:base\",\"xml:lang\",\"xml:space\"].forEach(function(a){var b=a.replace(ra,sa);z[b]=new v(b,1,!1,a,\"http://www.w3.org/XML/1998/namespace\",!1,!1)});[\"tabIndex\",\"crossOrigin\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!1,!1)});\nz.xlinkHref=new v(\"xlinkHref\",1,!1,\"xlink:href\",\"http://www.w3.org/1999/xlink\",!0,!1);[\"src\",\"href\",\"action\",\"formAction\"].forEach(function(a){z[a]=new v(a,1,!1,a.toLowerCase(),null,!0,!0)});\nfunction ta(a,b,c,d){var e=z.hasOwnProperty(b)?z[b]:null;if(null!==e?0!==e.type:d||!(2h||e[g]!==f[h]){var k=\"\\n\"+e[g].replace(\" at new \",\" at \");a.displayName&&k.includes(\"\")&&(k=k.replace(\"\",a.displayName));return k}while(1<=g&&0<=h)}break}}}finally{Na=!1,Error.prepareStackTrace=c}return(a=a?a.displayName||a.name:\"\")?Ma(a):\"\"}\nfunction Pa(a){switch(a.tag){case 5:return Ma(a.type);case 16:return Ma(\"Lazy\");case 13:return Ma(\"Suspense\");case 19:return Ma(\"SuspenseList\");case 0:case 2:case 15:return a=Oa(a.type,!1),a;case 11:return a=Oa(a.type.render,!1),a;case 1:return a=Oa(a.type,!0),a;default:return\"\"}}\nfunction Qa(a){if(null==a)return null;if(\"function\"===typeof a)return a.displayName||a.name||null;if(\"string\"===typeof a)return a;switch(a){case ya:return\"Fragment\";case wa:return\"Portal\";case Aa:return\"Profiler\";case za:return\"StrictMode\";case Ea:return\"Suspense\";case Fa:return\"SuspenseList\"}if(\"object\"===typeof a)switch(a.$$typeof){case Ca:return(a.displayName||\"Context\")+\".Consumer\";case Ba:return(a._context.displayName||\"Context\")+\".Provider\";case Da:var b=a.render;a=a.displayName;a||(a=b.displayName||\nb.name||\"\",a=\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");return a;case Ga:return b=a.displayName||null,null!==b?b:Qa(a.type)||\"Memo\";case Ha:b=a._payload;a=a._init;try{return Qa(a(b))}catch(c){}}return null}\nfunction Ra(a){var b=a.type;switch(a.tag){case 24:return\"Cache\";case 9:return(b.displayName||\"Context\")+\".Consumer\";case 10:return(b._context.displayName||\"Context\")+\".Provider\";case 18:return\"DehydratedFragment\";case 11:return a=b.render,a=a.displayName||a.name||\"\",b.displayName||(\"\"!==a?\"ForwardRef(\"+a+\")\":\"ForwardRef\");case 7:return\"Fragment\";case 5:return b;case 4:return\"Portal\";case 3:return\"Root\";case 6:return\"Text\";case 16:return Qa(b);case 8:return b===za?\"StrictMode\":\"Mode\";case 22:return\"Offscreen\";\ncase 12:return\"Profiler\";case 21:return\"Scope\";case 13:return\"Suspense\";case 19:return\"SuspenseList\";case 25:return\"TracingMarker\";case 1:case 0:case 17:case 2:case 14:case 15:if(\"function\"===typeof b)return b.displayName||b.name||null;if(\"string\"===typeof b)return b}return null}function Sa(a){switch(typeof a){case \"boolean\":case \"number\":case \"string\":case \"undefined\":return a;case \"object\":return a;default:return\"\"}}\nfunction Ta(a){var b=a.type;return(a=a.nodeName)&&\"input\"===a.toLowerCase()&&(\"checkbox\"===b||\"radio\"===b)}\nfunction Ua(a){var b=Ta(a)?\"checked\":\"value\",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=\"\"+a[b];if(!a.hasOwnProperty(b)&&\"undefined\"!==typeof c&&\"function\"===typeof c.get&&\"function\"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=\"\"+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=\"\"+a},stopTracking:function(){a._valueTracker=\nnull;delete a[b]}}}}function Va(a){a._valueTracker||(a._valueTracker=Ua(a))}function Wa(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d=\"\";a&&(d=Ta(a)?a.checked?\"true\":\"false\":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function Xa(a){a=a||(\"undefined\"!==typeof document?document:void 0);if(\"undefined\"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}\nfunction Ya(a,b){var c=b.checked;return A({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}function Za(a,b){var c=null==b.defaultValue?\"\":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=Sa(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:\"checkbox\"===b.type||\"radio\"===b.type?null!=b.checked:null!=b.value}}function ab(a,b){b=b.checked;null!=b&&ta(a,\"checked\",b,!1)}\nfunction bb(a,b){ab(a,b);var c=Sa(b.value),d=b.type;if(null!=c)if(\"number\"===d){if(0===c&&\"\"===a.value||a.value!=c)a.value=\"\"+c}else a.value!==\"\"+c&&(a.value=\"\"+c);else if(\"submit\"===d||\"reset\"===d){a.removeAttribute(\"value\");return}b.hasOwnProperty(\"value\")?cb(a,b.type,c):b.hasOwnProperty(\"defaultValue\")&&cb(a,b.type,Sa(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}\nfunction db(a,b,c){if(b.hasOwnProperty(\"value\")||b.hasOwnProperty(\"defaultValue\")){var d=b.type;if(!(\"submit\"!==d&&\"reset\"!==d||void 0!==b.value&&null!==b.value))return;b=\"\"+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;\"\"!==c&&(a.name=\"\");a.defaultChecked=!!a._wrapperState.initialChecked;\"\"!==c&&(a.name=c)}\nfunction cb(a,b,c){if(\"number\"!==b||Xa(a.ownerDocument)!==a)null==c?a.defaultValue=\"\"+a._wrapperState.initialValue:a.defaultValue!==\"\"+c&&(a.defaultValue=\"\"+c)}var eb=Array.isArray;\nfunction fb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e\"+b.valueOf().toString()+\"\";for(b=mb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});\nfunction ob(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}\nvar pb={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,\nzoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},qb=[\"Webkit\",\"ms\",\"Moz\",\"O\"];Object.keys(pb).forEach(function(a){qb.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);pb[b]=pb[a]})});function rb(a,b,c){return null==b||\"boolean\"===typeof b||\"\"===b?\"\":c||\"number\"!==typeof b||0===b||pb.hasOwnProperty(a)&&pb[a]?(\"\"+b).trim():b+\"px\"}\nfunction sb(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf(\"--\"),e=rb(c,b[c],d);\"float\"===c&&(c=\"cssFloat\");d?a.setProperty(c,e):a[c]=e}}var tb=A({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});\nfunction ub(a,b){if(b){if(tb[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(p(137,a));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(p(60));if(\"object\"!==typeof b.dangerouslySetInnerHTML||!(\"__html\"in b.dangerouslySetInnerHTML))throw Error(p(61));}if(null!=b.style&&\"object\"!==typeof b.style)throw Error(p(62));}}\nfunction vb(a,b){if(-1===a.indexOf(\"-\"))return\"string\"===typeof b.is;switch(a){case \"annotation-xml\":case \"color-profile\":case \"font-face\":case \"font-face-src\":case \"font-face-uri\":case \"font-face-format\":case \"font-face-name\":case \"missing-glyph\":return!1;default:return!0}}var wb=null;function xb(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}var yb=null,zb=null,Ab=null;\nfunction Bb(a){if(a=Cb(a)){if(\"function\"!==typeof yb)throw Error(p(280));var b=a.stateNode;b&&(b=Db(b),yb(a.stateNode,a.type,b))}}function Eb(a){zb?Ab?Ab.push(a):Ab=[a]:zb=a}function Fb(){if(zb){var a=zb,b=Ab;Ab=zb=null;Bb(a);if(b)for(a=0;a>>=0;return 0===a?32:31-(pc(a)/qc|0)|0}var rc=64,sc=4194304;\nfunction tc(a){switch(a&-a){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return a&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return a&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;\ndefault:return a}}function uc(a,b){var c=a.pendingLanes;if(0===c)return 0;var d=0,e=a.suspendedLanes,f=a.pingedLanes,g=c&268435455;if(0!==g){var h=g&~e;0!==h?d=tc(h):(f&=g,0!==f&&(d=tc(f)))}else g=c&~e,0!==g?d=tc(g):0!==f&&(d=tc(f));if(0===d)return 0;if(0!==b&&b!==d&&0===(b&e)&&(e=d&-d,f=b&-b,e>=f||16===e&&0!==(f&4194240)))return b;0!==(d&4)&&(d|=c&16);b=a.entangledLanes;if(0!==b)for(a=a.entanglements,b&=d;0c;c++)b.push(a);return b}\nfunction Ac(a,b,c){a.pendingLanes|=b;536870912!==b&&(a.suspendedLanes=0,a.pingedLanes=0);a=a.eventTimes;b=31-oc(b);a[b]=c}function Bc(a,b){var c=a.pendingLanes&~b;a.pendingLanes=b;a.suspendedLanes=0;a.pingedLanes=0;a.expiredLanes&=b;a.mutableReadLanes&=b;a.entangledLanes&=b;b=a.entanglements;var d=a.eventTimes;for(a=a.expirationTimes;0=be),ee=String.fromCharCode(32),fe=!1;\nfunction ge(a,b){switch(a){case \"keyup\":return-1!==$d.indexOf(b.keyCode);case \"keydown\":return 229!==b.keyCode;case \"keypress\":case \"mousedown\":case \"focusout\":return!0;default:return!1}}function he(a){a=a.detail;return\"object\"===typeof a&&\"data\"in a?a.data:null}var ie=!1;function je(a,b){switch(a){case \"compositionend\":return he(b);case \"keypress\":if(32!==b.which)return null;fe=!0;return ee;case \"textInput\":return a=b.data,a===ee&&fe?null:a;default:return null}}\nfunction ke(a,b){if(ie)return\"compositionend\"===a||!ae&&ge(a,b)?(a=nd(),md=ld=kd=null,ie=!1,a):null;switch(a){case \"paste\":return null;case \"keypress\":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=Je(c)}}function Le(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?Le(a,b.parentNode):\"contains\"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}\nfunction Me(){for(var a=window,b=Xa();b instanceof a.HTMLIFrameElement;){try{var c=\"string\"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=Xa(a.document)}return b}function Ne(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&(\"input\"===b&&(\"text\"===a.type||\"search\"===a.type||\"tel\"===a.type||\"url\"===a.type||\"password\"===a.type)||\"textarea\"===b||\"true\"===a.contentEditable)}\nfunction Oe(a){var b=Me(),c=a.focusedElem,d=a.selectionRange;if(b!==c&&c&&c.ownerDocument&&Le(c.ownerDocument.documentElement,c)){if(null!==d&&Ne(c))if(b=d.start,a=d.end,void 0===a&&(a=b),\"selectionStart\"in c)c.selectionStart=b,c.selectionEnd=Math.min(a,c.value.length);else if(a=(b=c.ownerDocument||document)&&b.defaultView||window,a.getSelection){a=a.getSelection();var e=c.textContent.length,f=Math.min(d.start,e);d=void 0===d.end?f:Math.min(d.end,e);!a.extend&&f>d&&(e=d,d=f,f=e);e=Ke(c,f);var g=Ke(c,\nd);e&&g&&(1!==a.rangeCount||a.anchorNode!==e.node||a.anchorOffset!==e.offset||a.focusNode!==g.node||a.focusOffset!==g.offset)&&(b=b.createRange(),b.setStart(e.node,e.offset),a.removeAllRanges(),f>d?(a.addRange(b),a.extend(g.node,g.offset)):(b.setEnd(g.node,g.offset),a.addRange(b)))}b=[];for(a=c;a=a.parentNode;)1===a.nodeType&&b.push({element:a,left:a.scrollLeft,top:a.scrollTop});\"function\"===typeof c.focus&&c.focus();for(c=0;c=document.documentMode,Qe=null,Re=null,Se=null,Te=!1;\nfunction Ue(a,b,c){var d=c.window===c?c.document:9===c.nodeType?c:c.ownerDocument;Te||null==Qe||Qe!==Xa(d)||(d=Qe,\"selectionStart\"in d&&Ne(d)?d={start:d.selectionStart,end:d.selectionEnd}:(d=(d.ownerDocument&&d.ownerDocument.defaultView||window).getSelection(),d={anchorNode:d.anchorNode,anchorOffset:d.anchorOffset,focusNode:d.focusNode,focusOffset:d.focusOffset}),Se&&Ie(Se,d)||(Se=d,d=oe(Re,\"onSelect\"),0Tf||(a.current=Sf[Tf],Sf[Tf]=null,Tf--)}function G(a,b){Tf++;Sf[Tf]=a.current;a.current=b}var Vf={},H=Uf(Vf),Wf=Uf(!1),Xf=Vf;function Yf(a,b){var c=a.type.contextTypes;if(!c)return Vf;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}\nfunction Zf(a){a=a.childContextTypes;return null!==a&&void 0!==a}function $f(){E(Wf);E(H)}function ag(a,b,c){if(H.current!==Vf)throw Error(p(168));G(H,b);G(Wf,c)}function bg(a,b,c){var d=a.stateNode;b=b.childContextTypes;if(\"function\"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in b))throw Error(p(108,Ra(a)||\"Unknown\",e));return A({},c,d)}\nfunction cg(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Vf;Xf=H.current;G(H,a);G(Wf,Wf.current);return!0}function dg(a,b,c){var d=a.stateNode;if(!d)throw Error(p(169));c?(a=bg(a,b,Xf),d.__reactInternalMemoizedMergedChildContext=a,E(Wf),E(H),G(H,a)):E(Wf);G(Wf,c)}var eg=null,fg=!1,gg=!1;function hg(a){null===eg?eg=[a]:eg.push(a)}function ig(a){fg=!0;hg(a)}\nfunction jg(){if(!gg&&null!==eg){gg=!0;var a=0,b=C;try{var c=eg;for(C=1;a>=g;e-=g;rg=1<<32-oc(b)+e|c<w?(x=u,u=null):x=u.sibling;var n=r(e,u,h[w],k);if(null===n){null===u&&(u=x);break}a&&u&&null===n.alternate&&b(e,u);g=f(n,g,w);null===m?l=n:m.sibling=n;m=n;u=x}if(w===h.length)return c(e,u),I&&tg(e,w),l;if(null===u){for(;ww?(x=m,m=null):x=m.sibling;var t=r(e,m,n.value,k);if(null===t){null===m&&(m=x);break}a&&m&&null===t.alternate&&b(e,m);g=f(t,g,w);null===u?l=t:u.sibling=t;u=t;m=x}if(n.done)return c(e,\nm),I&&tg(e,w),l;if(null===m){for(;!n.done;w++,n=h.next())n=q(e,n.value,k),null!==n&&(g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);I&&tg(e,w);return l}for(m=d(e,m);!n.done;w++,n=h.next())n=y(m,e,w,n.value,k),null!==n&&(a&&null!==n.alternate&&m.delete(null===n.key?w:n.key),g=f(n,g,w),null===u?l=n:u.sibling=n,u=n);a&&m.forEach(function(a){return b(e,a)});I&&tg(e,w);return l}function J(a,d,f,h){\"object\"===typeof f&&null!==f&&f.type===ya&&null===f.key&&(f=f.props.children);if(\"object\"===typeof f&&null!==f){switch(f.$$typeof){case va:a:{for(var k=\nf.key,l=d;null!==l;){if(l.key===k){k=f.type;if(k===ya){if(7===l.tag){c(a,l.sibling);d=e(l,f.props.children);d.return=a;a=d;break a}}else if(l.elementType===k||\"object\"===typeof k&&null!==k&&k.$$typeof===Ha&&Ng(k)===l.type){c(a,l.sibling);d=e(l,f.props);d.ref=Lg(a,l,f);d.return=a;a=d;break a}c(a,l);break}else b(a,l);l=l.sibling}f.type===ya?(d=Tg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Rg(f.type,f.key,f.props,null,a.mode,h),h.ref=Lg(a,d,f),h.return=a,a=h)}return g(a);case wa:a:{for(l=f.key;null!==\nd;){if(d.key===l)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=d.sibling}d=Sg(f,a.mode,h);d.return=a;a=d}return g(a);case Ha:return l=f._init,J(a,d,l(f._payload),h)}if(eb(f))return n(a,d,f,h);if(Ka(f))return t(a,d,f,h);Mg(a,f)}return\"string\"===typeof f&&\"\"!==f||\"number\"===typeof f?(f=\"\"+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):\n(c(a,d),d=Qg(f,a.mode,h),d.return=a,a=d),g(a)):c(a,d)}return J}var Ug=Og(!0),Vg=Og(!1),Wg=Uf(null),Xg=null,Yg=null,Zg=null;function $g(){Zg=Yg=Xg=null}function ah(a){var b=Wg.current;E(Wg);a._currentValue=b}function bh(a,b,c){for(;null!==a;){var d=a.alternate;(a.childLanes&b)!==b?(a.childLanes|=b,null!==d&&(d.childLanes|=b)):null!==d&&(d.childLanes&b)!==b&&(d.childLanes|=b);if(a===c)break;a=a.return}}\nfunction ch(a,b){Xg=a;Zg=Yg=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(0!==(a.lanes&b)&&(dh=!0),a.firstContext=null)}function eh(a){var b=a._currentValue;if(Zg!==a)if(a={context:a,memoizedValue:b,next:null},null===Yg){if(null===Xg)throw Error(p(308));Yg=a;Xg.dependencies={lanes:0,firstContext:a}}else Yg=Yg.next=a;return b}var fh=null;function gh(a){null===fh?fh=[a]:fh.push(a)}\nfunction hh(a,b,c,d){var e=b.interleaved;null===e?(c.next=c,gh(b)):(c.next=e.next,e.next=c);b.interleaved=c;return ih(a,d)}function ih(a,b){a.lanes|=b;var c=a.alternate;null!==c&&(c.lanes|=b);c=a;for(a=a.return;null!==a;)a.childLanes|=b,c=a.alternate,null!==c&&(c.childLanes|=b),c=a,a=a.return;return 3===c.tag?c.stateNode:null}var jh=!1;function kh(a){a.updateQueue={baseState:a.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}\nfunction lh(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,firstBaseUpdate:a.firstBaseUpdate,lastBaseUpdate:a.lastBaseUpdate,shared:a.shared,effects:a.effects})}function mh(a,b){return{eventTime:a,lane:b,tag:0,payload:null,callback:null,next:null}}\nfunction nh(a,b,c){var d=a.updateQueue;if(null===d)return null;d=d.shared;if(0!==(K&2)){var e=d.pending;null===e?b.next=b:(b.next=e.next,e.next=b);d.pending=b;return ih(a,c)}e=d.interleaved;null===e?(b.next=b,gh(d)):(b.next=e.next,e.next=b);d.interleaved=b;return ih(a,c)}function oh(a,b,c){b=b.updateQueue;if(null!==b&&(b=b.shared,0!==(c&4194240))){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nfunction ph(a,b){var c=a.updateQueue,d=a.alternate;if(null!==d&&(d=d.updateQueue,c===d)){var e=null,f=null;c=c.firstBaseUpdate;if(null!==c){do{var g={eventTime:c.eventTime,lane:c.lane,tag:c.tag,payload:c.payload,callback:c.callback,next:null};null===f?e=f=g:f=f.next=g;c=c.next}while(null!==c);null===f?e=f=b:f=f.next=b}else e=f=b;c={baseState:d.baseState,firstBaseUpdate:e,lastBaseUpdate:f,shared:d.shared,effects:d.effects};a.updateQueue=c;return}a=c.lastBaseUpdate;null===a?c.firstBaseUpdate=b:a.next=\nb;c.lastBaseUpdate=b}\nfunction qh(a,b,c,d){var e=a.updateQueue;jh=!1;var f=e.firstBaseUpdate,g=e.lastBaseUpdate,h=e.shared.pending;if(null!==h){e.shared.pending=null;var k=h,l=k.next;k.next=null;null===g?f=l:g.next=l;g=k;var m=a.alternate;null!==m&&(m=m.updateQueue,h=m.lastBaseUpdate,h!==g&&(null===h?m.firstBaseUpdate=l:h.next=l,m.lastBaseUpdate=k))}if(null!==f){var q=e.baseState;g=0;m=l=k=null;h=f;do{var r=h.lane,y=h.eventTime;if((d&r)===r){null!==m&&(m=m.next={eventTime:y,lane:0,tag:h.tag,payload:h.payload,callback:h.callback,\nnext:null});a:{var n=a,t=h;r=b;y=c;switch(t.tag){case 1:n=t.payload;if(\"function\"===typeof n){q=n.call(y,q,r);break a}q=n;break a;case 3:n.flags=n.flags&-65537|128;case 0:n=t.payload;r=\"function\"===typeof n?n.call(y,q,r):n;if(null===r||void 0===r)break a;q=A({},q,r);break a;case 2:jh=!0}}null!==h.callback&&0!==h.lane&&(a.flags|=64,r=e.effects,null===r?e.effects=[h]:r.push(h))}else y={eventTime:y,lane:r,tag:h.tag,payload:h.payload,callback:h.callback,next:null},null===m?(l=m=y,k=q):m=m.next=y,g|=r;\nh=h.next;if(null===h)if(h=e.shared.pending,null===h)break;else r=h,h=r.next,r.next=null,e.lastBaseUpdate=r,e.shared.pending=null}while(1);null===m&&(k=q);e.baseState=k;e.firstBaseUpdate=l;e.lastBaseUpdate=m;b=e.shared.interleaved;if(null!==b){e=b;do g|=e.lane,e=e.next;while(e!==b)}else null===f&&(e.shared.lanes=0);rh|=g;a.lanes=g;a.memoizedState=q}}\nfunction sh(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;bc?c:4;a(!0);var d=Gh.transition;Gh.transition={};try{a(!1),b()}finally{C=c,Gh.transition=d}}function wi(){return Uh().memoizedState}\nfunction xi(a,b,c){var d=yi(a);c={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,c);else if(c=hh(a,b,c,d),null!==c){var e=R();gi(c,a,d,e);Bi(c,b,d)}}\nfunction ii(a,b,c){var d=yi(a),e={lane:d,action:c,hasEagerState:!1,eagerState:null,next:null};if(zi(a))Ai(b,e);else{var f=a.alternate;if(0===a.lanes&&(null===f||0===f.lanes)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.hasEagerState=!0;e.eagerState=h;if(He(h,g)){var k=b.interleaved;null===k?(e.next=e,gh(b)):(e.next=k.next,k.next=e);b.interleaved=e;return}}catch(l){}finally{}c=hh(a,b,e,d);null!==c&&(e=R(),gi(c,a,d,e),Bi(c,b,d))}}\nfunction zi(a){var b=a.alternate;return a===M||null!==b&&b===M}function Ai(a,b){Jh=Ih=!0;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}function Bi(a,b,c){if(0!==(c&4194240)){var d=b.lanes;d&=a.pendingLanes;c|=d;b.lanes=c;Cc(a,c)}}\nvar Rh={readContext:eh,useCallback:P,useContext:P,useEffect:P,useImperativeHandle:P,useInsertionEffect:P,useLayoutEffect:P,useMemo:P,useReducer:P,useRef:P,useState:P,useDebugValue:P,useDeferredValue:P,useTransition:P,useMutableSource:P,useSyncExternalStore:P,useId:P,unstable_isNewReconciler:!1},Oh={readContext:eh,useCallback:function(a,b){Th().memoizedState=[a,void 0===b?null:b];return a},useContext:eh,useEffect:mi,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return ki(4194308,\n4,pi.bind(null,b,a),c)},useLayoutEffect:function(a,b){return ki(4194308,4,a,b)},useInsertionEffect:function(a,b){return ki(4,2,a,b)},useMemo:function(a,b){var c=Th();b=void 0===b?null:b;a=a();c.memoizedState=[a,b];return a},useReducer:function(a,b,c){var d=Th();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};d.queue=a;a=a.dispatch=xi.bind(null,M,a);return[d.memoizedState,a]},useRef:function(a){var b=\nTh();a={current:a};return b.memoizedState=a},useState:hi,useDebugValue:ri,useDeferredValue:function(a){return Th().memoizedState=a},useTransition:function(){var a=hi(!1),b=a[0];a=vi.bind(null,a[1]);Th().memoizedState=a;return[b,a]},useMutableSource:function(){},useSyncExternalStore:function(a,b,c){var d=M,e=Th();if(I){if(void 0===c)throw Error(p(407));c=c()}else{c=b();if(null===Q)throw Error(p(349));0!==(Hh&30)||di(d,b,c)}e.memoizedState=c;var f={value:c,getSnapshot:b};e.queue=f;mi(ai.bind(null,d,\nf,a),[a]);d.flags|=2048;bi(9,ci.bind(null,d,f,c,b),void 0,null);return c},useId:function(){var a=Th(),b=Q.identifierPrefix;if(I){var c=sg;var d=rg;c=(d&~(1<<32-oc(d)-1)).toString(32)+c;b=\":\"+b+\"R\"+c;c=Kh++;0\\x3c/script>\",a=a.removeChild(a.firstChild)):\n\"string\"===typeof d.is?a=g.createElement(c,{is:d.is}):(a=g.createElement(c),\"select\"===c&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,c);a[Of]=b;a[Pf]=d;zj(a,b,!1,!1);b.stateNode=a;a:{g=vb(c,d);switch(c){case \"dialog\":D(\"cancel\",a);D(\"close\",a);e=d;break;case \"iframe\":case \"object\":case \"embed\":D(\"load\",a);e=d;break;case \"video\":case \"audio\":for(e=0;eGj&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304)}else{if(!d)if(a=Ch(g),null!==a){if(b.flags|=128,d=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.flags|=4),Dj(f,!0),null===f.tail&&\"hidden\"===f.tailMode&&!g.alternate&&!I)return S(b),null}else 2*B()-f.renderingStartTime>Gj&&1073741824!==c&&(b.flags|=128,d=!0,Dj(f,!1),b.lanes=4194304);f.isBackwards?(g.sibling=b.child,b.child=g):(c=f.last,null!==c?c.sibling=g:b.child=g,f.last=g)}if(null!==f.tail)return b=f.tail,f.rendering=\nb,f.tail=b.sibling,f.renderingStartTime=B(),b.sibling=null,c=L.current,G(L,d?c&1|2:c&1),b;S(b);return null;case 22:case 23:return Hj(),d=null!==b.memoizedState,null!==a&&null!==a.memoizedState!==d&&(b.flags|=8192),d&&0!==(b.mode&1)?0!==(fj&1073741824)&&(S(b),b.subtreeFlags&6&&(b.flags|=8192)):S(b),null;case 24:return null;case 25:return null}throw Error(p(156,b.tag));}\nfunction Ij(a,b){wg(b);switch(b.tag){case 1:return Zf(b.type)&&$f(),a=b.flags,a&65536?(b.flags=a&-65537|128,b):null;case 3:return zh(),E(Wf),E(H),Eh(),a=b.flags,0!==(a&65536)&&0===(a&128)?(b.flags=a&-65537|128,b):null;case 5:return Bh(b),null;case 13:E(L);a=b.memoizedState;if(null!==a&&null!==a.dehydrated){if(null===b.alternate)throw Error(p(340));Ig()}a=b.flags;return a&65536?(b.flags=a&-65537|128,b):null;case 19:return E(L),null;case 4:return zh(),null;case 10:return ah(b.type._context),null;case 22:case 23:return Hj(),\nnull;case 24:return null;default:return null}}var Jj=!1,U=!1,Kj=\"function\"===typeof WeakSet?WeakSet:Set,V=null;function Lj(a,b){var c=a.ref;if(null!==c)if(\"function\"===typeof c)try{c(null)}catch(d){W(a,b,d)}else c.current=null}function Mj(a,b,c){try{c()}catch(d){W(a,b,d)}}var Nj=!1;\nfunction Oj(a,b){Cf=dd;a=Me();if(Ne(a)){if(\"selectionStart\"in a)var c={start:a.selectionStart,end:a.selectionEnd};else a:{c=(c=a.ownerDocument)&&c.defaultView||window;var d=c.getSelection&&c.getSelection();if(d&&0!==d.rangeCount){c=d.anchorNode;var e=d.anchorOffset,f=d.focusNode;d=d.focusOffset;try{c.nodeType,f.nodeType}catch(F){c=null;break a}var g=0,h=-1,k=-1,l=0,m=0,q=a,r=null;b:for(;;){for(var y;;){q!==c||0!==e&&3!==q.nodeType||(h=g+e);q!==f||0!==d&&3!==q.nodeType||(k=g+d);3===q.nodeType&&(g+=\nq.nodeValue.length);if(null===(y=q.firstChild))break;r=q;q=y}for(;;){if(q===a)break b;r===c&&++l===e&&(h=g);r===f&&++m===d&&(k=g);if(null!==(y=q.nextSibling))break;q=r;r=q.parentNode}q=y}c=-1===h||-1===k?null:{start:h,end:k}}else c=null}c=c||{start:0,end:0}}else c=null;Df={focusedElem:a,selectionRange:c};dd=!1;for(V=b;null!==V;)if(b=V,a=b.child,0!==(b.subtreeFlags&1028)&&null!==a)a.return=b,V=a;else for(;null!==V;){b=V;try{var n=b.alternate;if(0!==(b.flags&1024))switch(b.tag){case 0:case 11:case 15:break;\ncase 1:if(null!==n){var t=n.memoizedProps,J=n.memoizedState,x=b.stateNode,w=x.getSnapshotBeforeUpdate(b.elementType===b.type?t:Ci(b.type,t),J);x.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var u=b.stateNode.containerInfo;1===u.nodeType?u.textContent=\"\":9===u.nodeType&&u.documentElement&&u.removeChild(u.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(p(163));}}catch(F){W(b,b.return,F)}a=b.sibling;if(null!==a){a.return=b.return;V=a;break}V=b.return}n=Nj;Nj=!1;return n}\nfunction Pj(a,b,c){var d=b.updateQueue;d=null!==d?d.lastEffect:null;if(null!==d){var e=d=d.next;do{if((e.tag&a)===a){var f=e.destroy;e.destroy=void 0;void 0!==f&&Mj(b,c,f)}e=e.next}while(e!==d)}}function Qj(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}function Rj(a){var b=a.ref;if(null!==b){var c=a.stateNode;switch(a.tag){case 5:a=c;break;default:a=c}\"function\"===typeof b?b(a):b.current=a}}\nfunction Sj(a){var b=a.alternate;null!==b&&(a.alternate=null,Sj(b));a.child=null;a.deletions=null;a.sibling=null;5===a.tag&&(b=a.stateNode,null!==b&&(delete b[Of],delete b[Pf],delete b[of],delete b[Qf],delete b[Rf]));a.stateNode=null;a.return=null;a.dependencies=null;a.memoizedProps=null;a.memoizedState=null;a.pendingProps=null;a.stateNode=null;a.updateQueue=null}function Tj(a){return 5===a.tag||3===a.tag||4===a.tag}\nfunction Uj(a){a:for(;;){for(;null===a.sibling;){if(null===a.return||Tj(a.return))return null;a=a.return}a.sibling.return=a.return;for(a=a.sibling;5!==a.tag&&6!==a.tag&&18!==a.tag;){if(a.flags&2)continue a;if(null===a.child||4===a.tag)continue a;else a.child.return=a,a=a.child}if(!(a.flags&2))return a.stateNode}}\nfunction Vj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=Bf));else if(4!==d&&(a=a.child,null!==a))for(Vj(a,b,c),a=a.sibling;null!==a;)Vj(a,b,c),a=a.sibling}\nfunction Wj(a,b,c){var d=a.tag;if(5===d||6===d)a=a.stateNode,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Wj(a,b,c),a=a.sibling;null!==a;)Wj(a,b,c),a=a.sibling}var X=null,Xj=!1;function Yj(a,b,c){for(c=c.child;null!==c;)Zj(a,b,c),c=c.sibling}\nfunction Zj(a,b,c){if(lc&&\"function\"===typeof lc.onCommitFiberUnmount)try{lc.onCommitFiberUnmount(kc,c)}catch(h){}switch(c.tag){case 5:U||Lj(c,b);case 6:var d=X,e=Xj;X=null;Yj(a,b,c);X=d;Xj=e;null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?a.parentNode.removeChild(c):a.removeChild(c)):X.removeChild(c.stateNode));break;case 18:null!==X&&(Xj?(a=X,c=c.stateNode,8===a.nodeType?Kf(a.parentNode,c):1===a.nodeType&&Kf(a,c),bd(a)):Kf(X,c.stateNode));break;case 4:d=X;e=Xj;X=c.stateNode.containerInfo;Xj=!0;\nYj(a,b,c);X=d;Xj=e;break;case 0:case 11:case 14:case 15:if(!U&&(d=c.updateQueue,null!==d&&(d=d.lastEffect,null!==d))){e=d=d.next;do{var f=e,g=f.destroy;f=f.tag;void 0!==g&&(0!==(f&2)?Mj(c,b,g):0!==(f&4)&&Mj(c,b,g));e=e.next}while(e!==d)}Yj(a,b,c);break;case 1:if(!U&&(Lj(c,b),d=c.stateNode,\"function\"===typeof d.componentWillUnmount))try{d.props=c.memoizedProps,d.state=c.memoizedState,d.componentWillUnmount()}catch(h){W(c,b,h)}Yj(a,b,c);break;case 21:Yj(a,b,c);break;case 22:c.mode&1?(U=(d=U)||null!==\nc.memoizedState,Yj(a,b,c),U=d):Yj(a,b,c);break;default:Yj(a,b,c)}}function ak(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Kj);b.forEach(function(b){var d=bk.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}\nfunction ck(a,b){var c=b.deletions;if(null!==c)for(var d=0;de&&(e=g);d&=~f}d=e;d=B()-d;d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*lk(d/1960))-d;if(10a?16:a;if(null===wk)var d=!1;else{a=wk;wk=null;xk=0;if(0!==(K&6))throw Error(p(331));var e=K;K|=4;for(V=a.current;null!==V;){var f=V,g=f.child;if(0!==(V.flags&16)){var h=f.deletions;if(null!==h){for(var k=0;kB()-fk?Kk(a,0):rk|=c);Dk(a,b)}function Yk(a,b){0===b&&(0===(a.mode&1)?b=1:(b=sc,sc<<=1,0===(sc&130023424)&&(sc=4194304)));var c=R();a=ih(a,b);null!==a&&(Ac(a,b,c),Dk(a,c))}function uj(a){var b=a.memoizedState,c=0;null!==b&&(c=b.retryLane);Yk(a,c)}\nfunction bk(a,b){var c=0;switch(a.tag){case 13:var d=a.stateNode;var e=a.memoizedState;null!==e&&(c=e.retryLane);break;case 19:d=a.stateNode;break;default:throw Error(p(314));}null!==d&&d.delete(b);Yk(a,c)}var Vk;\nVk=function(a,b,c){if(null!==a)if(a.memoizedProps!==b.pendingProps||Wf.current)dh=!0;else{if(0===(a.lanes&c)&&0===(b.flags&128))return dh=!1,yj(a,b,c);dh=0!==(a.flags&131072)?!0:!1}else dh=!1,I&&0!==(b.flags&1048576)&&ug(b,ng,b.index);b.lanes=0;switch(b.tag){case 2:var d=b.type;ij(a,b);a=b.pendingProps;var e=Yf(b,H.current);ch(b,c);e=Nh(null,b,d,a,e,c);var f=Sh();b.flags|=1;\"object\"===typeof e&&null!==e&&\"function\"===typeof e.render&&void 0===e.$$typeof?(b.tag=1,b.memoizedState=null,b.updateQueue=\nnull,Zf(d)?(f=!0,cg(b)):f=!1,b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null,kh(b),e.updater=Ei,b.stateNode=e,e._reactInternals=b,Ii(b,d,a,c),b=jj(null,b,d,!0,f,c)):(b.tag=0,I&&f&&vg(b),Xi(null,b,e,c),b=b.child);return b;case 16:d=b.elementType;a:{ij(a,b);a=b.pendingProps;e=d._init;d=e(d._payload);b.type=d;e=b.tag=Zk(d);a=Ci(d,a);switch(e){case 0:b=cj(null,b,d,a,c);break a;case 1:b=hj(null,b,d,a,c);break a;case 11:b=Yi(null,b,d,a,c);break a;case 14:b=$i(null,b,d,Ci(d.type,a),c);break a}throw Error(p(306,\nd,\"\"));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),cj(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),hj(a,b,d,e,c);case 3:a:{kj(b);if(null===a)throw Error(p(387));d=b.pendingProps;f=b.memoizedState;e=f.element;lh(a,b);qh(b,d,null,c);var g=b.memoizedState;d=g.element;if(f.isDehydrated)if(f={element:d,isDehydrated:!1,cache:g.cache,pendingSuspenseBoundaries:g.pendingSuspenseBoundaries,transitions:g.transitions},b.updateQueue.baseState=\nf,b.memoizedState=f,b.flags&256){e=Ji(Error(p(423)),b);b=lj(a,b,d,c,e);break a}else if(d!==e){e=Ji(Error(p(424)),b);b=lj(a,b,d,c,e);break a}else for(yg=Lf(b.stateNode.containerInfo.firstChild),xg=b,I=!0,zg=null,c=Vg(b,null,d,c),b.child=c;c;)c.flags=c.flags&-3|4096,c=c.sibling;else{Ig();if(d===e){b=Zi(a,b,c);break a}Xi(a,b,d,c)}b=b.child}return b;case 5:return Ah(b),null===a&&Eg(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:null,g=e.children,Ef(d,e)?g=null:null!==f&&Ef(d,f)&&(b.flags|=32),\ngj(a,b),Xi(a,b,g,c),b.child;case 6:return null===a&&Eg(b),null;case 13:return oj(a,b,c);case 4:return yh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Ug(b,null,d,c):Xi(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),Yi(a,b,d,e,c);case 7:return Xi(a,b,b.pendingProps,c),b.child;case 8:return Xi(a,b,b.pendingProps.children,c),b.child;case 12:return Xi(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;f=b.memoizedProps;\ng=e.value;G(Wg,d._currentValue);d._currentValue=g;if(null!==f)if(He(f.value,g)){if(f.children===e.children&&!Wf.current){b=Zi(a,b,c);break a}}else for(f=b.child,null!==f&&(f.return=b);null!==f;){var h=f.dependencies;if(null!==h){g=f.child;for(var k=h.firstContext;null!==k;){if(k.context===d){if(1===f.tag){k=mh(-1,c&-c);k.tag=2;var l=f.updateQueue;if(null!==l){l=l.shared;var m=l.pending;null===m?k.next=k:(k.next=m.next,m.next=k);l.pending=k}}f.lanes|=c;k=f.alternate;null!==k&&(k.lanes|=c);bh(f.return,\nc,b);h.lanes|=c;break}k=k.next}}else if(10===f.tag)g=f.type===b.type?null:f.child;else if(18===f.tag){g=f.return;if(null===g)throw Error(p(341));g.lanes|=c;h=g.alternate;null!==h&&(h.lanes|=c);bh(g,c,b);g=f.sibling}else g=f.child;if(null!==g)g.return=f;else for(g=f;null!==g;){if(g===b){g=null;break}f=g.sibling;if(null!==f){f.return=g.return;g=f;break}g=g.return}f=g}Xi(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,d=b.pendingProps.children,ch(b,c),e=eh(e),d=d(e),b.flags|=1,Xi(a,b,d,c),\nb.child;case 14:return d=b.type,e=Ci(d,b.pendingProps),e=Ci(d.type,e),$i(a,b,d,e,c);case 15:return bj(a,b,b.type,b.pendingProps,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:Ci(d,e),ij(a,b),b.tag=1,Zf(d)?(a=!0,cg(b)):a=!1,ch(b,c),Gi(b,d,e),Ii(b,d,e,c),jj(null,b,d,!0,a,c);case 19:return xj(a,b,c);case 22:return dj(a,b,c)}throw Error(p(156,b.tag));};function Fk(a,b){return ac(a,b)}\nfunction $k(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.subtreeFlags=this.flags=0;this.deletions=null;this.childLanes=this.lanes=0;this.alternate=null}function Bg(a,b,c,d){return new $k(a,b,c,d)}function aj(a){a=a.prototype;return!(!a||!a.isReactComponent)}\nfunction Zk(a){if(\"function\"===typeof a)return aj(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===Da)return 11;if(a===Ga)return 14}return 2}\nfunction Pg(a,b){var c=a.alternate;null===c?(c=Bg(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.type=a.type,c.flags=0,c.subtreeFlags=0,c.deletions=null);c.flags=a.flags&14680064;c.childLanes=a.childLanes;c.lanes=a.lanes;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{lanes:b.lanes,firstContext:b.firstContext};\nc.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}\nfunction Rg(a,b,c,d,e,f){var g=2;d=a;if(\"function\"===typeof a)aj(a)&&(g=1);else if(\"string\"===typeof a)g=5;else a:switch(a){case ya:return Tg(c.children,e,f,b);case za:g=8;e|=8;break;case Aa:return a=Bg(12,c,b,e|2),a.elementType=Aa,a.lanes=f,a;case Ea:return a=Bg(13,c,b,e),a.elementType=Ea,a.lanes=f,a;case Fa:return a=Bg(19,c,b,e),a.elementType=Fa,a.lanes=f,a;case Ia:return pj(c,e,f,b);default:if(\"object\"===typeof a&&null!==a)switch(a.$$typeof){case Ba:g=10;break a;case Ca:g=9;break a;case Da:g=11;\nbreak a;case Ga:g=14;break a;case Ha:g=16;d=null;break a}throw Error(p(130,null==a?a:typeof a,\"\"));}b=Bg(g,c,b,e);b.elementType=a;b.type=d;b.lanes=f;return b}function Tg(a,b,c,d){a=Bg(7,a,d,b);a.lanes=c;return a}function pj(a,b,c,d){a=Bg(22,a,d,b);a.elementType=Ia;a.lanes=c;a.stateNode={isHidden:!1};return a}function Qg(a,b,c){a=Bg(6,a,null,b);a.lanes=c;return a}\nfunction Sg(a,b,c){b=Bg(4,null!==a.children?a.children:[],a.key,b);b.lanes=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}\nfunction al(a,b,c,d,e){this.tag=b;this.containerInfo=a;this.finishedWork=this.pingCache=this.current=this.pendingChildren=null;this.timeoutHandle=-1;this.callbackNode=this.pendingContext=this.context=null;this.callbackPriority=0;this.eventTimes=zc(0);this.expirationTimes=zc(-1);this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0;this.entanglements=zc(0);this.identifierPrefix=d;this.onRecoverableError=e;this.mutableSourceEagerHydrationData=\nnull}function bl(a,b,c,d,e,f,g,h,k){a=new al(a,b,c,h,k);1===b?(b=1,!0===f&&(b|=8)):b=0;f=Bg(3,null,null,b);a.current=f;f.stateNode=a;f.memoizedState={element:d,isDehydrated:c,cache:null,transitions:null,pendingSuspenseBoundaries:null};kh(f);return a}function cl(a,b,c){var d=3 true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nmodule.exports = eq;\n","var eq = require('./eq');\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nmodule.exports = assocIndexOf;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nmodule.exports = listCacheDelete;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nmodule.exports = listCacheGet;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nmodule.exports = listCacheHas;\n","var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nmodule.exports = listCacheSet;\n","var listCacheClear = require('./_listCacheClear'),\n listCacheDelete = require('./_listCacheDelete'),\n listCacheGet = require('./_listCacheGet'),\n listCacheHas = require('./_listCacheHas'),\n listCacheSet = require('./_listCacheSet');\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nmodule.exports = ListCache;\n","var ListCache = require('./_ListCache');\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nmodule.exports = stackClear;\n","/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nmodule.exports = stackDelete;\n","/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nmodule.exports = stackGet;\n","/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nmodule.exports = stackHas;\n","/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n","var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n","var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n","/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n","var baseGetTag = require('./_baseGetTag'),\n isObject = require('./isObject');\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nmodule.exports = isFunction;\n","var root = require('./_root');\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nmodule.exports = coreJsData;\n","var coreJsData = require('./_coreJsData');\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nmodule.exports = isMasked;\n","/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nmodule.exports = toSource;\n","var isFunction = require('./isFunction'),\n isMasked = require('./_isMasked'),\n isObject = require('./isObject'),\n toSource = require('./_toSource');\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nmodule.exports = baseIsNative;\n","/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nmodule.exports = getValue;\n","var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nmodule.exports = Map;\n","var getNative = require('./_getNative');\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nmodule.exports = nativeCreate;\n","var nativeCreate = require('./_nativeCreate');\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nmodule.exports = hashClear;\n","/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = hashDelete;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nmodule.exports = hashGet;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nmodule.exports = hashHas;\n","var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nmodule.exports = hashSet;\n","var hashClear = require('./_hashClear'),\n hashDelete = require('./_hashDelete'),\n hashGet = require('./_hashGet'),\n hashHas = require('./_hashHas'),\n hashSet = require('./_hashSet');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nmodule.exports = Hash;\n","var Hash = require('./_Hash'),\n ListCache = require('./_ListCache'),\n Map = require('./_Map');\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nmodule.exports = mapCacheClear;\n","/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nmodule.exports = isKeyable;\n","var isKeyable = require('./_isKeyable');\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nmodule.exports = getMapData;\n","var getMapData = require('./_getMapData');\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = mapCacheDelete;\n","var getMapData = require('./_getMapData');\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nmodule.exports = mapCacheGet;\n","var getMapData = require('./_getMapData');\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nmodule.exports = mapCacheHas;\n","var getMapData = require('./_getMapData');\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nmodule.exports = mapCacheSet;\n","var mapCacheClear = require('./_mapCacheClear'),\n mapCacheDelete = require('./_mapCacheDelete'),\n mapCacheGet = require('./_mapCacheGet'),\n mapCacheHas = require('./_mapCacheHas'),\n mapCacheSet = require('./_mapCacheSet');\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nmodule.exports = MapCache;\n","var ListCache = require('./_ListCache'),\n Map = require('./_Map'),\n MapCache = require('./_MapCache');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nmodule.exports = stackSet;\n","var ListCache = require('./_ListCache'),\n stackClear = require('./_stackClear'),\n stackDelete = require('./_stackDelete'),\n stackGet = require('./_stackGet'),\n stackHas = require('./_stackHas'),\n stackSet = require('./_stackSet');\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nmodule.exports = Stack;\n","/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nmodule.exports = setCacheAdd;\n","/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nmodule.exports = setCacheHas;\n","var MapCache = require('./_MapCache'),\n setCacheAdd = require('./_setCacheAdd'),\n setCacheHas = require('./_setCacheHas');\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nmodule.exports = SetCache;\n","/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nmodule.exports = arraySome;\n","/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nmodule.exports = cacheHas;\n","var SetCache = require('./_SetCache'),\n arraySome = require('./_arraySome'),\n cacheHas = require('./_cacheHas');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nmodule.exports = equalArrays;\n","var root = require('./_root');\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nmodule.exports = Uint8Array;\n","/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nmodule.exports = mapToArray;\n","/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nmodule.exports = setToArray;\n","var Symbol = require('./_Symbol'),\n Uint8Array = require('./_Uint8Array'),\n eq = require('./eq'),\n equalArrays = require('./_equalArrays'),\n mapToArray = require('./_mapToArray'),\n setToArray = require('./_setToArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nmodule.exports = equalByTag;\n","/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nmodule.exports = arrayPush;\n","/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n","var arrayPush = require('./_arrayPush'),\n isArray = require('./isArray');\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nmodule.exports = baseGetAllKeys;\n","/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nmodule.exports = arrayFilter;\n","/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nmodule.exports = stubArray;\n","var arrayFilter = require('./_arrayFilter'),\n stubArray = require('./stubArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nmodule.exports = getSymbols;\n","/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nmodule.exports = baseTimes;\n","/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nmodule.exports = baseIsArguments;\n","var baseIsArguments = require('./_baseIsArguments'),\n isObjectLike = require('./isObjectLike');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nmodule.exports = isArguments;\n","/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = stubFalse;\n","var root = require('./_root'),\n stubFalse = require('./stubFalse');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nmodule.exports = isBuffer;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nmodule.exports = isIndex;\n","/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nmodule.exports = isLength;\n","var baseGetTag = require('./_baseGetTag'),\n isLength = require('./isLength'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nmodule.exports = baseIsTypedArray;\n","/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nmodule.exports = baseUnary;\n","var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nmodule.exports = nodeUtil;\n","var baseIsTypedArray = require('./_baseIsTypedArray'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nmodule.exports = isTypedArray;\n","var baseTimes = require('./_baseTimes'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isIndex = require('./_isIndex'),\n isTypedArray = require('./isTypedArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = arrayLikeKeys;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nmodule.exports = isPrototype;\n","/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nmodule.exports = overArg;\n","var overArg = require('./_overArg');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nmodule.exports = nativeKeys;\n","var isPrototype = require('./_isPrototype'),\n nativeKeys = require('./_nativeKeys');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeys;\n","var isFunction = require('./isFunction'),\n isLength = require('./isLength');\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nmodule.exports = isArrayLike;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeys = require('./_baseKeys'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nmodule.exports = keys;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n getSymbols = require('./_getSymbols'),\n keys = require('./keys');\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nmodule.exports = getAllKeys;\n","var getAllKeys = require('./_getAllKeys');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nmodule.exports = equalObjects;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nmodule.exports = DataView;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nmodule.exports = Promise;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nmodule.exports = Set;\n","var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nmodule.exports = WeakMap;\n","var DataView = require('./_DataView'),\n Map = require('./_Map'),\n Promise = require('./_Promise'),\n Set = require('./_Set'),\n WeakMap = require('./_WeakMap'),\n baseGetTag = require('./_baseGetTag'),\n toSource = require('./_toSource');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nmodule.exports = getTag;\n","var Stack = require('./_Stack'),\n equalArrays = require('./_equalArrays'),\n equalByTag = require('./_equalByTag'),\n equalObjects = require('./_equalObjects'),\n getTag = require('./_getTag'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isTypedArray = require('./isTypedArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nmodule.exports = baseIsEqualDeep;\n","var baseIsEqualDeep = require('./_baseIsEqualDeep'),\n isObjectLike = require('./isObjectLike');\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nmodule.exports = baseIsEqual;\n","var baseIsEqual = require('./_baseIsEqual');\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\nmodule.exports = isEqual;\n","/**\n * @license React\n * use-sync-external-store-shim.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and 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\";\nvar React = require(\"react\");\nfunction is(x, y) {\n return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);\n}\nvar objectIs = \"function\" === typeof Object.is ? Object.is : is,\n useState = React.useState,\n useEffect = React.useEffect,\n useLayoutEffect = React.useLayoutEffect,\n useDebugValue = React.useDebugValue;\nfunction useSyncExternalStore$2(subscribe, getSnapshot) {\n var value = getSnapshot(),\n _useState = useState({ inst: { value: value, getSnapshot: getSnapshot } }),\n inst = _useState[0].inst,\n forceUpdate = _useState[1];\n useLayoutEffect(\n function () {\n inst.value = value;\n inst.getSnapshot = getSnapshot;\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n },\n [subscribe, value, getSnapshot]\n );\n useEffect(\n function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n return subscribe(function () {\n checkIfSnapshotChanged(inst) && forceUpdate({ inst: inst });\n });\n },\n [subscribe]\n );\n useDebugValue(value);\n return value;\n}\nfunction checkIfSnapshotChanged(inst) {\n var latestGetSnapshot = inst.getSnapshot;\n inst = inst.value;\n try {\n var nextValue = latestGetSnapshot();\n return !objectIs(inst, nextValue);\n } catch (error) {\n return !0;\n }\n}\nfunction useSyncExternalStore$1(subscribe, getSnapshot) {\n return getSnapshot();\n}\nvar shim =\n \"undefined\" === typeof window ||\n \"undefined\" === typeof window.document ||\n \"undefined\" === typeof window.document.createElement\n ? useSyncExternalStore$1\n : useSyncExternalStore$2;\nexports.useSyncExternalStore =\n void 0 !== React.useSyncExternalStore ? React.useSyncExternalStore : shim;\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim.production.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim.development.js');\n}\n","/**\n * @license React\n * use-sync-external-store-shim/with-selector.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and 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\";\nvar React = require(\"react\"),\n shim = require(\"use-sync-external-store/shim\");\nfunction is(x, y) {\n return (x === y && (0 !== x || 1 / x === 1 / y)) || (x !== x && y !== y);\n}\nvar objectIs = \"function\" === typeof Object.is ? Object.is : is,\n useSyncExternalStore = shim.useSyncExternalStore,\n useRef = React.useRef,\n useEffect = React.useEffect,\n useMemo = React.useMemo,\n useDebugValue = React.useDebugValue;\nexports.useSyncExternalStoreWithSelector = function (\n subscribe,\n getSnapshot,\n getServerSnapshot,\n selector,\n isEqual\n) {\n var instRef = useRef(null);\n if (null === instRef.current) {\n var inst = { hasValue: !1, value: null };\n instRef.current = inst;\n } else inst = instRef.current;\n instRef = useMemo(\n function () {\n function memoizedSelector(nextSnapshot) {\n if (!hasMemo) {\n hasMemo = !0;\n memoizedSnapshot = nextSnapshot;\n nextSnapshot = selector(nextSnapshot);\n if (void 0 !== isEqual && inst.hasValue) {\n var currentSelection = inst.value;\n if (isEqual(currentSelection, nextSnapshot))\n return (memoizedSelection = currentSelection);\n }\n return (memoizedSelection = nextSnapshot);\n }\n currentSelection = memoizedSelection;\n if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection;\n var nextSelection = selector(nextSnapshot);\n if (void 0 !== isEqual && isEqual(currentSelection, nextSelection))\n return (memoizedSnapshot = nextSnapshot), currentSelection;\n memoizedSnapshot = nextSnapshot;\n return (memoizedSelection = nextSelection);\n }\n var hasMemo = !1,\n memoizedSnapshot,\n memoizedSelection,\n maybeGetServerSnapshot =\n void 0 === getServerSnapshot ? null : getServerSnapshot;\n return [\n function () {\n return memoizedSelector(getSnapshot());\n },\n null === maybeGetServerSnapshot\n ? void 0\n : function () {\n return memoizedSelector(maybeGetServerSnapshot());\n }\n ];\n },\n [getSnapshot, getServerSnapshot, selector, isEqual]\n );\n var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]);\n useEffect(\n function () {\n inst.hasValue = !0;\n inst.value = value;\n },\n [value]\n );\n useDebugValue(value);\n return value;\n};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.production.js');\n} else {\n module.exports = require('../cjs/use-sync-external-store-shim/with-selector.development.js');\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n\r\nvar __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n };\r\n return __assign.apply(this, arguments);\r\n};\r\n\r\nfunction __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nfunction __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nfunction __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nfunction __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\n\nexport { __assign, __read, __rest, __spreadArray, __values };\n","var ActionTypes;\n\n(function (ActionTypes) {\n ActionTypes[\"Start\"] = \"xstate.start\";\n ActionTypes[\"Stop\"] = \"xstate.stop\";\n ActionTypes[\"Raise\"] = \"xstate.raise\";\n ActionTypes[\"Send\"] = \"xstate.send\";\n ActionTypes[\"Cancel\"] = \"xstate.cancel\";\n ActionTypes[\"NullEvent\"] = \"\";\n ActionTypes[\"Assign\"] = \"xstate.assign\";\n ActionTypes[\"After\"] = \"xstate.after\";\n ActionTypes[\"DoneState\"] = \"done.state\";\n ActionTypes[\"DoneInvoke\"] = \"done.invoke\";\n ActionTypes[\"Log\"] = \"xstate.log\";\n ActionTypes[\"Init\"] = \"xstate.init\";\n ActionTypes[\"Invoke\"] = \"xstate.invoke\";\n ActionTypes[\"ErrorExecution\"] = \"error.execution\";\n ActionTypes[\"ErrorCommunication\"] = \"error.communication\";\n ActionTypes[\"ErrorPlatform\"] = \"error.platform\";\n ActionTypes[\"ErrorCustom\"] = \"xstate.error\";\n ActionTypes[\"Update\"] = \"xstate.update\";\n ActionTypes[\"Pure\"] = \"xstate.pure\";\n ActionTypes[\"Choose\"] = \"xstate.choose\";\n})(ActionTypes || (ActionTypes = {}));\n\nvar SpecialTargets;\n\n(function (SpecialTargets) {\n SpecialTargets[\"Parent\"] = \"#_parent\";\n SpecialTargets[\"Internal\"] = \"#_internal\";\n})(SpecialTargets || (SpecialTargets = {}));\n\nexport { ActionTypes, SpecialTargets };\n","import { ActionTypes } from './types.js';\n\nvar start = ActionTypes.Start;\nvar stop = ActionTypes.Stop;\nvar raise = ActionTypes.Raise;\nvar send = ActionTypes.Send;\nvar cancel = ActionTypes.Cancel;\nvar nullEvent = ActionTypes.NullEvent;\nvar assign = ActionTypes.Assign;\nvar after = ActionTypes.After;\nvar doneState = ActionTypes.DoneState;\nvar log = ActionTypes.Log;\nvar init = ActionTypes.Init;\nvar invoke = ActionTypes.Invoke;\nvar errorExecution = ActionTypes.ErrorExecution;\nvar errorPlatform = ActionTypes.ErrorPlatform;\nvar error = ActionTypes.ErrorCustom;\nvar update = ActionTypes.Update;\nvar choose = ActionTypes.Choose;\nvar pure = ActionTypes.Pure;\n\nexport { after, assign, cancel, choose, doneState, error, errorExecution, errorPlatform, init, invoke, log, nullEvent, pure, raise, send, start, stop, update };\n","var STATE_DELIMITER = '.';\nvar EMPTY_ACTIVITY_MAP = {};\nvar DEFAULT_GUARD_TYPE = 'xstate.guard';\nvar TARGETLESS_KEY = '';\n\nexport { DEFAULT_GUARD_TYPE, EMPTY_ACTIVITY_MAP, STATE_DELIMITER, TARGETLESS_KEY };\n","import { __values, __spreadArray, __read, __assign } from './_virtual/_tslib.js';\nimport { SpecialTargets } from './types.js';\nimport { raise, send } from './actionTypes.js';\nimport { DEFAULT_GUARD_TYPE, TARGETLESS_KEY, STATE_DELIMITER } from './constants.js';\nimport { IS_PRODUCTION } from './environment.js';\n\nvar _a;\nfunction keys(value) {\n return Object.keys(value);\n}\nfunction matchesState(parentStateId, childStateId, delimiter) {\n if (delimiter === void 0) {\n delimiter = STATE_DELIMITER;\n }\n\n var parentStateValue = toStateValue(parentStateId, delimiter);\n var childStateValue = toStateValue(childStateId, delimiter);\n\n if (isString(childStateValue)) {\n if (isString(parentStateValue)) {\n return childStateValue === parentStateValue;\n } // Parent more specific than child\n\n\n return false;\n }\n\n if (isString(parentStateValue)) {\n return parentStateValue in childStateValue;\n }\n\n return Object.keys(parentStateValue).every(function (key) {\n if (!(key in childStateValue)) {\n return false;\n }\n\n return matchesState(parentStateValue[key], childStateValue[key]);\n });\n}\nfunction getEventType(event) {\n try {\n return isString(event) || typeof event === 'number' ? \"\".concat(event) : event.type;\n } catch (e) {\n throw new Error('Events must be strings or objects with a string event.type property.');\n }\n}\nfunction getActionType(action) {\n try {\n return isString(action) || typeof action === 'number' ? \"\".concat(action) : isFunction(action) ? action.name : action.type;\n } catch (e) {\n throw new Error('Actions must be strings or objects with a string action.type property.');\n }\n}\nfunction toStatePath(stateId, delimiter) {\n try {\n if (isArray(stateId)) {\n return stateId;\n }\n\n return stateId.toString().split(delimiter);\n } catch (e) {\n throw new Error(\"'\".concat(stateId, \"' is not a valid state path.\"));\n }\n}\nfunction isStateLike(state) {\n return typeof state === 'object' && 'value' in state && 'context' in state && 'event' in state && '_event' in state;\n}\nfunction toStateValue(stateValue, delimiter) {\n if (isStateLike(stateValue)) {\n return stateValue.value;\n }\n\n if (isArray(stateValue)) {\n return pathToStateValue(stateValue);\n }\n\n if (typeof stateValue !== 'string') {\n return stateValue;\n }\n\n var statePath = toStatePath(stateValue, delimiter);\n return pathToStateValue(statePath);\n}\nfunction pathToStateValue(statePath) {\n if (statePath.length === 1) {\n return statePath[0];\n }\n\n var value = {};\n var marker = value;\n\n for (var i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n marker[statePath[i]] = {};\n marker = marker[statePath[i]];\n }\n }\n\n return value;\n}\nfunction mapValues(collection, iteratee) {\n var result = {};\n var collectionKeys = Object.keys(collection);\n\n for (var i = 0; i < collectionKeys.length; i++) {\n var key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n\n return result;\n}\nfunction mapFilterValues(collection, iteratee, predicate) {\n var e_1, _a;\n\n var result = {};\n\n try {\n for (var _b = __values(Object.keys(collection)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var key = _c.value;\n var item = collection[key];\n\n if (!predicate(item)) {\n continue;\n }\n\n result[key] = iteratee(item, key, collection);\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n return result;\n}\n/**\r\n * Retrieves a value at the given path.\r\n * @param props The deep path to the prop of the desired value\r\n */\n\nvar path = function (props) {\n return function (object) {\n var e_2, _a;\n\n var result = object;\n\n try {\n for (var props_1 = __values(props), props_1_1 = props_1.next(); !props_1_1.done; props_1_1 = props_1.next()) {\n var prop = props_1_1.value;\n result = result[prop];\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (props_1_1 && !props_1_1.done && (_a = props_1.return)) _a.call(props_1);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n return result;\n };\n};\n/**\r\n * Retrieves a value at the given path via the nested accessor prop.\r\n * @param props The deep path to the prop of the desired value\r\n */\n\nfunction nestedPath(props, accessorProp) {\n return function (object) {\n var e_3, _a;\n\n var result = object;\n\n try {\n for (var props_2 = __values(props), props_2_1 = props_2.next(); !props_2_1.done; props_2_1 = props_2.next()) {\n var prop = props_2_1.value;\n result = result[accessorProp][prop];\n }\n } catch (e_3_1) {\n e_3 = {\n error: e_3_1\n };\n } finally {\n try {\n if (props_2_1 && !props_2_1.done && (_a = props_2.return)) _a.call(props_2);\n } finally {\n if (e_3) throw e_3.error;\n }\n }\n\n return result;\n };\n}\nfunction toStatePaths(stateValue) {\n if (!stateValue) {\n return [[]];\n }\n\n if (isString(stateValue)) {\n return [[stateValue]];\n }\n\n var result = flatten(Object.keys(stateValue).map(function (key) {\n var subStateValue = stateValue[key];\n\n if (typeof subStateValue !== 'string' && (!subStateValue || !Object.keys(subStateValue).length)) {\n return [[key]];\n }\n\n return toStatePaths(stateValue[key]).map(function (subPath) {\n return [key].concat(subPath);\n });\n }));\n return result;\n}\nfunction pathsToStateValue(paths) {\n var e_4, _a;\n\n var result = {};\n\n if (paths && paths.length === 1 && paths[0].length === 1) {\n return paths[0][0];\n }\n\n try {\n for (var paths_1 = __values(paths), paths_1_1 = paths_1.next(); !paths_1_1.done; paths_1_1 = paths_1.next()) {\n var currentPath = paths_1_1.value;\n var marker = result; // tslint:disable-next-line:prefer-for-of\n\n for (var i = 0; i < currentPath.length; i++) {\n var subPath = currentPath[i];\n\n if (i === currentPath.length - 2) {\n marker[subPath] = currentPath[i + 1];\n break;\n }\n\n marker[subPath] = marker[subPath] || {};\n marker = marker[subPath];\n }\n }\n } catch (e_4_1) {\n e_4 = {\n error: e_4_1\n };\n } finally {\n try {\n if (paths_1_1 && !paths_1_1.done && (_a = paths_1.return)) _a.call(paths_1);\n } finally {\n if (e_4) throw e_4.error;\n }\n }\n\n return result;\n}\nfunction flatten(array) {\n var _a;\n\n return (_a = []).concat.apply(_a, __spreadArray([], __read(array), false));\n}\nfunction toArrayStrict(value) {\n if (isArray(value)) {\n return value;\n }\n\n return [value];\n}\nfunction toArray(value) {\n if (value === undefined) {\n return [];\n }\n\n return toArrayStrict(value);\n}\nfunction mapContext(mapper, context, _event) {\n var e_5, _a;\n\n if (isFunction(mapper)) {\n return mapper(context, _event.data);\n }\n\n var result = {};\n\n try {\n for (var _b = __values(Object.keys(mapper)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var key = _c.value;\n var subMapper = mapper[key];\n\n if (isFunction(subMapper)) {\n result[key] = subMapper(context, _event.data);\n } else {\n result[key] = subMapper;\n }\n }\n } catch (e_5_1) {\n e_5 = {\n error: e_5_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_5) throw e_5.error;\n }\n }\n\n return result;\n}\nfunction isBuiltInEvent(eventType) {\n return /^(done|error)\\./.test(eventType);\n}\nfunction isPromiseLike(value) {\n if (value instanceof Promise) {\n return true;\n } // Check if shape matches the Promise/A+ specification for a \"thenable\".\n\n\n if (value !== null && (isFunction(value) || typeof value === 'object') && isFunction(value.then)) {\n return true;\n }\n\n return false;\n}\nfunction isBehavior(value) {\n return value !== null && typeof value === 'object' && 'transition' in value && typeof value.transition === 'function';\n}\nfunction partition(items, predicate) {\n var e_6, _a;\n\n var _b = __read([[], []], 2),\n truthy = _b[0],\n falsy = _b[1];\n\n try {\n for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {\n var item = items_1_1.value;\n\n if (predicate(item)) {\n truthy.push(item);\n } else {\n falsy.push(item);\n }\n }\n } catch (e_6_1) {\n e_6 = {\n error: e_6_1\n };\n } finally {\n try {\n if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);\n } finally {\n if (e_6) throw e_6.error;\n }\n }\n\n return [truthy, falsy];\n}\nfunction updateHistoryStates(hist, stateValue) {\n return mapValues(hist.states, function (subHist, key) {\n if (!subHist) {\n return undefined;\n }\n\n var subStateValue = (isString(stateValue) ? undefined : stateValue[key]) || (subHist ? subHist.current : undefined);\n\n if (!subStateValue) {\n return undefined;\n }\n\n return {\n current: subStateValue,\n states: updateHistoryStates(subHist, subStateValue)\n };\n });\n}\nfunction updateHistoryValue(hist, stateValue) {\n return {\n current: stateValue,\n states: updateHistoryStates(hist, stateValue)\n };\n}\nfunction updateContext(context, _event, assignActions, state) {\n if (!IS_PRODUCTION) {\n warn(!!context, 'Attempting to update undefined context');\n }\n\n var updatedContext = context ? assignActions.reduce(function (acc, assignAction) {\n var e_7, _a;\n\n var assignment = assignAction.assignment;\n var meta = {\n state: state,\n action: assignAction,\n _event: _event\n };\n var partialUpdate = {};\n\n if (isFunction(assignment)) {\n partialUpdate = assignment(acc, _event.data, meta);\n } else {\n try {\n for (var _b = __values(Object.keys(assignment)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var key = _c.value;\n var propAssignment = assignment[key];\n partialUpdate[key] = isFunction(propAssignment) ? propAssignment(acc, _event.data, meta) : propAssignment;\n }\n } catch (e_7_1) {\n e_7 = {\n error: e_7_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_7) throw e_7.error;\n }\n }\n }\n\n return Object.assign({}, acc, partialUpdate);\n }, context) : context;\n return updatedContext;\n} // tslint:disable-next-line:no-empty\n\nvar warn = function () {};\n\nif (!IS_PRODUCTION) {\n warn = function (condition, message) {\n var error = condition instanceof Error ? condition : undefined;\n\n if (!error && condition) {\n return;\n }\n\n if (console !== undefined) {\n var args = [\"Warning: \".concat(message)];\n\n if (error) {\n args.push(error);\n } // tslint:disable-next-line:no-console\n\n\n console.warn.apply(console, args);\n }\n };\n}\nfunction isArray(value) {\n return Array.isArray(value);\n} // tslint:disable-next-line:ban-types\n\nfunction isFunction(value) {\n return typeof value === 'function';\n}\nfunction isString(value) {\n return typeof value === 'string';\n}\nfunction toGuard(condition, guardMap) {\n if (!condition) {\n return undefined;\n }\n\n if (isString(condition)) {\n return {\n type: DEFAULT_GUARD_TYPE,\n name: condition,\n predicate: guardMap ? guardMap[condition] : undefined\n };\n }\n\n if (isFunction(condition)) {\n return {\n type: DEFAULT_GUARD_TYPE,\n name: condition.name,\n predicate: condition\n };\n }\n\n return condition;\n}\nfunction isObservable(value) {\n try {\n return 'subscribe' in value && isFunction(value.subscribe);\n } catch (e) {\n return false;\n }\n}\nvar symbolObservable = /*#__PURE__*/function () {\n return typeof Symbol === 'function' && Symbol.observable || '@@observable';\n}(); // TODO: to be removed in v5, left it out just to minimize the scope of the change and maintain compatibility with older versions of integration paackages\n\nvar interopSymbols = (_a = {}, _a[symbolObservable] = function () {\n return this;\n}, _a[Symbol.observable] = function () {\n return this;\n}, _a);\nfunction isMachine(value) {\n return !!value && '__xstatenode' in value;\n}\nfunction isActor(value) {\n return !!value && typeof value.send === 'function';\n}\nvar uniqueId = /*#__PURE__*/function () {\n var currentId = 0;\n return function () {\n currentId++;\n return currentId.toString(16);\n };\n}();\nfunction toEventObject(event, payload // id?: TEvent['type']\n) {\n if (isString(event) || typeof event === 'number') {\n return __assign({\n type: event\n }, payload);\n }\n\n return event;\n}\nfunction toSCXMLEvent(event, scxmlEvent) {\n if (!isString(event) && '$$type' in event && event.$$type === 'scxml') {\n return event;\n }\n\n var eventObject = toEventObject(event);\n return __assign({\n name: eventObject.type,\n data: eventObject,\n $$type: 'scxml',\n type: 'external'\n }, scxmlEvent);\n}\nfunction toTransitionConfigArray(event, configLike) {\n var transitions = toArrayStrict(configLike).map(function (transitionLike) {\n if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string' || isMachine(transitionLike)) {\n return {\n target: transitionLike,\n event: event\n };\n }\n\n return __assign(__assign({}, transitionLike), {\n event: event\n });\n });\n return transitions;\n}\nfunction normalizeTarget(target) {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n\n return toArray(target);\n}\nfunction reportUnhandledExceptionOnInvocation(originalError, currentError, id) {\n if (!IS_PRODUCTION) {\n var originalStackTrace = originalError.stack ? \" Stacktrace was '\".concat(originalError.stack, \"'\") : '';\n\n if (originalError === currentError) {\n // tslint:disable-next-line:no-console\n console.error(\"Missing onError handler for invocation '\".concat(id, \"', error was '\").concat(originalError, \"'.\").concat(originalStackTrace));\n } else {\n var stackTrace = currentError.stack ? \" Stacktrace was '\".concat(currentError.stack, \"'\") : ''; // tslint:disable-next-line:no-console\n\n console.error(\"Missing onError handler and/or unhandled exception/promise rejection for invocation '\".concat(id, \"'. \") + \"Original error: '\".concat(originalError, \"'. \").concat(originalStackTrace, \" Current error is '\").concat(currentError, \"'.\").concat(stackTrace));\n }\n }\n}\nfunction evaluateGuard(machine, guard, context, _event, state) {\n var guards = machine.options.guards;\n var guardMeta = {\n state: state,\n cond: guard,\n _event: _event\n }; // TODO: do not hardcode!\n\n if (guard.type === DEFAULT_GUARD_TYPE) {\n return ((guards === null || guards === void 0 ? void 0 : guards[guard.name]) || guard.predicate)(context, _event.data, guardMeta);\n }\n\n var condFn = guards === null || guards === void 0 ? void 0 : guards[guard.type];\n\n if (!condFn) {\n throw new Error(\"Guard '\".concat(guard.type, \"' is not implemented on machine '\").concat(machine.id, \"'.\"));\n }\n\n return condFn(context, _event.data, guardMeta);\n}\nfunction toInvokeSource(src) {\n if (typeof src === 'string') {\n return {\n type: src\n };\n }\n\n return src;\n}\nfunction toObserver(nextHandler, errorHandler, completionHandler) {\n var noop = function () {};\n\n var isObserver = typeof nextHandler === 'object';\n var self = isObserver ? nextHandler : null;\n return {\n next: ((isObserver ? nextHandler.next : nextHandler) || noop).bind(self),\n error: ((isObserver ? nextHandler.error : errorHandler) || noop).bind(self),\n complete: ((isObserver ? nextHandler.complete : completionHandler) || noop).bind(self)\n };\n}\nfunction createInvokeId(stateNodeId, index) {\n return \"\".concat(stateNodeId, \":invocation[\").concat(index, \"]\");\n}\nfunction isRaisableAction(action) {\n return (action.type === raise || action.type === send && action.to === SpecialTargets.Internal) && typeof action.delay !== 'number';\n}\n\nexport { createInvokeId, evaluateGuard, flatten, getActionType, getEventType, interopSymbols, isActor, isArray, isBehavior, isBuiltInEvent, isFunction, isMachine, isObservable, isPromiseLike, isRaisableAction, isStateLike, isString, keys, mapContext, mapFilterValues, mapValues, matchesState, nestedPath, normalizeTarget, partition, path, pathToStateValue, pathsToStateValue, reportUnhandledExceptionOnInvocation, symbolObservable, toArray, toArrayStrict, toEventObject, toGuard, toInvokeSource, toObserver, toSCXMLEvent, toStatePath, toStatePaths, toStateValue, toTransitionConfigArray, uniqueId, updateContext, updateHistoryStates, updateHistoryValue, warn };\n","import { __assign, __spreadArray, __read, __values } from './_virtual/_tslib.js';\nimport { SpecialTargets, ActionTypes } from './types.js';\nimport { init, raise as raise$1, send as send$1, update, log as log$1, cancel as cancel$1, assign as assign$1, error as error$1, stop as stop$1, pure as pure$1, choose as choose$1 } from './actionTypes.js';\nimport * as actionTypes from './actionTypes.js';\nexport { actionTypes };\nimport { toSCXMLEvent, isString, isFunction, toEventObject, getEventType, updateContext, flatten, isArray, toArray, toGuard, evaluateGuard, warn } from './utils.js';\nimport { IS_PRODUCTION } from './environment.js';\n\nvar initEvent = /*#__PURE__*/toSCXMLEvent({\n type: init\n});\nfunction getActionFunction(actionType, actionFunctionMap) {\n return actionFunctionMap ? actionFunctionMap[actionType] || undefined : undefined;\n}\nfunction toActionObject(action, actionFunctionMap) {\n var actionObject;\n\n if (isString(action) || typeof action === 'number') {\n var exec = getActionFunction(action, actionFunctionMap);\n\n if (isFunction(exec)) {\n actionObject = {\n type: action,\n exec: exec\n };\n } else if (exec) {\n actionObject = exec;\n } else {\n actionObject = {\n type: action,\n exec: undefined\n };\n }\n } else if (isFunction(action)) {\n actionObject = {\n // Convert action to string if unnamed\n type: action.name || action.toString(),\n exec: action\n };\n } else {\n var exec = getActionFunction(action.type, actionFunctionMap);\n\n if (isFunction(exec)) {\n actionObject = __assign(__assign({}, action), {\n exec: exec\n });\n } else if (exec) {\n var actionType = exec.type || action.type;\n actionObject = __assign(__assign(__assign({}, exec), action), {\n type: actionType\n });\n } else {\n actionObject = action;\n }\n }\n\n return actionObject;\n}\nvar toActionObjects = function (action, actionFunctionMap) {\n if (!action) {\n return [];\n }\n\n var actions = isArray(action) ? action : [action];\n return actions.map(function (subAction) {\n return toActionObject(subAction, actionFunctionMap);\n });\n};\nfunction toActivityDefinition(action) {\n var actionObject = toActionObject(action);\n return __assign(__assign({\n id: isString(action) ? action : actionObject.id\n }, actionObject), {\n type: actionObject.type\n });\n}\n/**\r\n * Raises an event. This places the event in the internal event queue, so that\r\n * the event is immediately consumed by the machine in the current step.\r\n *\r\n * @param eventType The event to raise.\r\n */\n\nfunction raise(event, options) {\n return {\n type: raise$1,\n event: typeof event === 'function' ? event : toEventObject(event),\n delay: options ? options.delay : undefined,\n id: options === null || options === void 0 ? void 0 : options.id\n };\n}\nfunction resolveRaise(action, ctx, _event, delaysMap) {\n var meta = {\n _event: _event\n };\n var resolvedEvent = toSCXMLEvent(isFunction(action.event) ? action.event(ctx, _event.data, meta) : action.event);\n var resolvedDelay;\n\n if (isString(action.delay)) {\n var configDelay = delaysMap && delaysMap[action.delay];\n resolvedDelay = isFunction(configDelay) ? configDelay(ctx, _event.data, meta) : configDelay;\n } else {\n resolvedDelay = isFunction(action.delay) ? action.delay(ctx, _event.data, meta) : action.delay;\n }\n\n return __assign(__assign({}, action), {\n type: raise$1,\n _event: resolvedEvent,\n delay: resolvedDelay\n });\n}\n/**\r\n * Sends an event. This returns an action that will be read by an interpreter to\r\n * send the event in the next step, after the current step is finished executing.\r\n *\r\n * @deprecated Use the `sendTo(...)` action creator instead.\r\n *\r\n * @param event The event to send.\r\n * @param options Options to pass into the send event:\r\n * - `id` - The unique send event identifier (used with `cancel()`).\r\n * - `delay` - The number of milliseconds to delay the sending of the event.\r\n * - `to` - The target of this event (by default, the machine the event was sent from).\r\n */\n\nfunction send(event, options) {\n return {\n to: options ? options.to : undefined,\n type: send$1,\n event: isFunction(event) ? event : toEventObject(event),\n delay: options ? options.delay : undefined,\n // TODO: don't auto-generate IDs here like that\n // there is too big chance of the ID collision\n id: options && options.id !== undefined ? options.id : isFunction(event) ? event.name : getEventType(event)\n };\n}\nfunction resolveSend(action, ctx, _event, delaysMap) {\n var meta = {\n _event: _event\n }; // TODO: helper function for resolving Expr\n\n var resolvedEvent = toSCXMLEvent(isFunction(action.event) ? action.event(ctx, _event.data, meta) : action.event);\n var resolvedDelay;\n\n if (isString(action.delay)) {\n var configDelay = delaysMap && delaysMap[action.delay];\n resolvedDelay = isFunction(configDelay) ? configDelay(ctx, _event.data, meta) : configDelay;\n } else {\n resolvedDelay = isFunction(action.delay) ? action.delay(ctx, _event.data, meta) : action.delay;\n }\n\n var resolvedTarget = isFunction(action.to) ? action.to(ctx, _event.data, meta) : action.to;\n return __assign(__assign({}, action), {\n to: resolvedTarget,\n _event: resolvedEvent,\n event: resolvedEvent.data,\n delay: resolvedDelay\n });\n}\n/**\r\n * Sends an event to this machine's parent.\r\n *\r\n * @param event The event to send to the parent machine.\r\n * @param options Options to pass into the send event.\r\n */\n\nfunction sendParent(event, options) {\n return send(event, __assign(__assign({}, options), {\n to: SpecialTargets.Parent\n }));\n}\n/**\r\n * Sends an event to an actor.\r\n *\r\n * @param actor The `ActorRef` to send the event to.\r\n * @param event The event to send, or an expression that evaluates to the event to send\r\n * @param options Send action options\r\n * @returns An XState send action object\r\n */\n\nfunction sendTo(actor, event, options) {\n return send(event, __assign(__assign({}, options), {\n to: actor\n }));\n}\n/**\r\n * Sends an update event to this machine's parent.\r\n */\n\nfunction sendUpdate() {\n return sendParent(update);\n}\n/**\r\n * Sends an event back to the sender of the original event.\r\n *\r\n * @param event The event to send back to the sender\r\n * @param options Options to pass into the send event\r\n */\n\nfunction respond(event, options) {\n return send(event, __assign(__assign({}, options), {\n to: function (_, __, _a) {\n var _event = _a._event;\n return _event.origin; // TODO: handle when _event.origin is undefined\n }\n }));\n}\n\nvar defaultLogExpr = function (context, event) {\n return {\n context: context,\n event: event\n };\n};\n/**\r\n *\r\n * @param expr The expression function to evaluate which will be logged.\r\n * Takes in 2 arguments:\r\n * - `ctx` - the current state context\r\n * - `event` - the event that caused this action to be executed.\r\n * @param label The label to give to the logged expression.\r\n */\n\n\nfunction log(expr, label) {\n if (expr === void 0) {\n expr = defaultLogExpr;\n }\n\n return {\n type: log$1,\n label: label,\n expr: expr\n };\n}\nvar resolveLog = function (action, ctx, _event) {\n return __assign(__assign({}, action), {\n value: isString(action.expr) ? action.expr : action.expr(ctx, _event.data, {\n _event: _event\n })\n });\n};\n/**\r\n * Cancels an in-flight `send(...)` action. A canceled sent action will not\r\n * be executed, nor will its event be sent, unless it has already been sent\r\n * (e.g., if `cancel(...)` is called after the `send(...)` action's `delay`).\r\n *\r\n * @param sendId The `id` of the `send(...)` action to cancel.\r\n */\n\nvar cancel = function (sendId) {\n return {\n type: cancel$1,\n sendId: sendId\n };\n};\n/**\r\n * Starts an activity.\r\n *\r\n * @param activity The activity to start.\r\n */\n\nfunction start(activity) {\n var activityDef = toActivityDefinition(activity);\n return {\n type: ActionTypes.Start,\n activity: activityDef,\n exec: undefined\n };\n}\n/**\r\n * Stops an activity.\r\n *\r\n * @param actorRef The activity to stop.\r\n */\n\nfunction stop(actorRef) {\n var activity = isFunction(actorRef) ? actorRef : toActivityDefinition(actorRef);\n return {\n type: ActionTypes.Stop,\n activity: activity,\n exec: undefined\n };\n}\nfunction resolveStop(action, context, _event) {\n var actorRefOrString = isFunction(action.activity) ? action.activity(context, _event.data) : action.activity;\n var resolvedActorRef = typeof actorRefOrString === 'string' ? {\n id: actorRefOrString\n } : actorRefOrString;\n var actionObject = {\n type: ActionTypes.Stop,\n activity: resolvedActorRef\n };\n return actionObject;\n}\n/**\r\n * Updates the current context of the machine.\r\n *\r\n * @param assignment An object that represents the partial context to update.\r\n */\n\nvar assign = function (assignment) {\n return {\n type: assign$1,\n assignment: assignment\n };\n};\nfunction isActionObject(action) {\n return typeof action === 'object' && 'type' in action;\n}\n/**\r\n * Returns an event type that represents an implicit event that\r\n * is sent after the specified `delay`.\r\n *\r\n * @param delayRef The delay in milliseconds\r\n * @param id The state node ID where this event is handled\r\n */\n\nfunction after(delayRef, id) {\n var idSuffix = id ? \"#\".concat(id) : '';\n return \"\".concat(ActionTypes.After, \"(\").concat(delayRef, \")\").concat(idSuffix);\n}\n/**\r\n * Returns an event that represents that a final state node\r\n * has been reached in the parent state node.\r\n *\r\n * @param id The final state node's parent state node `id`\r\n * @param data The data to pass into the event\r\n */\n\nfunction done(id, data) {\n var type = \"\".concat(ActionTypes.DoneState, \".\").concat(id);\n var eventObject = {\n type: type,\n data: data\n };\n\n eventObject.toString = function () {\n return type;\n };\n\n return eventObject;\n}\n/**\r\n * Returns an event that represents that an invoked service has terminated.\r\n *\r\n * An invoked service is terminated when it has reached a top-level final state node,\r\n * but not when it is canceled.\r\n *\r\n * @param id The final state node ID\r\n * @param data The data to pass into the event\r\n */\n\nfunction doneInvoke(id, data) {\n var type = \"\".concat(ActionTypes.DoneInvoke, \".\").concat(id);\n var eventObject = {\n type: type,\n data: data\n };\n\n eventObject.toString = function () {\n return type;\n };\n\n return eventObject;\n}\nfunction error(id, data) {\n var type = \"\".concat(ActionTypes.ErrorPlatform, \".\").concat(id);\n var eventObject = {\n type: type,\n data: data\n };\n\n eventObject.toString = function () {\n return type;\n };\n\n return eventObject;\n}\nfunction pure(getActions) {\n return {\n type: ActionTypes.Pure,\n get: getActions\n };\n}\n/**\r\n * Forwards (sends) an event to a specified service.\r\n *\r\n * @param target The target service to forward the event to.\r\n * @param options Options to pass into the send action creator.\r\n */\n\nfunction forwardTo(target, options) {\n if (!IS_PRODUCTION && (!target || typeof target === 'function')) {\n var originalTarget_1 = target;\n\n target = function () {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n var resolvedTarget = typeof originalTarget_1 === 'function' ? originalTarget_1.apply(void 0, __spreadArray([], __read(args), false)) : originalTarget_1;\n\n if (!resolvedTarget) {\n throw new Error(\"Attempted to forward event to undefined actor. This risks an infinite loop in the sender.\");\n }\n\n return resolvedTarget;\n };\n }\n\n return send(function (_, event) {\n return event;\n }, __assign(__assign({}, options), {\n to: target\n }));\n}\n/**\r\n * Escalates an error by sending it as an event to this machine's parent.\r\n *\r\n * @param errorData The error data to send, or the expression function that\r\n * takes in the `context`, `event`, and `meta`, and returns the error data to send.\r\n * @param options Options to pass into the send action creator.\r\n */\n\nfunction escalate(errorData, options) {\n return sendParent(function (context, event, meta) {\n return {\n type: error$1,\n data: isFunction(errorData) ? errorData(context, event, meta) : errorData\n };\n }, __assign(__assign({}, options), {\n to: SpecialTargets.Parent\n }));\n}\nfunction choose(conds) {\n return {\n type: ActionTypes.Choose,\n conds: conds\n };\n}\n\nvar pluckAssigns = function (actionBlocks) {\n var e_1, _a;\n\n var assignActions = [];\n\n try {\n for (var actionBlocks_1 = __values(actionBlocks), actionBlocks_1_1 = actionBlocks_1.next(); !actionBlocks_1_1.done; actionBlocks_1_1 = actionBlocks_1.next()) {\n var block = actionBlocks_1_1.value;\n var i = 0;\n\n while (i < block.actions.length) {\n if (block.actions[i].type === assign$1) {\n assignActions.push(block.actions[i]);\n block.actions.splice(i, 1);\n continue;\n }\n\n i++;\n }\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (actionBlocks_1_1 && !actionBlocks_1_1.done && (_a = actionBlocks_1.return)) _a.call(actionBlocks_1);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n return assignActions;\n};\n\nfunction resolveActions(machine, currentState, currentContext, _event, actionBlocks, predictableExec, preserveActionOrder) {\n if (preserveActionOrder === void 0) {\n preserveActionOrder = false;\n }\n\n var assignActions = preserveActionOrder ? [] : pluckAssigns(actionBlocks);\n var updatedContext = assignActions.length ? updateContext(currentContext, _event, assignActions, currentState) : currentContext;\n var preservedContexts = preserveActionOrder ? [currentContext] : undefined;\n var deferredToBlockEnd = [];\n\n function handleAction(blockType, actionObject) {\n var _a;\n\n switch (actionObject.type) {\n case raise$1:\n {\n var raisedAction = resolveRaise(actionObject, updatedContext, _event, machine.options.delays);\n\n if (predictableExec && typeof raisedAction.delay === 'number') {\n predictableExec(raisedAction, updatedContext, _event);\n }\n\n return raisedAction;\n }\n\n case send$1:\n var sendAction = resolveSend(actionObject, updatedContext, _event, machine.options.delays); // TODO: fix ActionTypes.Init\n\n if (!IS_PRODUCTION) {\n var configuredDelay = actionObject.delay; // warn after resolving as we can create better contextual message here\n\n warn(!isString(configuredDelay) || typeof sendAction.delay === 'number', // tslint:disable-next-line:max-line-length\n \"No delay reference for delay expression '\".concat(configuredDelay, \"' was found on machine '\").concat(machine.id, \"'\"));\n }\n\n if (predictableExec && sendAction.to !== SpecialTargets.Internal) {\n if (blockType === 'entry') {\n deferredToBlockEnd.push(sendAction);\n } else {\n predictableExec(sendAction, updatedContext, _event);\n }\n }\n\n return sendAction;\n\n case log$1:\n {\n var resolved = resolveLog(actionObject, updatedContext, _event);\n predictableExec === null || predictableExec === void 0 ? void 0 : predictableExec(resolved, updatedContext, _event);\n return resolved;\n }\n\n case choose$1:\n {\n var chooseAction = actionObject;\n var matchedActions = (_a = chooseAction.conds.find(function (condition) {\n var guard = toGuard(condition.cond, machine.options.guards);\n return !guard || evaluateGuard(machine, guard, updatedContext, _event, !predictableExec ? currentState : undefined);\n })) === null || _a === void 0 ? void 0 : _a.actions;\n\n if (!matchedActions) {\n return [];\n }\n\n var _b = __read(resolveActions(machine, currentState, updatedContext, _event, [{\n type: blockType,\n actions: toActionObjects(toArray(matchedActions), machine.options.actions)\n }], predictableExec, preserveActionOrder), 2),\n resolvedActionsFromChoose = _b[0],\n resolvedContextFromChoose = _b[1];\n\n updatedContext = resolvedContextFromChoose;\n preservedContexts === null || preservedContexts === void 0 ? void 0 : preservedContexts.push(updatedContext);\n return resolvedActionsFromChoose;\n }\n\n case pure$1:\n {\n var matchedActions = actionObject.get(updatedContext, _event.data);\n\n if (!matchedActions) {\n return [];\n }\n\n var _c = __read(resolveActions(machine, currentState, updatedContext, _event, [{\n type: blockType,\n actions: toActionObjects(toArray(matchedActions), machine.options.actions)\n }], predictableExec, preserveActionOrder), 2),\n resolvedActionsFromPure = _c[0],\n resolvedContext = _c[1];\n\n updatedContext = resolvedContext;\n preservedContexts === null || preservedContexts === void 0 ? void 0 : preservedContexts.push(updatedContext);\n return resolvedActionsFromPure;\n }\n\n case stop$1:\n {\n var resolved = resolveStop(actionObject, updatedContext, _event);\n predictableExec === null || predictableExec === void 0 ? void 0 : predictableExec(resolved, currentContext, _event);\n return resolved;\n }\n\n case assign$1:\n {\n updatedContext = updateContext(updatedContext, _event, [actionObject], !predictableExec ? currentState : undefined);\n preservedContexts === null || preservedContexts === void 0 ? void 0 : preservedContexts.push(updatedContext);\n break;\n }\n\n default:\n var resolvedActionObject = toActionObject(actionObject, machine.options.actions);\n var exec_1 = resolvedActionObject.exec;\n\n if (predictableExec) {\n predictableExec(resolvedActionObject, updatedContext, _event);\n } else if (exec_1 && preservedContexts) {\n var contextIndex_1 = preservedContexts.length - 1;\n\n var wrapped = __assign(__assign({}, resolvedActionObject), {\n exec: function (_ctx) {\n var args = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n\n exec_1.apply(void 0, __spreadArray([preservedContexts[contextIndex_1]], __read(args), false));\n }\n });\n\n resolvedActionObject = wrapped;\n }\n\n return resolvedActionObject;\n }\n }\n\n function processBlock(block) {\n var e_2, _a;\n\n var resolvedActions = [];\n\n try {\n for (var _b = __values(block.actions), _c = _b.next(); !_c.done; _c = _b.next()) {\n var action = _c.value;\n var resolved = handleAction(block.type, action);\n\n if (resolved) {\n resolvedActions = resolvedActions.concat(resolved);\n }\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n deferredToBlockEnd.forEach(function (action) {\n predictableExec(action, updatedContext, _event);\n });\n deferredToBlockEnd.length = 0;\n return resolvedActions;\n }\n\n var resolvedActions = flatten(actionBlocks.map(processBlock));\n return [resolvedActions, updatedContext];\n}\n\nexport { after, assign, cancel, choose, done, doneInvoke, error, escalate, forwardTo, getActionFunction, initEvent, isActionObject, log, pure, raise, resolveActions, resolveLog, resolveRaise, resolveSend, resolveStop, respond, send, sendParent, sendTo, sendUpdate, start, stop, toActionObject, toActionObjects, toActivityDefinition };\n","/**\r\n * Maintains a stack of the current service in scope.\r\n * This is used to provide the correct service to spawn().\r\n */\nvar serviceStack = [];\nvar provide = function (service, fn) {\n serviceStack.push(service);\n var result = fn(service);\n serviceStack.pop();\n return result;\n};\nvar consume = function (fn) {\n return fn(serviceStack[serviceStack.length - 1]);\n};\n\nexport { consume, provide };\n","import { __assign } from './_virtual/_tslib.js';\nimport { symbolObservable, toInvokeSource, mapContext, isMachine } from './utils.js';\nimport { provide } from './serviceScope.js';\n\nfunction createNullActor(id) {\n var _a;\n\n return _a = {\n id: id,\n send: function () {\n return void 0;\n },\n subscribe: function () {\n return {\n unsubscribe: function () {\n return void 0;\n }\n };\n },\n getSnapshot: function () {\n return undefined;\n },\n toJSON: function () {\n return {\n id: id\n };\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a;\n}\n/**\r\n * Creates a deferred actor that is able to be invoked given the provided\r\n * invocation information in its `.meta` value.\r\n *\r\n * @param invokeDefinition The meta information needed to invoke the actor.\r\n */\n\nfunction createInvocableActor(invokeDefinition, machine, context, _event) {\n var _a;\n\n var invokeSrc = toInvokeSource(invokeDefinition.src);\n var serviceCreator = (_a = machine === null || machine === void 0 ? void 0 : machine.options.services) === null || _a === void 0 ? void 0 : _a[invokeSrc.type];\n var resolvedData = invokeDefinition.data ? mapContext(invokeDefinition.data, context, _event) : undefined;\n var tempActor = serviceCreator ? createDeferredActor(serviceCreator, invokeDefinition.id, resolvedData) : createNullActor(invokeDefinition.id); // @ts-ignore\n\n tempActor.meta = invokeDefinition;\n return tempActor;\n}\nfunction createDeferredActor(entity, id, data) {\n var tempActor = createNullActor(id); // @ts-ignore\n\n tempActor.deferred = true;\n\n if (isMachine(entity)) {\n // \"mute\" the existing service scope so potential spawned actors within the `.initialState` stay deferred here\n var initialState_1 = tempActor.state = provide(undefined, function () {\n return (data ? entity.withContext(data) : entity).initialState;\n });\n\n tempActor.getSnapshot = function () {\n return initialState_1;\n };\n }\n\n return tempActor;\n}\nfunction isActor(item) {\n try {\n return typeof item.send === 'function';\n } catch (e) {\n return false;\n }\n}\nfunction isSpawnedActor(item) {\n return isActor(item) && 'id' in item;\n} // TODO: refactor the return type, this could be written in a better way but it's best to avoid unneccessary breaking changes now\n\nfunction toActorRef(actorRefLike) {\n var _a;\n\n return __assign((_a = {\n subscribe: function () {\n return {\n unsubscribe: function () {\n return void 0;\n }\n };\n },\n id: 'anonymous',\n getSnapshot: function () {\n return undefined;\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a), actorRefLike);\n}\n\nexport { createDeferredActor, createInvocableActor, createNullActor, isActor, isSpawnedActor, toActorRef };\n","import { __values, __spreadArray, __read } from './_virtual/_tslib.js';\nimport { flatten } from './utils.js';\n\nvar isLeafNode = function (stateNode) {\n return stateNode.type === 'atomic' || stateNode.type === 'final';\n};\nfunction getAllChildren(stateNode) {\n return Object.keys(stateNode.states).map(function (key) {\n return stateNode.states[key];\n });\n}\nfunction getChildren(stateNode) {\n return getAllChildren(stateNode).filter(function (sn) {\n return sn.type !== 'history';\n });\n}\nfunction getAllStateNodes(stateNode) {\n var stateNodes = [stateNode];\n\n if (isLeafNode(stateNode)) {\n return stateNodes;\n }\n\n return stateNodes.concat(flatten(getChildren(stateNode).map(getAllStateNodes)));\n}\nfunction getConfiguration(prevStateNodes, stateNodes) {\n var e_1, _a, e_2, _b, e_3, _c, e_4, _d;\n\n var prevConfiguration = new Set(prevStateNodes);\n var prevAdjList = getAdjList(prevConfiguration);\n var configuration = new Set(stateNodes);\n\n try {\n // add all ancestors\n for (var configuration_1 = __values(configuration), configuration_1_1 = configuration_1.next(); !configuration_1_1.done; configuration_1_1 = configuration_1.next()) {\n var s = configuration_1_1.value;\n var m = s.parent;\n\n while (m && !configuration.has(m)) {\n configuration.add(m);\n m = m.parent;\n }\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (configuration_1_1 && !configuration_1_1.done && (_a = configuration_1.return)) _a.call(configuration_1);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n\n var adjList = getAdjList(configuration);\n\n try {\n // add descendants\n for (var configuration_2 = __values(configuration), configuration_2_1 = configuration_2.next(); !configuration_2_1.done; configuration_2_1 = configuration_2.next()) {\n var s = configuration_2_1.value; // if previously active, add existing child nodes\n\n if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {\n if (prevAdjList.get(s)) {\n prevAdjList.get(s).forEach(function (sn) {\n return configuration.add(sn);\n });\n } else {\n s.initialStateNodes.forEach(function (sn) {\n return configuration.add(sn);\n });\n }\n } else {\n if (s.type === 'parallel') {\n try {\n for (var _e = (e_3 = void 0, __values(getChildren(s))), _f = _e.next(); !_f.done; _f = _e.next()) {\n var child = _f.value;\n\n if (!configuration.has(child)) {\n configuration.add(child);\n\n if (prevAdjList.get(child)) {\n prevAdjList.get(child).forEach(function (sn) {\n return configuration.add(sn);\n });\n } else {\n child.initialStateNodes.forEach(function (sn) {\n return configuration.add(sn);\n });\n }\n }\n }\n } catch (e_3_1) {\n e_3 = {\n error: e_3_1\n };\n } finally {\n try {\n if (_f && !_f.done && (_c = _e.return)) _c.call(_e);\n } finally {\n if (e_3) throw e_3.error;\n }\n }\n }\n }\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (configuration_2_1 && !configuration_2_1.done && (_b = configuration_2.return)) _b.call(configuration_2);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n try {\n // add all ancestors\n for (var configuration_3 = __values(configuration), configuration_3_1 = configuration_3.next(); !configuration_3_1.done; configuration_3_1 = configuration_3.next()) {\n var s = configuration_3_1.value;\n var m = s.parent;\n\n while (m && !configuration.has(m)) {\n configuration.add(m);\n m = m.parent;\n }\n }\n } catch (e_4_1) {\n e_4 = {\n error: e_4_1\n };\n } finally {\n try {\n if (configuration_3_1 && !configuration_3_1.done && (_d = configuration_3.return)) _d.call(configuration_3);\n } finally {\n if (e_4) throw e_4.error;\n }\n }\n\n return configuration;\n}\n\nfunction getValueFromAdj(baseNode, adjList) {\n var childStateNodes = adjList.get(baseNode);\n\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\n\n if (baseNode.type === 'compound') {\n var childStateNode = childStateNodes[0];\n\n if (childStateNode) {\n if (isLeafNode(childStateNode)) {\n return childStateNode.key;\n }\n } else {\n return {};\n }\n }\n\n var stateValue = {};\n childStateNodes.forEach(function (csn) {\n stateValue[csn.key] = getValueFromAdj(csn, adjList);\n });\n return stateValue;\n}\n\nfunction getAdjList(configuration) {\n var e_5, _a;\n\n var adjList = new Map();\n\n try {\n for (var configuration_4 = __values(configuration), configuration_4_1 = configuration_4.next(); !configuration_4_1.done; configuration_4_1 = configuration_4.next()) {\n var s = configuration_4_1.value;\n\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n\n if (s.parent) {\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n\n adjList.get(s.parent).push(s);\n }\n }\n } catch (e_5_1) {\n e_5 = {\n error: e_5_1\n };\n } finally {\n try {\n if (configuration_4_1 && !configuration_4_1.done && (_a = configuration_4.return)) _a.call(configuration_4);\n } finally {\n if (e_5) throw e_5.error;\n }\n }\n\n return adjList;\n}\nfunction getValue(rootNode, configuration) {\n var config = getConfiguration([rootNode], configuration);\n return getValueFromAdj(rootNode, getAdjList(config));\n}\nfunction has(iterable, item) {\n if (Array.isArray(iterable)) {\n return iterable.some(function (member) {\n return member === item;\n });\n }\n\n if (iterable instanceof Set) {\n return iterable.has(item);\n }\n\n return false; // TODO: fix\n}\nfunction nextEvents(configuration) {\n return __spreadArray([], __read(new Set(flatten(__spreadArray([], __read(configuration.map(function (sn) {\n return sn.ownEvents;\n })), false)))), false);\n}\nfunction isInFinalState(configuration, stateNode) {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(function (s) {\n return s.type === 'final' && has(configuration, s);\n });\n }\n\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every(function (sn) {\n return isInFinalState(configuration, sn);\n });\n }\n\n return false;\n}\nfunction getMeta(configuration) {\n if (configuration === void 0) {\n configuration = [];\n }\n\n return configuration.reduce(function (acc, stateNode) {\n if (stateNode.meta !== undefined) {\n acc[stateNode.id] = stateNode.meta;\n }\n\n return acc;\n }, {});\n}\nfunction getTagsFromConfiguration(configuration) {\n return new Set(flatten(configuration.map(function (sn) {\n return sn.tags;\n })));\n}\n\nexport { getAdjList, getAllChildren, getAllStateNodes, getChildren, getConfiguration, getMeta, getTagsFromConfiguration, getValue, has, isInFinalState, isLeafNode, nextEvents };\n","import { __assign, __spreadArray, __read, __rest } from './_virtual/_tslib.js';\nimport { EMPTY_ACTIVITY_MAP } from './constants.js';\nimport { isString, matchesState, warn } from './utils.js';\nimport { getMeta, nextEvents } from './stateUtils.js';\nimport { initEvent } from './actions.js';\nimport { IS_PRODUCTION } from './environment.js';\n\nfunction stateValuesEqual(a, b) {\n if (a === b) {\n return true;\n }\n\n if (a === undefined || b === undefined) {\n return false;\n }\n\n if (isString(a) || isString(b)) {\n return a === b;\n }\n\n var aKeys = Object.keys(a);\n var bKeys = Object.keys(b);\n return aKeys.length === bKeys.length && aKeys.every(function (key) {\n return stateValuesEqual(a[key], b[key]);\n });\n}\nfunction isStateConfig(state) {\n if (typeof state !== 'object' || state === null) {\n return false;\n }\n\n return 'value' in state && '_event' in state;\n}\n/**\r\n * @deprecated Use `isStateConfig(object)` or `state instanceof State` instead.\r\n */\n\nvar isState = isStateConfig;\nfunction bindActionToState(action, state) {\n var exec = action.exec;\n\n var boundAction = __assign(__assign({}, action), {\n exec: exec !== undefined ? function () {\n return exec(state.context, state.event, {\n action: action,\n state: state,\n _event: state._event\n });\n } : undefined\n });\n\n return boundAction;\n}\n\nvar State =\n/*#__PURE__*/\n\n/** @class */\nfunction () {\n /**\r\n * Creates a new State instance.\r\n * @param value The state value\r\n * @param context The extended state\r\n * @param historyValue The tree representing historical values of the state nodes\r\n * @param history The previous state\r\n * @param actions An array of action objects to execute as side-effects\r\n * @param activities A mapping of activities and whether they are started (`true`) or stopped (`false`).\r\n * @param meta\r\n * @param events Internal event queue. Should be empty with run-to-completion semantics.\r\n * @param configuration\r\n */\n function State(config) {\n var _this = this;\n\n var _a;\n\n this.actions = [];\n this.activities = EMPTY_ACTIVITY_MAP;\n this.meta = {};\n this.events = [];\n this.value = config.value;\n this.context = config.context;\n this._event = config._event;\n this._sessionid = config._sessionid;\n this.event = this._event.data;\n this.historyValue = config.historyValue;\n this.history = config.history;\n this.actions = config.actions || [];\n this.activities = config.activities || EMPTY_ACTIVITY_MAP;\n this.meta = getMeta(config.configuration);\n this.events = config.events || [];\n this.matches = this.matches.bind(this);\n this.toStrings = this.toStrings.bind(this);\n this.configuration = config.configuration;\n this.transitions = config.transitions;\n this.children = config.children;\n this.done = !!config.done;\n this.tags = (_a = Array.isArray(config.tags) ? new Set(config.tags) : config.tags) !== null && _a !== void 0 ? _a : new Set();\n this.machine = config.machine;\n Object.defineProperty(this, 'nextEvents', {\n get: function () {\n return nextEvents(_this.configuration);\n }\n });\n }\n /**\r\n * Creates a new State instance for the given `stateValue` and `context`.\r\n * @param stateValue\r\n * @param context\r\n */\n\n\n State.from = function (stateValue, context) {\n if (stateValue instanceof State) {\n if (stateValue.context !== context) {\n return new State({\n value: stateValue.value,\n context: context,\n _event: stateValue._event,\n _sessionid: null,\n historyValue: stateValue.historyValue,\n history: stateValue.history,\n actions: [],\n activities: stateValue.activities,\n meta: {},\n events: [],\n configuration: [],\n transitions: [],\n children: {}\n });\n }\n\n return stateValue;\n }\n\n var _event = initEvent;\n return new State({\n value: stateValue,\n context: context,\n _event: _event,\n _sessionid: null,\n historyValue: undefined,\n history: undefined,\n actions: [],\n activities: undefined,\n meta: undefined,\n events: [],\n configuration: [],\n transitions: [],\n children: {}\n });\n };\n /**\r\n * Creates a new State instance for the given `config`.\r\n * @param config The state config\r\n */\n\n\n State.create = function (config) {\n return new State(config);\n };\n /**\r\n * Creates a new `State` instance for the given `stateValue` and `context` with no actions (side-effects).\r\n * @param stateValue\r\n * @param context\r\n */\n\n\n State.inert = function (stateValue, context) {\n if (stateValue instanceof State) {\n if (!stateValue.actions.length) {\n return stateValue;\n }\n\n var _event = initEvent;\n return new State({\n value: stateValue.value,\n context: context,\n _event: _event,\n _sessionid: null,\n historyValue: stateValue.historyValue,\n history: stateValue.history,\n activities: stateValue.activities,\n configuration: stateValue.configuration,\n transitions: [],\n children: {}\n });\n }\n\n return State.from(stateValue, context);\n };\n /**\r\n * Returns an array of all the string leaf state node paths.\r\n * @param stateValue\r\n * @param delimiter The character(s) that separate each subpath in the string state node path.\r\n */\n\n\n State.prototype.toStrings = function (stateValue, delimiter) {\n var _this = this;\n\n if (stateValue === void 0) {\n stateValue = this.value;\n }\n\n if (delimiter === void 0) {\n delimiter = '.';\n }\n\n if (isString(stateValue)) {\n return [stateValue];\n }\n\n var valueKeys = Object.keys(stateValue);\n return valueKeys.concat.apply(valueKeys, __spreadArray([], __read(valueKeys.map(function (key) {\n return _this.toStrings(stateValue[key], delimiter).map(function (s) {\n return key + delimiter + s;\n });\n })), false));\n };\n\n State.prototype.toJSON = function () {\n var _a = this;\n _a.configuration;\n _a.transitions;\n var tags = _a.tags;\n _a.machine;\n var jsonValues = __rest(_a, [\"configuration\", \"transitions\", \"tags\", \"machine\"]);\n\n return __assign(__assign({}, jsonValues), {\n tags: Array.from(tags)\n });\n };\n\n State.prototype.matches = function (parentStateValue) {\n return matchesState(parentStateValue, this.value);\n };\n /**\r\n * Whether the current state configuration has a state node with the specified `tag`.\r\n * @param tag\r\n */\n\n\n State.prototype.hasTag = function (tag) {\n return this.tags.has(tag);\n };\n /**\r\n * Determines whether sending the `event` will cause a non-forbidden transition\r\n * to be selected, even if the transitions have no actions nor\r\n * change the state value.\r\n *\r\n * @param event The event to test\r\n * @returns Whether the event will cause a transition\r\n */\n\n\n State.prototype.can = function (event) {\n var _a;\n\n if (IS_PRODUCTION) {\n warn(!!this.machine, \"state.can(...) used outside of a machine-created State object; this will always return false.\");\n }\n\n var transitionData = (_a = this.machine) === null || _a === void 0 ? void 0 : _a.getTransitionData(this, event);\n return !!(transitionData === null || transitionData === void 0 ? void 0 : transitionData.transitions.length) && // Check that at least one transition is not forbidden\n transitionData.transitions.some(function (t) {\n return t.target !== undefined || t.actions.length;\n });\n };\n\n return State;\n}();\n\nexport { State, bindActionToState, isState, isStateConfig, stateValuesEqual };\n","import { __assign } from './_virtual/_tslib.js';\n\nvar defaultOptions = {\n deferEvents: false\n};\n\nvar Scheduler =\n/*#__PURE__*/\n\n/** @class */\nfunction () {\n function Scheduler(options) {\n this.processingEvent = false;\n this.queue = [];\n this.initialized = false;\n this.options = __assign(__assign({}, defaultOptions), options);\n }\n\n Scheduler.prototype.initialize = function (callback) {\n this.initialized = true;\n\n if (callback) {\n if (!this.options.deferEvents) {\n this.schedule(callback);\n return;\n }\n\n this.process(callback);\n }\n\n this.flushEvents();\n };\n\n Scheduler.prototype.schedule = function (task) {\n if (!this.initialized || this.processingEvent) {\n this.queue.push(task);\n return;\n }\n\n if (this.queue.length !== 0) {\n throw new Error('Event queue should be empty when it is not processing events');\n }\n\n this.process(task);\n this.flushEvents();\n };\n\n Scheduler.prototype.clear = function () {\n this.queue = [];\n };\n\n Scheduler.prototype.flushEvents = function () {\n var nextCallback = this.queue.shift();\n\n while (nextCallback) {\n this.process(nextCallback);\n nextCallback = this.queue.shift();\n }\n };\n\n Scheduler.prototype.process = function (callback) {\n this.processingEvent = true;\n\n try {\n callback();\n } catch (e) {\n // there is no use to keep the future events\n // as the situation is not anymore the same\n this.clear();\n throw e;\n } finally {\n this.processingEvent = false;\n }\n };\n\n return Scheduler;\n}();\n\nexport { Scheduler };\n","var children = /*#__PURE__*/new Map();\nvar sessionIdIndex = 0;\nvar registry = {\n bookId: function () {\n return \"x:\".concat(sessionIdIndex++);\n },\n register: function (id, actor) {\n children.set(id, actor);\n return id;\n },\n get: function (id) {\n return children.get(id);\n },\n free: function (id) {\n children.delete(id);\n }\n};\n\nexport { registry };\n","import { IS_PRODUCTION } from './environment.js';\n\nfunction getGlobal() {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n\n if (typeof self !== 'undefined') {\n return self;\n }\n\n if (typeof window !== 'undefined') {\n return window;\n }\n\n if (typeof global !== 'undefined') {\n return global;\n }\n\n if (!IS_PRODUCTION) {\n console.warn('XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues');\n }\n}\n\nfunction getDevTools() {\n var global = getGlobal();\n\n if (global && '__xstate__' in global) {\n return global.__xstate__;\n }\n\n return undefined;\n}\n\nfunction registerService(service) {\n if (!getGlobal()) {\n return;\n }\n\n var devTools = getDevTools();\n\n if (devTools) {\n devTools.register(service);\n }\n}\n\nexport { getGlobal, registerService };\n","import { error, doneInvoke } from './actions.js';\nimport { toActorRef } from './Actor.js';\nimport { toObserver } from './utils.js';\n\n/**\r\n * Returns an actor behavior from a reducer and its initial state.\r\n *\r\n * @param transition The pure reducer that returns the next state given the current state and event.\r\n * @param initialState The initial state of the reducer.\r\n * @returns An actor behavior\r\n */\n\nfunction fromReducer(transition, initialState) {\n return {\n transition: transition,\n initialState: initialState\n };\n}\nfunction fromPromise(promiseFn) {\n var initialState = {\n error: undefined,\n data: undefined,\n status: 'pending'\n };\n return {\n transition: function (state, event, _a) {\n var parent = _a.parent,\n id = _a.id,\n observers = _a.observers;\n\n switch (event.type) {\n case 'fulfill':\n parent === null || parent === void 0 ? void 0 : parent.send(doneInvoke(id, event.data));\n return {\n error: undefined,\n data: event.data,\n status: 'fulfilled'\n };\n\n case 'reject':\n parent === null || parent === void 0 ? void 0 : parent.send(error(id, event.error));\n observers.forEach(function (observer) {\n observer.error(event.error);\n });\n return {\n error: event.error,\n data: undefined,\n status: 'rejected'\n };\n\n default:\n return state;\n }\n },\n initialState: initialState,\n start: function (_a) {\n var self = _a.self;\n promiseFn().then(function (data) {\n self.send({\n type: 'fulfill',\n data: data\n });\n }, function (reason) {\n self.send({\n type: 'reject',\n error: reason\n });\n });\n return initialState;\n }\n };\n}\nfunction spawnBehavior(behavior, options) {\n if (options === void 0) {\n options = {};\n }\n\n var state = behavior.initialState;\n var observers = new Set();\n var mailbox = [];\n var flushing = false;\n\n var flush = function () {\n if (flushing) {\n return;\n }\n\n flushing = true;\n\n while (mailbox.length > 0) {\n var event_1 = mailbox.shift();\n state = behavior.transition(state, event_1, actorCtx);\n observers.forEach(function (observer) {\n return observer.next(state);\n });\n }\n\n flushing = false;\n };\n\n var actor = toActorRef({\n id: options.id,\n send: function (event) {\n mailbox.push(event);\n flush();\n },\n getSnapshot: function () {\n return state;\n },\n subscribe: function (next, handleError, complete) {\n var observer = toObserver(next, handleError, complete);\n observers.add(observer);\n observer.next(state);\n return {\n unsubscribe: function () {\n observers.delete(observer);\n }\n };\n }\n });\n var actorCtx = {\n parent: options.parent,\n self: actor,\n id: options.id || 'anonymous',\n observers: observers\n };\n state = behavior.start ? behavior.start(actorCtx) : state;\n return actor;\n}\n\nexport { fromPromise, fromReducer, spawnBehavior };\n","import { __values, __spreadArray, __read, __assign } from './_virtual/_tslib.js';\nimport { SpecialTargets, ActionTypes } from './types.js';\nimport { isStateConfig, State, bindActionToState } from './State.js';\nimport { errorPlatform, update, error as error$1, log, stop, start, cancel, send, raise } from './actionTypes.js';\nimport { initEvent, doneInvoke, toActionObjects, resolveActions, error, getActionFunction } from './actions.js';\nimport { IS_PRODUCTION } from './environment.js';\nimport { warn, mapContext, toObserver, isFunction, toSCXMLEvent, flatten, isRaisableAction, isPromiseLike, isObservable, isMachine, isBehavior, reportUnhandledExceptionOnInvocation, symbolObservable, isArray, toEventObject, isString, isActor, toInvokeSource, uniqueId } from './utils.js';\nimport { Scheduler } from './scheduler.js';\nimport { createDeferredActor, isSpawnedActor } from './Actor.js';\nimport { registry } from './registry.js';\nimport { getGlobal, registerService } from './devTools.js';\nimport { provide, consume } from './serviceScope.js';\nimport { spawnBehavior } from './behaviors.js';\n\nvar DEFAULT_SPAWN_OPTIONS = {\n sync: false,\n autoForward: false\n};\nvar InterpreterStatus;\n\n(function (InterpreterStatus) {\n InterpreterStatus[InterpreterStatus[\"NotStarted\"] = 0] = \"NotStarted\";\n InterpreterStatus[InterpreterStatus[\"Running\"] = 1] = \"Running\";\n InterpreterStatus[InterpreterStatus[\"Stopped\"] = 2] = \"Stopped\";\n})(InterpreterStatus || (InterpreterStatus = {}));\n\nvar Interpreter =\n/*#__PURE__*/\n\n/** @class */\nfunction () {\n /**\r\n * Creates a new Interpreter instance (i.e., service) for the given machine with the provided options, if any.\r\n *\r\n * @param machine The machine to be interpreted\r\n * @param options Interpreter options\r\n */\n function Interpreter(machine, options) {\n if (options === void 0) {\n options = Interpreter.defaultOptions;\n }\n\n var _this = this;\n\n this.machine = machine;\n this.delayedEventsMap = {};\n this.listeners = new Set();\n this.contextListeners = new Set();\n this.stopListeners = new Set();\n this.doneListeners = new Set();\n this.eventListeners = new Set();\n this.sendListeners = new Set();\n /**\r\n * Whether the service is started.\r\n */\n\n this.initialized = false;\n this.status = InterpreterStatus.NotStarted;\n this.children = new Map();\n this.forwardTo = new Set();\n this._outgoingQueue = [];\n /**\r\n * Alias for Interpreter.prototype.start\r\n */\n\n this.init = this.start;\n /**\r\n * Sends an event to the running interpreter to trigger a transition.\r\n *\r\n * An array of events (batched) can be sent as well, which will send all\r\n * batched events to the running interpreter. The listeners will be\r\n * notified only **once** when all events are processed.\r\n *\r\n * @param event The event(s) to send\r\n */\n\n this.send = function (event, payload) {\n if (isArray(event)) {\n _this.batch(event);\n\n return _this.state;\n }\n\n var _event = toSCXMLEvent(toEventObject(event, payload));\n\n if (_this.status === InterpreterStatus.Stopped) {\n // do nothing\n if (!IS_PRODUCTION) {\n warn(false, \"Event \\\"\".concat(_event.name, \"\\\" was sent to stopped service \\\"\").concat(_this.machine.id, \"\\\". This service has already reached its final state, and will not transition.\\nEvent: \").concat(JSON.stringify(_event.data)));\n }\n\n return _this.state;\n }\n\n if (_this.status !== InterpreterStatus.Running && !_this.options.deferEvents) {\n throw new Error(\"Event \\\"\".concat(_event.name, \"\\\" was sent to uninitialized service \\\"\").concat(_this.machine.id // tslint:disable-next-line:max-line-length\n , \"\\\". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\\nEvent: \").concat(JSON.stringify(_event.data)));\n }\n\n _this.scheduler.schedule(function () {\n // Forward copy of event to child actors\n _this.forward(_event);\n\n var nextState = _this._nextState(_event);\n\n _this.update(nextState, _event);\n });\n\n return _this._state; // TODO: deprecate (should return void)\n // tslint:disable-next-line:semicolon\n };\n\n this.sendTo = function (event, to, immediate) {\n var isParent = _this.parent && (to === SpecialTargets.Parent || _this.parent.id === to);\n var target = isParent ? _this.parent : isString(to) ? to === SpecialTargets.Internal ? _this : _this.children.get(to) || registry.get(to) : isActor(to) ? to : undefined;\n\n if (!target) {\n if (!isParent) {\n throw new Error(\"Unable to send event to child '\".concat(to, \"' from service '\").concat(_this.id, \"'.\"));\n } // tslint:disable-next-line:no-console\n\n\n if (!IS_PRODUCTION) {\n warn(false, \"Service '\".concat(_this.id, \"' has no parent: unable to send event \").concat(event.type));\n }\n\n return;\n }\n\n if ('machine' in target) {\n // perhaps those events should be rejected in the parent\n // but atm it doesn't have easy access to all of the information that is required to do it reliably\n if (_this.status !== InterpreterStatus.Stopped || _this.parent !== target || // we need to send events to the parent from exit handlers of a machine that reached its final state\n _this.state.done) {\n // Send SCXML events to machines\n var scxmlEvent = __assign(__assign({}, event), {\n name: event.name === error$1 ? \"\".concat(error(_this.id)) : event.name,\n origin: _this.sessionId\n });\n\n if (!immediate && _this.machine.config.predictableActionArguments) {\n _this._outgoingQueue.push([target, scxmlEvent]);\n } else {\n target.send(scxmlEvent);\n }\n }\n } else {\n // Send normal events to other targets\n if (!immediate && _this.machine.config.predictableActionArguments) {\n _this._outgoingQueue.push([target, event.data]);\n } else {\n target.send(event.data);\n }\n }\n };\n\n this._exec = function (action, context, _event, actionFunctionMap) {\n if (actionFunctionMap === void 0) {\n actionFunctionMap = _this.machine.options.actions;\n }\n\n var actionOrExec = action.exec || getActionFunction(action.type, actionFunctionMap);\n var exec = isFunction(actionOrExec) ? actionOrExec : actionOrExec ? actionOrExec.exec : action.exec;\n\n if (exec) {\n try {\n return exec(context, _event.data, !_this.machine.config.predictableActionArguments ? {\n action: action,\n state: _this.state,\n _event: _event\n } : {\n action: action,\n _event: _event\n });\n } catch (err) {\n if (_this.parent) {\n _this.parent.send({\n type: 'xstate.error',\n data: err\n });\n }\n\n throw err;\n }\n }\n\n switch (action.type) {\n case raise:\n {\n // if raise action reached the interpreter then it's a delayed one\n var sendAction_1 = action;\n\n _this.defer(sendAction_1);\n\n break;\n }\n\n case send:\n var sendAction = action;\n\n if (typeof sendAction.delay === 'number') {\n _this.defer(sendAction);\n\n return;\n } else {\n if (sendAction.to) {\n _this.sendTo(sendAction._event, sendAction.to, _event === initEvent);\n } else {\n _this.send(sendAction._event);\n }\n }\n\n break;\n\n case cancel:\n _this.cancel(action.sendId);\n\n break;\n\n case start:\n {\n if (_this.status !== InterpreterStatus.Running) {\n return;\n }\n\n var activity = action.activity; // If the activity will be stopped right after it's started\n // (such as in transient states)\n // don't bother starting the activity.\n\n if ( // in v4 with `predictableActionArguments` invokes are called eagerly when the `this.state` still points to the previous state\n !_this.machine.config.predictableActionArguments && !_this.state.activities[activity.id || activity.type]) {\n break;\n } // Invoked services\n\n\n if (activity.type === ActionTypes.Invoke) {\n var invokeSource = toInvokeSource(activity.src);\n var serviceCreator = _this.machine.options.services ? _this.machine.options.services[invokeSource.type] : undefined;\n var id = activity.id,\n data = activity.data;\n\n if (!IS_PRODUCTION) {\n warn(!('forward' in activity), // tslint:disable-next-line:max-line-length\n \"`forward` property is deprecated (found in invocation of '\".concat(activity.src, \"' in in machine '\").concat(_this.machine.id, \"'). \") + \"Please use `autoForward` instead.\");\n }\n\n var autoForward = 'autoForward' in activity ? activity.autoForward : !!activity.forward;\n\n if (!serviceCreator) {\n // tslint:disable-next-line:no-console\n if (!IS_PRODUCTION) {\n warn(false, \"No service found for invocation '\".concat(activity.src, \"' in machine '\").concat(_this.machine.id, \"'.\"));\n }\n\n return;\n }\n\n var resolvedData = data ? mapContext(data, context, _event) : undefined;\n\n if (typeof serviceCreator === 'string') {\n // TODO: warn\n return;\n }\n\n var source = isFunction(serviceCreator) ? serviceCreator(context, _event.data, {\n data: resolvedData,\n src: invokeSource,\n meta: activity.meta\n }) : serviceCreator;\n\n if (!source) {\n // TODO: warn?\n return;\n }\n\n var options = void 0;\n\n if (isMachine(source)) {\n source = resolvedData ? source.withContext(resolvedData) : source;\n options = {\n autoForward: autoForward\n };\n }\n\n _this.spawn(source, id, options);\n } else {\n _this.spawnActivity(activity);\n }\n\n break;\n }\n\n case stop:\n {\n _this.stopChild(action.activity.id);\n\n break;\n }\n\n case log:\n var _a = action,\n label = _a.label,\n value = _a.value;\n\n if (label) {\n _this.logger(label, value);\n } else {\n _this.logger(value);\n }\n\n break;\n\n default:\n if (!IS_PRODUCTION) {\n warn(false, \"No implementation found for action type '\".concat(action.type, \"'\"));\n }\n\n break;\n }\n };\n\n var resolvedOptions = __assign(__assign({}, Interpreter.defaultOptions), options);\n\n var clock = resolvedOptions.clock,\n logger = resolvedOptions.logger,\n parent = resolvedOptions.parent,\n id = resolvedOptions.id;\n var resolvedId = id !== undefined ? id : machine.id;\n this.id = resolvedId;\n this.logger = logger;\n this.clock = clock;\n this.parent = parent;\n this.options = resolvedOptions;\n this.scheduler = new Scheduler({\n deferEvents: this.options.deferEvents\n });\n this.sessionId = registry.bookId();\n }\n\n Object.defineProperty(Interpreter.prototype, \"initialState\", {\n get: function () {\n var _this = this;\n\n if (this._initialState) {\n return this._initialState;\n }\n\n return provide(this, function () {\n _this._initialState = _this.machine.initialState;\n return _this._initialState;\n });\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(Interpreter.prototype, \"state\", {\n /**\r\n * @deprecated Use `.getSnapshot()` instead.\r\n */\n get: function () {\n if (!IS_PRODUCTION) {\n warn(this.status !== InterpreterStatus.NotStarted, \"Attempted to read state from uninitialized service '\".concat(this.id, \"'. Make sure the service is started first.\"));\n }\n\n return this._state;\n },\n enumerable: false,\n configurable: true\n });\n /**\r\n * Executes the actions of the given state, with that state's `context` and `event`.\r\n *\r\n * @param state The state whose actions will be executed\r\n * @param actionsConfig The action implementations to use\r\n */\n\n Interpreter.prototype.execute = function (state, actionsConfig) {\n var e_1, _a;\n\n try {\n for (var _b = __values(state.actions), _c = _b.next(); !_c.done; _c = _b.next()) {\n var action = _c.value;\n this.exec(action, state, actionsConfig);\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n };\n\n Interpreter.prototype.update = function (state, _event) {\n var e_2, _a, e_3, _b, e_4, _c, e_5, _d;\n\n var _this = this; // Attach session ID to state\n\n\n state._sessionid = this.sessionId; // Update state\n\n this._state = state; // Execute actions\n\n if ((!this.machine.config.predictableActionArguments || // this is currently required to execute initial actions as the `initialState` gets cached\n // we can't just recompute it (and execute actions while doing so) because we try to preserve identity of actors created within initial assigns\n _event === initEvent) && this.options.execute) {\n this.execute(this.state);\n } else {\n var item = void 0;\n\n while (item = this._outgoingQueue.shift()) {\n item[0].send(item[1]);\n }\n } // Update children\n\n\n this.children.forEach(function (child) {\n _this.state.children[child.id] = child;\n }); // Dev tools\n\n if (this.devTools) {\n this.devTools.send(_event.data, state);\n } // Execute listeners\n\n\n if (state.event) {\n try {\n for (var _e = __values(this.eventListeners), _f = _e.next(); !_f.done; _f = _e.next()) {\n var listener = _f.value;\n listener(state.event);\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (_f && !_f.done && (_a = _e.return)) _a.call(_e);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n }\n\n try {\n for (var _g = __values(this.listeners), _h = _g.next(); !_h.done; _h = _g.next()) {\n var listener = _h.value;\n listener(state, state.event);\n }\n } catch (e_3_1) {\n e_3 = {\n error: e_3_1\n };\n } finally {\n try {\n if (_h && !_h.done && (_b = _g.return)) _b.call(_g);\n } finally {\n if (e_3) throw e_3.error;\n }\n }\n\n try {\n for (var _j = __values(this.contextListeners), _k = _j.next(); !_k.done; _k = _j.next()) {\n var contextListener = _k.value;\n contextListener(this.state.context, this.state.history ? this.state.history.context : undefined);\n }\n } catch (e_4_1) {\n e_4 = {\n error: e_4_1\n };\n } finally {\n try {\n if (_k && !_k.done && (_c = _j.return)) _c.call(_j);\n } finally {\n if (e_4) throw e_4.error;\n }\n }\n\n if (this.state.done) {\n // get final child state node\n var finalChildStateNode = state.configuration.find(function (sn) {\n return sn.type === 'final' && sn.parent === _this.machine;\n });\n var doneData = finalChildStateNode && finalChildStateNode.doneData ? mapContext(finalChildStateNode.doneData, state.context, _event) : undefined;\n this._doneEvent = doneInvoke(this.id, doneData);\n\n try {\n for (var _l = __values(this.doneListeners), _m = _l.next(); !_m.done; _m = _l.next()) {\n var listener = _m.value;\n listener(this._doneEvent);\n }\n } catch (e_5_1) {\n e_5 = {\n error: e_5_1\n };\n } finally {\n try {\n if (_m && !_m.done && (_d = _l.return)) _d.call(_l);\n } finally {\n if (e_5) throw e_5.error;\n }\n }\n\n this._stop();\n\n this._stopChildren();\n\n registry.free(this.sessionId);\n }\n };\n /*\r\n * Adds a listener that is notified whenever a state transition happens. The listener is called with\r\n * the next state and the event object that caused the state transition.\r\n *\r\n * @param listener The state listener\r\n */\n\n\n Interpreter.prototype.onTransition = function (listener) {\n this.listeners.add(listener); // Send current state to listener\n\n if (this.status === InterpreterStatus.Running) {\n listener(this.state, this.state.event);\n }\n\n return this;\n };\n\n Interpreter.prototype.subscribe = function (nextListenerOrObserver, _, // TODO: error listener\n completeListener) {\n var _this = this;\n\n var observer = toObserver(nextListenerOrObserver, _, completeListener);\n this.listeners.add(observer.next); // Send current state to listener\n\n if (this.status !== InterpreterStatus.NotStarted) {\n observer.next(this.state);\n }\n\n var completeOnce = function () {\n _this.doneListeners.delete(completeOnce);\n\n _this.stopListeners.delete(completeOnce);\n\n observer.complete();\n };\n\n if (this.status === InterpreterStatus.Stopped) {\n observer.complete();\n } else {\n this.onDone(completeOnce);\n this.onStop(completeOnce);\n }\n\n return {\n unsubscribe: function () {\n _this.listeners.delete(observer.next);\n\n _this.doneListeners.delete(completeOnce);\n\n _this.stopListeners.delete(completeOnce);\n }\n };\n };\n /**\r\n * Adds an event listener that is notified whenever an event is sent to the running interpreter.\r\n * @param listener The event listener\r\n */\n\n\n Interpreter.prototype.onEvent = function (listener) {\n this.eventListeners.add(listener);\n return this;\n };\n /**\r\n * Adds an event listener that is notified whenever a `send` event occurs.\r\n * @param listener The event listener\r\n */\n\n\n Interpreter.prototype.onSend = function (listener) {\n this.sendListeners.add(listener);\n return this;\n };\n /**\r\n * Adds a context listener that is notified whenever the state context changes.\r\n * @param listener The context listener\r\n */\n\n\n Interpreter.prototype.onChange = function (listener) {\n this.contextListeners.add(listener);\n return this;\n };\n /**\r\n * Adds a listener that is notified when the machine is stopped.\r\n * @param listener The listener\r\n */\n\n\n Interpreter.prototype.onStop = function (listener) {\n this.stopListeners.add(listener);\n return this;\n };\n /**\r\n * Adds a state listener that is notified when the statechart has reached its final state.\r\n * @param listener The state listener\r\n */\n\n\n Interpreter.prototype.onDone = function (listener) {\n if (this.status === InterpreterStatus.Stopped && this._doneEvent) {\n listener(this._doneEvent);\n } else {\n this.doneListeners.add(listener);\n }\n\n return this;\n };\n /**\r\n * Removes a listener.\r\n * @param listener The listener to remove\r\n */\n\n\n Interpreter.prototype.off = function (listener) {\n this.listeners.delete(listener);\n this.eventListeners.delete(listener);\n this.sendListeners.delete(listener);\n this.stopListeners.delete(listener);\n this.doneListeners.delete(listener);\n this.contextListeners.delete(listener);\n return this;\n };\n /**\r\n * Starts the interpreter from the given state, or the initial state.\r\n * @param initialState The state to start the statechart from\r\n */\n\n\n Interpreter.prototype.start = function (initialState) {\n var _this = this;\n\n if (this.status === InterpreterStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n } // yes, it's a hack but we need the related cache to be populated for some things to work (like delayed transitions)\n // this is usually called by `machine.getInitialState` but if we rehydrate from a state we might bypass this call\n // we also don't want to call this method here as it resolves the full initial state which might involve calling assign actions\n // and that could potentially lead to some unwanted side-effects (even such as creating some rogue actors)\n\n\n this.machine._init();\n\n registry.register(this.sessionId, this);\n this.initialized = true;\n this.status = InterpreterStatus.Running;\n var resolvedState = initialState === undefined ? this.initialState : provide(this, function () {\n return isStateConfig(initialState) ? _this.machine.resolveState(initialState) : _this.machine.resolveState(State.from(initialState, _this.machine.context));\n });\n\n if (this.options.devTools) {\n this.attachDev();\n }\n\n this.scheduler.initialize(function () {\n _this.update(resolvedState, initEvent);\n });\n return this;\n };\n\n Interpreter.prototype._stopChildren = function () {\n // TODO: think about converting those to actions\n this.children.forEach(function (child) {\n if (isFunction(child.stop)) {\n child.stop();\n }\n });\n this.children.clear();\n };\n\n Interpreter.prototype._stop = function () {\n var e_6, _a, e_7, _b, e_8, _c, e_9, _d, e_10, _e;\n\n try {\n for (var _f = __values(this.listeners), _g = _f.next(); !_g.done; _g = _f.next()) {\n var listener = _g.value;\n this.listeners.delete(listener);\n }\n } catch (e_6_1) {\n e_6 = {\n error: e_6_1\n };\n } finally {\n try {\n if (_g && !_g.done && (_a = _f.return)) _a.call(_f);\n } finally {\n if (e_6) throw e_6.error;\n }\n }\n\n try {\n for (var _h = __values(this.stopListeners), _j = _h.next(); !_j.done; _j = _h.next()) {\n var listener = _j.value; // call listener, then remove\n\n listener();\n this.stopListeners.delete(listener);\n }\n } catch (e_7_1) {\n e_7 = {\n error: e_7_1\n };\n } finally {\n try {\n if (_j && !_j.done && (_b = _h.return)) _b.call(_h);\n } finally {\n if (e_7) throw e_7.error;\n }\n }\n\n try {\n for (var _k = __values(this.contextListeners), _l = _k.next(); !_l.done; _l = _k.next()) {\n var listener = _l.value;\n this.contextListeners.delete(listener);\n }\n } catch (e_8_1) {\n e_8 = {\n error: e_8_1\n };\n } finally {\n try {\n if (_l && !_l.done && (_c = _k.return)) _c.call(_k);\n } finally {\n if (e_8) throw e_8.error;\n }\n }\n\n try {\n for (var _m = __values(this.doneListeners), _o = _m.next(); !_o.done; _o = _m.next()) {\n var listener = _o.value;\n this.doneListeners.delete(listener);\n }\n } catch (e_9_1) {\n e_9 = {\n error: e_9_1\n };\n } finally {\n try {\n if (_o && !_o.done && (_d = _m.return)) _d.call(_m);\n } finally {\n if (e_9) throw e_9.error;\n }\n }\n\n if (!this.initialized) {\n // Interpreter already stopped; do nothing\n return this;\n }\n\n this.initialized = false;\n this.status = InterpreterStatus.Stopped;\n this._initialState = undefined;\n\n try {\n // we are going to stop within the current sync frame\n // so we can safely just cancel this here as nothing async should be fired anyway\n for (var _p = __values(Object.keys(this.delayedEventsMap)), _q = _p.next(); !_q.done; _q = _p.next()) {\n var key = _q.value;\n this.clock.clearTimeout(this.delayedEventsMap[key]);\n }\n } catch (e_10_1) {\n e_10 = {\n error: e_10_1\n };\n } finally {\n try {\n if (_q && !_q.done && (_e = _p.return)) _e.call(_p);\n } finally {\n if (e_10) throw e_10.error;\n }\n } // clear everything that might be enqueued\n\n\n this.scheduler.clear();\n this.scheduler = new Scheduler({\n deferEvents: this.options.deferEvents\n });\n };\n /**\r\n * Stops the interpreter and unsubscribe all listeners.\r\n *\r\n * This will also notify the `onStop` listeners.\r\n */\n\n\n Interpreter.prototype.stop = function () {\n // TODO: add warning for stopping non-root interpreters\n var _this = this; // grab the current scheduler as it will be replaced in _stop\n\n\n var scheduler = this.scheduler;\n\n this._stop(); // let what is currently processed to be finished\n\n\n scheduler.schedule(function () {\n var _a;\n\n if ((_a = _this._state) === null || _a === void 0 ? void 0 : _a.done) {\n return;\n } // it feels weird to handle this here but we need to handle this even slightly \"out of band\"\n\n\n var _event = toSCXMLEvent({\n type: 'xstate.stop'\n });\n\n var nextState = provide(_this, function () {\n var exitActions = flatten(__spreadArray([], __read(_this.state.configuration), false).sort(function (a, b) {\n return b.order - a.order;\n }).map(function (stateNode) {\n return toActionObjects(stateNode.onExit, _this.machine.options.actions);\n }));\n\n var _a = __read(resolveActions(_this.machine, _this.state, _this.state.context, _event, [{\n type: 'exit',\n actions: exitActions\n }], _this.machine.config.predictableActionArguments ? _this._exec : undefined, _this.machine.config.predictableActionArguments || _this.machine.config.preserveActionOrder), 2),\n resolvedActions = _a[0],\n updatedContext = _a[1];\n\n var newState = new State({\n value: _this.state.value,\n context: updatedContext,\n _event: _event,\n _sessionid: _this.sessionId,\n historyValue: undefined,\n history: _this.state,\n actions: resolvedActions.filter(function (action) {\n return !isRaisableAction(action);\n }),\n activities: {},\n events: [],\n configuration: [],\n transitions: [],\n children: {},\n done: _this.state.done,\n tags: _this.state.tags,\n machine: _this.machine\n });\n newState.changed = true;\n return newState;\n });\n\n _this.update(nextState, _event);\n\n _this._stopChildren();\n\n registry.free(_this.sessionId);\n });\n return this;\n };\n\n Interpreter.prototype.batch = function (events) {\n var _this = this;\n\n if (this.status === InterpreterStatus.NotStarted && this.options.deferEvents) {\n // tslint:disable-next-line:no-console\n if (!IS_PRODUCTION) {\n warn(false, \"\".concat(events.length, \" event(s) were sent to uninitialized service \\\"\").concat(this.machine.id, \"\\\" and are deferred. Make sure .start() is called for this service.\\nEvent: \").concat(JSON.stringify(event)));\n }\n } else if (this.status !== InterpreterStatus.Running) {\n throw new Error( // tslint:disable-next-line:max-line-length\n \"\".concat(events.length, \" event(s) were sent to uninitialized service \\\"\").concat(this.machine.id, \"\\\". Make sure .start() is called for this service, or set { deferEvents: true } in the service options.\"));\n }\n\n if (!events.length) {\n return;\n }\n\n var exec = !!this.machine.config.predictableActionArguments && this._exec;\n this.scheduler.schedule(function () {\n var e_11, _a;\n\n var nextState = _this.state;\n var batchChanged = false;\n var batchedActions = [];\n\n var _loop_1 = function (event_1) {\n var _event = toSCXMLEvent(event_1);\n\n _this.forward(_event);\n\n nextState = provide(_this, function () {\n return _this.machine.transition(nextState, _event, undefined, exec || undefined);\n });\n batchedActions.push.apply(batchedActions, __spreadArray([], __read(_this.machine.config.predictableActionArguments ? nextState.actions : nextState.actions.map(function (a) {\n return bindActionToState(a, nextState);\n })), false));\n batchChanged = batchChanged || !!nextState.changed;\n };\n\n try {\n for (var events_1 = __values(events), events_1_1 = events_1.next(); !events_1_1.done; events_1_1 = events_1.next()) {\n var event_1 = events_1_1.value;\n\n _loop_1(event_1);\n }\n } catch (e_11_1) {\n e_11 = {\n error: e_11_1\n };\n } finally {\n try {\n if (events_1_1 && !events_1_1.done && (_a = events_1.return)) _a.call(events_1);\n } finally {\n if (e_11) throw e_11.error;\n }\n }\n\n nextState.changed = batchChanged;\n nextState.actions = batchedActions;\n\n _this.update(nextState, toSCXMLEvent(events[events.length - 1]));\n });\n };\n /**\r\n * Returns a send function bound to this interpreter instance.\r\n *\r\n * @param event The event to be sent by the sender.\r\n */\n\n\n Interpreter.prototype.sender = function (event) {\n return this.send.bind(this, event);\n };\n\n Interpreter.prototype._nextState = function (event, exec) {\n var _this = this;\n\n if (exec === void 0) {\n exec = !!this.machine.config.predictableActionArguments && this._exec;\n }\n\n var _event = toSCXMLEvent(event);\n\n if (_event.name.indexOf(errorPlatform) === 0 && !this.state.nextEvents.some(function (nextEvent) {\n return nextEvent.indexOf(errorPlatform) === 0;\n })) {\n throw _event.data.data;\n }\n\n var nextState = provide(this, function () {\n return _this.machine.transition(_this.state, _event, undefined, exec || undefined);\n });\n return nextState;\n };\n /**\r\n * Returns the next state given the interpreter's current state and the event.\r\n *\r\n * This is a pure method that does _not_ update the interpreter's state.\r\n *\r\n * @param event The event to determine the next state\r\n */\n\n\n Interpreter.prototype.nextState = function (event) {\n return this._nextState(event, false);\n };\n\n Interpreter.prototype.forward = function (event) {\n var e_12, _a;\n\n try {\n for (var _b = __values(this.forwardTo), _c = _b.next(); !_c.done; _c = _b.next()) {\n var id = _c.value;\n var child = this.children.get(id);\n\n if (!child) {\n throw new Error(\"Unable to forward event '\".concat(event, \"' from interpreter '\").concat(this.id, \"' to nonexistant child '\").concat(id, \"'.\"));\n }\n\n child.send(event);\n }\n } catch (e_12_1) {\n e_12 = {\n error: e_12_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_12) throw e_12.error;\n }\n }\n };\n\n Interpreter.prototype.defer = function (sendAction) {\n var _this = this;\n\n var timerId = this.clock.setTimeout(function () {\n if ('to' in sendAction && sendAction.to) {\n _this.sendTo(sendAction._event, sendAction.to, true);\n } else {\n _this.send(sendAction._event);\n }\n }, sendAction.delay);\n\n if (sendAction.id) {\n this.delayedEventsMap[sendAction.id] = timerId;\n }\n };\n\n Interpreter.prototype.cancel = function (sendId) {\n this.clock.clearTimeout(this.delayedEventsMap[sendId]);\n delete this.delayedEventsMap[sendId];\n };\n\n Interpreter.prototype.exec = function (action, state, actionFunctionMap) {\n if (actionFunctionMap === void 0) {\n actionFunctionMap = this.machine.options.actions;\n }\n\n this._exec(action, state.context, state._event, actionFunctionMap);\n };\n\n Interpreter.prototype.removeChild = function (childId) {\n var _a;\n\n this.children.delete(childId);\n this.forwardTo.delete(childId); // this.state might not exist at the time this is called,\n // such as when a child is added then removed while initializing the state\n\n (_a = this.state) === null || _a === void 0 ? true : delete _a.children[childId];\n };\n\n Interpreter.prototype.stopChild = function (childId) {\n var child = this.children.get(childId);\n\n if (!child) {\n return;\n }\n\n this.removeChild(childId);\n\n if (isFunction(child.stop)) {\n child.stop();\n }\n };\n\n Interpreter.prototype.spawn = function (entity, name, options) {\n if (this.status !== InterpreterStatus.Running) {\n return createDeferredActor(entity, name);\n }\n\n if (isPromiseLike(entity)) {\n return this.spawnPromise(Promise.resolve(entity), name);\n } else if (isFunction(entity)) {\n return this.spawnCallback(entity, name);\n } else if (isSpawnedActor(entity)) {\n return this.spawnActor(entity, name);\n } else if (isObservable(entity)) {\n return this.spawnObservable(entity, name);\n } else if (isMachine(entity)) {\n return this.spawnMachine(entity, __assign(__assign({}, options), {\n id: name\n }));\n } else if (isBehavior(entity)) {\n return this.spawnBehavior(entity, name);\n } else {\n throw new Error(\"Unable to spawn entity \\\"\".concat(name, \"\\\" of type \\\"\").concat(typeof entity, \"\\\".\"));\n }\n };\n\n Interpreter.prototype.spawnMachine = function (machine, options) {\n var _this = this;\n\n if (options === void 0) {\n options = {};\n }\n\n var childService = new Interpreter(machine, __assign(__assign({}, this.options), {\n parent: this,\n id: options.id || machine.id\n }));\n\n var resolvedOptions = __assign(__assign({}, DEFAULT_SPAWN_OPTIONS), options);\n\n if (resolvedOptions.sync) {\n childService.onTransition(function (state) {\n _this.send(update, {\n state: state,\n id: childService.id\n });\n });\n }\n\n var actor = childService;\n this.children.set(childService.id, actor);\n\n if (resolvedOptions.autoForward) {\n this.forwardTo.add(childService.id);\n }\n\n childService.onDone(function (doneEvent) {\n _this.removeChild(childService.id);\n\n _this.send(toSCXMLEvent(doneEvent, {\n origin: childService.id\n }));\n }).start();\n return actor;\n };\n\n Interpreter.prototype.spawnBehavior = function (behavior, id) {\n var actorRef = spawnBehavior(behavior, {\n id: id,\n parent: this\n });\n this.children.set(id, actorRef);\n return actorRef;\n };\n\n Interpreter.prototype.spawnPromise = function (promise, id) {\n var _a;\n\n var _this = this;\n\n var canceled = false;\n var resolvedData;\n promise.then(function (response) {\n if (!canceled) {\n resolvedData = response;\n\n _this.removeChild(id);\n\n _this.send(toSCXMLEvent(doneInvoke(id, response), {\n origin: id\n }));\n }\n }, function (errorData) {\n if (!canceled) {\n _this.removeChild(id);\n\n var errorEvent = error(id, errorData);\n\n try {\n // Send \"error.platform.id\" to this (parent).\n _this.send(toSCXMLEvent(errorEvent, {\n origin: id\n }));\n } catch (error) {\n reportUnhandledExceptionOnInvocation(errorData, error, id);\n\n if (_this.devTools) {\n _this.devTools.send(errorEvent, _this.state);\n }\n\n if (_this.machine.strict) {\n // it would be better to always stop the state machine if unhandled\n // exception/promise rejection happens but because we don't want to\n // break existing code so enforce it on strict mode only especially so\n // because documentation says that onError is optional\n _this.stop();\n }\n }\n }\n });\n var actor = (_a = {\n id: id,\n send: function () {\n return void 0;\n },\n subscribe: function (next, handleError, complete) {\n var observer = toObserver(next, handleError, complete);\n var unsubscribed = false;\n promise.then(function (response) {\n if (unsubscribed) {\n return;\n }\n\n observer.next(response);\n\n if (unsubscribed) {\n return;\n }\n\n observer.complete();\n }, function (err) {\n if (unsubscribed) {\n return;\n }\n\n observer.error(err);\n });\n return {\n unsubscribe: function () {\n return unsubscribed = true;\n }\n };\n },\n stop: function () {\n canceled = true;\n },\n toJSON: function () {\n return {\n id: id\n };\n },\n getSnapshot: function () {\n return resolvedData;\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a);\n this.children.set(id, actor);\n return actor;\n };\n\n Interpreter.prototype.spawnCallback = function (callback, id) {\n var _a;\n\n var _this = this;\n\n var canceled = false;\n var receivers = new Set();\n var listeners = new Set();\n var emitted;\n\n var receive = function (e) {\n emitted = e;\n listeners.forEach(function (listener) {\n return listener(e);\n });\n\n if (canceled) {\n return;\n }\n\n _this.send(toSCXMLEvent(e, {\n origin: id\n }));\n };\n\n var callbackStop;\n\n try {\n callbackStop = callback(receive, function (newListener) {\n receivers.add(newListener);\n });\n } catch (err) {\n this.send(error(id, err));\n }\n\n if (isPromiseLike(callbackStop)) {\n // it turned out to be an async function, can't reliably check this before calling `callback`\n // because transpiled async functions are not recognizable\n return this.spawnPromise(callbackStop, id);\n }\n\n var actor = (_a = {\n id: id,\n send: function (event) {\n return receivers.forEach(function (receiver) {\n return receiver(event);\n });\n },\n subscribe: function (next) {\n var observer = toObserver(next);\n listeners.add(observer.next);\n return {\n unsubscribe: function () {\n listeners.delete(observer.next);\n }\n };\n },\n stop: function () {\n canceled = true;\n\n if (isFunction(callbackStop)) {\n callbackStop();\n }\n },\n toJSON: function () {\n return {\n id: id\n };\n },\n getSnapshot: function () {\n return emitted;\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a);\n this.children.set(id, actor);\n return actor;\n };\n\n Interpreter.prototype.spawnObservable = function (source, id) {\n var _a;\n\n var _this = this;\n\n var emitted;\n var subscription = source.subscribe(function (value) {\n emitted = value;\n\n _this.send(toSCXMLEvent(value, {\n origin: id\n }));\n }, function (err) {\n _this.removeChild(id);\n\n _this.send(toSCXMLEvent(error(id, err), {\n origin: id\n }));\n }, function () {\n _this.removeChild(id);\n\n _this.send(toSCXMLEvent(doneInvoke(id), {\n origin: id\n }));\n });\n var actor = (_a = {\n id: id,\n send: function () {\n return void 0;\n },\n subscribe: function (next, handleError, complete) {\n return source.subscribe(next, handleError, complete);\n },\n stop: function () {\n return subscription.unsubscribe();\n },\n getSnapshot: function () {\n return emitted;\n },\n toJSON: function () {\n return {\n id: id\n };\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a);\n this.children.set(id, actor);\n return actor;\n };\n\n Interpreter.prototype.spawnActor = function (actor, name) {\n this.children.set(name, actor);\n return actor;\n };\n\n Interpreter.prototype.spawnActivity = function (activity) {\n var implementation = this.machine.options && this.machine.options.activities ? this.machine.options.activities[activity.type] : undefined;\n\n if (!implementation) {\n if (!IS_PRODUCTION) {\n warn(false, \"No implementation found for activity '\".concat(activity.type, \"'\"));\n } // tslint:disable-next-line:no-console\n\n\n return;\n } // Start implementation\n\n\n var dispose = implementation(this.state.context, activity);\n this.spawnEffect(activity.id, dispose);\n };\n\n Interpreter.prototype.spawnEffect = function (id, dispose) {\n var _a;\n\n this.children.set(id, (_a = {\n id: id,\n send: function () {\n return void 0;\n },\n subscribe: function () {\n return {\n unsubscribe: function () {\n return void 0;\n }\n };\n },\n stop: dispose || undefined,\n getSnapshot: function () {\n return undefined;\n },\n toJSON: function () {\n return {\n id: id\n };\n }\n }, _a[symbolObservable] = function () {\n return this;\n }, _a));\n };\n\n Interpreter.prototype.attachDev = function () {\n var global = getGlobal();\n\n if (this.options.devTools && global) {\n if (global.__REDUX_DEVTOOLS_EXTENSION__) {\n var devToolsOptions = typeof this.options.devTools === 'object' ? this.options.devTools : undefined;\n this.devTools = global.__REDUX_DEVTOOLS_EXTENSION__.connect(__assign(__assign({\n name: this.id,\n autoPause: true,\n stateSanitizer: function (state) {\n return {\n value: state.value,\n context: state.context,\n actions: state.actions\n };\n }\n }, devToolsOptions), {\n features: __assign({\n jump: false,\n skip: false\n }, devToolsOptions ? devToolsOptions.features : undefined)\n }), this.machine);\n this.devTools.init(this.state);\n } // add XState-specific dev tooling hook\n\n\n registerService(this);\n }\n };\n\n Interpreter.prototype.toJSON = function () {\n return {\n id: this.id\n };\n };\n\n Interpreter.prototype[symbolObservable] = function () {\n return this;\n };\n\n Interpreter.prototype.getSnapshot = function () {\n if (this.status === InterpreterStatus.NotStarted) {\n return this.initialState;\n }\n\n return this._state;\n };\n /**\r\n * The default interpreter options:\r\n *\r\n * - `clock` uses the global `setTimeout` and `clearTimeout` functions\r\n * - `logger` uses the global `console.log()` method\r\n */\n\n\n Interpreter.defaultOptions = {\n execute: true,\n deferEvents: true,\n clock: {\n setTimeout: function (fn, ms) {\n return setTimeout(fn, ms);\n },\n clearTimeout: function (id) {\n return clearTimeout(id);\n }\n },\n logger: /*#__PURE__*/console.log.bind(console),\n devTools: false\n };\n Interpreter.interpret = interpret;\n return Interpreter;\n}();\n\nvar resolveSpawnOptions = function (nameOrOptions) {\n if (isString(nameOrOptions)) {\n return __assign(__assign({}, DEFAULT_SPAWN_OPTIONS), {\n name: nameOrOptions\n });\n }\n\n return __assign(__assign(__assign({}, DEFAULT_SPAWN_OPTIONS), {\n name: uniqueId()\n }), nameOrOptions);\n};\n\nfunction spawn(entity, nameOrOptions) {\n var resolvedOptions = resolveSpawnOptions(nameOrOptions);\n return consume(function (service) {\n if (!IS_PRODUCTION) {\n var isLazyEntity = isMachine(entity) || isFunction(entity);\n warn(!!service || isLazyEntity, \"Attempted to spawn an Actor (ID: \\\"\".concat(isMachine(entity) ? entity.id : 'undefined', \"\\\") outside of a service. This will have no effect.\"));\n }\n\n if (service) {\n return service.spawn(entity, resolvedOptions.name, resolvedOptions);\n } else {\n return createDeferredActor(entity, resolvedOptions.name);\n }\n });\n}\n/**\r\n * Creates a new Interpreter instance for the given machine with the provided options, if any.\r\n *\r\n * @param machine The machine to interpret\r\n * @param options Interpreter options\r\n */\n\nfunction interpret(machine, options) {\n var interpreter = new Interpreter(machine, options);\n return interpreter;\n}\n\nexport { Interpreter, InterpreterStatus, interpret, spawn };\n","import { __assign, __rest } from './_virtual/_tslib.js';\nimport './types.js';\nimport { invoke } from './actionTypes.js';\nimport './utils.js';\nimport './environment.js';\n\nfunction toInvokeSource(src) {\n if (typeof src === 'string') {\n var simpleSrc = {\n type: src\n };\n\n simpleSrc.toString = function () {\n return src;\n }; // v4 compat - TODO: remove in v5\n\n\n return simpleSrc;\n }\n\n return src;\n}\nfunction toInvokeDefinition(invokeConfig) {\n return __assign(__assign({\n type: invoke\n }, invokeConfig), {\n toJSON: function () {\n invokeConfig.onDone;\n invokeConfig.onError;\n var invokeDef = __rest(invokeConfig, [\"onDone\", \"onError\"]);\n\n return __assign(__assign({}, invokeDef), {\n type: invoke,\n src: toInvokeSource(invokeConfig.src)\n });\n }\n });\n}\n\nexport { toInvokeDefinition, toInvokeSource };\n","import { __assign, __spreadArray, __read, __values, __rest } from './_virtual/_tslib.js';\nimport { isFunction, mapValues, isArray, flatten, toArray, toStateValue, isString, getEventType, toSCXMLEvent, matchesState, path, evaluateGuard, mapContext, isRaisableAction, pathToStateValue, isBuiltInEvent, partition, updateHistoryValue, toStatePath, mapFilterValues, warn, toStatePaths, nestedPath, normalizeTarget, toGuard, toTransitionConfigArray, isMachine, createInvokeId } from './utils.js';\nimport { State, stateValuesEqual } from './State.js';\nimport { start as start$1, stop as stop$1, invoke, update, nullEvent } from './actionTypes.js';\nimport { done, start, toActionObjects, raise, stop, resolveActions, doneInvoke, error, toActionObject, toActivityDefinition, after, send, cancel, initEvent } from './actions.js';\nimport { IS_PRODUCTION } from './environment.js';\nimport { STATE_DELIMITER } from './constants.js';\nimport { getAllStateNodes, getConfiguration, isInFinalState, getTagsFromConfiguration, has, getChildren, getValue, isLeafNode, getAllChildren } from './stateUtils.js';\nimport { createInvocableActor } from './Actor.js';\nimport { toInvokeDefinition } from './invokeUtils.js';\n\nvar NULL_EVENT = '';\nvar STATE_IDENTIFIER = '#';\nvar WILDCARD = '*';\nvar EMPTY_OBJECT = {};\n\nvar isStateId = function (str) {\n return str[0] === STATE_IDENTIFIER;\n};\n\nvar createDefaultOptions = function () {\n return {\n actions: {},\n guards: {},\n services: {},\n activities: {},\n delays: {}\n };\n};\n\nvar validateArrayifiedTransitions = function (stateNode, event, transitions) {\n var hasNonLastUnguardedTarget = transitions.slice(0, -1).some(function (transition) {\n return !('cond' in transition) && !('in' in transition) && (isString(transition.target) || isMachine(transition.target));\n });\n var eventText = event === NULL_EVENT ? 'the transient event' : \"event '\".concat(event, \"'\");\n warn(!hasNonLastUnguardedTarget, \"One or more transitions for \".concat(eventText, \" on state '\").concat(stateNode.id, \"' are unreachable. \") + \"Make sure that the default transition is the last one defined.\");\n};\n\nvar StateNode =\n/*#__PURE__*/\n\n/** @class */\nfunction () {\n function StateNode(\n /**\r\n * The raw config used to create the machine.\r\n */\n config, options,\n /**\r\n * The initial extended state\r\n */\n _context, // TODO: this is unsafe, but we're removing it in v5 anyway\n _stateInfo) {\n if (_context === void 0) {\n _context = 'context' in config ? config.context : undefined;\n }\n\n var _this = this;\n\n var _a;\n\n this.config = config;\n this._context = _context;\n /**\r\n * The order this state node appears. Corresponds to the implicit SCXML document order.\r\n */\n\n this.order = -1;\n this.__xstatenode = true;\n this.__cache = {\n events: undefined,\n relativeValue: new Map(),\n initialStateValue: undefined,\n initialState: undefined,\n on: undefined,\n transitions: undefined,\n candidates: {},\n delayedTransitions: undefined\n };\n this.idMap = {};\n this.tags = [];\n this.options = Object.assign(createDefaultOptions(), options);\n this.parent = _stateInfo === null || _stateInfo === void 0 ? void 0 : _stateInfo.parent;\n this.key = this.config.key || (_stateInfo === null || _stateInfo === void 0 ? void 0 : _stateInfo.key) || this.config.id || '(machine)';\n this.machine = this.parent ? this.parent.machine : this;\n this.path = this.parent ? this.parent.path.concat(this.key) : [];\n this.delimiter = this.config.delimiter || (this.parent ? this.parent.delimiter : STATE_DELIMITER);\n this.id = this.config.id || __spreadArray([this.machine.key], __read(this.path), false).join(this.delimiter);\n this.version = this.parent ? this.parent.version : this.config.version;\n this.type = this.config.type || (this.config.parallel ? 'parallel' : this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');\n this.schema = this.parent ? this.machine.schema : (_a = this.config.schema) !== null && _a !== void 0 ? _a : {};\n this.description = this.config.description;\n\n if (!IS_PRODUCTION) {\n warn(!('parallel' in this.config), \"The \\\"parallel\\\" property is deprecated and will be removed in version 4.1. \".concat(this.config.parallel ? \"Replace with `type: 'parallel'`\" : \"Use `type: '\".concat(this.type, \"'`\"), \" in the config for state node '\").concat(this.id, \"' instead.\"));\n }\n\n this.initial = this.config.initial;\n this.states = this.config.states ? mapValues(this.config.states, function (stateConfig, key) {\n var _a;\n\n var stateNode = new StateNode(stateConfig, {}, undefined, {\n parent: _this,\n key: key\n });\n Object.assign(_this.idMap, __assign((_a = {}, _a[stateNode.id] = stateNode, _a), stateNode.idMap));\n return stateNode;\n }) : EMPTY_OBJECT; // Document order\n\n var order = 0;\n\n function dfs(stateNode) {\n var e_1, _a;\n\n stateNode.order = order++;\n\n try {\n for (var _b = __values(getAllChildren(stateNode)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var child = _c.value;\n dfs(child);\n }\n } catch (e_1_1) {\n e_1 = {\n error: e_1_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_1) throw e_1.error;\n }\n }\n }\n\n dfs(this); // History config\n\n this.history = this.config.history === true ? 'shallow' : this.config.history || false;\n this._transient = !!this.config.always || (!this.config.on ? false : Array.isArray(this.config.on) ? this.config.on.some(function (_a) {\n var event = _a.event;\n return event === NULL_EVENT;\n }) : NULL_EVENT in this.config.on);\n this.strict = !!this.config.strict; // TODO: deprecate (entry)\n\n this.onEntry = toArray(this.config.entry || this.config.onEntry).map(function (action) {\n return toActionObject(action);\n }); // TODO: deprecate (exit)\n\n this.onExit = toArray(this.config.exit || this.config.onExit).map(function (action) {\n return toActionObject(action);\n });\n this.meta = this.config.meta;\n this.doneData = this.type === 'final' ? this.config.data : undefined;\n this.invoke = toArray(this.config.invoke).map(function (invokeConfig, i) {\n var _a, _b;\n\n if (isMachine(invokeConfig)) {\n var invokeId = createInvokeId(_this.id, i);\n _this.machine.options.services = __assign((_a = {}, _a[invokeId] = invokeConfig, _a), _this.machine.options.services);\n return toInvokeDefinition({\n src: invokeId,\n id: invokeId\n });\n } else if (isString(invokeConfig.src)) {\n var invokeId = invokeConfig.id || createInvokeId(_this.id, i);\n return toInvokeDefinition(__assign(__assign({}, invokeConfig), {\n id: invokeId,\n src: invokeConfig.src\n }));\n } else if (isMachine(invokeConfig.src) || isFunction(invokeConfig.src)) {\n var invokeId = invokeConfig.id || createInvokeId(_this.id, i);\n _this.machine.options.services = __assign((_b = {}, _b[invokeId] = invokeConfig.src, _b), _this.machine.options.services);\n return toInvokeDefinition(__assign(__assign({\n id: invokeId\n }, invokeConfig), {\n src: invokeId\n }));\n } else {\n var invokeSource = invokeConfig.src;\n return toInvokeDefinition(__assign(__assign({\n id: createInvokeId(_this.id, i)\n }, invokeConfig), {\n src: invokeSource\n }));\n }\n });\n this.activities = toArray(this.config.activities).concat(this.invoke).map(function (activity) {\n return toActivityDefinition(activity);\n });\n this.transition = this.transition.bind(this);\n this.tags = toArray(this.config.tags); // TODO: this is the real fix for initialization once\n // state node getters are deprecated\n // if (!this.parent) {\n // this._init();\n // }\n }\n\n StateNode.prototype._init = function () {\n if (this.__cache.transitions) {\n return;\n }\n\n getAllStateNodes(this).forEach(function (stateNode) {\n return stateNode.on;\n });\n };\n /**\r\n * Clones this state machine with custom options and context.\r\n *\r\n * @param options Options (actions, guards, activities, services) to recursively merge with the existing options.\r\n * @param context Custom context (will override predefined context)\r\n */\n\n\n StateNode.prototype.withConfig = function (options, context) {\n var _a = this.options,\n actions = _a.actions,\n activities = _a.activities,\n guards = _a.guards,\n services = _a.services,\n delays = _a.delays;\n return new StateNode(this.config, {\n actions: __assign(__assign({}, actions), options.actions),\n activities: __assign(__assign({}, activities), options.activities),\n guards: __assign(__assign({}, guards), options.guards),\n services: __assign(__assign({}, services), options.services),\n delays: __assign(__assign({}, delays), options.delays)\n }, context !== null && context !== void 0 ? context : this.context);\n };\n /**\r\n * Clones this state machine with custom context.\r\n *\r\n * @param context Custom context (will override predefined context, not recursive)\r\n */\n\n\n StateNode.prototype.withContext = function (context) {\n return new StateNode(this.config, this.options, context);\n };\n\n Object.defineProperty(StateNode.prototype, \"context\", {\n get: function () {\n return isFunction(this._context) ? this._context() : this._context;\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"definition\", {\n /**\r\n * The well-structured state node definition.\r\n */\n get: function () {\n return {\n id: this.id,\n key: this.key,\n version: this.version,\n context: this.context,\n type: this.type,\n initial: this.initial,\n history: this.history,\n states: mapValues(this.states, function (state) {\n return state.definition;\n }),\n on: this.on,\n transitions: this.transitions,\n entry: this.onEntry,\n exit: this.onExit,\n activities: this.activities || [],\n meta: this.meta,\n order: this.order || -1,\n data: this.doneData,\n invoke: this.invoke,\n description: this.description,\n tags: this.tags\n };\n },\n enumerable: false,\n configurable: true\n });\n\n StateNode.prototype.toJSON = function () {\n return this.definition;\n };\n\n Object.defineProperty(StateNode.prototype, \"on\", {\n /**\r\n * The mapping of events to transitions.\r\n */\n get: function () {\n if (this.__cache.on) {\n return this.__cache.on;\n }\n\n var transitions = this.transitions;\n return this.__cache.on = transitions.reduce(function (map, transition) {\n map[transition.eventType] = map[transition.eventType] || [];\n map[transition.eventType].push(transition);\n return map;\n }, {});\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"after\", {\n get: function () {\n return this.__cache.delayedTransitions || (this.__cache.delayedTransitions = this.getDelayedTransitions(), this.__cache.delayedTransitions);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"transitions\", {\n /**\r\n * All the transitions that can be taken from this state node.\r\n */\n get: function () {\n return this.__cache.transitions || (this.__cache.transitions = this.formatTransitions(), this.__cache.transitions);\n },\n enumerable: false,\n configurable: true\n });\n\n StateNode.prototype.getCandidates = function (eventName) {\n if (this.__cache.candidates[eventName]) {\n return this.__cache.candidates[eventName];\n }\n\n var transient = eventName === NULL_EVENT;\n var candidates = this.transitions.filter(function (transition) {\n var sameEventType = transition.eventType === eventName; // null events should only match against eventless transitions\n\n return transient ? sameEventType : sameEventType || transition.eventType === WILDCARD;\n });\n this.__cache.candidates[eventName] = candidates;\n return candidates;\n };\n /**\r\n * All delayed transitions from the config.\r\n */\n\n\n StateNode.prototype.getDelayedTransitions = function () {\n var _this = this;\n\n var afterConfig = this.config.after;\n\n if (!afterConfig) {\n return [];\n }\n\n var mutateEntryExit = function (delay, i) {\n var delayRef = isFunction(delay) ? \"\".concat(_this.id, \":delay[\").concat(i, \"]\") : delay;\n var eventType = after(delayRef, _this.id);\n\n _this.onEntry.push(send(eventType, {\n delay: delay\n }));\n\n _this.onExit.push(cancel(eventType));\n\n return eventType;\n };\n\n var delayedTransitions = isArray(afterConfig) ? afterConfig.map(function (transition, i) {\n var eventType = mutateEntryExit(transition.delay, i);\n return __assign(__assign({}, transition), {\n event: eventType\n });\n }) : flatten(Object.keys(afterConfig).map(function (delay, i) {\n var configTransition = afterConfig[delay];\n var resolvedTransition = isString(configTransition) ? {\n target: configTransition\n } : configTransition;\n var resolvedDelay = !isNaN(+delay) ? +delay : delay;\n var eventType = mutateEntryExit(resolvedDelay, i);\n return toArray(resolvedTransition).map(function (transition) {\n return __assign(__assign({}, transition), {\n event: eventType,\n delay: resolvedDelay\n });\n });\n }));\n return delayedTransitions.map(function (delayedTransition) {\n var delay = delayedTransition.delay;\n return __assign(__assign({}, _this.formatTransition(delayedTransition)), {\n delay: delay\n });\n });\n };\n /**\r\n * Returns the state nodes represented by the current state value.\r\n *\r\n * @param state The state value or State instance\r\n */\n\n\n StateNode.prototype.getStateNodes = function (state) {\n var _a;\n\n var _this = this;\n\n if (!state) {\n return [];\n }\n\n var stateValue = state instanceof State ? state.value : toStateValue(state, this.delimiter);\n\n if (isString(stateValue)) {\n var initialStateValue = this.getStateNode(stateValue).initial;\n return initialStateValue !== undefined ? this.getStateNodes((_a = {}, _a[stateValue] = initialStateValue, _a)) : [this, this.states[stateValue]];\n }\n\n var subStateKeys = Object.keys(stateValue);\n var subStateNodes = [this];\n subStateNodes.push.apply(subStateNodes, __spreadArray([], __read(flatten(subStateKeys.map(function (subStateKey) {\n return _this.getStateNode(subStateKey).getStateNodes(stateValue[subStateKey]);\n }))), false));\n return subStateNodes;\n };\n /**\r\n * Returns `true` if this state node explicitly handles the given event.\r\n *\r\n * @param event The event in question\r\n */\n\n\n StateNode.prototype.handles = function (event) {\n var eventType = getEventType(event);\n return this.events.includes(eventType);\n };\n /**\r\n * Resolves the given `state` to a new `State` instance relative to this machine.\r\n *\r\n * This ensures that `.events` and `.nextEvents` represent the correct values.\r\n *\r\n * @param state The state to resolve\r\n */\n\n\n StateNode.prototype.resolveState = function (state) {\n var stateFromConfig = state instanceof State ? state : State.create(state);\n var configuration = Array.from(getConfiguration([], this.getStateNodes(stateFromConfig.value)));\n return new State(__assign(__assign({}, stateFromConfig), {\n value: this.resolve(stateFromConfig.value),\n configuration: configuration,\n done: isInFinalState(configuration, this),\n tags: getTagsFromConfiguration(configuration),\n machine: this.machine\n }));\n };\n\n StateNode.prototype.transitionLeafNode = function (stateValue, state, _event) {\n var stateNode = this.getStateNode(stateValue);\n var next = stateNode.next(state, _event);\n\n if (!next || !next.transitions.length) {\n return this.next(state, _event);\n }\n\n return next;\n };\n\n StateNode.prototype.transitionCompoundNode = function (stateValue, state, _event) {\n var subStateKeys = Object.keys(stateValue);\n var stateNode = this.getStateNode(subStateKeys[0]);\n\n var next = stateNode._transition(stateValue[subStateKeys[0]], state, _event);\n\n if (!next || !next.transitions.length) {\n return this.next(state, _event);\n }\n\n return next;\n };\n\n StateNode.prototype.transitionParallelNode = function (stateValue, state, _event) {\n var e_2, _a;\n\n var transitionMap = {};\n\n try {\n for (var _b = __values(Object.keys(stateValue)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var subStateKey = _c.value;\n var subStateValue = stateValue[subStateKey];\n\n if (!subStateValue) {\n continue;\n }\n\n var subStateNode = this.getStateNode(subStateKey);\n\n var next = subStateNode._transition(subStateValue, state, _event);\n\n if (next) {\n transitionMap[subStateKey] = next;\n }\n }\n } catch (e_2_1) {\n e_2 = {\n error: e_2_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_2) throw e_2.error;\n }\n }\n\n var stateTransitions = Object.keys(transitionMap).map(function (key) {\n return transitionMap[key];\n });\n var enabledTransitions = flatten(stateTransitions.map(function (st) {\n return st.transitions;\n }));\n var willTransition = stateTransitions.some(function (st) {\n return st.transitions.length > 0;\n });\n\n if (!willTransition) {\n return this.next(state, _event);\n }\n\n var configuration = flatten(Object.keys(transitionMap).map(function (key) {\n return transitionMap[key].configuration;\n }));\n return {\n transitions: enabledTransitions,\n exitSet: flatten(stateTransitions.map(function (t) {\n return t.exitSet;\n })),\n configuration: configuration,\n source: state,\n actions: flatten(Object.keys(transitionMap).map(function (key) {\n return transitionMap[key].actions;\n }))\n };\n };\n\n StateNode.prototype._transition = function (stateValue, state, _event) {\n // leaf node\n if (isString(stateValue)) {\n return this.transitionLeafNode(stateValue, state, _event);\n } // hierarchical node\n\n\n if (Object.keys(stateValue).length === 1) {\n return this.transitionCompoundNode(stateValue, state, _event);\n } // orthogonal node\n\n\n return this.transitionParallelNode(stateValue, state, _event);\n };\n\n StateNode.prototype.getTransitionData = function (state, event) {\n return this._transition(state.value, state, toSCXMLEvent(event));\n };\n\n StateNode.prototype.next = function (state, _event) {\n var e_3, _a;\n\n var _this = this;\n\n var eventName = _event.name;\n var actions = [];\n var nextStateNodes = [];\n var selectedTransition;\n\n try {\n for (var _b = __values(this.getCandidates(eventName)), _c = _b.next(); !_c.done; _c = _b.next()) {\n var candidate = _c.value;\n var cond = candidate.cond,\n stateIn = candidate.in;\n var resolvedContext = state.context;\n var isInState = stateIn ? isString(stateIn) && isStateId(stateIn) ? // Check if in state by ID\n state.matches(toStateValue(this.getStateNodeById(stateIn).path, this.delimiter)) : // Check if in state by relative grandparent\n matchesState(toStateValue(stateIn, this.delimiter), path(this.path.slice(0, -2))(state.value)) : true;\n var guardPassed = false;\n\n try {\n guardPassed = !cond || evaluateGuard(this.machine, cond, resolvedContext, _event, state);\n } catch (err) {\n throw new Error(\"Unable to evaluate guard '\".concat(cond.name || cond.type, \"' in transition for event '\").concat(eventName, \"' in state node '\").concat(this.id, \"':\\n\").concat(err.message));\n }\n\n if (guardPassed && isInState) {\n if (candidate.target !== undefined) {\n nextStateNodes = candidate.target;\n }\n\n actions.push.apply(actions, __spreadArray([], __read(candidate.actions), false));\n selectedTransition = candidate;\n break;\n }\n }\n } catch (e_3_1) {\n e_3 = {\n error: e_3_1\n };\n } finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n } finally {\n if (e_3) throw e_3.error;\n }\n }\n\n if (!selectedTransition) {\n return undefined;\n }\n\n if (!nextStateNodes.length) {\n return {\n transitions: [selectedTransition],\n exitSet: [],\n configuration: state.value ? [this] : [],\n source: state,\n actions: actions\n };\n }\n\n var allNextStateNodes = flatten(nextStateNodes.map(function (stateNode) {\n return _this.getRelativeStateNodes(stateNode, state.historyValue);\n }));\n var isInternal = !!selectedTransition.internal;\n return {\n transitions: [selectedTransition],\n exitSet: isInternal ? [] : flatten(nextStateNodes.map(function (targetNode) {\n return _this.getPotentiallyReenteringNodes(targetNode);\n })),\n configuration: allNextStateNodes,\n source: state,\n actions: actions\n };\n }; // even though the name of this function mentions reentry nodes\n // we are pushing its result into `exitSet`\n // that's because what we exit might be reentered (it's an invariant of reentrancy)\n\n\n StateNode.prototype.getPotentiallyReenteringNodes = function (targetNode) {\n if (this.order < targetNode.order) {\n return [this];\n }\n\n var nodes = [];\n var marker = this;\n var possibleAncestor = targetNode;\n\n while (marker && marker !== possibleAncestor) {\n nodes.push(marker);\n marker = marker.parent;\n }\n\n if (marker !== possibleAncestor) {\n // we never got to `possibleAncestor`, therefore the initial `marker` \"escapes\" it\n // it's in a different part of the tree so no states will be reentered for such an external transition\n return [];\n }\n\n nodes.push(possibleAncestor);\n return nodes;\n };\n\n StateNode.prototype.getActions = function (resolvedConfig, isDone, transition, currentContext, _event, prevState, predictableExec) {\n var e_4, _a, e_5, _b;\n\n var _this = this;\n\n var prevConfig = prevState ? getConfiguration([], this.getStateNodes(prevState.value)) : [];\n var entrySet = new Set();\n\n try {\n for (var _c = __values(Array.from(resolvedConfig).sort(function (a, b) {\n return a.order - b.order;\n })), _d = _c.next(); !_d.done; _d = _c.next()) {\n var sn = _d.value;\n\n if (!has(prevConfig, sn) || has(transition.exitSet, sn) || sn.parent && entrySet.has(sn.parent)) {\n entrySet.add(sn);\n }\n }\n } catch (e_4_1) {\n e_4 = {\n error: e_4_1\n };\n } finally {\n try {\n if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\n } finally {\n if (e_4) throw e_4.error;\n }\n }\n\n try {\n for (var prevConfig_1 = __values(prevConfig), prevConfig_1_1 = prevConfig_1.next(); !prevConfig_1_1.done; prevConfig_1_1 = prevConfig_1.next()) {\n var sn = prevConfig_1_1.value;\n\n if (!has(resolvedConfig, sn) || has(transition.exitSet, sn.parent)) {\n transition.exitSet.push(sn);\n }\n }\n } catch (e_5_1) {\n e_5 = {\n error: e_5_1\n };\n } finally {\n try {\n if (prevConfig_1_1 && !prevConfig_1_1.done && (_b = prevConfig_1.return)) _b.call(prevConfig_1);\n } finally {\n if (e_5) throw e_5.error;\n }\n }\n\n transition.exitSet.sort(function (a, b) {\n return b.order - a.order;\n });\n var entryStates = Array.from(entrySet).sort(function (a, b) {\n return a.order - b.order;\n });\n var exitStates = new Set(transition.exitSet);\n var doneEvents = flatten(entryStates.map(function (sn) {\n var events = [];\n\n if (sn.type !== 'final') {\n return events;\n }\n\n var parent = sn.parent;\n\n if (!parent.parent) {\n return events;\n }\n\n events.push(done(sn.id, sn.doneData), // TODO: deprecate - final states should not emit done events for their own state.\n done(parent.id, sn.doneData ? mapContext(sn.doneData, currentContext, _event) : undefined));\n var grandparent = parent.parent;\n\n if (grandparent.type === 'parallel') {\n if (getChildren(grandparent).every(function (parentNode) {\n return isInFinalState(transition.configuration, parentNode);\n })) {\n events.push(done(grandparent.id));\n }\n }\n\n return events;\n }));\n var entryActions = entryStates.map(function (stateNode) {\n var entryActions = stateNode.onEntry;\n var invokeActions = stateNode.activities.map(function (activity) {\n return start(activity);\n });\n return {\n type: 'entry',\n actions: toActionObjects(predictableExec ? __spreadArray(__spreadArray([], __read(entryActions), false), __read(invokeActions), false) : __spreadArray(__spreadArray([], __read(invokeActions), false), __read(entryActions), false), _this.machine.options.actions)\n };\n }).concat({\n type: 'state_done',\n actions: doneEvents.map(function (event) {\n return raise(event);\n })\n });\n var exitActions = Array.from(exitStates).map(function (stateNode) {\n return {\n type: 'exit',\n actions: toActionObjects(__spreadArray(__spreadArray([], __read(stateNode.onExit), false), __read(stateNode.activities.map(function (activity) {\n return stop(activity);\n })), false), _this.machine.options.actions)\n };\n });\n var actions = exitActions.concat({\n type: 'transition',\n actions: toActionObjects(transition.actions, this.machine.options.actions)\n }).concat(entryActions);\n\n if (isDone) {\n var stopActions = toActionObjects(flatten(__spreadArray([], __read(resolvedConfig), false).sort(function (a, b) {\n return b.order - a.order;\n }).map(function (stateNode) {\n return stateNode.onExit;\n })), this.machine.options.actions).filter(function (action) {\n return !isRaisableAction(action);\n });\n return actions.concat({\n type: 'stop',\n actions: stopActions\n });\n }\n\n return actions;\n };\n /**\r\n * Determines the next state given the current `state` and sent `event`.\r\n *\r\n * @param state The current State instance or state value\r\n * @param event The event that was sent at the current state\r\n * @param context The current context (extended state) of the current state\r\n */\n\n\n StateNode.prototype.transition = function (state, event, context, exec) {\n if (state === void 0) {\n state = this.initialState;\n }\n\n var _event = toSCXMLEvent(event);\n\n var currentState;\n\n if (state instanceof State) {\n currentState = context === undefined ? state : this.resolveState(State.from(state, context));\n } else {\n var resolvedStateValue = isString(state) ? this.resolve(pathToStateValue(this.getResolvedPath(state))) : this.resolve(state);\n var resolvedContext = context !== null && context !== void 0 ? context : this.machine.context;\n currentState = this.resolveState(State.from(resolvedStateValue, resolvedContext));\n }\n\n if (!IS_PRODUCTION && _event.name === WILDCARD) {\n throw new Error(\"An event cannot have the wildcard type ('\".concat(WILDCARD, \"')\"));\n }\n\n if (this.strict) {\n if (!this.events.includes(_event.name) && !isBuiltInEvent(_event.name)) {\n throw new Error(\"Machine '\".concat(this.id, \"' does not accept event '\").concat(_event.name, \"'\"));\n }\n }\n\n var stateTransition = this._transition(currentState.value, currentState, _event) || {\n transitions: [],\n configuration: [],\n exitSet: [],\n source: currentState,\n actions: []\n };\n var prevConfig = getConfiguration([], this.getStateNodes(currentState.value));\n var resolvedConfig = stateTransition.configuration.length ? getConfiguration(prevConfig, stateTransition.configuration) : prevConfig;\n stateTransition.configuration = __spreadArray([], __read(resolvedConfig), false);\n return this.resolveTransition(stateTransition, currentState, currentState.context, exec, _event);\n };\n\n StateNode.prototype.resolveRaisedTransition = function (state, _event, originalEvent, predictableExec) {\n var _a;\n\n var currentActions = state.actions;\n state = this.transition(state, _event, undefined, predictableExec); // Save original event to state\n // TODO: this should be the raised event! Delete in V5 (breaking)\n\n state._event = originalEvent;\n state.event = originalEvent.data;\n\n (_a = state.actions).unshift.apply(_a, __spreadArray([], __read(currentActions), false));\n\n return state;\n };\n\n StateNode.prototype.resolveTransition = function (stateTransition, currentState, context, predictableExec, _event) {\n var e_6, _a, e_7, _b;\n\n var _this = this;\n\n if (_event === void 0) {\n _event = initEvent;\n }\n\n var configuration = stateTransition.configuration; // Transition will \"apply\" if:\n // - this is the initial state (there is no current state)\n // - OR there are transitions\n\n var willTransition = !currentState || stateTransition.transitions.length > 0;\n var resolvedConfiguration = willTransition ? stateTransition.configuration : currentState ? currentState.configuration : [];\n var isDone = isInFinalState(resolvedConfiguration, this);\n var resolvedStateValue = willTransition ? getValue(this.machine, configuration) : undefined;\n var historyValue = currentState ? currentState.historyValue ? currentState.historyValue : stateTransition.source ? this.machine.historyValue(currentState.value) : undefined : undefined;\n var actionBlocks = this.getActions(new Set(resolvedConfiguration), isDone, stateTransition, context, _event, currentState, predictableExec);\n var activities = currentState ? __assign({}, currentState.activities) : {};\n\n try {\n for (var actionBlocks_1 = __values(actionBlocks), actionBlocks_1_1 = actionBlocks_1.next(); !actionBlocks_1_1.done; actionBlocks_1_1 = actionBlocks_1.next()) {\n var block = actionBlocks_1_1.value;\n\n try {\n for (var _c = (e_7 = void 0, __values(block.actions)), _d = _c.next(); !_d.done; _d = _c.next()) {\n var action = _d.value;\n\n if (action.type === start$1) {\n activities[action.activity.id || action.activity.type] = action;\n } else if (action.type === stop$1) {\n activities[action.activity.id || action.activity.type] = false;\n }\n }\n } catch (e_7_1) {\n e_7 = {\n error: e_7_1\n };\n } finally {\n try {\n if (_d && !_d.done && (_b = _c.return)) _b.call(_c);\n } finally {\n if (e_7) throw e_7.error;\n }\n }\n }\n } catch (e_6_1) {\n e_6 = {\n error: e_6_1\n };\n } finally {\n try {\n if (actionBlocks_1_1 && !actionBlocks_1_1.done && (_a = actionBlocks_1.return)) _a.call(actionBlocks_1);\n } finally {\n if (e_6) throw e_6.error;\n }\n }\n\n var _e = __read(resolveActions(this, currentState, context, _event, actionBlocks, predictableExec, this.machine.config.predictableActionArguments || this.machine.config.preserveActionOrder), 2),\n resolvedActions = _e[0],\n updatedContext = _e[1];\n\n var _f = __read(partition(resolvedActions, isRaisableAction), 2),\n raisedEvents = _f[0],\n nonRaisedActions = _f[1];\n\n var invokeActions = resolvedActions.filter(function (action) {\n var _a;\n\n return action.type === start$1 && ((_a = action.activity) === null || _a === void 0 ? void 0 : _a.type) === invoke;\n });\n var children = invokeActions.reduce(function (acc, action) {\n acc[action.activity.id] = createInvocableActor(action.activity, _this.machine, updatedContext, _event);\n return acc;\n }, currentState ? __assign({}, currentState.children) : {});\n var nextState = new State({\n value: resolvedStateValue || currentState.value,\n context: updatedContext,\n _event: _event,\n // Persist _sessionid between states\n _sessionid: currentState ? currentState._sessionid : null,\n historyValue: resolvedStateValue ? historyValue ? updateHistoryValue(historyValue, resolvedStateValue) : undefined : currentState ? currentState.historyValue : undefined,\n history: !resolvedStateValue || stateTransition.source ? currentState : undefined,\n actions: resolvedStateValue ? nonRaisedActions : [],\n activities: resolvedStateValue ? activities : currentState ? currentState.activities : {},\n events: [],\n configuration: resolvedConfiguration,\n transitions: stateTransition.transitions,\n children: children,\n done: isDone,\n tags: getTagsFromConfiguration(resolvedConfiguration),\n machine: this\n });\n var didUpdateContext = context !== updatedContext;\n nextState.changed = _event.name === update || didUpdateContext; // Dispose of penultimate histories to prevent memory leaks\n\n var history = nextState.history;\n\n if (history) {\n delete history.history;\n } // There are transient transitions if the machine is not in a final state\n // and if some of the state nodes have transient (\"always\") transitions.\n\n\n var hasAlwaysTransitions = !isDone && (this._transient || configuration.some(function (stateNode) {\n return stateNode._transient;\n })); // If there are no enabled transitions, check if there are transient transitions.\n // If there are transient transitions, continue checking for more transitions\n // because an transient transition should be triggered even if there are no\n // enabled transitions.\n //\n // If we're already working on an transient transition then stop to prevent an infinite loop.\n //\n // Otherwise, if there are no enabled nor transient transitions, we are done.\n\n if (!willTransition && (!hasAlwaysTransitions || _event.name === NULL_EVENT)) {\n return nextState;\n }\n\n var maybeNextState = nextState;\n\n if (!isDone) {\n if (hasAlwaysTransitions) {\n maybeNextState = this.resolveRaisedTransition(maybeNextState, {\n type: nullEvent\n }, _event, predictableExec);\n }\n\n while (raisedEvents.length) {\n var raisedEvent = raisedEvents.shift();\n maybeNextState = this.resolveRaisedTransition(maybeNextState, raisedEvent._event, _event, predictableExec);\n }\n } // Detect if state changed\n\n\n var changed = maybeNextState.changed || (history ? !!maybeNextState.actions.length || didUpdateContext || typeof history.value !== typeof maybeNextState.value || !stateValuesEqual(maybeNextState.value, history.value) : undefined);\n maybeNextState.changed = changed; // Preserve original history after raised events\n\n maybeNextState.history = history;\n return maybeNextState;\n };\n /**\r\n * Returns the child state node from its relative `stateKey`, or throws.\r\n */\n\n\n StateNode.prototype.getStateNode = function (stateKey) {\n if (isStateId(stateKey)) {\n return this.machine.getStateNodeById(stateKey);\n }\n\n if (!this.states) {\n throw new Error(\"Unable to retrieve child state '\".concat(stateKey, \"' from '\").concat(this.id, \"'; no child states exist.\"));\n }\n\n var result = this.states[stateKey];\n\n if (!result) {\n throw new Error(\"Child state '\".concat(stateKey, \"' does not exist on '\").concat(this.id, \"'\"));\n }\n\n return result;\n };\n /**\r\n * Returns the state node with the given `stateId`, or throws.\r\n *\r\n * @param stateId The state ID. The prefix \"#\" is removed.\r\n */\n\n\n StateNode.prototype.getStateNodeById = function (stateId) {\n var resolvedStateId = isStateId(stateId) ? stateId.slice(STATE_IDENTIFIER.length) : stateId;\n\n if (resolvedStateId === this.id) {\n return this;\n }\n\n var stateNode = this.machine.idMap[resolvedStateId];\n\n if (!stateNode) {\n throw new Error(\"Child state node '#\".concat(resolvedStateId, \"' does not exist on machine '\").concat(this.id, \"'\"));\n }\n\n return stateNode;\n };\n /**\r\n * Returns the relative state node from the given `statePath`, or throws.\r\n *\r\n * @param statePath The string or string array relative path to the state node.\r\n */\n\n\n StateNode.prototype.getStateNodeByPath = function (statePath) {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return this.getStateNodeById(statePath.slice(1));\n } catch (e) {// try individual paths\n // throw e;\n }\n }\n\n var arrayStatePath = toStatePath(statePath, this.delimiter).slice();\n var currentStateNode = this;\n\n while (arrayStatePath.length) {\n var key = arrayStatePath.shift();\n\n if (!key.length) {\n break;\n }\n\n currentStateNode = currentStateNode.getStateNode(key);\n }\n\n return currentStateNode;\n };\n /**\r\n * Resolves a partial state value with its full representation in this machine.\r\n *\r\n * @param stateValue The partial state value to resolve.\r\n */\n\n\n StateNode.prototype.resolve = function (stateValue) {\n var _a;\n\n var _this = this;\n\n if (!stateValue) {\n return this.initialStateValue || EMPTY_OBJECT; // TODO: type-specific properties\n }\n\n switch (this.type) {\n case 'parallel':\n return mapValues(this.initialStateValue, function (subStateValue, subStateKey) {\n return subStateValue ? _this.getStateNode(subStateKey).resolve(stateValue[subStateKey] || subStateValue) : EMPTY_OBJECT;\n });\n\n case 'compound':\n if (isString(stateValue)) {\n var subStateNode = this.getStateNode(stateValue);\n\n if (subStateNode.type === 'parallel' || subStateNode.type === 'compound') {\n return _a = {}, _a[stateValue] = subStateNode.initialStateValue, _a;\n }\n\n return stateValue;\n }\n\n if (!Object.keys(stateValue).length) {\n return this.initialStateValue || {};\n }\n\n return mapValues(stateValue, function (subStateValue, subStateKey) {\n return subStateValue ? _this.getStateNode(subStateKey).resolve(subStateValue) : EMPTY_OBJECT;\n });\n\n default:\n return stateValue || EMPTY_OBJECT;\n }\n };\n\n StateNode.prototype.getResolvedPath = function (stateIdentifier) {\n if (isStateId(stateIdentifier)) {\n var stateNode = this.machine.idMap[stateIdentifier.slice(STATE_IDENTIFIER.length)];\n\n if (!stateNode) {\n throw new Error(\"Unable to find state node '\".concat(stateIdentifier, \"'\"));\n }\n\n return stateNode.path;\n }\n\n return toStatePath(stateIdentifier, this.delimiter);\n };\n\n Object.defineProperty(StateNode.prototype, \"initialStateValue\", {\n get: function () {\n var _a;\n\n if (this.__cache.initialStateValue) {\n return this.__cache.initialStateValue;\n }\n\n var initialStateValue;\n\n if (this.type === 'parallel') {\n initialStateValue = mapFilterValues(this.states, function (state) {\n return state.initialStateValue || EMPTY_OBJECT;\n }, function (stateNode) {\n return !(stateNode.type === 'history');\n });\n } else if (this.initial !== undefined) {\n if (!this.states[this.initial]) {\n throw new Error(\"Initial state '\".concat(this.initial, \"' not found on '\").concat(this.key, \"'\"));\n }\n\n initialStateValue = isLeafNode(this.states[this.initial]) ? this.initial : (_a = {}, _a[this.initial] = this.states[this.initial].initialStateValue, _a);\n } else {\n // The finite state value of a machine without child states is just an empty object\n initialStateValue = {};\n }\n\n this.__cache.initialStateValue = initialStateValue;\n return this.__cache.initialStateValue;\n },\n enumerable: false,\n configurable: true\n });\n\n StateNode.prototype.getInitialState = function (stateValue, context) {\n this._init(); // TODO: this should be in the constructor (see note in constructor)\n\n\n var configuration = this.getStateNodes(stateValue);\n return this.resolveTransition({\n configuration: configuration,\n exitSet: [],\n transitions: [],\n source: undefined,\n actions: []\n }, undefined, context !== null && context !== void 0 ? context : this.machine.context, undefined);\n };\n\n Object.defineProperty(StateNode.prototype, \"initialState\", {\n /**\r\n * The initial State instance, which includes all actions to be executed from\r\n * entering the initial state.\r\n */\n get: function () {\n var initialStateValue = this.initialStateValue;\n\n if (!initialStateValue) {\n throw new Error(\"Cannot retrieve initial state from simple state '\".concat(this.id, \"'.\"));\n }\n\n return this.getInitialState(initialStateValue);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"target\", {\n /**\r\n * The target state value of the history state node, if it exists. This represents the\r\n * default state value to transition to if no history value exists yet.\r\n */\n get: function () {\n var target;\n\n if (this.type === 'history') {\n var historyConfig = this.config;\n\n if (isString(historyConfig.target)) {\n target = isStateId(historyConfig.target) ? pathToStateValue(this.machine.getStateNodeById(historyConfig.target).path.slice(this.path.length - 1)) : historyConfig.target;\n } else {\n target = historyConfig.target;\n }\n }\n\n return target;\n },\n enumerable: false,\n configurable: true\n });\n /**\r\n * Returns the leaf nodes from a state path relative to this state node.\r\n *\r\n * @param relativeStateId The relative state path to retrieve the state nodes\r\n * @param history The previous state to retrieve history\r\n * @param resolve Whether state nodes should resolve to initial child state nodes\r\n */\n\n StateNode.prototype.getRelativeStateNodes = function (relativeStateId, historyValue, resolve) {\n if (resolve === void 0) {\n resolve = true;\n }\n\n return resolve ? relativeStateId.type === 'history' ? relativeStateId.resolveHistory(historyValue) : relativeStateId.initialStateNodes : [relativeStateId];\n };\n\n Object.defineProperty(StateNode.prototype, \"initialStateNodes\", {\n get: function () {\n var _this = this;\n\n if (isLeafNode(this)) {\n return [this];\n } // Case when state node is compound but no initial state is defined\n\n\n if (this.type === 'compound' && !this.initial) {\n if (!IS_PRODUCTION) {\n warn(false, \"Compound state node '\".concat(this.id, \"' has no initial state.\"));\n }\n\n return [this];\n }\n\n var initialStateNodePaths = toStatePaths(this.initialStateValue);\n return flatten(initialStateNodePaths.map(function (initialPath) {\n return _this.getFromRelativePath(initialPath);\n }));\n },\n enumerable: false,\n configurable: true\n });\n /**\r\n * Retrieves state nodes from a relative path to this state node.\r\n *\r\n * @param relativePath The relative path from this state node\r\n * @param historyValue\r\n */\n\n StateNode.prototype.getFromRelativePath = function (relativePath) {\n if (!relativePath.length) {\n return [this];\n }\n\n var _a = __read(relativePath),\n stateKey = _a[0],\n childStatePath = _a.slice(1);\n\n if (!this.states) {\n throw new Error(\"Cannot retrieve subPath '\".concat(stateKey, \"' from node with no states\"));\n }\n\n var childStateNode = this.getStateNode(stateKey);\n\n if (childStateNode.type === 'history') {\n return childStateNode.resolveHistory();\n }\n\n if (!this.states[stateKey]) {\n throw new Error(\"Child state '\".concat(stateKey, \"' does not exist on '\").concat(this.id, \"'\"));\n }\n\n return this.states[stateKey].getFromRelativePath(childStatePath);\n };\n\n StateNode.prototype.historyValue = function (relativeStateValue) {\n if (!Object.keys(this.states).length) {\n return undefined;\n }\n\n return {\n current: relativeStateValue || this.initialStateValue,\n states: mapFilterValues(this.states, function (stateNode, key) {\n if (!relativeStateValue) {\n return stateNode.historyValue();\n }\n\n var subStateValue = isString(relativeStateValue) ? undefined : relativeStateValue[key];\n return stateNode.historyValue(subStateValue || stateNode.initialStateValue);\n }, function (stateNode) {\n return !stateNode.history;\n })\n };\n };\n /**\r\n * Resolves to the historical value(s) of the parent state node,\r\n * represented by state nodes.\r\n *\r\n * @param historyValue\r\n */\n\n\n StateNode.prototype.resolveHistory = function (historyValue) {\n var _this = this;\n\n if (this.type !== 'history') {\n return [this];\n }\n\n var parent = this.parent;\n\n if (!historyValue) {\n var historyTarget = this.target;\n return historyTarget ? flatten(toStatePaths(historyTarget).map(function (relativeChildPath) {\n return parent.getFromRelativePath(relativeChildPath);\n })) : parent.initialStateNodes;\n }\n\n var subHistoryValue = nestedPath(parent.path, 'states')(historyValue).current;\n\n if (isString(subHistoryValue)) {\n return [parent.getStateNode(subHistoryValue)];\n }\n\n return flatten(toStatePaths(subHistoryValue).map(function (subStatePath) {\n return _this.history === 'deep' ? parent.getFromRelativePath(subStatePath) : [parent.states[subStatePath[0]]];\n }));\n };\n\n Object.defineProperty(StateNode.prototype, \"stateIds\", {\n /**\r\n * All the state node IDs of this state node and its descendant state nodes.\r\n */\n get: function () {\n var _this = this;\n\n var childStateIds = flatten(Object.keys(this.states).map(function (stateKey) {\n return _this.states[stateKey].stateIds;\n }));\n return [this.id].concat(childStateIds);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"events\", {\n /**\r\n * All the event types accepted by this state node and its descendants.\r\n */\n get: function () {\n var e_8, _a, e_9, _b;\n\n if (this.__cache.events) {\n return this.__cache.events;\n }\n\n var states = this.states;\n var events = new Set(this.ownEvents);\n\n if (states) {\n try {\n for (var _c = __values(Object.keys(states)), _d = _c.next(); !_d.done; _d = _c.next()) {\n var stateId = _d.value;\n var state = states[stateId];\n\n if (state.states) {\n try {\n for (var _e = (e_9 = void 0, __values(state.events)), _f = _e.next(); !_f.done; _f = _e.next()) {\n var event_1 = _f.value;\n events.add(\"\".concat(event_1));\n }\n } catch (e_9_1) {\n e_9 = {\n error: e_9_1\n };\n } finally {\n try {\n if (_f && !_f.done && (_b = _e.return)) _b.call(_e);\n } finally {\n if (e_9) throw e_9.error;\n }\n }\n }\n }\n } catch (e_8_1) {\n e_8 = {\n error: e_8_1\n };\n } finally {\n try {\n if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\n } finally {\n if (e_8) throw e_8.error;\n }\n }\n }\n\n return this.__cache.events = Array.from(events);\n },\n enumerable: false,\n configurable: true\n });\n Object.defineProperty(StateNode.prototype, \"ownEvents\", {\n /**\r\n * All the events that have transitions directly from this state node.\r\n *\r\n * Excludes any inert events.\r\n */\n get: function () {\n var events = new Set(this.transitions.filter(function (transition) {\n return !(!transition.target && !transition.actions.length && transition.internal);\n }).map(function (transition) {\n return transition.eventType;\n }));\n return Array.from(events);\n },\n enumerable: false,\n configurable: true\n });\n\n StateNode.prototype.resolveTarget = function (_target) {\n var _this = this;\n\n if (_target === undefined) {\n // an undefined target signals that the state node should not transition from that state when receiving that event\n return undefined;\n }\n\n return _target.map(function (target) {\n if (!isString(target)) {\n return target;\n }\n\n var isInternalTarget = target[0] === _this.delimiter; // If internal target is defined on machine,\n // do not include machine key on target\n\n if (isInternalTarget && !_this.parent) {\n return _this.getStateNodeByPath(target.slice(1));\n }\n\n var resolvedTarget = isInternalTarget ? _this.key + target : target;\n\n if (_this.parent) {\n try {\n var targetStateNode = _this.parent.getStateNodeByPath(resolvedTarget);\n\n return targetStateNode;\n } catch (err) {\n throw new Error(\"Invalid transition definition for state node '\".concat(_this.id, \"':\\n\").concat(err.message));\n }\n } else {\n return _this.getStateNodeByPath(resolvedTarget);\n }\n });\n };\n\n StateNode.prototype.formatTransition = function (transitionConfig) {\n var _this = this;\n\n var normalizedTarget = normalizeTarget(transitionConfig.target);\n var internal = 'internal' in transitionConfig ? transitionConfig.internal : normalizedTarget ? normalizedTarget.some(function (_target) {\n return isString(_target) && _target[0] === _this.delimiter;\n }) : true;\n var guards = this.machine.options.guards;\n var target = this.resolveTarget(normalizedTarget);\n\n var transition = __assign(__assign({}, transitionConfig), {\n actions: toActionObjects(toArray(transitionConfig.actions)),\n cond: toGuard(transitionConfig.cond, guards),\n target: target,\n source: this,\n internal: internal,\n eventType: transitionConfig.event,\n toJSON: function () {\n return __assign(__assign({}, transition), {\n target: transition.target ? transition.target.map(function (t) {\n return \"#\".concat(t.id);\n }) : undefined,\n source: \"#\".concat(_this.id)\n });\n }\n });\n\n return transition;\n };\n\n StateNode.prototype.formatTransitions = function () {\n var e_10, _a;\n\n var _this = this;\n\n var onConfig;\n\n if (!this.config.on) {\n onConfig = [];\n } else if (Array.isArray(this.config.on)) {\n onConfig = this.config.on;\n } else {\n var _b = this.config.on,\n _c = WILDCARD,\n _d = _b[_c],\n wildcardConfigs = _d === void 0 ? [] : _d,\n strictTransitionConfigs_1 = __rest(_b, [typeof _c === \"symbol\" ? _c : _c + \"\"]);\n\n onConfig = flatten(Object.keys(strictTransitionConfigs_1).map(function (key) {\n if (!IS_PRODUCTION && key === NULL_EVENT) {\n warn(false, \"Empty string transition configs (e.g., `{ on: { '': ... }}`) for transient transitions are deprecated. Specify the transition in the `{ always: ... }` property instead. \" + \"Please check the `on` configuration for \\\"#\".concat(_this.id, \"\\\".\"));\n }\n\n var transitionConfigArray = toTransitionConfigArray(key, strictTransitionConfigs_1[key]);\n\n if (!IS_PRODUCTION) {\n validateArrayifiedTransitions(_this, key, transitionConfigArray);\n }\n\n return transitionConfigArray;\n }).concat(toTransitionConfigArray(WILDCARD, wildcardConfigs)));\n }\n\n var eventlessConfig = this.config.always ? toTransitionConfigArray('', this.config.always) : [];\n var doneConfig = this.config.onDone ? toTransitionConfigArray(String(done(this.id)), this.config.onDone) : [];\n\n if (!IS_PRODUCTION) {\n warn(!(this.config.onDone && !this.parent), \"Root nodes cannot have an \\\".onDone\\\" transition. Please check the config of \\\"\".concat(this.id, \"\\\".\"));\n }\n\n var invokeConfig = flatten(this.invoke.map(function (invokeDef) {\n var settleTransitions = [];\n\n if (invokeDef.onDone) {\n settleTransitions.push.apply(settleTransitions, __spreadArray([], __read(toTransitionConfigArray(String(doneInvoke(invokeDef.id)), invokeDef.onDone)), false));\n }\n\n if (invokeDef.onError) {\n settleTransitions.push.apply(settleTransitions, __spreadArray([], __read(toTransitionConfigArray(String(error(invokeDef.id)), invokeDef.onError)), false));\n }\n\n return settleTransitions;\n }));\n var delayedTransitions = this.after;\n var formattedTransitions = flatten(__spreadArray(__spreadArray(__spreadArray(__spreadArray([], __read(doneConfig), false), __read(invokeConfig), false), __read(onConfig), false), __read(eventlessConfig), false).map(function (transitionConfig) {\n return toArray(transitionConfig).map(function (transition) {\n return _this.formatTransition(transition);\n });\n }));\n\n try {\n for (var delayedTransitions_1 = __values(delayedTransitions), delayedTransitions_1_1 = delayedTransitions_1.next(); !delayedTransitions_1_1.done; delayedTransitions_1_1 = delayedTransitions_1.next()) {\n var delayedTransition = delayedTransitions_1_1.value;\n formattedTransitions.push(delayedTransition);\n }\n } catch (e_10_1) {\n e_10 = {\n error: e_10_1\n };\n } finally {\n try {\n if (delayedTransitions_1_1 && !delayedTransitions_1_1.done && (_a = delayedTransitions_1.return)) _a.call(delayedTransitions_1);\n } finally {\n if (e_10) throw e_10.error;\n }\n }\n\n return formattedTransitions;\n };\n\n return StateNode;\n}();\n\nexport { StateNode };\n","import { StateNode } from './StateNode.js';\nimport { IS_PRODUCTION } from './environment.js';\n\nvar warned = false;\nfunction Machine(config, options, initialContext) {\n if (initialContext === void 0) {\n initialContext = config.context;\n }\n\n return new StateNode(config, options, initialContext);\n}\nfunction createMachine(config, options) {\n if (!IS_PRODUCTION && !('predictableActionArguments' in config) && !warned) {\n warned = true;\n console.warn('It is highly recommended to set `predictableActionArguments` to `true` when using `createMachine`. https://xstate.js.org/docs/guides/actions.html');\n }\n\n return new StateNode(config, options);\n}\n\nexport { Machine, createMachine };\n","import { assign as assign$1, cancel as cancel$1, send as send$1, sendTo as sendTo$1, sendParent as sendParent$1, sendUpdate as sendUpdate$1, forwardTo as forwardTo$1, doneInvoke as doneInvoke$1, raise as raise$1, log as log$1, pure as pure$1, choose as choose$1, stop as stop$1 } from './actions.js';\nimport * as actions from './actions.js';\nexport { actions };\nexport { toActorRef } from './Actor.js';\nexport { Interpreter, InterpreterStatus, interpret, spawn } from './interpreter.js';\nexport { Machine, createMachine } from './Machine.js';\nexport { mapState } from './mapState.js';\nexport { matchState } from './match.js';\nexport { createSchema, t } from './schema.js';\nexport { State } from './State.js';\nexport { StateNode } from './StateNode.js';\nexport { spawnBehavior } from './behaviors.js';\nexport { ActionTypes, SpecialTargets } from './types.js';\nexport { matchesState, toEventObject, toObserver, toSCXMLEvent } from './utils.js';\n\nvar assign = assign$1,\n cancel = cancel$1,\n send = send$1,\n sendTo = sendTo$1,\n sendParent = sendParent$1,\n sendUpdate = sendUpdate$1,\n forwardTo = forwardTo$1,\n doneInvoke = doneInvoke$1,\n raise = raise$1,\n log = log$1,\n pure = pure$1,\n choose = choose$1,\n stop = stop$1;\n\nexport { assign, cancel, choose, doneInvoke, forwardTo, log, pure, raise, send, sendParent, sendTo, sendUpdate, stop };\n","import { useLayoutEffect } from 'react';\n\nvar index = useLayoutEffect ;\n\nexport default index;\n","import * as React from 'react';\nexport default function useConstant(fn) {\n var ref = React.useRef();\n if (!ref.current) {\n ref.current = { v: fn() };\n }\n return ref.current.v;\n}\n","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nimport { useEffect, useState } from 'react';\nimport useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';\nimport { interpret, InterpreterStatus, State, toObserver } from 'xstate';\nimport useConstant from './useConstant';\nexport function useIdleInterpreter(getMachine, options) {\n var machine = useConstant(function () {\n return typeof getMachine === 'function' ? getMachine() : getMachine;\n });\n if (process.env.NODE_ENV !== 'production' &&\n typeof getMachine !== 'function') {\n var _a = __read(useState(machine), 1), initialMachine = _a[0];\n if (getMachine !== initialMachine) {\n console.warn('Machine given to `useMachine` has changed between renders. This is not supported and might lead to unexpected results.\\n' +\n 'Please make sure that you pass the same Machine as argument each time.');\n }\n }\n var context = options.context, guards = options.guards, actions = options.actions, activities = options.activities, services = options.services, delays = options.delays, rehydratedState = options.state, interpreterOptions = __rest(options, [\"context\", \"guards\", \"actions\", \"activities\", \"services\", \"delays\", \"state\"]);\n var service = useConstant(function () {\n var machineConfig = {\n context: context,\n guards: guards,\n actions: actions,\n activities: activities,\n services: services,\n delays: delays\n };\n var machineWithConfig = machine.withConfig(machineConfig, function () { return (__assign(__assign({}, machine.context), context)); });\n return interpret(machineWithConfig, interpreterOptions);\n });\n // Make sure options are kept updated when they change.\n // This mutation assignment is safe because the service instance is only used\n // in one place -- this hook's caller.\n useIsomorphicLayoutEffect(function () {\n Object.assign(service.machine.options.actions, actions);\n Object.assign(service.machine.options.guards, guards);\n Object.assign(service.machine.options.activities, activities);\n Object.assign(service.machine.options.services, services);\n Object.assign(service.machine.options.delays, delays);\n }, [actions, guards, activities, services, delays]);\n return service;\n}\nexport function useInterpret(getMachine) {\n var _a = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n _a[_i - 1] = arguments[_i];\n }\n var _b = __read(_a, 2), _c = _b[0], options = _c === void 0 ? {} : _c, observerOrListener = _b[1];\n var service = useIdleInterpreter(getMachine, options);\n useEffect(function () {\n if (!observerOrListener) {\n return;\n }\n var sub = service.subscribe(toObserver(observerOrListener));\n return function () {\n sub.unsubscribe();\n };\n }, [observerOrListener]);\n useEffect(function () {\n var rehydratedState = options.state;\n service.start(rehydratedState ? State.create(rehydratedState) : undefined);\n return function () {\n service.stop();\n service.status = InterpreterStatus.NotStarted;\n };\n }, []);\n return service;\n}\n","var __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport { InterpreterStatus } from 'xstate';\nexport function partition(items, predicate) {\n var e_1, _a;\n var _b = __read([[], []], 2), truthy = _b[0], falsy = _b[1];\n try {\n for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {\n var item = items_1_1.value;\n if (predicate(item)) {\n truthy.push(item);\n }\n else {\n falsy.push(item);\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return [truthy, falsy];\n}\nexport function getServiceSnapshot(service) {\n return service.status !== 0\n ? service.getSnapshot()\n : service.machine.initialState;\n}\n// From https://github.com/reduxjs/react-redux/blob/master/src/utils/shallowEqual.ts\nfunction is(x, y) {\n if (x === y) {\n return x !== 0 || y !== 0 || 1 / x === 1 / y;\n }\n else {\n return x !== x && y !== y;\n }\n}\nexport function shallowEqual(objA, objB) {\n if (is(objA, objB))\n return true;\n if (typeof objA !== 'object' ||\n objA === null ||\n typeof objB !== 'object' ||\n objB === null) {\n return false;\n }\n var keysA = Object.keys(objA);\n var keysB = Object.keys(objB);\n if (keysA.length !== keysB.length)\n return false;\n for (var i = 0; i < keysA.length; i++) {\n if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) ||\n !is(objA[keysA[i]], objB[keysA[i]])) {\n return false;\n }\n }\n return true;\n}\nexport function isService(actor) {\n return 'state' in actor && 'machine' in actor;\n}\nexport function isInterpreterStateEqual(service, prevState, nextState) {\n if (service.status === InterpreterStatus.NotStarted) {\n return true;\n }\n // Only change the current state if:\n // - the incoming state is the \"live\" initial state (since it might have new actors)\n // - OR the incoming state actually changed.\n //\n // The \"live\" initial state will have .changed === undefined.\n var initialStateChanged = nextState.changed === undefined &&\n (Object.keys(nextState.children).length > 0 ||\n typeof prevState.changed === 'boolean');\n return !(nextState.changed || initialStateChanged);\n}\n","import { useRef, useCallback } from 'react';\nimport useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';\nimport useConstant from './useConstant';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';\nimport { getServiceSnapshot, isInterpreterStateEqual, isService } from './utils';\nfunction identity(a) {\n return a;\n}\nexport function isActorWithState(actorRef) {\n return 'state' in actorRef;\n}\nfunction isDeferredActor(actorRef) {\n return 'deferred' in actorRef;\n}\nfunction defaultGetSnapshot(actorRef) {\n return 'getSnapshot' in actorRef\n ? isService(actorRef)\n ? getServiceSnapshot(actorRef)\n : actorRef.getSnapshot()\n : isActorWithState(actorRef)\n ? actorRef.state\n : undefined;\n}\nexport function useActor(actorRef, getSnapshot) {\n if (getSnapshot === void 0) { getSnapshot = defaultGetSnapshot; }\n var actorRefRef = useRef(actorRef);\n var deferredEventsRef = useRef([]);\n var subscribe = useCallback(function (handleStoreChange) {\n var unsubscribe = actorRef.subscribe(handleStoreChange).unsubscribe;\n return unsubscribe;\n }, [actorRef]);\n var boundGetSnapshot = useCallback(function () { return getSnapshot(actorRef); }, [actorRef, getSnapshot]);\n var isEqual = useCallback(function (prevState, nextState) {\n if (isService(actorRef)) {\n return isInterpreterStateEqual(actorRef, prevState, nextState);\n }\n return prevState === nextState;\n }, [actorRef]);\n var storeSnapshot = useSyncExternalStoreWithSelector(subscribe, boundGetSnapshot, boundGetSnapshot, identity, isEqual);\n var send = useConstant(function () { return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var event = args[0];\n if (process.env.NODE_ENV !== 'production' && args.length > 1) {\n console.warn(\"Unexpected payload: \".concat(JSON.stringify(args[1]), \". Only a single event object can be sent to actor send() functions.\"));\n }\n var currentActorRef = actorRefRef.current;\n // If the previous actor is a deferred actor,\n // queue the events so that they can be replayed\n // on the non-deferred actor.\n if (isDeferredActor(currentActorRef) && currentActorRef.deferred) {\n deferredEventsRef.current.push(event);\n }\n else {\n currentActorRef.send(event);\n }\n }; });\n useIsomorphicLayoutEffect(function () {\n actorRefRef.current = actorRef;\n // Dequeue deferred events from the previous deferred actorRef\n while (deferredEventsRef.current.length > 0) {\n var deferredEvent = deferredEventsRef.current.shift();\n actorRef.send(deferredEvent);\n }\n }, [actorRef]);\n return [storeSnapshot, send];\n}\n","import { useCallback, useRef } from 'react';\nimport { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector';\nimport { isActorWithState } from './useActor';\nimport { getServiceSnapshot, isService } from './utils';\nvar defaultCompare = function (a, b) { return a === b; };\nvar defaultGetSnapshot = function (a, initialStateCacheRef) {\n if (isService(a)) {\n // A status of 0 = interpreter not started\n if (a.status === 0 && initialStateCacheRef.current) {\n return initialStateCacheRef.current;\n }\n var snapshot = getServiceSnapshot(a);\n initialStateCacheRef.current = a.status === 0 ? snapshot : null;\n return snapshot;\n }\n return isActorWithState(a) ? a.state : undefined;\n};\nexport function useSelector(actor, selector, compare, getSnapshot) {\n if (compare === void 0) { compare = defaultCompare; }\n var initialStateCacheRef = useRef(null);\n var subscribe = useCallback(function (handleStoreChange) {\n var unsubscribe = actor.subscribe(handleStoreChange).unsubscribe;\n return unsubscribe;\n }, [actor]);\n var boundGetSnapshot = useCallback(function () {\n if (getSnapshot) {\n return getSnapshot(actor);\n }\n return defaultGetSnapshot(actor, initialStateCacheRef);\n }, [actor, getSnapshot]);\n var selectedSnapshot = useSyncExternalStoreWithSelector(subscribe, boundGetSnapshot, boundGetSnapshot, selector, compare);\n return selectedSnapshot;\n}\n","/**\n * This file contains helpers that lets you easily access current actor's state\n * and context.\n */\n/**\n * Get the state of current actor. This is useful for checking which screen\n * to render: e.g. `getActorState(state).matches('confirmSignUp.edit').\n */\nconst getActorState = (state) => {\n return state.context.actorRef?.getSnapshot();\n};\n/**\n * Get the context of current actor. Useful for getting any nested context\n * like remoteError.\n */\nconst getActorContext = (state) => {\n return getActorState(state)?.context;\n};\n\nexport { getActorContext, getActorState };\n","import { Category, AiAction, AuthAction, StorageAction, InAppMessagingAction, GeoAction } from '@aws-amplify/core/internals/utils';\n\nconst AI_INPUT_BASE = {\n category: Category.AI,\n apis: [\n AiAction.CreateConversation,\n AiAction.DeleteConversation,\n AiAction.ListConversations,\n AiAction.UpdateConversation,\n AiAction.OnMessage,\n AiAction.SendMessage,\n AiAction.Generation,\n ],\n};\nconst ACCOUNT_SETTINGS_INPUT_BASE = {\n apis: [AuthAction.DeleteUser, AuthAction.UpdatePassword],\n category: Category.Auth,\n};\nconst AUTHENTICATOR_INPUT_BASE = {\n apis: [\n AuthAction.SignUp,\n AuthAction.ConfirmSignUp,\n AuthAction.ResendSignUpCode,\n AuthAction.SignIn,\n AuthAction.ConfirmSignIn,\n AuthAction.FetchUserAttributes,\n AuthAction.SignOut,\n AuthAction.ResetPassword,\n AuthAction.ConfirmResetPassword,\n AuthAction.SignInWithRedirect,\n ],\n category: Category.Auth,\n};\nconst FILE_UPLOADER_BASE_INPUT = {\n apis: [StorageAction.UploadData],\n category: Category.Storage,\n};\nconst IN_APP_MESSAGING_INPUT_BASE = {\n apis: [InAppMessagingAction.NotifyMessageInteraction],\n category: Category.InAppMessaging,\n};\nconst LOCATION_SEARCH_INPUT_BASE = {\n category: Category.Geo,\n apis: [\n GeoAction.SearchByText,\n GeoAction.SearchForSuggestions,\n GeoAction.SearchByPlaceId,\n ],\n};\nconst MAP_VIEW_INPUT_BASE = {\n category: Category.Geo,\n apis: [],\n};\nconst STORAGE_MANAGER_INPUT_BASE = {\n apis: [StorageAction.UploadData],\n category: Category.Storage,\n};\nconst STORAGE_BROWSER_INPUT_BASE = {\n apis: [\n StorageAction.UploadData,\n StorageAction.Copy,\n StorageAction.GetUrl,\n StorageAction.List,\n StorageAction.Remove,\n StorageAction.GetDataAccess,\n StorageAction.ListCallerAccessGrants,\n ],\n category: Category.Storage,\n};\n\nexport { ACCOUNT_SETTINGS_INPUT_BASE, AI_INPUT_BASE, AUTHENTICATOR_INPUT_BASE, FILE_UPLOADER_BASE_INPUT, IN_APP_MESSAGING_INPUT_BASE, LOCATION_SEARCH_INPUT_BASE, MAP_VIEW_INPUT_BASE, STORAGE_BROWSER_INPUT_BASE, STORAGE_MANAGER_INPUT_BASE };\n","/**\n * Some libraries may not follow Node ES module spec and could be loaded as CommonJS modules,\n * To ensure the interoperability between ESM and CJS, modules from those libraries have to be loaded via namespace import\n * And sanitized by the function below because unlike ESM namespace, CJS namespace set `module.exports` object on the `default` key\n * https://nodejs.org/api/esm.html#interoperability-with-commonjs\n */\nconst sanitizeNamespaceImport = (namespaceModule) => {\n const sanitizedNamespaceModule = { default: undefined, ...namespaceModule };\n return sanitizedNamespaceModule.default ?? sanitizedNamespaceModule;\n};\n/**\n * Checks if `value` is an Object (non-primitive, non-array, non-function)\n * Will return false for Arrays and functions\n *\n *\n * @param {unknown} value The value to check\n * @returns {boolean} Returns `true` if `value` is an object, `false` otherwise\n */\nfunction isObject(value) {\n return value != null && !Array.isArray(value) && typeof value === 'object';\n}\n/**\n * Checks if `value` is a string primitive or object\n *\n * @param {unknown} value The value to check\n * @returns {boolean} Returns `true` if `value` is a string, `false` otherwise\n */\nfunction isString(value) {\n return (typeof value === 'string' ||\n (typeof value === 'object' &&\n Object.prototype.toString.call(value) === '[object String]'));\n}\n/**\n * Checks if `value` is a Map\n *\n * @param {unknown} value The value to check\n * @returns {boolean} Returns `true` if `value` is a Map, `false` otherwise\n */\nfunction isMap(value) {\n return (isObject(value) && Object.prototype.toString.call(value) === '[object Map]');\n}\n/**\n * Checks if `value` is a Set\n *\n * @param {unknown} value The value to check\n * @returns {boolean} Returns `true` if `value` is a Set, `false` otherwise\n */\nfunction isSet(value) {\n return (isObject(value) && Object.prototype.toString.call(value) === '[object Set]');\n}\n/**\n * Checks if `value` is undefined\n *\n * @param {unknown} value The value to check\n * @returns {boolean} Returns `true` if `value` is undefined, `false` otherwise\n */\nfunction isUndefined(value) {\n return value === undefined;\n}\n/**\n * Checks if `value` is nullish\n *\n * @param {unknown} value The value to check\n * @returns {boolean} Returns `true` if `value` is nullish, `false` otherwise\n */\nfunction isNil(value) {\n return value == null;\n}\n/**\n * Checks if `value` is empty\n *\n * @param {unknown} value The value to check\n * @returns {boolean} Returns `true` if `value` is empty, `false` otherwise\n */\nfunction isEmpty(value) {\n if (value === null || value === undefined)\n return true;\n if (isObject(value) && (isMap(value) || isSet(value))) {\n return !value.size;\n }\n if (isObject(value) && (isString(value) || Array.isArray(value))) {\n return !value.length;\n }\n for (const key in value) {\n if (has(value, key)) {\n return false;\n }\n }\n return true;\n}\n/**\n * Checks if `value` is an empty array\n *\n * @param {unknown} value The value to check\n * @returns {boolean} Returns `true` if `value` is a empty, `false` otherwise\n */\nfunction isEmptyArray(value) {\n return Array.isArray(value) && isEmpty(value);\n}\n/**\n * Checks if all members of the `values` param are empty arrays\n *\n * @param {unknown} value The values to check\n * @returns {boolean} Returns `true` if all members of `values` are empty, `false` otherwise\n */\nfunction areEmptyArrays(...values) {\n return values.every(isEmptyArray);\n}\n/**\n * Checks if `value` is an empty object\n *\n * @param {unknown} value The value to check\n * @returns {boolean} Returns `true` if `value` is empty, `false` otherwise\n */\nfunction isEmptyObject(value) {\n return isObject(value) && isEmpty(value);\n}\n/**\n * Checks if all members of the `values` param are empty objects\n *\n * @param {unknown} values The values to check\n * @returns {boolean} Returns `true` if all members of the `values` param are empty, `false` otherwise\n */\nfunction areEmptyObjects(...values) {\n return values.every(isEmptyObject);\n}\n/**\n * Capitalizes `value` and its return type\n *\n * @param {string} value string to capitalize\n * @returns {string} capitalized string\n */\nfunction capitalize(value) {\n return (isString(value) ? value.charAt(0).toUpperCase() + value.slice(1) : '');\n}\n/**\n * Checks if `key` is a direct property of `value`\n *\n * @param {unknown} value `object` potentially containing property\n * @param {string} key property key\n * @returns whether `key` param is a property of the `obj` param\n */\nfunction has(value, key) {\n return value != null && Object.prototype.hasOwnProperty.call(value, key);\n}\n/**\n * Checks if `value` is a function\n *\n * @param {unknown} value param to check\n * @returns {boolean} whether `value` is a function\n */\nfunction isFunction(value) {\n return typeof value === 'function';\n}\n/**\n * This helper function creates modifier class names that are used for our flat BEM styling\n * it takes in a base and modifier and returns the modified class if a modifier was passed in and null otherwise\n * @param base The base class of the output\n * @param modifier The modifier to add onto the base\n * @returns the modified class name or empty string\n */\nconst classNameModifier = (base, modifier) => {\n return modifier ? `${base}--${modifier}` : '';\n};\n/**\n * This helper function creates modified class names that are used for our flat BEM styling\n * it takes in a base, modifier, and flag and returns the modified class name if the flag is true and null if the flag is false\n * @param base\n * @param modifier\n * @param flag\n * @returns the modified class name or empty string\n */\nconst classNameModifierByFlag = (base, modifier, flag) => {\n return flag ? `${base}--${modifier}` : '';\n};\n/**\n * Similar to `Array.join`, with an optional callback/template param\n * for formatting returned string values\n *\n * @param {string[]} values string array\n * @param {(value: string) => string} template callback format param\n * @returns formatted string array\n */\nfunction templateJoin(values, template) {\n return values.reduce((acc, curr) => `${acc}${isString(curr) ? template(curr) : ''}`, '');\n}\n/**\n * A function that does nothing\n *\n * @param {any[]} _ accepts any parameters\n * @returns nothing\n */\nfunction noop(..._) {\n return;\n}\n/**\n * @param {string} groupName name of group\n * @param events string values related to group\n */\nfunction groupLog(groupName, ...events) {\n const hasEvents = !!events?.length;\n if (hasEvents) {\n // eslint-disable-next-line no-console\n console.groupCollapsed(groupName);\n events?.forEach((event) => {\n // eslint-disable-next-line no-console\n console.log(event);\n });\n // eslint-disable-next-line no-console\n console.groupEnd();\n }\n else {\n // eslint-disable-next-line no-console\n console.log(groupName);\n }\n}\n/**\n * Splits an object into 2 objects based on a predicate\n *\n * @param {object} obj an object to split into two\n * @param {function} predicate function to determin where an element should go\n * @returns\n */\nfunction splitObject(obj, predicate) {\n const left = {};\n const right = {};\n Object.entries(obj).forEach(([key, value]) => {\n if (predicate(key)) {\n left[key] = value;\n }\n else {\n right[key] = value;\n }\n });\n return [left, right];\n}\nconst cloneDeep = (obj) => {\n if (obj === null || obj === undefined || typeof obj !== 'object') {\n return obj;\n }\n if (obj instanceof Array) {\n return obj.reduce((arr, item, i) => {\n arr[i] = cloneDeep(item);\n return arr;\n }, []);\n }\n if (obj instanceof Object) {\n return Object.keys(obj || {}).reduce((cpObj, key) => {\n cpObj[key] = cloneDeep(obj[key]);\n return cpObj;\n }, {});\n }\n};\n\nexport { areEmptyArrays, areEmptyObjects, capitalize, classNameModifier, classNameModifierByFlag, cloneDeep, groupLog, has, isEmpty, isEmptyObject, isFunction, isMap, isNil, isObject, isSet, isString, isUndefined, noop, sanitizeNamespaceImport, splitObject, templateJoin };\n","import { Hub } from 'aws-amplify/utils';\nimport '@aws-amplify/core/internals/utils';\nimport '../../utils/setUserAgent/constants.mjs';\nimport { isFunction } from '../../utils/utils.mjs';\n\n/**\n * Handles Amplify JS Auth hub events, by forwarding hub events as appropriate\n * xstate events.\n */\nconst defaultAuthHubHandler = ({ payload }, service, options) => {\n const { event } = payload;\n const { send } = service;\n const { onSignIn, onSignOut } = options ?? {};\n switch (event) {\n case 'signedIn': {\n if (isFunction(onSignIn)) {\n onSignIn(payload);\n }\n break;\n }\n case 'signInWithRedirect': {\n send('SIGN_IN_WITH_REDIRECT');\n break;\n }\n case 'signedOut':\n case 'tokenRefresh_failure': {\n if (event === 'signedOut' && isFunction(onSignOut)) {\n onSignOut();\n }\n send('SIGN_OUT');\n break;\n }\n }\n};\n/**\n * Listens to external auth Hub events and sends corresponding event to\n * the `service.send` of interest\n *\n * @param service - contains state machine `send` function\n * @param handler - auth event handler\n * @returns function that unsubscribes to the hub evenmt\n */\nconst listenToAuthHub = (service, handler = defaultAuthHubHandler) => {\n const eventHandler = (data) => handler(data, service);\n return Hub.listen('auth', eventHandler, 'authenticator-hub-handler');\n};\n\nexport { defaultAuthHubHandler, listenToAuthHub };\n","const countryDialCodes = [\n '+1',\n '+7',\n '+20',\n '+27',\n '+30',\n '+31',\n '+32',\n '+33',\n '+34',\n '+36',\n '+39',\n '+40',\n '+41',\n '+43',\n '+44',\n '+45',\n '+46',\n '+47',\n '+48',\n '+49',\n '+51',\n '+52',\n '+53',\n '+54',\n '+55',\n '+56',\n '+57',\n '+58',\n '+60',\n '+61',\n '+62',\n '+63',\n '+64',\n '+65',\n '+66',\n '+81',\n '+82',\n '+84',\n '+86',\n '+90',\n '+91',\n '+92',\n '+93',\n '+94',\n '+95',\n '+98',\n '+212',\n '+213',\n '+216',\n '+218',\n '+220',\n '+221',\n '+222',\n '+223',\n '+224',\n '+225',\n '+226',\n '+227',\n '+228',\n '+229',\n '+230',\n '+231',\n '+232',\n '+233',\n '+234',\n '+235',\n '+236',\n '+237',\n '+238',\n '+239',\n '+240',\n '+241',\n '+242',\n '+243',\n '+244',\n '+245',\n '+246',\n '+248',\n '+249',\n '+250',\n '+251',\n '+252',\n '+253',\n '+254',\n '+255',\n '+256',\n '+257',\n '+258',\n '+260',\n '+261',\n '+262',\n '+263',\n '+264',\n '+265',\n '+266',\n '+267',\n '+268',\n '+269',\n '+290',\n '+291',\n '+297',\n '+298',\n '+299',\n '+345',\n '+350',\n '+351',\n '+352',\n '+353',\n '+354',\n '+355',\n '+356',\n '+357',\n '+358',\n '+359',\n '+370',\n '+371',\n '+372',\n '+373',\n '+374',\n '+375',\n '+376',\n '+377',\n '+378',\n '+379',\n '+380',\n '+381',\n '+382',\n '+385',\n '+386',\n '+387',\n '+389',\n '+420',\n '+421',\n '+423',\n '+500',\n '+501',\n '+502',\n '+503',\n '+504',\n '+505',\n '+506',\n '+507',\n '+508',\n '+509',\n '+537',\n '+590',\n '+591',\n '+593',\n '+594',\n '+595',\n '+596',\n '+597',\n '+598',\n '+599',\n '+670',\n '+672',\n '+673',\n '+674',\n '+675',\n '+676',\n '+677',\n '+678',\n '+679',\n '+680',\n '+681',\n '+682',\n '+683',\n '+685',\n '+686',\n '+687',\n '+688',\n '+689',\n '+690',\n '+691',\n '+692',\n '+850',\n '+852',\n '+853',\n '+855',\n '+856',\n '+872',\n '+880',\n '+886',\n '+960',\n '+961',\n '+962',\n '+963',\n '+964',\n '+965',\n '+966',\n '+967',\n '+968',\n '+970',\n '+971',\n '+972',\n '+973',\n '+974',\n '+975',\n '+976',\n '+977',\n '+992',\n '+993',\n '+994',\n '+995',\n '+996',\n '+998',\n];\n\nexport { countryDialCodes };\n","import { countryDialCodes } from '../../i18n/country-dial-codes.mjs';\nimport 'aws-amplify/utils';\n\n/**\n * This file contains helpers related to forms and input attributes.\n */\nconst defaultFormFieldOptions = {\n birthdate: {\n label: 'Birthdate',\n placeholder: 'Enter your Birthdate',\n type: 'date',\n autocomplete: 'bday',\n isRequired: true,\n },\n confirmation_code: {\n label: 'Confirmation Code',\n placeholder: 'Enter your Confirmation Code',\n type: 'text',\n autocomplete: 'one-time-code',\n isRequired: true,\n },\n confirm_password: {\n label: 'Confirm Password',\n placeholder: 'Please confirm your Password',\n type: 'password',\n autocomplete: 'new-password',\n isRequired: true,\n },\n email: {\n label: 'Email',\n placeholder: 'Enter your Email',\n type: 'email',\n autocomplete: 'username',\n isRequired: true,\n },\n family_name: {\n label: 'Family Name',\n placeholder: 'Enter your Family Name',\n type: 'text',\n autocomplete: 'family-name',\n isRequired: true,\n },\n given_name: {\n label: 'Given Name',\n placeholder: 'Enter your Given Name',\n type: 'text',\n autocomplete: 'given-name',\n isRequired: true,\n },\n middle_name: {\n label: 'Middle Name',\n placeholder: 'Enter your Middle Name',\n type: 'text',\n autocomplete: 'additional-name',\n isRequired: true,\n },\n name: {\n label: 'Name',\n placeholder: 'Enter your Name',\n type: 'text',\n autocomplete: 'name',\n isRequired: true,\n },\n nickname: {\n label: 'Nickname',\n placeholder: 'Enter your Nickname',\n type: 'text',\n autocomplete: 'tel',\n isRequired: true,\n },\n password: {\n label: 'Password',\n placeholder: 'Enter your Password',\n type: 'password',\n autocomplete: 'new-password',\n isRequired: true,\n },\n phone_number: {\n label: 'Phone Number',\n placeholder: 'Enter your Phone Number',\n type: 'tel',\n autocomplete: 'tel',\n dialCode: '+1',\n dialCodeList: countryDialCodes,\n isRequired: true,\n },\n preferred_username: {\n label: 'Preferred Username',\n placeholder: 'Enter your Preferred Username',\n type: 'text',\n isRequired: true,\n },\n profile: {\n label: 'Profile',\n placeholder: 'Add your Profile',\n type: 'url',\n autocomplete: 'url',\n isRequired: true,\n },\n website: {\n label: 'Website',\n placeholder: 'Add your Website',\n type: 'url',\n autocomplete: 'url',\n isRequired: true,\n },\n username: {\n label: 'Username',\n placeholder: 'Enter your Username',\n type: 'text',\n autocomplete: 'username',\n isRequired: true,\n },\n};\n/**\n * List of special characters that Cognito allows.\n *\n * Adapted from https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-policies.html\n */\n// prettier-ignore\nconst ALLOWED_SPECIAL_CHARACTERS = [\n '^', '$', '*', '.', '[', ']',\n '{', '}', '(', ')', '?', '\"',\n '!', '@', '#', '%', '&', '/',\n '\\\\', ',', '>', '<', \"'\", ':',\n ';', '|', '_', '~', '`', '=',\n '+', '-', ' '\n];\n/**\n * Email validation regex\n *\n * source: HTML5 spec https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address\n */\nconst emailRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/**\n+ * map navigable route keys to auth event names\n+ */\nconst NAVIGABLE_ROUTE_EVENT = {\n forgotPassword: 'FORGOT_PASSWORD',\n signIn: 'SIGN_IN',\n signUp: 'SIGN_UP',\n};\n\nexport { ALLOWED_SPECIAL_CHARACTERS, NAVIGABLE_ROUTE_EVENT, defaultFormFieldOptions, emailRegex };\n","const getRoute = (state, actorState) => {\n // 'federatedSignIn' exists as a state on both the 'signInActor' and 'signUpActor',\n // match against the `actorState` initially to determine if the federated sign in flow\n // has begun, then which actor has begun the flow and return the corresponding `route`\n if (actorState?.matches('federatedSignIn')) {\n if (state.matches('signUpActor')) {\n return 'signUp';\n }\n if (state.matches('signInActor')) {\n return 'signIn';\n }\n }\n switch (true) {\n case state.matches('idle'):\n return 'idle';\n case state.matches('setup'):\n return 'setup';\n case state.matches('signOut'):\n return 'signOut';\n case state.matches('authenticated'):\n return 'authenticated';\n case actorState?.matches('confirmSignUp'):\n case actorState?.matches('resendSignUpCode'):\n return 'confirmSignUp';\n case actorState?.matches('confirmSignIn'):\n return 'confirmSignIn';\n case actorState?.matches('setupTotp.edit'):\n case actorState?.matches('setupTotp.submit'):\n return 'setupTotp';\n case actorState?.matches('signIn'):\n return 'signIn';\n case actorState?.matches('signUp'):\n case actorState?.matches('autoSignIn'):\n return 'signUp';\n case actorState?.matches('forceChangePassword'):\n return 'forceNewPassword';\n case actorState?.matches('forgotPassword'):\n return 'forgotPassword';\n case actorState?.matches('confirmResetPassword'):\n return 'confirmResetPassword';\n case actorState?.matches('selectUserAttributes'):\n return 'verifyUser';\n case actorState?.matches('confirmVerifyUserAttribute'):\n return 'confirmVerifyUser';\n case state.matches('getCurrentUser'):\n case actorState?.matches('fetchUserAttributes'):\n /**\n * This route is needed for autoSignIn to capture both the\n * autoSignIn.pending and the resolved states when the\n * signIn actor is running.\n */\n return 'transition';\n default:\n return null;\n }\n};\n\nexport { getRoute };\n","import { getActorContext, getActorState } from './actor.mjs';\nimport { NAVIGABLE_ROUTE_EVENT } from './constants.mjs';\nimport { getRoute } from './getRoute.mjs';\n\n/**\n * This file contains helpers that translates xstate internals to more\n * understandable authenticator contexts. We provide these contexts with\n * `useAuthenticator` hook/composable/service.\n */\n/**\n * Creates public facing auth helpers that abstracts out xstate implementation\n * detail. Each framework implementation can export these helpers so that\n * developers can send events without having to learn internals.\n *\n * ```\n * const [state, send] = useActor(...);\n * const { submit } = getSendEventAliases(send);\n * submit({ username, password})\n * ```\n */\nconst getSendEventAliases = (send) => {\n const sendToMachine = (type) => {\n // TODO If these were created during the creation of the machine & provider,\n // then invalid transitions could be caught via https://xstate.js.org/docs/guides/states.html#state-can-event\n return (data) => send({ type, data });\n };\n return {\n initializeMachine: sendToMachine('INIT'),\n resendCode: sendToMachine('RESEND'),\n signOut: sendToMachine('SIGN_OUT'),\n submitForm: sendToMachine('SUBMIT'),\n updateForm: sendToMachine('CHANGE'),\n updateBlur: sendToMachine('BLUR'),\n // Actions that don't immediately invoke a service but instead transition to a screen\n // are prefixed with `to*`\n toFederatedSignIn: sendToMachine('FEDERATED_SIGN_IN'),\n toForgotPassword: sendToMachine('FORGOT_PASSWORD'),\n toSignIn: sendToMachine('SIGN_IN'),\n toSignUp: sendToMachine('SIGN_UP'),\n skipVerification: sendToMachine('SKIP'),\n };\n};\nconst getNextSendEventAliases = (send) => {\n const { toFederatedSignIn, submitForm, resendCode, skipVerification } = getSendEventAliases(send);\n return {\n handleSubmit: submitForm,\n resendConfirmationCode: resendCode,\n // manual \"route\" navigation\n setRoute: (route) => send({ type: NAVIGABLE_ROUTE_EVENT[route] }),\n skipAttributeVerification: skipVerification,\n toFederatedSignIn,\n };\n};\nconst getServiceContextFacade = (state) => {\n const actorContext = (getActorContext(state) ?? {});\n const { challengeName, codeDeliveryDetails, remoteError: error, validationError: validationErrors, totpSecretCode = null, unverifiedUserAttributes, username, } = actorContext;\n const { socialProviders = [] } = state.context?.config ?? {};\n // check for user in actorContext prior to state context. actorContext is more \"up to date\",\n // but is not available on all states\n const user = actorContext?.user ?? state.context?.user;\n const hasValidationErrors = !!(validationErrors && Object.keys(validationErrors).length > 0);\n const actorState = getActorState(state);\n const isPending = state.hasTag('pending') || actorState?.hasTag('pending');\n const route = getRoute(state, actorState);\n // Auth status represents the current state of the auth flow\n // The `configuring` state is used to indicate when the xState machine is loading\n const authStatus = ((route) => {\n switch (route) {\n case 'idle':\n case 'setup':\n return 'configuring';\n case 'authenticated':\n return 'authenticated';\n default:\n return 'unauthenticated';\n }\n })(route);\n const facade = {\n authStatus,\n challengeName,\n codeDeliveryDetails,\n error,\n hasValidationErrors,\n isPending,\n route,\n socialProviders,\n totpSecretCode,\n unverifiedUserAttributes,\n user,\n username,\n validationErrors,\n // @v6-migration-note\n // While most of the properties\n // on `AuthenticatorServiceContextFacade` can resolve to `undefined`, updating\n // the interface requires material changes in consumers (namely `useAuthenticator`)\n // which will have implications on the UI layer as typeguards and non-null checks\n // are required to pass type checking. As the `Authenticator` is behaving as expected\n // with the `AuthenticatorServiceContextFacade` interface, prefer to cast\n };\n return facade;\n};\nconst getNextServiceContextFacade = (state) => {\n const actorContext = (getActorContext(state) ?? {});\n const { challengeName, codeDeliveryDetails, remoteError: errorMessage, totpSecretCode, unverifiedUserAttributes, username, } = actorContext;\n const { socialProviders: federatedProviders, loginMechanisms } = state.context?.config ?? {};\n const loginMechanism = loginMechanisms?.[0];\n const actorState = getActorState(state);\n const isPending = state.hasTag('pending') || actorState?.hasTag('pending');\n // @todo-migration remove this cast for Authenticator.Next\n const route = getRoute(state, actorState);\n return {\n challengeName,\n codeDeliveryDetails,\n errorMessage,\n federatedProviders,\n isPending,\n loginMechanism,\n route,\n totpSecretCode,\n unverifiedUserAttributes,\n username,\n };\n};\nconst getServiceFacade = ({ send, state, }) => {\n const sendEventAliases = getSendEventAliases(send);\n const serviceContext = getServiceContextFacade(state);\n return {\n ...sendEventAliases,\n ...serviceContext,\n };\n};\nconst getNextServiceFacade = ({ send, state, }) => ({\n ...getNextSendEventAliases(send),\n ...getNextServiceContextFacade(state),\n});\n\nexport { getNextServiceContextFacade, getNextServiceFacade, getSendEventAliases, getServiceContextFacade, getServiceFacade };\n","/** Federated IDPs that Authenticator supports */\nvar FederatedIdentityProviders;\n(function (FederatedIdentityProviders) {\n FederatedIdentityProviders[\"Apple\"] = \"Apple\";\n FederatedIdentityProviders[\"Amazon\"] = \"Amazon\";\n FederatedIdentityProviders[\"Facebook\"] = \"Facebook\";\n FederatedIdentityProviders[\"Google\"] = \"Google\";\n})(FederatedIdentityProviders || (FederatedIdentityProviders = {}));\n/**\n * Cognito user contact method types that have not been verified as valid\n */\nvar UnverifiedContactMethodType;\n(function (UnverifiedContactMethodType) {\n UnverifiedContactMethodType[\"Email\"] = \"email\";\n UnverifiedContactMethodType[\"PhoneNumber\"] = \"phone_number\";\n})(UnverifiedContactMethodType || (UnverifiedContactMethodType = {}));\n\nexport { FederatedIdentityProviders, UnverifiedContactMethodType };\n","/** Array of auth fields that we supply defaults with */\nconst signUpFieldsWithDefault = [\n 'birthdate',\n 'email',\n 'family_name',\n 'given_name',\n 'middle_name',\n 'name',\n 'nickname',\n 'phone_number',\n 'preferred_username',\n 'profile',\n 'website',\n];\n/** Array of auth fields that we do not supply defaults with */\nconst signUpFieldsWithoutDefault = [\n 'address',\n 'gender',\n 'locale',\n 'picture',\n 'updated_at',\n 'zoneinfo',\n];\n/** Array of known login mechanisms */\nconst LoginMechanismArray = [\n 'username',\n 'email',\n 'phone_number',\n];\nconst authFieldsWithDefaults = [\n ...LoginMechanismArray,\n ...signUpFieldsWithDefault,\n 'confirmation_code',\n 'password',\n 'confirm_password',\n];\nconst isAuthFieldsWithDefaults = (field) => {\n return authFieldsWithDefaults.includes(field);\n};\n\nexport { LoginMechanismArray, authFieldsWithDefaults, isAuthFieldsWithDefaults, signUpFieldsWithDefault, signUpFieldsWithoutDefault };\n","import '../../types/authenticator/user.mjs';\nimport { authFieldsWithDefaults } from '../../types/authenticator/attributes.mjs';\n\nconst getFormDataFromEvent = (event) => {\n const formData = new FormData(event.target);\n return Object.fromEntries(formData);\n};\nconst setFormOrder = (formOverrides, fieldNames) => {\n let orderedKeys = [];\n if (formOverrides) {\n orderedKeys = Object.keys(formOverrides)\n .reduce((prev, key) => {\n // reduce to array that can be sorted\n prev.push([key, formOverrides[key]?.order]);\n return prev;\n }, [])\n .sort((a, b) => \n //sort them based on order\n a[1] - b[1]) // returned just key\n .filter((a) => a[1] !== undefined)\n .map((a) => a[0]);\n }\n // remove duplicates\n return Array.from(new Set([...orderedKeys, ...fieldNames]));\n};\nconst isAuthFieldWithDefaults = (field) => {\n return authFieldsWithDefaults.includes(field);\n};\nconst isArray = (val) => {\n return Array.isArray(val);\n};\nconst getErrors = (errors) => {\n if (!errors)\n return null;\n if (isArray(errors)) {\n return errors;\n }\n else {\n return [errors];\n }\n};\n\nexport { getErrors, getFormDataFromEvent, isAuthFieldWithDefaults, setFormOrder };\n","import { ALLOWED_SPECIAL_CHARACTERS, emailRegex } from './constants.mjs';\n\n// replaces all characters in a string with '*', except for the first and last char\nconst censorAllButFirstAndLast = (value) => {\n const split = value.trim().split('');\n for (let i = 0; i < split.length; i++) {\n if (i > 0 && i < split.length - 1) {\n split[i] = '*';\n }\n }\n return split.join('');\n};\n// censors all but the last four characters of a phone number\nconst censorPhoneNumber = (val) => {\n if (val.length < 4) {\n return val;\n }\n const split = val.split('');\n for (let i = 0; i < split.length - 4; i++) {\n split[i] = '*';\n }\n return split.join('');\n};\n// censors all but the first and last of the name of an email and keeps domain\nconst censorEmail = (val) => {\n const splitEmail = val.split('@');\n const censoredName = censorAllButFirstAndLast(splitEmail[0]);\n return `${censoredName}@${splitEmail[1]}`;\n};\n// based on the ContactMethod type, returns a censored contact value\nconst censorContactMethod = (type, value) => {\n return type === 'Phone Number'\n ? censorPhoneNumber(value)\n : censorEmail(value);\n};\nconst hasSpecialChars = (password) => ALLOWED_SPECIAL_CHARACTERS.some((char) => password.includes(char));\nconst getTotpCodeURL = (issuer, username, secret) => encodeURI(`otpauth://totp/${issuer}:${username}?secret=${secret}&issuer=${issuer}`);\nfunction trimValues(values, ...ignored) {\n return Object.entries(values).reduce((acc, [name, value]) => ({\n ...acc,\n [name]: ignored.includes(name) ? value : value?.trim(),\n }), {});\n}\nconst isValidEmail = (value) => {\n if (!value)\n return false;\n return emailRegex.test(value);\n};\n\nexport { censorAllButFirstAndLast, censorContactMethod, censorEmail, censorPhoneNumber, getTotpCodeURL, hasSpecialChars, isValidEmail, trimValues };\n","const defaultTexts = {\n ADD_PROFILE: 'Add your Profile',\n ADD_WEBSITE: 'Add your Website',\n BACK_SIGN_IN: 'Back to Sign In',\n BIRTHDATE: 'Birthdate',\n CHANGE_PASSWORD: 'Change Password',\n CHANGING_PASSWORD: 'Changing',\n CODE: 'Code',\n CODE_ARRIVAL: 'It may take a minute to arrive',\n CODE_EMAILED: 'Your code is on the way. To log in, enter the code we emailed to',\n CODE_SENT: 'Your code is on the way. To log in, enter the code we sent you',\n CODE_TEXTED: 'Your code is on the way. To log in, enter the code we texted to',\n CONFIRM_PASSWORD: 'Confirm Password',\n CONFIRM_PASSWORD_PLACEHOLDER: 'Please confirm your Password',\n CONFIRM_RESET_PASSWORD_HEADING: 'Reset your Password',\n CONFIRM_SIGNUP_HEADING: 'Confirm Sign Up',\n CONFIRM_SMS: 'Confirm SMS Code',\n // If challenge name is not returned\n CONFIRM_MFA_DEFAULT: 'Confirm MFA Code',\n CONFIRM_TOTP: 'Confirm TOTP Code',\n CONFIRM: 'Confirm',\n CONFIRMATION_CODE: 'Confirmation Code',\n CONFIRMING: 'Confirming',\n CREATE_ACCOUNT: 'Create Account',\n CREATING_ACCOUNT: 'Creating Account',\n EMAIL_ADDRESS: 'Email',\n ENTER_BIRTHDATE: 'Enter your Birthdate',\n ENTER_CODE: 'Enter your code',\n ENTER_CONFIRMATION_CODE: 'Enter your Confirmation Code',\n ENTER_EMAIL: 'Enter your Email',\n ENTER_FAMILY_NAME: 'Enter your Family Name',\n ENTER_GIVEN_NAME: 'Enter your Given Name',\n ENTER_MIDDLE_NAME: 'Enter your Middle Name',\n ENTER_NAME: 'Enter your Name',\n ENTER_NICK_NAME: 'Enter your Nickname',\n ENTER_PASSWORD: 'Enter your Password',\n ENTER_PHONE_NUMBER: 'Enter your Phone Number',\n ENTER_PREFERRED_USERNAME: 'Enter your Preferred Username',\n ENTER_USERNAME: 'Enter your username',\n FAMILY_NAME: 'Family Name',\n GIVEN_NAME: 'Given Name',\n FORGOT_PASSWORD: 'Forgot Password?',\n FORGOT_YOUR_PASSWORD: 'Forgot your password?',\n HIDE_PASSWORD: 'Hide password',\n LOADING: 'Loading',\n LOGIN_NAME: 'Username',\n MIDDLE_NAME: 'Middle Name',\n NAME: 'Name',\n NICKNAME: 'Nickname',\n NEW_PASSWORD: 'New password',\n OR: 'or',\n PASSWORD: 'Password',\n PHONE_NUMBER: 'Phone Number',\n PREFERRED_USERNAME: 'Preferred Username',\n PROFILE: 'Profile',\n RESEND_CODE: 'Resend Code',\n RESET_PASSWORD_HEADING: 'Reset your password',\n RESET_PASSWORD: 'Reset Password',\n SEND_CODE: 'Send code',\n SENDING: 'Sending',\n SETUP_TOTP: 'Setup TOTP',\n SHOW_PASSWORD: 'Show password',\n SIGN_IN_BUTTON: 'Sign in',\n SIGN_IN_TAB: 'Sign In',\n SIGN_IN_WITH_AMAZON: 'Sign In with Amazon',\n SIGN_IN_WITH_APPLE: 'Sign In with Apple',\n SIGN_IN_WITH_FACEBOOK: 'Sign In with Facebook',\n SIGN_IN_WITH_GOOGLE: 'Sign In with Google',\n SIGN_IN: 'Sign in to your account',\n SIGN_UP_BUTTON: 'Create a new account',\n SIGNING_IN_BUTTON: 'Signing in',\n SKIP: 'Skip',\n SUBMIT: 'Submit',\n SUBMITTING: 'Submitting',\n UPPERCASE_COPY: 'COPY',\n VERIFY_CONTACT: 'Verify Contact',\n VERIFY_HEADING: 'Account recovery requires verified contact information',\n VERIFY: 'Verify',\n WE_EMAILED: 'We Emailed You',\n WE_SENT_CODE: 'We Sent A Code',\n WE_TEXTED: 'We Texted You',\n WEBSITE: 'Website',\n};\n\nexport { defaultTexts };\n","import { deDict as deDict$1 } from './authenticator/de.mjs';\nimport { enDict as enDict$1 } from './authenticator/en.mjs';\nimport { esDict as esDict$1 } from './authenticator/es.mjs';\nimport { frDict as frDict$1 } from './authenticator/fr.mjs';\nimport { itDict as itDict$1 } from './authenticator/it.mjs';\nimport { jaDict as jaDict$1 } from './authenticator/ja.mjs';\nimport { krDict as krDict$1 } from './authenticator/kr.mjs';\nimport { nbDict as nbDict$1 } from './authenticator/nb.mjs';\nimport { nlDict as nlDict$1 } from './authenticator/nl.mjs';\nimport { plDict as plDict$1 } from './authenticator/pl.mjs';\nimport { ptDict as ptDict$1 } from './authenticator/pt.mjs';\nimport { zhDict as zhDict$1 } from './authenticator/zh.mjs';\nimport { svDict as svDict$1 } from './authenticator/sv.mjs';\nimport { idDict as idDict$1 } from './authenticator/id.mjs';\nimport { trDict as trDict$1 } from './authenticator/tr.mjs';\nimport { ruDict as ruDict$1 } from './authenticator/ru.mjs';\nimport { heDict as heDict$1 } from './authenticator/he.mjs';\nimport { uaDict as uaDict$1 } from './authenticator/ua.mjs';\nimport { thDict as thDict$1 } from './authenticator/th.mjs';\nimport { defaultTexts as defaultTexts$1 } from './authenticator/defaultTexts.mjs';\n\n//merge all the new module translations in respective locale constants\nconst deDict = { ...deDict$1 };\nconst enDict = {\n ...enDict$1,\n};\nconst esDict = { ...esDict$1 };\nconst frDict = { ...frDict$1 };\nconst itDict = { ...itDict$1 };\nconst jaDict = { ...jaDict$1 };\nconst krDict = { ...krDict$1 };\nconst nbDict = { ...nbDict$1 };\nconst nlDict = { ...nlDict$1 };\nconst plDict = { ...plDict$1 };\nconst ptDict = { ...ptDict$1 };\nconst zhDict = { ...zhDict$1 };\nconst svDict = { ...svDict$1 };\nconst idDict = { ...idDict$1 };\nconst trDict = { ...trDict$1 };\nconst ruDict = { ...ruDict$1 };\nconst heDict = { ...heDict$1 };\nconst uaDict = { ...uaDict$1 };\nconst thDict = { ...thDict$1 };\nconst defaultTexts = {\n ...defaultTexts$1,\n // new module related default texts goes here\n};\n\nexport { deDict, defaultTexts, enDict, esDict, frDict, heDict, idDict, itDict, jaDict, krDict, nbDict, nlDict, plDict, ptDict, ruDict, svDict, thDict, trDict, uaDict, zhDict };\n","import { I18n } from 'aws-amplify/utils';\nimport { defaultTexts, deDict, enDict, esDict, frDict, idDict, itDict, jaDict, krDict, nbDict, nlDict, plDict, ptDict, zhDict, svDict, trDict, ruDict, heDict, uaDict, thDict } from './dictionaries/index.mjs';\n\n/*\n * Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with\n * the License. A copy of the License is located at\n *\n * http://aws.amazon.com/apache2.0/\n *\n * or in the \"license\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions\n * and limitations under the License.\n */\n/**\n * Contains translatable strings that authenticator provides by default. Customers\n * can use this to add custom vocabularies:\n *\n * ```\n * I18n.putVocabulariesForLanguage(\"en\", {\n * [DefaultTexts.SIGN_IN]: \"Custom Sign In Text\",\n * [DefaultTexts.SIGN_IN_BUTTON]: \"Custom Click Here to Sign In\"\n * });\n * ```\n */\nconst DefaultTexts = { ...defaultTexts };\n/**\n * This helper type checks that given phrase is one of the texts @aws-amplify/ui\n * provides by default. This enables vscode autocompletion to help catch typos\n * during development.\n *\n * You can also use translate to handle custom strings or dynamic content.\n */\nfunction translate(phrase) {\n return I18n.get(phrase);\n}\n/**\n * Whether I18n has a translation entry for given phrase\n */\nfunction hasTranslation(phrase) {\n return I18n.get(phrase) !== phrase;\n}\nconst translations = {\n de: deDict,\n en: enDict,\n es: esDict,\n fr: frDict,\n id: idDict,\n it: itDict,\n ja: jaDict,\n // TODO: remove kr in next major release\n kr: krDict,\n ko: krDict,\n nb: nbDict,\n nl: nlDict,\n pl: plDict,\n pt: ptDict,\n zh: zhDict,\n sv: svDict,\n tr: trDict,\n ru: ruDict,\n he: heDict,\n ua: uaDict,\n th: thDict,\n};\n\nexport { DefaultTexts, hasTranslation, translate, translations };\n","import { translate } from '../../../i18n/translations.mjs';\n\nconst getPrimaryAlias = (state) => {\n const loginMechanisms = state?.context.config?.loginMechanisms;\n /**\n * @migration this is where we grab only the first index of `aws_cognito_username_attributes`\n */\n const [primaryAlias] = loginMechanisms ?? ['username'];\n return primaryAlias;\n};\n/** Applies translations to label and placeholder */\nconst applyTranslation = (formFields) => {\n const newFormFields = { ...formFields };\n for (const [name, options] of Object.entries(formFields)) {\n const { label, placeholder } = options;\n newFormFields[name] = {\n ...options,\n label: label ? translate(label) : undefined,\n placeholder: placeholder ? translate(placeholder) : undefined,\n };\n }\n return newFormFields;\n};\n/** Sorts formFields according to their `order`. */\nconst sortFormFields = (formFields) => {\n return Object.entries(formFields)\n .sort((a, b) => {\n const orderA = a[1].order || Number.MAX_VALUE;\n const orderB = b[1].order || Number.MAX_VALUE;\n return orderA - orderB;\n })\n .filter((formFieldEntry) => formFieldEntry[1] !== undefined);\n};\n\nexport { applyTranslation, getPrimaryAlias, sortFormFields };\n","import { getActorState } from '../actor.mjs';\nimport { defaultFormFieldOptions } from '../constants.mjs';\nimport { isAuthFieldWithDefaults } from '../form.mjs';\nimport { getPrimaryAlias } from './utils.mjs';\n\n/**\n * This file contains helpers that generate default formFields for each screen\n */\nconst DEFAULT_COUNTRY_CODE = '+1';\n/** Helper function that gets the default formField for given field name */\nconst getDefaultFormField = (fieldName) => {\n let options = defaultFormFieldOptions[fieldName];\n const { type } = options;\n if (type === 'tel') {\n options = { ...options, dialCode: DEFAULT_COUNTRY_CODE };\n }\n return options;\n};\n// Helper function that returns default form field for configured primary alias\nconst getAliasDefaultFormField = (state) => {\n const primaryAlias = getPrimaryAlias(state);\n return {\n ...getDefaultFormField(primaryAlias),\n autocomplete: 'username',\n };\n};\n/** Reusable confirmation code form fields. */\nconst getConfirmationCodeFormFields = (_) => ({\n confirmation_code: {\n ...getDefaultFormField('confirmation_code'),\n label: 'Code *',\n placeholder: 'Code',\n },\n});\nconst getSignInFormFields = (state) => ({\n username: { ...getAliasDefaultFormField(state) },\n password: {\n ...getDefaultFormField('password'),\n autocomplete: 'current-password',\n },\n});\nconst getSignUpFormFields = (state) => {\n const { loginMechanisms, signUpAttributes } = state.context.config;\n const primaryAlias = getPrimaryAlias(state);\n /**\n * @migration signUp Fields created here\n */\n const fieldNames = Array.from(new Set([\n ...loginMechanisms,\n 'password',\n 'confirm_password',\n ...signUpAttributes,\n ]));\n const formField = {};\n for (const fieldName of fieldNames) {\n if (isAuthFieldWithDefaults(fieldName)) {\n const fieldAttrs = fieldName === primaryAlias\n ? getAliasDefaultFormField(state)\n : getDefaultFormField(fieldName);\n formField[fieldName] = { ...fieldAttrs };\n }\n else {\n // There's a `custom:*` attribute or one we don't already have an implementation for\n // eslint-disable-next-line no-console\n console.debug(`Authenticator does not have a default implementation for ${fieldName}. Customize SignUp FormFields to add your own.`);\n }\n }\n return formField;\n};\nconst getConfirmSignUpFormFields = (_) => ({\n confirmation_code: {\n ...getDefaultFormField('confirmation_code'),\n placeholder: 'Enter your code',\n },\n});\nconst getForgotPasswordFormFields = (state) => {\n const primaryAlias = getPrimaryAlias(state);\n const { label } = defaultFormFieldOptions[primaryAlias];\n return {\n username: {\n ...getAliasDefaultFormField(state),\n label: `Enter your ${label.toLowerCase()}`,\n placeholder: `Enter your ${label.toLowerCase()}`,\n },\n };\n};\nconst getConfirmResetPasswordFormFields = (state) => ({\n ...getConfirmationCodeFormFields(),\n password: {\n ...getDefaultFormField('password'),\n label: 'New Password',\n placeholder: 'New Password',\n },\n confirm_password: {\n ...getDefaultFormField('confirm_password'),\n label: 'Confirm Password',\n placeholder: 'Confirm Password',\n },\n});\nconst getForceNewPasswordFormFields = (state) => {\n const actorState = getActorState(state);\n const { missingAttributes } = actorState.context;\n const fieldNames = Array.from(new Set([\n 'password',\n 'confirm_password',\n ...(missingAttributes ?? []),\n ]));\n const formField = {};\n for (const fieldName of fieldNames) {\n if (isAuthFieldWithDefaults(fieldName)) {\n formField[fieldName] = { ...getDefaultFormField(fieldName) };\n }\n else {\n // There's a `custom:*` attribute or one we don't already have an implementation for\n // eslint-disable-next-line no-console\n console.debug(`Authenticator does not have a default implementation for ${fieldName}. Customize ForceNewPassword FormFields to add your own.`);\n }\n }\n return formField;\n};\n/** Collect all the defaultFormFields getters */\nconst defaultFormFieldsGetters = {\n signIn: getSignInFormFields,\n signUp: getSignUpFormFields,\n confirmSignUp: getConfirmSignUpFormFields,\n confirmSignIn: getConfirmationCodeFormFields,\n forceNewPassword: getForceNewPasswordFormFields,\n forgotPassword: getForgotPasswordFormFields,\n confirmResetPassword: getConfirmResetPasswordFormFields,\n confirmVerifyUser: getConfirmationCodeFormFields,\n setupTotp: getConfirmationCodeFormFields,\n};\n\nexport { DEFAULT_COUNTRY_CODE, defaultFormFieldsGetters, getAliasDefaultFormField };\n","import '../../../types/authenticator/user.mjs';\nimport { isAuthFieldsWithDefaults } from '../../../types/authenticator/attributes.mjs';\nimport { getActorContext } from '../actor.mjs';\nimport { defaultFormFieldOptions } from '../constants.mjs';\nimport { defaultFormFieldsGetters, getAliasDefaultFormField } from './defaults.mjs';\nimport { applyTranslation, sortFormFields } from './utils.mjs';\n\n// Gets the default formFields for given route\nconst getDefaultFormFields = (route, state) => {\n const formFieldGetter = defaultFormFieldsGetters[route];\n return formFieldGetter(state);\n};\n// Gets custom formFields, and applies default values\nconst getCustomFormFields = (route, state) => {\n const customFormFields = getActorContext(state)?.formFields?.[route];\n if (!customFormFields || Object.keys(customFormFields).length === 0) {\n return {};\n }\n return Object.entries(customFormFields).reduce((acc, [fieldName, customOptions]) => {\n if ((route === 'signIn' || route === 'forgotPassword') &&\n fieldName === 'username') {\n // Unlike other screens, `signIn` and `forgotPassword` screens default login\n // alias field names to \"username\", even if it's a phone number or email.\n // In this case, we get the default formFieldOptions based on loginMechanism.\n const defaultOptions = getAliasDefaultFormField(state);\n // apply default to fill any gaps that are not present in customOptions\n const mergedOptions = { ...defaultOptions, ...customOptions };\n return { ...acc, [fieldName]: mergedOptions };\n }\n else if (isAuthFieldsWithDefaults(fieldName)) {\n // if this field is a known auth attribute that we have defaults for,\n // apply defaults to customOptions.\n const defaultOptions = defaultFormFieldOptions[fieldName];\n const mergedOptions = { ...defaultOptions, ...customOptions };\n return { ...acc, [fieldName]: mergedOptions };\n }\n else {\n // if this is not a known field, use customOptions as is.\n return { ...acc, [fieldName]: customOptions };\n }\n }, {});\n};\nconst getFormFields = (route, state) => {\n const defaultFormFields = getDefaultFormFields(route, state);\n const customFormFields = getCustomFormFields(route, state);\n const formFields = { ...defaultFormFields, ...customFormFields };\n delete formFields['QR'];\n return applyTranslation(formFields);\n};\nconst removeOrderKeys = (formFields) => formFields.map((field) => {\n const key = field[0];\n // Drop order key to prevent passing to form field UI components\n const values = { ...field[1], order: undefined };\n return [key, values];\n});\n/** Calls `getFormFields` above, then sorts it into an indexed array */\nconst getSortedFormFields = (route, state) => {\n const formFields = getFormFields(route, state);\n return removeOrderKeys(sortFormFields(formFields));\n};\n\nexport { getCustomFormFields, getDefaultFormFields, getFormFields, getSortedFormFields, removeOrderKeys };\n","import { translate, DefaultTexts } from '../../i18n/translations.mjs';\n\n/**\n * ConfirmSignIn\n */\nconst getChallengeText = (challengeName) => {\n switch (challengeName) {\n case 'SMS_MFA':\n return translate(DefaultTexts.CONFIRM_SMS);\n case 'SOFTWARE_TOKEN_MFA':\n return translate(DefaultTexts.CONFIRM_TOTP);\n default:\n return translate(DefaultTexts.CONFIRM_MFA_DEFAULT);\n }\n};\n/**\n * ConfirmSignUp\n */\nconst getDeliveryMessageText = (codeDeliveryDetails) => {\n const { DeliveryMedium, Destination } = codeDeliveryDetails ?? {};\n const isEmailMessage = DeliveryMedium === 'EMAIL';\n const isTextMessage = DeliveryMedium === 'SMS';\n const arrivalMessage = translate(DefaultTexts.CODE_ARRIVAL);\n if (!(isEmailMessage || isTextMessage)) {\n return `${translate(DefaultTexts.CODE_SENT)}. ${arrivalMessage}.`;\n }\n const instructionMessage = isEmailMessage\n ? translate(DefaultTexts.CODE_EMAILED)\n : translate(DefaultTexts.CODE_TEXTED);\n return `${instructionMessage} ${Destination}. ${arrivalMessage}.`;\n};\nconst getDeliveryMethodText = (codeDeliveryDetails) => {\n const { DeliveryMedium } = codeDeliveryDetails ?? {};\n const isEmailMessage = DeliveryMedium === 'EMAIL';\n const isTextMessage = DeliveryMedium === 'SMS';\n if (!isEmailMessage && isTextMessage) {\n return translate(DefaultTexts.WE_SENT_CODE);\n }\n return isEmailMessage\n ? translate(DefaultTexts.WE_EMAILED)\n : translate(DefaultTexts.WE_TEXTED);\n};\n/**\n * FederatedSignIn\n */\nconst providerNameMap = {\n amazon: 'Amazon',\n apple: 'Apple',\n facebook: 'Facebook',\n google: 'Google',\n};\nconst getSignInWithFederationText = (route, provider) => {\n const isSignIn = route === 'signIn';\n return translate(`Sign ${isSignIn ? 'In' : 'Up'} with ${providerNameMap[provider]}`);\n};\nconst authenticatorTextUtil = {\n /** Shared */\n getBackToSignInText: () => translate(DefaultTexts.BACK_SIGN_IN),\n getChangePasswordText: () => translate(DefaultTexts.CHANGE_PASSWORD),\n getChangingText: () => translate(DefaultTexts.CHANGING_PASSWORD),\n getConfirmText: () => translate(DefaultTexts.CONFIRM),\n getConfirmingText: () => translate(DefaultTexts.CONFIRMING),\n getCopyText: () => translate(DefaultTexts.UPPERCASE_COPY),\n getHidePasswordText: () => translate(DefaultTexts.HIDE_PASSWORD),\n getLoadingText: () => translate(DefaultTexts.LOADING),\n getOrText: () => translate(DefaultTexts.OR),\n getResendCodeText: () => translate(DefaultTexts.RESEND_CODE),\n getSendCodeText: () => translate(DefaultTexts.SEND_CODE),\n getSendingText: () => translate(DefaultTexts.SENDING),\n getShowPasswordText: () => translate(DefaultTexts.SHOW_PASSWORD),\n getSubmitText: () => translate(DefaultTexts.SUBMIT),\n getSubmittingText: () => translate(DefaultTexts.SUBMITTING),\n /** SignInSignUpTabs */\n getSignInTabText: () => translate(DefaultTexts.SIGN_IN_TAB),\n getSignUpTabText: () => translate(DefaultTexts.CREATE_ACCOUNT),\n /** SignIn */\n getForgotPasswordText: (shortVersion) => translate(shortVersion\n ? DefaultTexts.FORGOT_PASSWORD\n : DefaultTexts.FORGOT_YOUR_PASSWORD),\n getSigningInText: () => translate(DefaultTexts.SIGNING_IN_BUTTON),\n getSignInText: () => translate(DefaultTexts.SIGN_IN_BUTTON),\n /** SignUp */\n getCreatingAccountText: () => translate(DefaultTexts.CREATING_ACCOUNT),\n getCreateAccountText: () => translate(DefaultTexts.CREATE_ACCOUNT),\n /** ConfirmSignUp */\n getDeliveryMessageText,\n getDeliveryMethodText,\n /** ConfirmSignIn */\n getChallengeText,\n /** ForgotPassword */\n getResetYourPasswordText: () => translate(DefaultTexts.RESET_PASSWORD),\n /** SetupTotp */\n getSetupTotpText: () => translate(DefaultTexts.SETUP_TOTP),\n // TODO: add defaultText for below\n getSetupTotpInstructionsText: () => translate('Copy and paste the secret key below into an authenticator app and then enter the code in the text field below.'),\n // TODO: add defaultText for \"COPIED\"\n getCopiedText: () => translate('COPIED'),\n /** FederatedSignIn */\n getSignInWithFederationText,\n /** VerifyUser */\n getSkipText: () => translate(DefaultTexts.SKIP),\n getVerifyText: () => translate(DefaultTexts.VERIFY),\n getVerifyContactText: () => translate(DefaultTexts.VERIFY_CONTACT),\n getAccountRecoveryInfoText: () => translate(DefaultTexts.VERIFY_HEADING),\n /** Validations */\n // TODO: add defaultText\n getInvalidEmailText: () => translate('Please enter a valid email'),\n // TODO: add defaultText\n getRequiredFieldText: () => translate('This field is required'),\n}; // using `as const` so that keys are strongly typed\n\nexport { authenticatorTextUtil };\n","/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nmodule.exports = arrayMap;\n","var Stack = require('./_Stack'),\n baseIsEqual = require('./_baseIsEqual');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\nfunction baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n}\n\nmodule.exports = baseIsMatch;\n","var isObject = require('./isObject');\n\n/**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\nfunction isStrictComparable(value) {\n return value === value && !isObject(value);\n}\n\nmodule.exports = isStrictComparable;\n","var isStrictComparable = require('./_isStrictComparable'),\n keys = require('./keys');\n\n/**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\nfunction getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n}\n\nmodule.exports = getMatchData;\n","/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nmodule.exports = matchesStrictComparable;\n","var baseIsMatch = require('./_baseIsMatch'),\n getMatchData = require('./_getMatchData'),\n matchesStrictComparable = require('./_matchesStrictComparable');\n\n/**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n}\n\nmodule.exports = baseMatches;\n","var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n","var isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used to match property names within property paths. */\nvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/;\n\n/**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\nfunction isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n}\n\nmodule.exports = isKey;\n","var MapCache = require('./_MapCache');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\nfunction memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n}\n\n// Expose `MapCache`.\nmemoize.Cache = MapCache;\n\nmodule.exports = memoize;\n","var memoize = require('./memoize');\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\n\n/**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\nfunction memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n}\n\nmodule.exports = memoizeCapped;\n","var memoizeCapped = require('./_memoizeCapped');\n\n/** Used to match property names within property paths. */\nvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n/** Used to match backslashes in property paths. */\nvar reEscapeChar = /\\\\(\\\\)?/g;\n\n/**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\nvar stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n});\n\nmodule.exports = stringToPath;\n","var Symbol = require('./_Symbol'),\n arrayMap = require('./_arrayMap'),\n isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = baseToString;\n","var baseToString = require('./_baseToString');\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nmodule.exports = toString;\n","var isArray = require('./isArray'),\n isKey = require('./_isKey'),\n stringToPath = require('./_stringToPath'),\n toString = require('./toString');\n\n/**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\nfunction castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nmodule.exports = castPath;\n","var isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = toKey;\n","var castPath = require('./_castPath'),\n toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\nfunction baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n}\n\nmodule.exports = baseGet;\n","var baseGet = require('./_baseGet');\n\n/**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\nfunction get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n}\n\nmodule.exports = get;\n","/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nmodule.exports = baseHasIn;\n","var castPath = require('./_castPath'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isIndex = require('./_isIndex'),\n isLength = require('./isLength'),\n toKey = require('./_toKey');\n\n/**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\nfunction hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n}\n\nmodule.exports = hasPath;\n","var baseHasIn = require('./_baseHasIn'),\n hasPath = require('./_hasPath');\n\n/**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\nfunction hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n}\n\nmodule.exports = hasIn;\n","var baseIsEqual = require('./_baseIsEqual'),\n get = require('./get'),\n hasIn = require('./hasIn'),\n isKey = require('./_isKey'),\n isStrictComparable = require('./_isStrictComparable'),\n matchesStrictComparable = require('./_matchesStrictComparable'),\n toKey = require('./_toKey');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n}\n\nmodule.exports = baseMatchesProperty;\n","/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nmodule.exports = identity;\n","/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nmodule.exports = baseProperty;\n","var baseGet = require('./_baseGet');\n\n/**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n}\n\nmodule.exports = basePropertyDeep;\n","var baseProperty = require('./_baseProperty'),\n basePropertyDeep = require('./_basePropertyDeep'),\n isKey = require('./_isKey'),\n toKey = require('./_toKey');\n\n/**\n * Creates a function that returns the value at `path` of a given object.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n * @example\n *\n * var objects = [\n * { 'a': { 'b': 2 } },\n * { 'a': { 'b': 1 } }\n * ];\n *\n * _.map(objects, _.property('a.b'));\n * // => [2, 1]\n *\n * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');\n * // => [1, 2]\n */\nfunction property(path) {\n return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);\n}\n\nmodule.exports = property;\n","var baseMatches = require('./_baseMatches'),\n baseMatchesProperty = require('./_baseMatchesProperty'),\n identity = require('./identity'),\n isArray = require('./isArray'),\n property = require('./property');\n\n/**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\nfunction baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n}\n\nmodule.exports = baseIteratee;\n","var getNative = require('./_getNative');\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nmodule.exports = defineProperty;\n","var defineProperty = require('./_defineProperty');\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nmodule.exports = baseAssignValue;\n","var baseAssignValue = require('./_baseAssignValue'),\n eq = require('./eq');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nmodule.exports = assignValue;\n","var assignValue = require('./_assignValue'),\n castPath = require('./_castPath'),\n isIndex = require('./_isIndex'),\n isObject = require('./isObject'),\n toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\nfunction baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n}\n\nmodule.exports = baseSet;\n","var baseGet = require('./_baseGet'),\n baseSet = require('./_baseSet'),\n castPath = require('./_castPath');\n\n/**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\nfunction basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n}\n\nmodule.exports = basePickBy;\n","var overArg = require('./_overArg');\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nmodule.exports = getPrototype;\n","var arrayPush = require('./_arrayPush'),\n getPrototype = require('./_getPrototype'),\n getSymbols = require('./_getSymbols'),\n stubArray = require('./stubArray');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n};\n\nmodule.exports = getSymbolsIn;\n","/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = nativeKeysIn;\n","var isObject = require('./isObject'),\n isPrototype = require('./_isPrototype'),\n nativeKeysIn = require('./_nativeKeysIn');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeysIn;\n","var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeysIn = require('./_baseKeysIn'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nmodule.exports = keysIn;\n","var baseGetAllKeys = require('./_baseGetAllKeys'),\n getSymbolsIn = require('./_getSymbolsIn'),\n keysIn = require('./keysIn');\n\n/**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n}\n\nmodule.exports = getAllKeysIn;\n","var arrayMap = require('./_arrayMap'),\n baseIteratee = require('./_baseIteratee'),\n basePickBy = require('./_basePickBy'),\n getAllKeysIn = require('./_getAllKeysIn');\n\n/**\n * Creates an object composed of the `object` properties `predicate` returns\n * truthy for. The predicate is invoked with two arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pickBy(object, _.isNumber);\n * // => { 'a': 1, 'c': 3 }\n */\nfunction pickBy(object, predicate) {\n if (object == null) {\n return {};\n }\n var props = arrayMap(getAllKeysIn(object), function(prop) {\n return [prop];\n });\n predicate = baseIteratee(predicate);\n return basePickBy(object, props, function(value, path) {\n return predicate(value, path[0]);\n });\n}\n\nmodule.exports = pickBy;\n","import pickBy from 'lodash/pickBy.js';\nimport '@aws-amplify/core/internals/utils';\nimport '../../utils/setUserAgent/constants.mjs';\nimport { isString } from '../../utils/utils.mjs';\n\n// default `autoSignIn` flag is `true`\nconst DEFAULT_AUTO_SIGN_IN = true;\nconst EMPTY_STRING = '';\nconst sanitizePhoneNumber = (dialCode, phoneNumber) => `${dialCode}${phoneNumber}`.replace(/[^A-Z0-9+]/gi, '');\nconst selectUserAttributes = (_, key) => {\n // Allowlist of Cognito User Pool Attributes (from OpenID Connect specification)\n // See: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-attributes.html\n switch (key) {\n case 'address':\n case 'birthdate':\n case 'email':\n case 'family_name':\n case 'gender':\n case 'given_name':\n case 'locale':\n case 'middle_name':\n case 'name':\n case 'nickname':\n case 'phone_number':\n case 'picture':\n case 'preferred_username':\n case 'profile':\n case 'updated_at':\n case 'website':\n case 'zoneinfo':\n return true;\n // Otherwise, it's a custom attribute\n default:\n return key.startsWith('custom:');\n }\n};\nconst getUserAttributes = (formValues) => {\n const { phone_number, ...userAttributes } = pickBy(formValues, selectUserAttributes);\n // only include `phone_number` attribute in `userAttributes` if it has a value\n if (isString(phone_number) && phone_number !== EMPTY_STRING) {\n const { country_code } = formValues;\n return {\n ...userAttributes,\n phone_number: sanitizePhoneNumber(country_code, phone_number),\n };\n }\n return userAttributes;\n};\nconst getSignUpInput = (username, formValues, loginMechanism) => {\n const { password, ...values } = formValues;\n const attributes = getUserAttributes(values);\n const options = {\n autoSignIn: DEFAULT_AUTO_SIGN_IN,\n userAttributes: {\n // use `username` value for `phone_number`\n ...(loginMechanism === 'phone_number'\n ? { ...attributes, phone_number: username }\n : attributes),\n },\n };\n return { username, password, options };\n};\nconst getUsernameSignUp = ({ formValues, loginMechanisms, }) => {\n const loginMechanism = loginMechanisms[0];\n if (loginMechanism === 'phone_number') {\n const { country_code, phone_number } = formValues;\n return sanitizePhoneNumber(country_code, phone_number);\n }\n return formValues[loginMechanism];\n};\n\nexport { getSignUpInput, getUserAttributes, getUsernameSignUp, sanitizePhoneNumber };\n","import { actions } from 'xstate';\nimport 'aws-amplify/utils';\nimport '@aws-amplify/core/internals/utils';\nimport '../../utils/setUserAgent/constants.mjs';\nimport '../../types/authenticator/user.mjs';\nimport '../../types/authenticator/attributes.mjs';\nimport { trimValues } from '../../helpers/authenticator/utils.mjs';\nimport '../../helpers/accountSettings/utils.mjs';\nimport 'aws-amplify';\nimport { sanitizePhoneNumber, getUsernameSignUp } from './utils.mjs';\n\nconst { assign } = actions;\nconst clearActorDoneData = assign({ actorDoneData: undefined });\nconst clearChallengeName = assign({ challengeName: undefined });\nconst clearMissingAttributes = assign({ missingAttributes: undefined });\nconst clearError = assign({ remoteError: undefined });\nconst clearFormValues = assign({ formValues: {} });\nconst clearTouched = assign({ touched: {} });\nconst clearUser = assign({ user: undefined });\nconst clearValidationError = assign({ validationError: {} });\n/**\n * \"set\" actions\n */\nconst setTotpSecretCode = assign({\n totpSecretCode: (_, { data }) => {\n const { sharedSecret } = (data.nextStep?.totpSetupDetails ??\n {});\n return sharedSecret;\n },\n});\nconst setSignInStep = assign({ step: 'SIGN_IN' });\nconst setShouldVerifyUserAttributeStep = assign({\n step: 'SHOULD_CONFIRM_USER_ATTRIBUTE',\n});\nconst setConfirmAttributeCompleteStep = assign({\n step: 'CONFIRM_ATTRIBUTE_COMPLETE',\n});\n// map v6 `signInStep` to v5 `challengeName`\nconst setChallengeName = assign({\n challengeName: (_, { data }) => {\n const { signInStep } = data.nextStep;\n return signInStep === 'CONFIRM_SIGN_IN_WITH_SMS_CODE'\n ? 'SMS_MFA'\n : signInStep === 'CONFIRM_SIGN_IN_WITH_TOTP_CODE'\n ? 'SOFTWARE_TOKEN_MFA'\n : undefined;\n },\n});\nconst setUsernameForgotPassword = assign({\n username: ({ formValues, loginMechanisms }) => {\n const loginMechanism = loginMechanisms[0];\n const { username, country_code } = formValues;\n if (loginMechanism === 'phone_number') {\n // forgot password `formValues` uses `username` for base phone number value\n // prefix `country_code` for full `username`\n return sanitizePhoneNumber(country_code, username);\n }\n // default username field for loginMechanism === 'email' is \"username\" for SignIn\n return username;\n },\n});\nconst setUsernameSignUp = assign({ username: getUsernameSignUp });\nconst setUsernameSignIn = assign({\n username: ({ formValues, loginMechanisms }) => {\n const loginMechanism = loginMechanisms[0];\n const { username, country_code } = formValues;\n if (loginMechanism === 'phone_number') {\n // sign in `formValues` uses `username` for base phone number value\n // prefix `country_code` for full `username`\n return sanitizePhoneNumber(country_code, username);\n }\n // return `email` and `username`\n return username;\n },\n});\nconst setNextSignInStep = assign({\n step: (_, { data }) => data.nextStep.signInStep === 'DONE'\n ? 'SIGN_IN_COMPLETE'\n : data.nextStep.signInStep,\n});\nconst setNextSignUpStep = assign({\n step: (_, { data }) => data.nextStep.signUpStep === 'DONE'\n ? 'SIGN_UP_COMPLETE'\n : data.nextStep.signUpStep,\n});\nconst setNextResetPasswordStep = assign({\n step: (_, { data }) => data.nextStep.resetPasswordStep === 'DONE'\n ? 'RESET_PASSWORD_COMPLETE'\n : data.nextStep.resetPasswordStep,\n});\nconst setMissingAttributes = assign({\n missingAttributes: (_, { data }) => data.nextStep?.missingAttributes,\n});\nconst setFieldErrors = assign({\n validationError: (_, { data }) => data,\n});\nconst setRemoteError = assign({\n remoteError: (_, { data }) => {\n if (data.name === 'NoUserPoolError') {\n return `Configuration error (see console) – please contact the administrator`;\n }\n return data?.message || data;\n },\n});\nconst setUser = assign({ user: (_, { data }) => data });\nconst resolveCodeDeliveryDetails = (details) => ({\n Destination: details.destination,\n DeliveryMedium: details.deliveryMedium,\n AttributeName: details.attributName,\n});\nconst setCodeDeliveryDetails = assign({\n codeDeliveryDetails: (_, { data }) => {\n if (data\n ?.nextStep?.codeDeliveryDetails) {\n return resolveCodeDeliveryDetails(data\n .nextStep.codeDeliveryDetails);\n }\n return resolveCodeDeliveryDetails(data);\n },\n});\nconst handleInput = assign({\n formValues: (context, { data }) => {\n const { name, value } = data;\n return { ...context['formValues'], [name]: value };\n },\n});\nconst handleSubmit = assign({\n formValues: (context, { data }) => \n // do not trim password\n trimValues({ ...context['formValues'], ...data }, 'password'),\n});\nconst handleBlur = assign({\n touched: (context, { data }) => ({\n ...context['touched'],\n [data.name]: true,\n }),\n});\nconst setUnverifiedUserAttributes = assign({\n unverifiedUserAttributes: (_, { data }) => {\n const { email, phone_number } = data;\n const unverifiedUserAttributes = {\n ...(email && { email }),\n ...(phone_number && { phone_number }),\n };\n return unverifiedUserAttributes;\n },\n});\nconst clearSelectedUserAttribute = assign({ selectedUserAttribute: undefined });\nconst setSelectedUserAttribute = assign({\n selectedUserAttribute: (context) => context.formValues?.unverifiedAttr,\n});\n// Maps to unexposed `ConfirmSignUpSignUpStep`\nconst setConfirmSignUpSignUpStep = assign({ step: 'CONFIRM_SIGN_UP' });\nconst ACTIONS = {\n clearActorDoneData,\n clearChallengeName,\n clearError,\n clearFormValues,\n clearMissingAttributes,\n clearSelectedUserAttribute,\n clearTouched,\n clearUser,\n clearValidationError,\n handleBlur,\n handleInput,\n handleSubmit,\n setChallengeName,\n setCodeDeliveryDetails,\n setFieldErrors,\n setMissingAttributes,\n setNextResetPasswordStep,\n setNextSignInStep,\n setNextSignUpStep,\n setRemoteError,\n setConfirmAttributeCompleteStep,\n setConfirmSignUpSignUpStep,\n setShouldVerifyUserAttributeStep,\n setSelectedUserAttribute,\n setSignInStep,\n setTotpSecretCode,\n setUser,\n setUnverifiedUserAttributes,\n setUsernameForgotPassword,\n setUsernameSignIn,\n setUsernameSignUp,\n};\n\nexport { ACTIONS as default };\n","const SIGN_IN_STEP_MFA_CONFIRMATION = [\n 'CONFIRM_SIGN_IN_WITH_SMS_CODE',\n 'CONFIRM_SIGN_IN_WITH_TOTP_CODE',\n];\n// response next step guards\nconst shouldConfirmSignInWithNewPassword = (_, { data }) => data?.nextStep.signInStep ===\n 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED';\nconst shouldResetPasswordFromSignIn = (_, { data }) => data?.nextStep?.signInStep === 'RESET_PASSWORD';\nconst shouldConfirmSignUpFromSignIn = (_, { data }) => data?.nextStep.signInStep === 'CONFIRM_SIGN_UP';\nconst shouldAutoSignIn = (_, { data }) => data?.nextStep.signUpStep === 'COMPLETE_AUTO_SIGN_IN';\nconst hasCompletedSignIn = (_, { data }) => data?.nextStep.signInStep === 'DONE';\nconst hasCompletedSignUp = (_, { data }) => data?.nextStep.signUpStep === 'DONE';\nconst hasCompletedResetPassword = (_, { data }) => data?.nextStep.resetPasswordStep === 'DONE';\n// actor done guards read `step` from actor exit event\nconst hasCompletedAttributeConfirmation = (_, { data }) => data?.step === 'CONFIRM_ATTRIBUTE_COMPLETE';\nconst isConfirmUserAttributeStep = (_, { data }) => data?.step === 'CONFIRM_ATTRIBUTE_WITH_CODE';\nconst isShouldConfirmUserAttributeStep = (_, { data }) => data?.step === 'SHOULD_CONFIRM_USER_ATTRIBUTE';\nconst isResetPasswordStep = (_, { data }) => data?.step === 'RESET_PASSWORD';\nconst isConfirmSignUpStep = (_, { data }) => data?.step === 'CONFIRM_SIGN_UP';\n// actor entry guards read `step` from actor context\nconst shouldConfirmSignIn = ({ step }) => SIGN_IN_STEP_MFA_CONFIRMATION.includes(step);\nconst shouldSetupTotp = ({ step }) => step === 'CONTINUE_SIGN_IN_WITH_TOTP_SETUP';\nconst shouldResetPassword = ({ step }) => step === 'RESET_PASSWORD';\nconst shouldConfirmResetPassword = ({ step }) => step === 'CONFIRM_RESET_PASSWORD_WITH_CODE';\nconst shouldConfirmSignUp = ({ step }) => step === 'CONFIRM_SIGN_UP';\n// miscellaneous guards\nconst shouldVerifyAttribute = (_, { data }) => {\n const { phone_number_verified, email_verified } = data;\n // email/phone_verified is returned as a string\n const emailNotVerified = email_verified === undefined || email_verified === 'false';\n const phoneNotVerified = phone_number_verified === undefined || phone_number_verified === 'false';\n // only request verification if both email and phone are not verified\n return emailNotVerified && phoneNotVerified;\n};\n/**\n * This guard covers an edge case that exists in the current state of the UI.\n * As of now, our ConfirmSignUp screen only supports showing an input for a\n * confirmation code. However, a Cognito UserPool can instead verify users\n * through a link that gets emailed to them. If a user verifies through the\n * link and then they click on the \"Resend Code\" button, they will get an error\n * saying that the user has already been confirmed. If we encounter that error,\n * we want to just funnel them through the rest of the flow. In the future, we will\n * want to update our UI to support both confirmation codes and links.\n *\n * https://github.com/aws-amplify/amplify-ui/issues/219\n */\nconst isUserAlreadyConfirmed = (_, { data }) => data.message === 'User is already confirmed.';\nconst GUARDS = {\n hasCompletedAttributeConfirmation,\n hasCompletedResetPassword,\n hasCompletedSignIn,\n hasCompletedSignUp,\n isConfirmSignUpStep,\n isConfirmUserAttributeStep,\n isResetPasswordStep,\n isShouldConfirmUserAttributeStep,\n isUserAlreadyConfirmed,\n shouldAutoSignIn,\n shouldConfirmResetPassword,\n shouldConfirmSignIn,\n shouldConfirmSignInWithNewPassword,\n shouldConfirmSignUp,\n shouldConfirmSignUpFromSignIn,\n shouldResetPassword,\n shouldResetPasswordFromSignIn,\n shouldSetupTotp,\n shouldVerifyAttribute,\n};\n\nexport { GUARDS as default };\n","var baseAssignValue = require('./_baseAssignValue'),\n eq = require('./eq');\n\n/**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nmodule.exports = assignMergeValue;\n","/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nmodule.exports = createBaseFor;\n","var createBaseFor = require('./_createBaseFor');\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nmodule.exports = baseFor;\n","var root = require('./_root');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nmodule.exports = cloneBuffer;\n","var Uint8Array = require('./_Uint8Array');\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nmodule.exports = cloneArrayBuffer;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer');\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nmodule.exports = cloneTypedArray;\n","/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nmodule.exports = copyArray;\n","var isObject = require('./isObject');\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nmodule.exports = baseCreate;\n","var baseCreate = require('./_baseCreate'),\n getPrototype = require('./_getPrototype'),\n isPrototype = require('./_isPrototype');\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nmodule.exports = initCloneObject;\n","var isArrayLike = require('./isArrayLike'),\n isObjectLike = require('./isObjectLike');\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nmodule.exports = isArrayLikeObject;\n","var baseGetTag = require('./_baseGetTag'),\n getPrototype = require('./_getPrototype'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nmodule.exports = isPlainObject;\n","/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nmodule.exports = safeGet;\n","var assignValue = require('./_assignValue'),\n baseAssignValue = require('./_baseAssignValue');\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nmodule.exports = copyObject;\n","var copyObject = require('./_copyObject'),\n keysIn = require('./keysIn');\n\n/**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\nfunction toPlainObject(value) {\n return copyObject(value, keysIn(value));\n}\n\nmodule.exports = toPlainObject;\n","var assignMergeValue = require('./_assignMergeValue'),\n cloneBuffer = require('./_cloneBuffer'),\n cloneTypedArray = require('./_cloneTypedArray'),\n copyArray = require('./_copyArray'),\n initCloneObject = require('./_initCloneObject'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isArrayLikeObject = require('./isArrayLikeObject'),\n isBuffer = require('./isBuffer'),\n isFunction = require('./isFunction'),\n isObject = require('./isObject'),\n isPlainObject = require('./isPlainObject'),\n isTypedArray = require('./isTypedArray'),\n safeGet = require('./_safeGet'),\n toPlainObject = require('./toPlainObject');\n\n/**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n}\n\nmodule.exports = baseMergeDeep;\n","var Stack = require('./_Stack'),\n assignMergeValue = require('./_assignMergeValue'),\n baseFor = require('./_baseFor'),\n baseMergeDeep = require('./_baseMergeDeep'),\n isObject = require('./isObject'),\n keysIn = require('./keysIn'),\n safeGet = require('./_safeGet');\n\n/**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n}\n\nmodule.exports = baseMerge;\n","/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nmodule.exports = apply;\n","var apply = require('./_apply');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nmodule.exports = overRest;\n","/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nmodule.exports = constant;\n","var constant = require('./constant'),\n defineProperty = require('./_defineProperty'),\n identity = require('./identity');\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n};\n\nmodule.exports = baseSetToString;\n","/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nmodule.exports = shortOut;\n","var baseSetToString = require('./_baseSetToString'),\n shortOut = require('./_shortOut');\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nmodule.exports = setToString;\n","var identity = require('./identity'),\n overRest = require('./_overRest'),\n setToString = require('./_setToString');\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nmodule.exports = baseRest;\n","var eq = require('./eq'),\n isArrayLike = require('./isArrayLike'),\n isIndex = require('./_isIndex'),\n isObject = require('./isObject');\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nmodule.exports = isIterateeCall;\n","var baseRest = require('./_baseRest'),\n isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\nfunction createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n}\n\nmodule.exports = createAssigner;\n","var baseMerge = require('./_baseMerge'),\n createAssigner = require('./_createAssigner');\n\n/**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\nvar merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n});\n\nmodule.exports = merge;\n","import merge from 'lodash/merge.js';\nimport '@aws-amplify/core/internals/utils';\nimport '../utils/setUserAgent/constants.mjs';\nimport { isEmpty } from '../utils/utils.mjs';\n\n// Runs all validators given. Resolves if there are no error. Rejects otherwise.\nconst runValidators = async (formData, touchData, passwordSettings, validators) => {\n const errors = await Promise.all(validators.map((validator) => validator(formData, touchData, passwordSettings)));\n const mergedError = merge({}, ...errors);\n if (isEmpty(mergedError)) {\n // no errors were found\n return Promise.resolve();\n }\n else {\n return Promise.reject(mergedError);\n }\n};\n\nexport { runValidators };\n","import { Amplify } from 'aws-amplify';\nimport { getCurrentUser, signIn, signUp, confirmSignIn, confirmSignUp, confirmResetPassword, resetPassword } from 'aws-amplify/auth';\nimport 'aws-amplify/utils';\nimport '@aws-amplify/core/internals/utils';\nimport '../../utils/setUserAgent/constants.mjs';\nimport '../../types/authenticator/user.mjs';\nimport '../../types/authenticator/attributes.mjs';\nimport { hasSpecialChars } from '../../helpers/authenticator/utils.mjs';\nimport '../../helpers/accountSettings/utils.mjs';\n\n// Cognito does not allow a password length less then 8 characters\nconst DEFAULT_COGNITO_PASSWORD_MIN_LENGTH = 8;\nconst isInvalidUserAtributes = (userAttributes) => Array.isArray(userAttributes);\nconst parseUserAttributes = (userAttributes) => {\n if (!userAttributes) {\n return undefined;\n }\n // `aws-amplify` versions <= 6.0.5 return an array of `userAttributes` rather than an object\n if (isInvalidUserAtributes(userAttributes)) {\n return Object.entries(userAttributes).map(([_, value]) => Object.keys(value)[0]);\n }\n return Object.keys(userAttributes);\n};\nconst defaultServices = {\n async getAmplifyConfig() {\n const result = Amplify.getConfig();\n const cliConfig = result.Auth?.Cognito;\n const { loginWith, userAttributes } = result.Auth?.Cognito ?? {};\n const parsedLoginMechanisms = loginWith\n ? Object.entries(loginWith)\n .filter(([key, _value]) => key !== 'oauth')\n .filter(([_key, value]) => !!value)\n .map((keyValueArray) => {\n return keyValueArray[0] === 'phone' // the key for phone_number is phone in getConfig but everywhere else we treat is as phone_number\n ? 'phone_number'\n : keyValueArray[0];\n })\n : undefined;\n const parsedSignupAttributes = parseUserAttributes(userAttributes);\n const parsedSocialProviders = loginWith?.oauth?.providers\n ? loginWith.oauth.providers?.map((provider) => provider.toString().toLowerCase())\n : undefined;\n return {\n ...cliConfig,\n loginMechanisms: parsedLoginMechanisms,\n signUpAttributes: parsedSignupAttributes,\n socialProviders: parsedSocialProviders,\n };\n },\n getCurrentUser,\n handleSignIn: signIn,\n handleSignUp: signUp,\n handleConfirmSignIn: confirmSignIn,\n handleConfirmSignUp: confirmSignUp,\n handleForgotPasswordSubmit: confirmResetPassword,\n handleForgotPassword: resetPassword,\n // Validation hooks for overriding\n async validateCustomSignUp(_, __) { },\n async validateFormPassword(formData, touchData, passwordSettings) {\n const { password } = formData;\n const { password: touched_password } = touchData;\n /**\n * If the password is not touched,\n * or if the password settings are not set, we don't need to validate it.\n */\n if (!touched_password || !passwordSettings)\n return null;\n const password_complexity = [];\n const policyMinLength = passwordSettings.minLength ?? DEFAULT_COGNITO_PASSWORD_MIN_LENGTH;\n if (password.length < policyMinLength) {\n password_complexity.push(`Password must have at least ${policyMinLength} characters`);\n }\n if (passwordSettings.requireLowercase && !/[a-z]/.test(password))\n password_complexity.push('Password must have lower case letters');\n if (passwordSettings.requireUppercase && !/[A-Z]/.test(password))\n password_complexity.push('Password must have upper case letters');\n if (passwordSettings.requireNumbers && !/[0-9]/.test(password))\n password_complexity.push('Password must have numbers');\n // https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-policies.html\n if (passwordSettings.requireSpecialCharacters && !hasSpecialChars(password))\n password_complexity.push('Password must have special characters');\n /**\n * Only return an error if there is at least one error.\n */\n return password_complexity.length !== 0\n ? { password: password_complexity }\n : null;\n },\n async validateConfirmPassword(formData, touchData) {\n const { password, confirm_password } = formData;\n const { confirm_password: touched_confirm_password, password: touched_password, } = touchData;\n if (!password && !confirm_password) {\n // these inputs are clean, don't complain yet\n return null;\n }\n else if ((password || confirm_password) &&\n password !== confirm_password &&\n ((touched_confirm_password && touched_password) ||\n (password?.length >= 6 && confirm_password?.length >= 6))) {\n // Only return an error if both fields have text entered,\n // the passwords do not match, and the fields have been\n // touched or the password and confirm password is longer then or equal to 6.\n return {\n confirm_password: 'Your passwords must match',\n };\n }\n },\n async validatePreferredUsername(_, __) { },\n};\n\nexport { defaultServices };\n","import { createMachine, sendUpdate } from 'xstate';\nimport { runValidators } from '../../../validators/index.mjs';\nimport ACTIONS from '../actions.mjs';\nimport GUARDS from '../guards.mjs';\nimport { defaultServices } from '../defaultServices.mjs';\n\nfunction forgotPasswordActor({ services, }) {\n return createMachine({\n id: 'forgotPasswordActor',\n initial: 'init',\n predictableActionArguments: true,\n states: {\n init: {\n always: [\n {\n cond: 'shouldResetPassword',\n target: 'confirmResetPassword',\n },\n {\n cond: 'shouldConfirmResetPassword',\n target: 'confirmResetPassword',\n },\n {\n target: 'forgotPassword',\n },\n ],\n },\n forgotPassword: {\n initial: 'edit',\n entry: 'sendUpdate',\n exit: ['clearError', 'clearTouched'],\n states: {\n edit: {\n entry: 'sendUpdate',\n on: {\n SUBMIT: { actions: 'handleSubmit', target: 'submit' },\n CHANGE: { actions: 'handleInput' },\n BLUR: { actions: 'handleBlur' },\n },\n },\n submit: {\n tags: 'pending',\n entry: ['sendUpdate', 'clearError', 'setUsernameForgotPassword'],\n invoke: {\n src: 'handleResetPassword',\n onDone: {\n actions: [\n 'setCodeDeliveryDetails',\n 'setNextResetPasswordStep',\n ],\n target: '#forgotPasswordActor.confirmResetPassword',\n },\n onError: {\n actions: 'setRemoteError',\n target: 'edit',\n },\n },\n },\n },\n },\n confirmResetPassword: {\n type: 'parallel',\n exit: ['clearFormValues', 'clearError', 'clearTouched'],\n states: {\n validation: {\n initial: 'pending',\n states: {\n pending: {\n invoke: {\n src: 'validateFields',\n onDone: {\n target: 'valid',\n actions: 'clearValidationError',\n },\n onError: {\n target: 'invalid',\n actions: 'setFieldErrors',\n },\n },\n },\n valid: { entry: 'sendUpdate' },\n invalid: { entry: 'sendUpdate' },\n },\n on: {\n CHANGE: {\n actions: 'handleInput',\n target: '.pending',\n },\n BLUR: {\n actions: 'handleBlur',\n target: '.pending',\n },\n },\n },\n submission: {\n initial: 'idle',\n states: {\n idle: {\n entry: 'sendUpdate',\n on: {\n SUBMIT: { actions: 'handleSubmit', target: 'validate' },\n RESEND: 'resendCode',\n CHANGE: { actions: 'handleInput' },\n BLUR: { actions: 'handleBlur' },\n },\n },\n validate: {\n entry: 'sendUpdate',\n invoke: {\n src: 'validateFields',\n onDone: {\n target: 'pending',\n actions: 'clearValidationError',\n },\n onError: {\n target: 'idle',\n actions: 'setFieldErrors',\n },\n },\n },\n resendCode: {\n tags: 'pending',\n entry: ['clearError', 'sendUpdate'],\n invoke: {\n src: 'handleResetPassword',\n onDone: { target: 'idle' },\n onError: { actions: 'setRemoteError', target: 'idle' },\n },\n },\n pending: {\n tags: 'pending',\n entry: ['clearError', 'sendUpdate'],\n invoke: {\n src: 'handleConfirmResetPassword',\n onDone: [\n {\n cond: 'hasCompletedResetPassword',\n actions: 'setNextResetPasswordStep',\n target: '#forgotPasswordActor.resolved',\n },\n {\n actions: 'setSignInStep',\n target: '#forgotPasswordActor.resolved',\n },\n ],\n onError: { actions: 'setRemoteError', target: 'idle' },\n },\n },\n },\n },\n },\n },\n resolved: {\n type: 'final',\n data: ({ step }) => ({ step }),\n },\n },\n }, {\n // sendUpdate is a HOC\n actions: { ...ACTIONS, sendUpdate: sendUpdate() },\n guards: GUARDS,\n services: {\n handleResetPassword({ username }) {\n return services.handleForgotPassword({ username });\n },\n handleConfirmResetPassword({ formValues, username }) {\n const { confirmation_code: confirmationCode, password: newPassword } = formValues;\n return services.handleForgotPasswordSubmit({\n confirmationCode,\n newPassword,\n username,\n });\n },\n validateFields(context) {\n return runValidators(context.formValues, context.touched, context.passwordSettings, [\n defaultServices.validateFormPassword,\n defaultServices.validateConfirmPassword,\n ]);\n },\n },\n });\n}\n\nexport { forgotPasswordActor };\n","const getFederatedSignInState = (target) => ({\n entry: ['sendUpdate', 'clearError'],\n invoke: {\n src: 'signInWithRedirect',\n onDone: { target },\n onError: { actions: 'setRemoteError', target },\n },\n});\n\nexport { getFederatedSignInState };\n","import { createMachine, sendUpdate } from 'xstate';\nimport { fetchUserAttributes, resetPassword, resendSignUpCode, confirmSignIn, signInWithRedirect } from 'aws-amplify/auth';\nimport { runValidators } from '../../../validators/index.mjs';\nimport ACTIONS from '../actions.mjs';\nimport { defaultServices } from '../defaultServices.mjs';\nimport GUARDS from '../guards.mjs';\nimport { getFederatedSignInState } from './utils.mjs';\n\nconst handleSignInResponse = {\n onDone: [\n {\n cond: 'hasCompletedSignIn',\n actions: 'setNextSignInStep',\n target: '#signInActor.fetchUserAttributes',\n },\n {\n cond: 'shouldConfirmSignInWithNewPassword',\n actions: ['setMissingAttributes', 'setNextSignInStep'],\n target: '#signInActor.forceChangePassword',\n },\n {\n cond: 'shouldResetPasswordFromSignIn',\n actions: 'setNextSignInStep',\n target: '#signInActor.resetPassword',\n },\n {\n cond: 'shouldConfirmSignUpFromSignIn',\n actions: 'setNextSignInStep',\n target: '#signInActor.resendSignUpCode',\n },\n {\n actions: [\n 'setChallengeName',\n 'setMissingAttributes',\n 'setNextSignInStep',\n 'setTotpSecretCode',\n ],\n target: '#signInActor.init',\n },\n ],\n onError: { actions: 'setRemoteError', target: 'edit' },\n};\nconst handleFetchUserAttributesResponse = {\n onDone: [\n {\n cond: 'shouldVerifyAttribute',\n actions: [\n 'setShouldVerifyUserAttributeStep',\n 'setUnverifiedUserAttributes',\n ],\n target: '#signInActor.resolved',\n },\n {\n actions: 'setConfirmAttributeCompleteStep',\n target: '#signInActor.resolved',\n },\n ],\n onError: {\n actions: 'setConfirmAttributeCompleteStep',\n target: '#signInActor.resolved',\n },\n};\nfunction signInActor({ services }) {\n return createMachine({\n id: 'signInActor',\n initial: 'init',\n predictableActionArguments: true,\n states: {\n init: {\n always: [\n {\n cond: 'shouldConfirmSignIn',\n target: 'confirmSignIn',\n },\n {\n cond: 'shouldSetupTotp',\n target: 'setupTotp',\n },\n {\n cond: ({ step }) => step === 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED',\n actions: 'setActorDoneData',\n target: 'forceChangePassword',\n },\n { target: 'signIn' },\n ],\n },\n federatedSignIn: getFederatedSignInState('signIn'),\n fetchUserAttributes: {\n invoke: {\n src: 'fetchUserAttributes',\n ...handleFetchUserAttributesResponse,\n },\n },\n resendSignUpCode: {\n invoke: {\n src: 'handleResendSignUpCode',\n onDone: {\n actions: 'setCodeDeliveryDetails',\n target: '#signInActor.resolved',\n },\n onError: {\n actions: 'setRemoteError',\n target: '#signInActor.signIn',\n },\n },\n },\n resetPassword: {\n invoke: {\n src: 'resetPassword',\n onDone: [\n {\n actions: 'setCodeDeliveryDetails',\n target: '#signInActor.resolved',\n },\n ],\n onError: { actions: ['setRemoteError', 'sendUpdate'] },\n },\n },\n signIn: {\n initial: 'edit',\n exit: 'clearTouched',\n states: {\n edit: {\n entry: 'sendUpdate',\n on: {\n CHANGE: { actions: 'handleInput' },\n FEDERATED_SIGN_IN: { target: '#signInActor.federatedSignIn' },\n SUBMIT: { actions: 'handleSubmit', target: 'submit' },\n },\n },\n submit: {\n tags: 'pending',\n entry: ['clearError', 'sendUpdate', 'setUsernameSignIn'],\n exit: 'clearFormValues',\n invoke: { src: 'handleSignIn', ...handleSignInResponse },\n },\n },\n },\n confirmSignIn: {\n initial: 'edit',\n exit: [\n 'clearChallengeName',\n 'clearFormValues',\n 'clearError',\n 'clearTouched',\n ],\n states: {\n edit: {\n entry: 'sendUpdate',\n on: {\n SUBMIT: { actions: 'handleSubmit', target: 'submit' },\n SIGN_IN: '#signInActor.signIn',\n CHANGE: { actions: 'handleInput' },\n },\n },\n submit: {\n tags: 'pending',\n entry: ['clearError', 'sendUpdate'],\n invoke: {\n src: 'confirmSignIn',\n ...handleSignInResponse,\n },\n },\n },\n },\n forceChangePassword: {\n entry: 'sendUpdate',\n type: 'parallel',\n exit: ['clearFormValues', 'clearError', 'clearTouched'],\n states: {\n validation: {\n initial: 'pending',\n states: {\n pending: {\n invoke: {\n src: 'validateFields',\n onDone: {\n target: 'valid',\n actions: 'clearValidationError',\n },\n onError: {\n target: 'invalid',\n actions: 'setFieldErrors',\n },\n },\n },\n valid: { entry: 'sendUpdate' },\n invalid: { entry: 'sendUpdate' },\n },\n on: {\n SIGN_IN: {\n actions: 'setSignInStep',\n target: '#signInActor.resolved',\n },\n CHANGE: {\n actions: 'handleInput',\n target: '.pending',\n },\n BLUR: {\n actions: 'handleBlur',\n target: '.pending',\n },\n },\n },\n submit: {\n initial: 'edit',\n entry: 'clearError',\n states: {\n edit: {\n entry: 'sendUpdate',\n on: {\n SUBMIT: { actions: 'handleSubmit', target: 'validate' },\n },\n },\n validate: {\n entry: 'sendUpdate',\n invoke: {\n src: 'validateFields',\n onDone: {\n actions: 'clearValidationError',\n target: 'pending',\n },\n onError: { actions: 'setFieldErrors', target: 'edit' },\n },\n },\n pending: {\n tags: 'pending',\n entry: ['sendUpdate', 'clearError'],\n invoke: {\n src: 'handleForceChangePassword',\n ...handleSignInResponse,\n },\n },\n },\n },\n },\n },\n setupTotp: {\n initial: 'edit',\n exit: ['clearFormValues', 'clearError', 'clearTouched'],\n states: {\n edit: {\n entry: 'sendUpdate',\n on: {\n SUBMIT: { actions: 'handleSubmit', target: 'submit' },\n SIGN_IN: '#signInActor.signIn',\n CHANGE: { actions: 'handleInput' },\n },\n },\n submit: {\n tags: 'pending',\n entry: ['sendUpdate', 'clearError'],\n invoke: { src: 'confirmSignIn', ...handleSignInResponse },\n },\n },\n },\n resolved: {\n type: 'final',\n data: (context) => ({\n codeDeliveryDetails: context.codeDeliveryDetails,\n remoteError: context.remoteError,\n step: context.step,\n unverifiedUserAttributes: context.unverifiedUserAttributes,\n username: context.username,\n }),\n },\n },\n }, {\n // sendUpdate is a HOC\n actions: { ...ACTIONS, sendUpdate: sendUpdate() },\n guards: GUARDS,\n services: {\n async fetchUserAttributes() {\n return fetchUserAttributes();\n },\n resetPassword({ username }) {\n return resetPassword({ username });\n },\n handleResendSignUpCode({ username }) {\n return resendSignUpCode({ username });\n },\n handleSignIn({ formValues, username }) {\n const { password } = formValues;\n return services.handleSignIn({ username, password });\n },\n confirmSignIn({ formValues }) {\n const { confirmation_code: challengeResponse } = formValues;\n return services.handleConfirmSignIn({ challengeResponse });\n },\n async handleForceChangePassword({ formValues }) {\n let { password: challengeResponse, phone_number, country_code, \n // destructure and toss UI confirm_password field\n // to prevent error from sending to confirmSignIn\n confirm_password, ...userAttributes } = formValues;\n let phoneNumberWithCountryCode;\n if (phone_number) {\n phoneNumberWithCountryCode =\n `${country_code}${phone_number}`.replace(/[^A-Z0-9+]/gi, '');\n userAttributes = {\n ...userAttributes,\n phone_number: phoneNumberWithCountryCode,\n };\n }\n const input = {\n challengeResponse,\n options: { userAttributes },\n };\n return confirmSignIn(input);\n },\n signInWithRedirect(_, { data }) {\n return signInWithRedirect(data);\n },\n async validateFields(context) {\n return runValidators(context.formValues, context.touched, context.passwordSettings, [\n defaultServices.validateFormPassword,\n defaultServices.validateConfirmPassword,\n ]);\n },\n },\n });\n}\n\nexport { signInActor };\n","import { createMachine, sendUpdate } from 'xstate';\nimport { autoSignIn, fetchUserAttributes, resendSignUpCode, signInWithRedirect } from 'aws-amplify/auth';\nimport { getSignUpInput } from '../utils.mjs';\nimport { runValidators } from '../../../validators/index.mjs';\nimport ACTIONS from '../actions.mjs';\nimport GUARDS from '../guards.mjs';\nimport { getFederatedSignInState } from './utils.mjs';\n\nconst handleResetPasswordResponse = {\n onDone: [\n { actions: 'setCodeDeliveryDetails', target: '#signUpActor.resolved' },\n ],\n onError: { actions: ['setRemoteError', 'sendUpdate'] },\n};\nconst handleAutoSignInResponse = {\n onDone: [\n {\n cond: 'hasCompletedSignIn',\n actions: 'setNextSignInStep',\n target: '#signUpActor.fetchUserAttributes',\n },\n {\n cond: 'shouldConfirmSignInWithNewPassword',\n actions: 'setNextSignInStep',\n target: '#signUpActor.resolved',\n },\n {\n cond: 'shouldResetPasswordFromSignIn',\n actions: 'setNextSignInStep',\n target: '#signUpActor.resetPassword',\n },\n {\n cond: 'shouldConfirmSignUpFromSignIn',\n actions: 'setNextSignInStep',\n target: '#signUpActor.resendSignUpCode',\n },\n {\n actions: [\n 'setNextSignInStep',\n 'setChallengeName',\n 'setMissingAttributes',\n 'setTotpSecretCode',\n ],\n target: '#signUpActor.resolved',\n },\n ],\n onError: {\n actions: 'setRemoteError',\n target: '#signUpActor.resolved',\n },\n};\nconst handleFetchUserAttributesResponse = {\n onDone: [\n {\n cond: 'shouldVerifyAttribute',\n actions: [\n 'setShouldVerifyUserAttributeStep',\n 'setUnverifiedUserAttributes',\n ],\n target: '#signUpActor.resolved',\n },\n {\n actions: 'setConfirmAttributeCompleteStep',\n target: '#signUpActor.resolved',\n },\n ],\n onError: {\n actions: 'setConfirmAttributeCompleteStep',\n target: '#signUpActor.resolved',\n },\n};\nfunction signUpActor({ services }) {\n return createMachine({\n id: 'signUpActor',\n initial: 'init',\n predictableActionArguments: true,\n states: {\n init: {\n always: [\n { cond: 'shouldConfirmSignUp', target: 'confirmSignUp' },\n { target: 'signUp' },\n ],\n },\n autoSignIn: {\n tags: 'pending',\n invoke: { src: 'autoSignIn', ...handleAutoSignInResponse },\n },\n fetchUserAttributes: {\n invoke: {\n src: 'fetchUserAttributes',\n ...handleFetchUserAttributesResponse,\n },\n },\n federatedSignIn: getFederatedSignInState('signUp'),\n resetPassword: {\n invoke: { src: 'resetPassword', ...handleResetPasswordResponse },\n },\n resendSignUpCode: {\n tags: 'pending',\n entry: 'sendUpdate',\n exit: 'sendUpdate',\n invoke: {\n src: 'resendSignUpCode',\n onDone: {\n actions: ['setCodeDeliveryDetails', 'sendUpdate'],\n target: '#signUpActor.confirmSignUp',\n },\n onError: [\n {\n cond: 'isUserAlreadyConfirmed',\n target: '#signUpActor.resolved',\n },\n { actions: ['setRemoteError', 'sendUpdate'] },\n ],\n },\n },\n signUp: {\n type: 'parallel',\n exit: 'clearTouched',\n on: {\n FEDERATED_SIGN_IN: { target: 'federatedSignIn' },\n },\n states: {\n validation: {\n initial: 'pending',\n states: {\n pending: {\n invoke: {\n src: 'validateSignUp',\n onDone: {\n actions: 'clearValidationError',\n target: 'valid',\n },\n onError: { actions: 'setFieldErrors', target: 'invalid' },\n },\n },\n valid: { entry: 'sendUpdate' },\n invalid: { entry: 'sendUpdate' },\n },\n on: {\n BLUR: { actions: 'handleBlur', target: '.pending' },\n CHANGE: { actions: 'handleInput', target: '.pending' },\n },\n },\n submission: {\n initial: 'idle',\n states: {\n idle: {\n entry: ['sendUpdate'],\n on: {\n SUBMIT: { actions: 'handleSubmit', target: 'validate' },\n },\n },\n validate: {\n entry: 'sendUpdate',\n invoke: {\n src: 'validateSignUp',\n onDone: {\n target: 'handleSignUp',\n actions: 'clearValidationError',\n },\n onError: { actions: 'setFieldErrors', target: 'idle' },\n },\n },\n handleSignUp: {\n tags: 'pending',\n entry: ['setUsernameSignUp', 'clearError'],\n exit: 'sendUpdate',\n invoke: {\n src: 'handleSignUp',\n onDone: [\n {\n cond: 'hasCompletedSignUp',\n actions: 'setNextSignUpStep',\n target: '#signUpActor.resolved',\n },\n {\n cond: 'shouldAutoSignIn',\n actions: 'setNextSignUpStep',\n target: '#signUpActor.autoSignIn',\n },\n {\n actions: [\n 'setCodeDeliveryDetails',\n 'setNextSignUpStep',\n ],\n target: '#signUpActor.init',\n },\n ],\n onError: {\n actions: ['sendUpdate', 'setRemoteError'],\n target: 'idle',\n },\n },\n },\n },\n },\n },\n },\n confirmSignUp: {\n initial: 'edit',\n entry: 'sendUpdate',\n states: {\n edit: {\n on: {\n SUBMIT: { actions: 'handleSubmit', target: 'submit' },\n CHANGE: { actions: 'handleInput' },\n BLUR: { actions: 'handleBlur' },\n RESEND: '#signUpActor.resendSignUpCode',\n },\n },\n submit: {\n tags: 'pending',\n entry: ['clearError', 'sendUpdate'],\n invoke: {\n src: 'confirmSignUp',\n onDone: [\n {\n cond: 'shouldAutoSignIn',\n actions: ['setNextSignUpStep', 'clearFormValues'],\n target: '#signUpActor.autoSignIn',\n },\n {\n actions: 'setNextSignUpStep',\n target: '#signUpActor.init',\n },\n ],\n onError: {\n actions: ['setRemoteError', 'sendUpdate'],\n target: 'edit',\n },\n },\n },\n },\n },\n resolved: {\n type: 'final',\n data: (context) => ({\n challengeName: context.challengeName,\n missingAttributes: context.missingAttributes,\n remoteError: context.remoteError,\n step: context.step,\n totpSecretCode: context.totpSecretCode,\n username: context.username,\n unverifiedUserAttributes: context.unverifiedUserAttributes,\n }),\n },\n },\n }, {\n // sendUpdate is a HOC\n actions: { ...ACTIONS, sendUpdate: sendUpdate() },\n guards: GUARDS,\n services: {\n autoSignIn() {\n return autoSignIn();\n },\n async fetchUserAttributes() {\n return fetchUserAttributes();\n },\n confirmSignUp({ formValues, username }) {\n const { confirmation_code: confirmationCode } = formValues;\n const input = { username, confirmationCode };\n return services.handleConfirmSignUp(input);\n },\n resendSignUpCode({ username }) {\n return resendSignUpCode({ username });\n },\n signInWithRedirect(_, { data }) {\n return signInWithRedirect(data);\n },\n handleSignUp(context) {\n const { formValues, loginMechanisms, username } = context;\n const loginMechanism = loginMechanisms[0];\n const input = getSignUpInput(username, formValues, loginMechanism);\n return services.handleSignUp(input);\n },\n async validateSignUp(context) {\n // This needs to exist in the machine to reference new `services`\n return runValidators(context.formValues, context.touched, context.passwordSettings, [\n // Validation of password\n services.validateFormPassword,\n // Validation for default form fields\n services.validateConfirmPassword,\n services.validatePreferredUsername,\n // Validation for any custom Sign Up fields\n services.validateCustomSignUp,\n ]);\n },\n },\n });\n}\n\nexport { signUpActor };\n","import { createMachine } from 'xstate';\nimport { signOut } from 'aws-amplify/auth';\n\nconst signOutActor = () => {\n return createMachine({\n initial: 'pending',\n id: 'signOutActor',\n predictableActionArguments: true,\n states: {\n pending: {\n tags: 'pending',\n invoke: {\n src: 'signOut',\n onDone: 'resolved',\n onError: 'rejected',\n },\n },\n resolved: { type: 'final' },\n rejected: { type: 'final' },\n },\n }, {\n services: {\n signOut: () => signOut(),\n },\n });\n};\n\nexport { signOutActor };\n","import { createMachine, sendUpdate } from 'xstate';\nimport { sendUserAttributeVerificationCode, confirmUserAttribute } from 'aws-amplify/auth';\nimport { runValidators } from '../../../validators/index.mjs';\nimport ACTIONS from '../actions.mjs';\nimport { defaultServices } from '../defaultServices.mjs';\n\nfunction verifyUserAttributesActor() {\n return createMachine({\n id: 'verifyUserAttributesActor',\n initial: 'selectUserAttributes',\n predictableActionArguments: true,\n states: {\n selectUserAttributes: {\n initial: 'edit',\n exit: ['clearError', 'clearTouched', 'sendUpdate'],\n states: {\n edit: {\n entry: 'sendUpdate',\n on: {\n SUBMIT: { actions: 'handleSubmit', target: 'submit' },\n SKIP: { target: '#verifyUserAttributesActor.resolved' },\n CHANGE: { actions: 'handleInput' },\n },\n },\n submit: {\n tags: 'pending',\n entry: ['clearError', 'sendUpdate'],\n invoke: {\n src: 'sendUserAttributeVerificationCode',\n onDone: {\n actions: [\n 'setSelectedUserAttribute',\n 'setCodeDeliveryDetails',\n ],\n target: '#verifyUserAttributesActor.confirmVerifyUserAttribute',\n },\n onError: {\n actions: 'setRemoteError',\n target: 'edit',\n },\n },\n },\n },\n },\n confirmVerifyUserAttribute: {\n initial: 'edit',\n exit: ['clearError', 'clearFormValues', 'clearTouched'],\n states: {\n edit: {\n entry: 'sendUpdate',\n on: {\n SUBMIT: { actions: 'handleSubmit', target: 'submit' },\n SKIP: '#verifyUserAttributesActor.resolved',\n CHANGE: { actions: 'handleInput' },\n },\n },\n submit: {\n tags: 'pending',\n entry: ['clearError', 'sendUpdate'],\n invoke: {\n src: 'confirmVerifyUserAttribute',\n onDone: {\n actions: [\n 'setConfirmAttributeCompleteStep',\n 'clearSelectedUserAttribute',\n ],\n target: '#verifyUserAttributesActor.resolved',\n },\n onError: {\n actions: 'setRemoteError',\n target: 'edit',\n },\n },\n },\n },\n },\n resolved: { type: 'final', data: ({ step }) => ({ step }) },\n },\n }, {\n // sendUpdate is a HOC\n actions: { ...ACTIONS, sendUpdate: sendUpdate() },\n services: {\n sendUserAttributeVerificationCode({ formValues: { unverifiedAttr } }) {\n const input = {\n userAttributeKey: unverifiedAttr,\n };\n return sendUserAttributeVerificationCode(input);\n },\n async confirmVerifyUserAttribute({ formValues: { confirmation_code: confirmationCode }, selectedUserAttribute, }) {\n const input = {\n confirmationCode,\n userAttributeKey: selectedUserAttribute,\n };\n return confirmUserAttribute(input);\n },\n async validateFields(context) {\n return runValidators(context.formValues, context.touched, context.passwordSettings, [\n defaultServices.validateFormPassword,\n defaultServices.validateConfirmPassword,\n ]);\n },\n },\n });\n}\n\nexport { verifyUserAttributesActor };\n","import { createMachine, forwardTo, assign, spawn, actions } from 'xstate';\nimport '@aws-amplify/core/internals/utils';\nimport '../../utils/setUserAgent/constants.mjs';\nimport { isEmptyObject } from '../../utils/utils.mjs';\nimport ACTIONS from './actions.mjs';\nimport GUARDS from './guards.mjs';\nimport { forgotPasswordActor } from './actors/forgotPassword.mjs';\nimport { signInActor } from './actors/signIn.mjs';\nimport { signUpActor } from './actors/signUp.mjs';\nimport { signOutActor } from './actors/signOut.mjs';\nimport { verifyUserAttributesActor } from './actors/verifyUserAttributes.mjs';\nimport { defaultServices } from './defaultServices.mjs';\n\nconst getActorContext = (context, defaultStep) => ({\n ...context.actorDoneData,\n step: context?.actorDoneData?.step ?? defaultStep,\n // initialize empty objects on actor start\n formValues: {},\n touched: {},\n validationError: {},\n // values included on `context.config` that should be available in actors\n formFields: context.config?.formFields,\n loginMechanisms: context.config?.loginMechanisms,\n passwordSettings: context.config?.passwordSettings,\n signUpAttributes: context.config?.signUpAttributes,\n socialProviders: context.config?.socialProviders,\n});\nconst { choose, stop } = actions;\nconst stopActor = (machineId) => stop(machineId);\n// setup step waits for ui to emit INIT action to proceed to configure\nconst LEGACY_WAIT_CONFIG = {\n on: {\n INIT: {\n actions: 'configure',\n target: 'getConfig',\n },\n SIGN_OUT: '#authenticator.signOut',\n },\n};\n// setup step proceeds directly to configure\nconst NEXT_WAIT_CONFIG = {\n always: { actions: 'configure', target: 'getConfig' },\n};\nfunction createAuthenticatorMachine(options) {\n const { useNextWaitConfig, ...overrideConfigServices } = options ?? {};\n const initConfig = useNextWaitConfig ? NEXT_WAIT_CONFIG : LEGACY_WAIT_CONFIG;\n return createMachine({\n id: 'authenticator',\n initial: 'idle',\n context: {\n user: undefined,\n config: {},\n services: defaultServices,\n actorRef: undefined,\n hasSetup: false,\n },\n predictableActionArguments: true,\n states: {\n // See: https://xstate.js.org/docs/guides/communication.html#invoking-promises\n idle: {\n invoke: {\n src: 'handleGetCurrentUser',\n onDone: { actions: 'setUser', target: 'setup' },\n onError: { target: 'setup' },\n },\n },\n setup: {\n initial: 'initConfig',\n states: {\n initConfig,\n getConfig: {\n invoke: {\n src: 'getAmplifyConfig',\n onDone: [\n {\n actions: ['applyAmplifyConfig', 'setHasSetup'],\n cond: 'hasUser',\n target: '#authenticator.authenticated',\n },\n {\n actions: ['applyAmplifyConfig', 'setHasSetup'],\n target: 'goToInitialState',\n },\n ],\n },\n },\n goToInitialState: {\n always: [\n {\n cond: 'isInitialStateSignUp',\n target: '#authenticator.signUpActor',\n },\n {\n cond: 'isInitialStateResetPassword',\n target: '#authenticator.forgotPasswordActor',\n },\n { target: '#authenticator.signInActor' },\n ],\n },\n },\n },\n getCurrentUser: {\n invoke: {\n src: 'handleGetCurrentUser',\n onDone: {\n actions: 'setUser',\n target: '#authenticator.authenticated',\n },\n onError: { target: '#authenticator.setup' },\n },\n },\n signInActor: {\n initial: 'spawnActor',\n states: {\n spawnActor: {\n always: { actions: 'spawnSignInActor', target: 'runActor' },\n },\n runActor: {\n entry: 'clearActorDoneData',\n exit: stopActor('signInActor'),\n },\n },\n on: {\n FORGOT_PASSWORD: 'forgotPasswordActor',\n SIGN_IN: 'signInActor',\n SIGN_UP: 'signUpActor',\n 'done.invoke.signInActor': [\n {\n cond: 'hasCompletedAttributeConfirmation',\n target: '#authenticator.getCurrentUser',\n },\n {\n cond: 'isShouldConfirmUserAttributeStep',\n actions: 'setActorDoneData',\n target: '#authenticator.verifyUserAttributesActor',\n },\n {\n cond: 'isResetPasswordStep',\n actions: 'setActorDoneData',\n target: '#authenticator.forgotPasswordActor',\n },\n {\n cond: 'isConfirmSignUpStep',\n actions: 'setActorDoneData',\n target: '#authenticator.signUpActor',\n },\n ],\n },\n },\n signUpActor: {\n initial: 'spawnActor',\n states: {\n spawnActor: {\n always: { actions: 'spawnSignUpActor', target: 'runActor' },\n },\n runActor: {\n entry: 'clearActorDoneData',\n exit: stopActor('signUpActor'),\n },\n },\n on: {\n SIGN_IN: 'signInActor',\n 'done.invoke.signUpActor': [\n {\n cond: 'hasCompletedAttributeConfirmation',\n target: '#authenticator.getCurrentUser',\n },\n {\n cond: 'isShouldConfirmUserAttributeStep',\n actions: 'setActorDoneData',\n target: '#authenticator.verifyUserAttributesActor',\n },\n {\n cond: 'isConfirmUserAttributeStep',\n target: '#authenticator.verifyUserAttributesActor',\n },\n {\n actions: 'setActorDoneData',\n target: '#authenticator.signInActor',\n },\n ],\n },\n },\n forgotPasswordActor: {\n initial: 'spawnActor',\n states: {\n spawnActor: {\n always: {\n actions: 'spawnForgotPasswordActor',\n target: 'runActor',\n },\n },\n runActor: {\n entry: 'clearActorDoneData',\n exit: stopActor('forgotPasswordActor'),\n },\n },\n on: {\n SIGN_IN: 'signInActor',\n 'done.invoke.forgotPasswordActor': [\n { target: '#authenticator.signInActor' },\n ],\n },\n },\n verifyUserAttributesActor: {\n initial: 'spawnActor',\n states: {\n spawnActor: {\n always: {\n actions: 'spawnVerifyUserAttributesActor',\n target: 'runActor',\n },\n },\n runActor: {\n entry: 'clearActorDoneData',\n exit: stopActor('verifyUserAttributesActor'),\n },\n },\n on: {\n 'done.invoke.verifyUserAttributesActor': [\n {\n actions: 'setActorDoneData',\n target: '#authenticator.getCurrentUser',\n },\n ],\n },\n },\n authenticated: {\n initial: 'idle',\n states: {\n idle: { on: { TOKEN_REFRESH: 'refreshUser' } },\n refreshUser: {\n invoke: {\n src: '#authenticator.getCurrentUser',\n onDone: { actions: 'setUser', target: 'idle' },\n onError: { target: '#authenticator.signOut' },\n },\n },\n },\n on: { SIGN_OUT: 'signOut' },\n },\n signOut: {\n initial: 'spawnActor',\n states: {\n spawnActor: {\n always: { actions: 'spawnSignOutActor', target: 'runActor' },\n },\n runActor: {\n entry: 'clearActorDoneData',\n exit: stopActor('signOutActor'),\n },\n },\n on: {\n 'done.invoke.signOutActor': {\n actions: 'clearUser',\n target: 'setup.getConfig',\n },\n },\n },\n },\n on: {\n SIGN_IN_WITH_REDIRECT: { target: '#authenticator.getCurrentUser' },\n CHANGE: { actions: 'forwardToActor' },\n BLUR: { actions: 'forwardToActor' },\n SUBMIT: { actions: 'forwardToActor' },\n FEDERATED_SIGN_IN: { actions: 'forwardToActor' },\n RESEND: { actions: 'forwardToActor' },\n SIGN_IN: { actions: 'forwardToActor' },\n SKIP: { actions: 'forwardToActor' },\n },\n }, {\n actions: {\n ...ACTIONS,\n forwardToActor: choose([\n { cond: 'hasActor', actions: forwardTo(({ actorRef }) => actorRef) },\n ]),\n setActorDoneData: assign({\n actorDoneData: (context, event) => ({\n challengeName: event.data.challengeName,\n codeDeliveryDetails: event.data.codeDeliveryDetails,\n missingAttributes: event.data.missingAttributes,\n remoteError: event.data.remoteError,\n username: event.data.username,\n step: event.data.step,\n totpSecretCode: event.data.totpSecretCode,\n unverifiedUserAttributes: event.data.unverifiedUserAttributes,\n }),\n }),\n applyAmplifyConfig: assign({\n config(context, { data: cliConfig }) {\n // Prefer explicitly configured settings over default CLI values\\\n const { loginMechanisms = cliConfig.loginMechanisms ?? [], signUpAttributes = cliConfig.signUpAttributes ?? [], socialProviders = cliConfig.socialProviders ?? [], initialState, formFields: _formFields, passwordSettings = cliConfig.passwordFormat ??\n {}, } = context.config;\n // By default, Cognito assumes `username`, so there isn't a different username attribute like `email`.\n // We explicitly add it as a login mechanism to be consistent with Admin UI's language.\n if (loginMechanisms.length === 0) {\n loginMechanisms.push('username');\n }\n const formFields = convertFormFields(_formFields) ?? {};\n return {\n formFields,\n initialState,\n loginMechanisms,\n passwordSettings,\n signUpAttributes,\n socialProviders,\n };\n },\n }),\n spawnSignInActor: assign({\n actorRef: (context, _) => {\n const { services } = context;\n const actor = signInActor({ services }).withContext(getActorContext(context, 'SIGN_IN'));\n return spawn(actor, { name: 'signInActor' });\n },\n }),\n spawnSignUpActor: assign({\n actorRef: (context, _) => {\n const { services } = context;\n const actor = signUpActor({ services }).withContext(getActorContext(context, 'SIGN_UP'));\n return spawn(actor, { name: 'signUpActor' });\n },\n }),\n spawnForgotPasswordActor: assign({\n actorRef: (context, _) => {\n const { services } = context;\n const actor = forgotPasswordActor({ services }).withContext(getActorContext(context, 'FORGOT_PASSWORD'));\n return spawn(actor, { name: 'forgotPasswordActor' });\n },\n }),\n spawnVerifyUserAttributesActor: assign({\n actorRef: (context) => {\n const actor = verifyUserAttributesActor().withContext(getActorContext(context));\n return spawn(actor, { name: 'verifyUserAttributesActor' });\n },\n }),\n spawnSignOutActor: assign({\n actorRef: (context) => {\n const actor = signOutActor().withContext({ user: context?.user });\n return spawn(actor, { name: 'signOutActor' });\n },\n }),\n configure: assign((_, event) => {\n const { services: customServices, ...config } = !isEmptyObject(overrideConfigServices)\n ? overrideConfigServices\n : event.data ?? {};\n return {\n services: { ...defaultServices, ...customServices },\n config,\n };\n }),\n setHasSetup: assign({ hasSetup: true }),\n },\n guards: {\n ...GUARDS,\n hasActor: ({ actorRef }) => !!actorRef,\n isInitialStateSignUp: ({ config }) => config.initialState === 'signUp',\n isInitialStateResetPassword: ({ config }) => config.initialState === 'forgotPassword',\n shouldSetup: ({ hasSetup }) => !hasSetup,\n hasUser: ({ user }) => {\n return !!user;\n },\n },\n services: {\n getAmplifyConfig: ({ services }) => services.getAmplifyConfig(),\n handleGetCurrentUser: ({ services }) => services.getCurrentUser(),\n },\n });\n}\nfunction convertFormFields(formFields) {\n if (formFields) {\n Object.keys(formFields).forEach((component) => {\n Object.keys(formFields[component]).forEach((inputName) => {\n let ff = formFields[component][inputName];\n ff.required = ff.isRequired;\n });\n });\n }\n return formFields;\n}\n\nexport { createAuthenticatorMachine };\n","const borderWidths = {\n small: { value: '1px' },\n medium: { value: '2px' },\n large: { value: '3px' },\n};\n\nexport { borderWidths };\n","const colors = {\n red: {\n 10: { value: 'hsl(0, 75%, 95%)' },\n 20: { value: 'hsl(0, 75%, 85%)' },\n 40: { value: 'hsl(0, 75%, 75%)' },\n 60: { value: 'hsl(0, 50%, 50%)' },\n 80: { value: 'hsl(0, 95%, 30%)' },\n 90: { value: 'hsl(0, 100%, 20%)' },\n 100: { value: 'hsl(0, 100%, 15%)' },\n },\n orange: {\n 10: { value: 'hsl(30, 75%, 95%)' },\n 20: { value: 'hsl(30, 75%, 85%)' },\n 40: { value: 'hsl(30, 75%, 75%)' },\n 60: { value: 'hsl(30, 50%, 50%)' },\n 80: { value: 'hsl(30, 95%, 30%)' },\n 90: { value: 'hsl(30, 100%, 20%)' },\n 100: { value: 'hsl(30, 100%, 15%)' },\n },\n yellow: {\n 10: { value: 'hsl(60, 75%, 95%)' },\n 20: { value: 'hsl(60, 75%, 85%)' },\n 40: { value: 'hsl(60, 75%, 75%)' },\n 60: { value: 'hsl(60, 50%, 50%)' },\n 80: { value: 'hsl(60, 95%, 30%)' },\n 90: { value: 'hsl(60, 100%, 20%)' },\n 100: { value: 'hsl(60, 100%, 15%)' },\n },\n green: {\n 10: { value: 'hsl(130, 60%, 95%)' },\n 20: { value: 'hsl(130, 60%, 90%)' },\n 40: { value: 'hsl(130, 44%, 63%)' },\n 60: { value: 'hsl(130, 43%, 46%)' },\n 80: { value: 'hsl(130, 33%, 37%)' },\n 90: { value: 'hsl(130, 27%, 29%)' },\n 100: { value: 'hsl(130, 22%, 23%)' },\n },\n teal: {\n 10: { value: 'hsl(190, 75%, 95%)' },\n 20: { value: 'hsl(190, 75%, 85%)' },\n 40: { value: 'hsl(190, 70%, 70%)' },\n 60: { value: 'hsl(190, 50%, 50%)' },\n 80: { value: 'hsl(190, 95%, 30%)' },\n 90: { value: 'hsl(190, 100%, 20%)' },\n 100: { value: 'hsl(190, 100%, 15%)' },\n },\n blue: {\n 10: { value: 'hsl(220, 95%, 95%)' },\n 20: { value: 'hsl(220, 85%, 85%)' },\n 40: { value: 'hsl(220, 70%, 70%)' },\n 60: { value: 'hsl(220, 50%, 50%)' },\n 80: { value: 'hsl(220, 95%, 30%)' },\n 90: { value: 'hsl(220, 100%, 20%)' },\n 100: { value: 'hsl(220, 100%, 15%)' },\n },\n purple: {\n 10: { value: 'hsl(300, 95%, 95%)' },\n 20: { value: 'hsl(300, 85%, 85%)' },\n 40: { value: 'hsl(300, 70%, 70%)' },\n 60: { value: 'hsl(300, 50%, 50%)' },\n 80: { value: 'hsl(300, 95%, 30%)' },\n 90: { value: 'hsl(300, 100%, 20%)' },\n 100: { value: 'hsl(300, 100%, 15%)' },\n },\n pink: {\n 10: { value: 'hsl(340, 95%, 95%)' },\n 20: { value: 'hsl(340, 90%, 85%)' },\n 40: { value: 'hsl(340, 70%, 70%)' },\n 60: { value: 'hsl(340, 50%, 50%)' },\n 80: { value: 'hsl(340, 95%, 30%)' },\n 90: { value: 'hsl(340, 100%, 20%)' },\n 100: { value: 'hsl(340, 100%, 15%)' },\n },\n neutral: {\n 10: { value: 'hsl(210, 5%, 98%)' },\n 20: { value: 'hsl(210, 5%, 94%)' },\n 40: { value: 'hsl(210, 5%, 87%)' },\n 60: { value: 'hsl(210, 10%, 58%)' },\n 80: { value: 'hsl(210, 10%, 40%)' },\n 90: { value: 'hsl(210, 25%, 25%)' },\n 100: { value: 'hsl(210, 50%, 10%)' },\n },\n primary: {\n 10: { value: '{colors.teal.10.value}' },\n 20: { value: '{colors.teal.20.value}' },\n 40: { value: '{colors.teal.40.value}' },\n 60: { value: '{colors.teal.60.value}' },\n 80: { value: '{colors.teal.80.value}' },\n 90: { value: '{colors.teal.90.value}' },\n 100: { value: '{colors.teal.100.value}' },\n },\n secondary: {\n 10: { value: '{colors.purple.10.value}' },\n 20: { value: '{colors.purple.20.value}' },\n 40: { value: '{colors.purple.40.value}' },\n 60: { value: '{colors.purple.60.value}' },\n 80: { value: '{colors.purple.80.value}' },\n 90: { value: '{colors.purple.90.value}' },\n 100: { value: '{colors.purple.100.value}' },\n },\n font: {\n primary: { value: '{colors.neutral.100.value}' },\n secondary: { value: '{colors.neutral.90.value}' },\n tertiary: { value: '{colors.neutral.80.value}' },\n disabled: { value: '{colors.neutral.60.value}' },\n inverse: { value: '{colors.white.value}' },\n interactive: { value: '{colors.primary.80.value}' },\n // Hover and Focus colors are intentionally different colors.\n // This allows users to distinguish between the current keyboard focus\n // and the location of their pointer\n hover: { value: '{colors.primary.90.value}' },\n // Focus color is set to 100 to ensure enough contrast for accessibility\n focus: { value: '{colors.primary.100.value}' },\n active: { value: '{colors.primary.100.value}' },\n info: { value: '{colors.blue.90.value}' },\n warning: { value: '{colors.orange.90.value}' },\n error: { value: '{colors.red.90.value}' },\n success: { value: '{colors.green.90.value}' },\n },\n background: {\n primary: { value: '{colors.white.value}' },\n secondary: { value: '{colors.neutral.10.value}' },\n tertiary: { value: '{colors.neutral.20.value}' },\n quaternary: { value: '{colors.neutral.60.value}' },\n disabled: { value: '{colors.background.tertiary.value}' },\n info: { value: '{colors.blue.10.value}' },\n warning: { value: '{colors.orange.10.value}' },\n error: { value: '{colors.red.10.value}' },\n success: { value: '{colors.green.10.value}' },\n },\n border: {\n primary: { value: '{colors.neutral.60.value}' },\n secondary: { value: '{colors.neutral.40.value}' },\n tertiary: { value: '{colors.neutral.20.value}' },\n disabled: { value: '{colors.border.tertiary.value}' },\n pressed: { value: '{colors.primary.100.value}' },\n // Focus color is set to 100 to ensure enough contrast for accessibility\n focus: { value: '{colors.primary.100.value}' },\n error: { value: '{colors.red.80.value}' },\n info: { value: '{colors.blue.80.value}' },\n success: { value: '{colors.green.80.value}' },\n warning: { value: '{colors.orange.80.value}' },\n },\n shadow: {\n primary: { value: 'hsla(210, 50%, 10%, 0.25)' },\n secondary: { value: 'hsla(210, 50%, 10%, 0.15)' },\n tertiary: { value: 'hsla(210, 50%, 10%, 0.05)' },\n },\n overlay: {\n 5: { value: 'hsla(0, 0%, 0%, 0.05)' },\n 10: { value: 'hsla(0, 0%, 0%, 0.1)' },\n 20: { value: 'hsla(0, 0%, 0%, 0.2)' },\n 30: { value: 'hsla(0, 0%, 0%, 0.3)' },\n 40: { value: 'hsla(0, 0%, 0%, 0.4)' },\n 50: { value: 'hsla(0, 0%, 0%, 0.5)' },\n 60: { value: 'hsla(0, 0%, 0%, 0.6)' },\n 70: { value: 'hsla(0, 0%, 0%, 0.7)' },\n 80: { value: 'hsla(0, 0%, 0%, 0.8)' },\n 90: { value: 'hsla(0, 0%, 0%, 0.9)' },\n },\n black: { value: 'hsl(0, 0%, 0%)' },\n white: { value: 'hsl(0, 0%, 100%)' },\n transparent: { value: 'transparent' },\n};\n\nexport { colors };\n","const alert = {\n // Default styles\n alignItems: { value: 'center' },\n justifyContent: { value: 'space-between' },\n color: { value: '{colors.font.primary.value}' },\n backgroundColor: { value: '{colors.background.tertiary.value}' },\n paddingBlock: { value: '{space.small.value}' },\n paddingInline: { value: '{space.medium.value}' },\n icon: {\n size: { value: '{fontSizes.xl.value}' },\n },\n heading: {\n fontSize: { value: '{fontSizes.medium.value}' },\n fontWeight: { value: '{fontWeights.bold.value}' },\n },\n // Variations\n info: {\n color: { value: '{colors.font.info.value}' },\n backgroundColor: { value: '{colors.background.info.value}' },\n },\n error: {\n color: { value: '{colors.font.error.value}' },\n backgroundColor: { value: '{colors.background.error.value}' },\n },\n warning: {\n color: { value: '{colors.font.warning.value}' },\n backgroundColor: { value: '{colors.background.warning.value}' },\n },\n success: {\n color: { value: '{colors.font.success.value}' },\n backgroundColor: { value: '{colors.background.success.value}' },\n },\n};\n\nexport { alert };\n","const aiConversation = {\n message: {\n backgroundColor: { value: '{colors.background.secondary.value}' },\n borderRadius: { value: '{radii.large.value}' },\n gap: { value: '{space.small.value}' },\n paddingBlock: { value: '{space.small.value}' },\n paddingInline: { value: '{space.small.value}' },\n user: {\n backgroundColor: { value: '{colors.background.secondary.value}' },\n },\n assistant: {\n backgroundColor: { value: '{colors.primary.10.value}' },\n },\n sender: {\n gap: { value: '{space.small.value}' },\n username: {\n color: { value: '{colors.font.primary.value}' },\n fontSize: { value: 'inherit' },\n fontWeight: { value: '{fontWeights.bold.value}' },\n },\n timestamp: {\n color: { value: '{colors.font.tertiary.value}' },\n fontSize: { value: 'inherit' },\n fontWeight: { value: 'inherit' },\n },\n },\n body: { gap: { value: '{space.xs.value}' } },\n actions: { gap: { value: '{space.xs.value}' } },\n },\n form: {\n gap: { value: '{space.small.value}' },\n padding: { value: '{space.small.value}' },\n },\n attachment: {\n borderColor: { value: '{colors.border.secondary.value}' },\n borderWidth: { value: '{borderWidths.small.value}' },\n borderRadius: { value: '{radii.small.value}' },\n fontSize: { value: '{fontSizes.small.value}' },\n paddingBlock: { value: '{space.xxxs.value}' },\n paddingInline: { value: '{space.xs.value}' },\n gap: { value: '{space.xs.value}' },\n list: {\n paddingBlockStart: { value: '{space.xs.value}' },\n gap: { value: '{space.xxs.value}' },\n },\n name: {\n color: { value: '{colors.font.primary.value}' },\n fontSize: { value: '{fontSizes.small.value}' },\n fontWeight: { value: '{fontWeights.normal.value}' },\n },\n size: {\n color: { value: '{colors.font.tertiary.value}' },\n fontSize: { value: '{fontSizes.small.value}' },\n fontWeight: { value: '{fontWeights.normal.value}' },\n },\n remove: {\n padding: { value: '{space.xxs.value}' },\n },\n image: {\n width: { value: '{fontSizes.medium.value}' },\n height: { value: '{fontSizes.medium.value}' },\n },\n },\n};\n\nexport { aiConversation };\n","const autocomplete = {\n menu: {\n width: { value: '100%' },\n marginBlockStart: { value: '{space.xxxs}' },\n backgroundColor: { value: '{colors.background.primary}' },\n borderColor: { value: '{colors.border.primary}' },\n borderWidth: { value: '{borderWidths.small}' },\n borderStyle: { value: 'solid' },\n borderRadius: { value: '{radii.small}' },\n options: {\n display: { value: 'flex' },\n flexDirection: { value: 'column' },\n maxHeight: { value: '300px' },\n },\n option: {\n backgroundColor: { value: '{colors.background.primary}' },\n color: { value: 'currentcolor' },\n cursor: { value: 'pointer' },\n transitionDuration: { value: '{time.short}' },\n transitionProperty: { value: 'background-color, color' },\n transitionTimingFunction: { value: 'ease' },\n _active: {\n backgroundColor: { value: '{colors.primary.80}' },\n color: { value: '{colors.white}' },\n },\n },\n _empty: {\n display: { value: 'flex' },\n },\n _loading: {\n alignItems: { value: 'center' },\n display: { value: 'flex' },\n gap: { value: '{space.xxxs}' },\n },\n spaceShared: {\n paddingBlock: { value: '{space.xs}' },\n paddingInline: { value: '{space.small}' },\n },\n },\n};\n\nexport { autocomplete };\n","const authenticator = {\n maxWidth: { value: '60rem' },\n modal: {\n width: { value: '{space.relative.full}' },\n height: { value: '{space.relative.full}' },\n backgroundColor: { value: '{colors.overlay.50.value}' },\n top: { value: '{space.zero}' },\n left: { value: '{space.zero}' },\n },\n container: {\n widthMax: { value: '30rem' },\n },\n router: {\n borderWidth: { value: '{borderWidths.small.value}' },\n borderStyle: { value: 'solid' },\n borderColor: { value: '{colors.border.primary.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n boxShadow: { value: '{shadows.medium.value}' },\n },\n footer: {\n paddingBottom: { value: '{space.medium.value}' },\n },\n form: {\n padding: { value: '{space.xl.value}' },\n },\n state: {\n inactive: {\n backgroundColor: { value: '{colors.background.secondary.value}' },\n },\n },\n orContainer: {\n color: { value: '{colors.neutral.80.value}' },\n orLine: {\n backgroundColor: { value: '{colors.background.primary.value}' },\n },\n },\n};\n\nexport { authenticator };\n","const avatar = {\n // Default styles\n color: { value: '{colors.font.tertiary.value}' },\n lineHeight: { value: 1 },\n fontWeight: { value: '{fontWeights.semibold.value}' },\n fontSize: { value: '{fontSizes.small.value}' },\n textAlign: { value: 'center' },\n width: { value: '{fontSizes.xxl.value}' },\n height: { value: '{fontSizes.xxl.value}' },\n backgroundColor: { value: '{colors.background.tertiary}' },\n borderRadius: { value: '100%' },\n borderColor: { value: '{colors.border.primary.value}' },\n borderWidth: { value: '{borderWidths.medium.value}' },\n // Color Theme Variations\n info: {\n color: { value: '{colors.font.info.value}' },\n backgroundColor: { value: '{colors.background.info.value}' },\n borderColor: { value: '{colors.border.info.value}' },\n },\n warning: {\n color: { value: '{colors.font.warning.value}' },\n backgroundColor: { value: '{colors.background.warning.value}' },\n borderColor: { value: '{colors.border.warning.value}' },\n },\n success: {\n color: { value: '{colors.font.success.value}' },\n backgroundColor: { value: '{colors.background.success.value}' },\n borderColor: { value: '{colors.border.success.value}' },\n },\n error: {\n color: { value: '{colors.font.error.value}' },\n backgroundColor: { value: '{colors.background.error.value}' },\n borderColor: { value: '{colors.border.error.value}' },\n },\n // Sizes\n small: {\n fontSize: { value: '{fontSizes.xs.value}' },\n width: { value: '{fontSizes.xl.value}' },\n height: { value: '{fontSizes.xl.value}' },\n },\n // medium is the default size\n large: {\n fontSize: { value: '{fontSizes.medium.value}' },\n width: { value: '{fontSizes.xxxl.value}' },\n height: { value: '{fontSizes.xxxl.value}' },\n },\n};\n\nexport { avatar };\n","const badge = {\n // Default styles\n color: { value: '{colors.font.primary.value}' },\n lineHeight: { value: 1 },\n fontWeight: { value: '{fontWeights.semibold.value}' },\n fontSize: { value: '{fontSizes.small.value}' },\n textAlign: { value: 'center' },\n paddingVertical: { value: '{space.xs.value}' },\n paddingHorizontal: { value: '{space.small.value}' },\n backgroundColor: { value: '{colors.background.tertiary.value}' },\n // An arbitrarily large value to ensure that the left and right sides of the badge are perfectly rounded for any size variation\n borderRadius: { value: '{radii.xl.value}' },\n // Variations\n info: {\n color: { value: '{colors.font.info.value}' },\n backgroundColor: { value: '{colors.background.info.value}' },\n },\n warning: {\n color: { value: '{colors.font.warning.value}' },\n backgroundColor: { value: '{colors.background.warning.value}' },\n },\n success: {\n color: { value: '{colors.font.success.value}' },\n backgroundColor: { value: '{colors.background.success.value}' },\n },\n error: {\n color: { value: '{colors.font.error.value}' },\n backgroundColor: { value: '{colors.background.error.value}' },\n },\n // Sizes\n small: {\n fontSize: { value: '{fontSizes.xs.value}' },\n paddingVertical: { value: '{space.xxs.value}' },\n paddingHorizontal: { value: '{space.xs.value}' },\n },\n // medium is the default size\n large: {\n fontSize: { value: '{fontSizes.medium.value}' },\n paddingVertical: { value: '{space.small.value}' },\n paddingHorizontal: { value: '{space.medium.value}' },\n },\n};\n\nexport { badge };\n","const breadcrumbs = {\n flexDirection: { value: 'row' },\n flexWrap: { value: 'wrap' },\n gap: { value: '0' },\n color: { value: '{colors.font.tertiary}' },\n item: {\n flexDirection: { value: 'row' },\n color: { value: 'inherit' },\n fontSize: { value: 'inherit' },\n alignItems: { value: 'center' },\n lineHeight: { value: '1' },\n },\n separator: {\n color: { value: 'inherit' },\n fontSize: { value: 'inherit' },\n paddingInline: { value: '{space.xxs}' },\n },\n link: {\n color: { value: '{components.link.color}' },\n fontSize: { value: 'inherit' },\n fontWeight: { value: 'normal' },\n textDecoration: { value: 'none' },\n paddingInline: { value: '{space.xs}' },\n paddingBlock: { value: '{space.xxs}' },\n current: {\n color: { value: 'inherit' },\n fontSize: { value: 'inherit' },\n fontWeight: { value: 'normal' },\n textDecoration: { value: 'none' },\n },\n },\n};\n\nexport { breadcrumbs };\n","const button = {\n // shared styles\n fontWeight: { value: '{fontWeights.bold.value}' },\n transitionDuration: {\n value: '{components.fieldcontrol.transitionDuration.value}',\n },\n fontSize: { value: '{components.fieldcontrol.fontSize.value}' },\n lineHeight: { value: '{components.fieldcontrol.lineHeight.value}' },\n paddingBlockStart: {\n value: '{components.fieldcontrol.paddingBlockStart.value}',\n },\n paddingBlockEnd: {\n value: '{components.fieldcontrol.paddingBlockEnd.value}',\n },\n paddingInlineStart: {\n value: '{components.fieldcontrol.paddingInlineStart.value}',\n },\n paddingInlineEnd: {\n value: '{components.fieldcontrol.paddingInlineEnd.value}',\n },\n backgroundColor: { value: 'transparent' },\n borderColor: { value: '{components.fieldcontrol.borderColor.value}' },\n borderWidth: { value: '{components.fieldcontrol.borderWidth.value}' },\n borderStyle: { value: '{components.fieldcontrol.borderStyle.value}' },\n borderRadius: { value: '{components.fieldcontrol.borderRadius.value}' },\n color: { value: '{colors.font.primary.value}' },\n _hover: {\n color: { value: '{colors.font.focus.value}' },\n backgroundColor: { value: '{colors.primary.10.value}' },\n borderColor: { value: '{colors.primary.60.value}' },\n },\n _focus: {\n color: { value: '{colors.font.focus.value}' },\n backgroundColor: { value: '{colors.primary.10.value}' },\n borderColor: { value: '{colors.border.focus.value}' },\n boxShadow: { value: '{components.fieldcontrol._focus.boxShadow.value}' },\n },\n _active: {\n color: { value: '{colors.font.active.value}' },\n backgroundColor: { value: '{colors.primary.20.value}' },\n borderColor: { value: '{colors.primary.100.value}' },\n },\n _loading: {\n color: { value: '{colors.font.disabled.value}' },\n backgroundColor: { value: 'transparent' },\n borderColor: { value: '{colors.border.tertiary.value}' },\n },\n _disabled: {\n color: { value: '{colors.font.disabled.value}' },\n backgroundColor: { value: 'transparent' },\n borderColor: { value: '{colors.border.tertiary.value}' },\n },\n // variations\n outlined: {\n info: {\n borderColor: { value: '{colors.blue.60.value}' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.blue.100}' },\n _hover: {\n borderColor: { value: '{colors.blue.60.value}' },\n backgroundColor: { value: '{colors.blue.10.value}' },\n color: { value: '{colors.blue.100.value}' },\n },\n _focus: {\n borderColor: { value: '{colors.blue.100.value}' },\n backgroundColor: { value: '{colors.blue.10.value}' },\n color: { value: '{colors.blue.100.value}' },\n boxShadow: {\n value: '{components.fieldcontrol.info._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: '{colors.blue.100.value}' },\n backgroundColor: { value: '{colors.blue.20.value}' },\n color: { value: '{colors.blue.100.value}' },\n },\n },\n warning: {\n borderColor: { value: '{colors.orange.60.value}' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.orange.100}' },\n _hover: {\n borderColor: { value: '{colors.orange.60.value}' },\n backgroundColor: { value: '{colors.orange.10.value}' },\n color: { value: '{colors.orange.100.value}' },\n },\n _focus: {\n borderColor: { value: '{colors.orange.100.value}' },\n backgroundColor: { value: '{colors.orange.10.value}' },\n color: { value: '{colors.orange.100.value}' },\n boxShadow: {\n value: '{components.fieldcontrol.warning._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: '{colors.orange.100.value}' },\n backgroundColor: { value: '{colors.orange.20.value}' },\n color: { value: '{colors.orange.100.value}' },\n },\n },\n success: {\n borderColor: { value: '{colors.green.60.value}' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.green.100}' },\n _hover: {\n borderColor: { value: '{colors.green.60.value}' },\n backgroundColor: { value: '{colors.green.10.value}' },\n color: { value: '{colors.green.100.value}' },\n },\n _focus: {\n borderColor: { value: '{colors.green.100.value}' },\n backgroundColor: { value: '{colors.green.10.value}' },\n color: { value: '{colors.green.100.value}' },\n boxShadow: {\n value: '{components.fieldcontrol.success._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: '{colors.green.100.value}' },\n backgroundColor: { value: '{colors.green.20.value}' },\n color: { value: '{colors.green.100.value}' },\n },\n },\n error: {\n borderColor: { value: '{colors.red.80.value}' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.red.100}' },\n _hover: {\n borderColor: { value: '{colors.red.80.value}' },\n backgroundColor: { value: '{colors.red.10.value}' },\n color: { value: '{colors.red.100.value}' },\n },\n _focus: {\n borderColor: { value: '{colors.red.100.value}' },\n backgroundColor: { value: '{colors.red.10.value}' },\n color: { value: '{colors.red.100.value}' },\n boxShadow: {\n value: '{components.fieldcontrol._error._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: '{colors.red.100.value}' },\n backgroundColor: { value: '{colors.red.20.value}' },\n color: { value: '{colors.red.100.value}' },\n },\n },\n overlay: {\n borderColor: { value: '{colors.overlay.60.value}' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.font.primary.value}' },\n _hover: {\n borderColor: { value: '{colors.overlay.60.value}' },\n backgroundColor: { value: '{colors.overlay.5.value}' },\n color: { value: '{colors.neutral.90.value}' },\n },\n _focus: {\n borderColor: { value: '{colors.overlay.90.value}' },\n backgroundColor: { value: '{colors.overlay.5.value}' },\n color: { value: '{colors.neutral.90.value}' },\n boxShadow: {\n value: '{components.fieldcontrol.overlay._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: '{colors.overlay.90.value}' },\n backgroundColor: { value: '{colors.overlay.10.value}' },\n color: { value: '{colors.neutral.100.value}' },\n },\n },\n },\n primary: {\n borderColor: { value: 'transparent' },\n borderWidth: { value: '{borderWidths.small.value}' },\n borderStyle: { value: 'solid' },\n backgroundColor: { value: '{colors.primary.80.value}' },\n color: { value: '{colors.font.inverse.value}' },\n _disabled: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.background.disabled.value}' },\n color: { value: '{colors.font.disabled.value}' },\n },\n _loading: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.background.disabled.value}' },\n color: { value: '{colors.font.disabled.value}' },\n },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.primary.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.primary.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n boxShadow: { value: '{components.fieldcontrol._focus.boxShadow.value}' },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.primary.100.value}' },\n color: { value: '{colors.font.inverse.value}' },\n },\n info: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.blue.80}' },\n color: { value: '{colors.font.inverse.value}' },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.blue.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.blue.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n boxShadow: {\n value: '{components.fieldcontrol.info._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.blue.100.value}' },\n color: { value: '{colors.font.inverse.value}' },\n },\n },\n warning: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.orange.80}' },\n color: { value: '{colors.font.inverse.value}' },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.orange.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.orange.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n boxShadow: {\n value: '{components.fieldcontrol.overlay._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.orange.100.value}' },\n color: { value: '{colors.font.inverse.value}' },\n },\n },\n error: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.red.80}' },\n color: { value: '{colors.font.inverse.value}' },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.red.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.red.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n boxShadow: {\n value: '{components.fieldcontrol._error._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.red.100.value}' },\n color: { value: '{colors.font.inverse.value}' },\n },\n },\n success: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.green.80}' },\n color: { value: '{colors.font.inverse.value}' },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.green.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.green.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n boxShadow: {\n value: '{components.fieldcontrol.success._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.green.100.value}' },\n color: { value: '{colors.font.inverse.value}' },\n },\n },\n overlay: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.overlay.70}' },\n color: { value: '{colors.font.inverse.value}' },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.overlay.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.overlay.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n boxShadow: {\n value: '{components.fieldcontrol.overlay._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.overlay.90.value}' },\n color: { value: '{colors.font.inverse.value}' },\n },\n },\n },\n menu: {\n borderWidth: { value: '{space.zero.value}' },\n backgroundColor: { value: 'transparent' },\n justifyContent: { value: 'start' },\n // Focus and hover styles are identical for menu variation\n // because for Menu primitive, menu items are forced to be focused even\n // for mouse interactions, making it impossible to distinguish the two interactions\n _hover: {\n color: { value: '{colors.font.inverse.value}' },\n backgroundColor: { value: '{colors.primary.80.value}' },\n },\n _focus: {\n color: { value: '{colors.font.inverse.value}' },\n backgroundColor: { value: '{colors.primary.80.value}' },\n },\n _active: {\n color: { value: '{colors.font.inverse.value}' },\n backgroundColor: { value: '{colors.primary.90.value}' },\n },\n _disabled: {\n color: { value: '{colors.font.disabled.value}' },\n },\n },\n link: {\n backgroundColor: { value: 'transparent' },\n borderColor: { value: 'transparent' },\n borderWidth: { value: '{borderWidths.small.value}' },\n color: { value: '{colors.font.interactive.value}' },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.primary.10.value}' },\n color: { value: '{colors.font.hover.value}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.primary.10.value}' },\n color: { value: '{colors.font.focus.value}' },\n boxShadow: { value: '{components.fieldcontrol._focus.boxShadow.value}' },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.primary.20.value}' },\n color: { value: '{colors.font.active.value}' },\n },\n _disabled: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.font.disabled.value}' },\n },\n _loading: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.font.disabled.value}' },\n },\n info: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.blue.100}' },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.blue.10.value}' },\n color: { value: '{colors.blue.90.value}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.blue.10.value}' },\n color: { value: '{colors.blue.100.value}' },\n boxShadow: {\n value: '{components.fieldcontrol.info._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.blue.20.value}' },\n color: { value: '{colors.blue.100.value}' },\n },\n },\n warning: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.orange.100}' },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.orange.10.value}' },\n color: { value: '{colors.orange.90.value}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.orange.10.value}' },\n color: { value: '{colors.orange.100.value}' },\n boxShadow: {\n value: '{components.fieldcontrol.warning._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.orange.20.value}' },\n color: { value: '{colors.orange.100.value}' },\n },\n },\n success: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.green.100}' },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.green.10.value}' },\n color: { value: '{colors.green.90.value}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.green.10.value}' },\n color: { value: '{colors.green.100.value}' },\n boxShadow: {\n value: '{components.fieldcontrol.success._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.green.20.value}' },\n color: { value: '{colors.green.100.value}' },\n },\n },\n error: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.red.100}' },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.red.10.value}' },\n color: { value: '{colors.red.90.value}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.red.10.value}' },\n color: { value: '{colors.red.100.value}' },\n boxShadow: {\n value: '{components.fieldcontrol._error._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.red.20.value}' },\n color: { value: '{colors.red.100.value}' },\n },\n },\n overlay: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.neutral.100}' },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.overlay.5.value}' },\n color: { value: '{colors.overlay.80.value}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.overlay.5.value}' },\n color: { value: '{colors.overlay.90.value}' },\n boxShadow: {\n value: '{components.fieldcontrol.overlay._focus.boxShadow.value}',\n },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.overlay.10.value}' },\n color: { value: '{colors.overlay.90.value}' },\n },\n },\n },\n warning: {\n backgroundColor: { value: 'transparent' },\n borderColor: { value: '{colors.red.60}' },\n borderWidth: { value: '{borderWidths.small}' },\n color: { value: '{colors.red.60}' },\n _hover: {\n borderColor: { value: '{colors.red.80}' },\n backgroundColor: { value: '{colors.red.10}' },\n color: { value: '{colors.font.error}' },\n },\n _focus: {\n borderColor: { value: '{colors.red.80}' },\n backgroundColor: { value: '{colors.red.10}' },\n color: { value: '{colors.red.80}' },\n boxShadow: { value: '{components.fieldcontrol._error._focus.boxShadow}' },\n },\n _active: {\n borderColor: { value: '{colors.red.100}' },\n backgroundColor: { value: '{colors.red.20}' },\n color: { value: '{colors.red.100}' },\n },\n _disabled: {\n borderColor: { value: '{colors.border.tertiary}' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.font.disabled}' },\n },\n _loading: {\n borderColor: { value: '{colors.border.tertiary}' },\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.font.disabled}' },\n },\n },\n destructive: {\n borderColor: { value: 'transparent' },\n borderWidth: { value: '{borderWidths.small}' },\n borderStyle: { value: 'solid' },\n backgroundColor: { value: '{colors.red.60}' },\n color: { value: '{colors.font.inverse}' },\n _disabled: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.background.disabled}' },\n color: { value: '{colors.font.disabled}' },\n },\n _loading: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.background.disabled}' },\n color: { value: '{colors.font.disabled}' },\n },\n _hover: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.red.80}' },\n color: { value: '{colors.font.inverse}' },\n },\n _focus: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.red.80}' },\n color: { value: '{colors.font.inverse}' },\n boxShadow: { value: '{components.fieldcontrol._error._focus.boxShadow}' },\n },\n _active: {\n borderColor: { value: 'transparent' },\n backgroundColor: { value: '{colors.red.100}' },\n color: { value: '{colors.font.inverse}' },\n },\n },\n // sizes\n small: {\n fontSize: { value: '{components.fieldcontrol.small.fontSize.value}' },\n paddingBlockStart: {\n value: '{components.fieldcontrol.small.paddingBlockStart.value}',\n },\n paddingBlockEnd: {\n value: '{components.fieldcontrol.small.paddingBlockEnd.value}',\n },\n paddingInlineStart: {\n value: '{components.fieldcontrol.small.paddingInlineStart.value}',\n },\n paddingInlineEnd: {\n value: '{components.fieldcontrol.small.paddingInlineEnd.value}',\n },\n },\n large: {\n fontSize: { value: '{components.fieldcontrol.large.fontSize.value}' },\n paddingBlockStart: {\n value: '{components.fieldcontrol.large.paddingBlockStart.value}',\n },\n paddingBlockEnd: {\n value: '{components.fieldcontrol.large.paddingBlockEnd.value}',\n },\n paddingInlineStart: {\n value: '{components.fieldcontrol.large.paddingInlineStart.value}',\n },\n paddingInlineEnd: {\n value: '{components.fieldcontrol.large.paddingInlineEnd.value}',\n },\n },\n loaderWrapper: {\n alignItems: {\n value: 'center',\n },\n gap: {\n value: '{space.xs.value}',\n },\n },\n};\n\nexport { button };\n","const card = {\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderRadius: { value: '{radii.xs.value}' },\n borderWidth: { value: '0' },\n borderStyle: { value: 'solid' },\n borderColor: { value: 'transparent' },\n boxShadow: { value: 'none' },\n padding: { value: '{space.medium.value}' },\n outlined: {\n backgroundColor: { value: '{components.card.backgroundColor.value}' },\n borderRadius: { value: '{radii.xs.value}' },\n borderWidth: { value: '{borderWidths.small.value}' },\n borderStyle: { value: 'solid' },\n borderColor: { value: '{colors.border.primary.value}' },\n boxShadow: { value: '{components.card.boxShadow.value}' },\n },\n elevated: {\n backgroundColor: { value: '{components.card.backgroundColor.value}' },\n borderRadius: { value: '{radii.xs.value}' },\n borderWidth: { value: '0' },\n borderStyle: { value: 'solid' },\n borderColor: { value: 'transparent' },\n boxShadow: { value: '{shadows.medium.value}' },\n },\n};\n\nexport { card };\n","const checkbox = {\n cursor: { value: 'pointer' },\n alignItems: { value: 'center' },\n _disabled: {\n cursor: {\n value: 'not-allowed',\n },\n },\n button: {\n position: { value: 'relative' },\n alignItems: { value: 'center' },\n justifyContent: { value: 'center' },\n color: { value: '{colors.font.inverse.value}' },\n before: {\n width: { value: '100%' },\n height: { value: '100%' },\n borderWidth: { value: '{borderWidths.medium.value}' },\n borderRadius: { value: '20%' },\n borderStyle: { value: 'solid' },\n borderColor: { value: '{colors.border.primary.value}' },\n },\n _focus: {\n outlineColor: { value: '{colors.transparent.value}' },\n outlineStyle: { value: 'solid' },\n outlineWidth: { value: '{outlineWidths.medium.value}' },\n outlineOffset: { value: '{outlineOffsets.medium.value}' },\n borderColor: { value: '{colors.border.focus.value}' },\n boxShadow: { value: '{components.fieldcontrol._focus.boxShadow.value}' },\n },\n _disabled: {\n borderColor: { value: '{colors.border.disabled.value}' },\n },\n _error: {\n borderColor: { value: '{colors.border.error.value}' },\n _focus: {\n borderColor: { value: '{colors.border.error.value}' },\n boxShadow: {\n value: '{components.fieldcontrol._error._focus.boxShadow.value}',\n },\n },\n },\n },\n icon: {\n backgroundColor: { value: '{colors.primary.80.value}' },\n borderRadius: { value: '20%' },\n opacity: { value: '{opacities.0.value}' },\n transform: { value: 'scale(0)' },\n transitionProperty: { value: 'all' },\n transitionDuration: { value: '{time.short.value}' },\n transitionTimingFunction: { value: 'ease-in-out' },\n _checked: {\n opacity: { value: '{opacities.100.value}' },\n transform: { value: 'scale(1)' },\n _disabled: {\n backgroundColor: { value: '{colors.background.disabled.value}' },\n },\n },\n _indeterminate: {\n opacity: { value: '{opacities.100.value}' },\n transform: { value: 'scale(1)' },\n _disabled: {\n backgroundColor: { value: '{colors.background.disabled.value}' },\n },\n },\n },\n label: {\n color: { value: '{components.text.color.value}' },\n _disabled: {\n color: {\n value: '{colors.font.disabled.value}',\n },\n },\n },\n};\n\nexport { checkbox };\n","const checkboxfield = {\n alignItems: { value: 'flex-start' },\n alignContent: { value: 'center' },\n flexDirection: { value: 'column' },\n justifyContent: { value: 'center' },\n};\n\nexport { checkboxfield };\n","//we are reusing the types from the nested components but new tokens need to be created that reference the previous tokens so that they can inherit the needed values but can be overwritten and only effect the collection component.\n//only a subset of the design tokens of the nested components are being exposed, this can be expanded later.\nconst collection = {\n pagination: {\n current: {\n color: { value: '{components.pagination.current.color}' },\n backgroundColor: {\n value: '{components.pagination.current.backgroundColor}',\n },\n },\n button: {\n color: { value: '{components.pagination.button.color}' },\n _hover: {\n backgroundColor: {\n value: '{components.pagination.button.hover.backgroundColor}',\n },\n color: { value: '{components.pagination.button.hover.color}' },\n },\n _disabled: {\n color: { value: '{components.pagination.button.disabled.color}' },\n },\n },\n },\n search: {\n input: {\n color: { value: '{components.searchfield.color}' },\n },\n button: {\n color: { value: '{components.searchfield.button.color}' },\n _active: {\n backgroundColor: {\n value: '{components.searchfield.button._active.backgroundColor}',\n },\n borderColor: {\n value: '{components.searchfield.button._active.borderColor}',\n },\n color: { value: '{components.searchfield.button._active.color}' },\n },\n _disabled: {\n backgroundColor: {\n value: '{components.searchfield.button._disabled.backgroundColor}',\n },\n borderColor: {\n value: '{components.searchfield.button._disabled.borderColor}',\n },\n color: {\n value: '{components.searchfield.button._disabled.color}',\n },\n },\n _focus: {\n backgroundColor: {\n value: '{components.searchfield.button._focus.backgroundColor}',\n },\n borderColor: {\n value: '{components.searchfield.button._focus.borderColor}',\n },\n color: { value: '{components.searchfield.button._focus.color}' },\n },\n _hover: {\n backgroundColor: {\n value: '{components.searchfield.button._hover.backgroundColor}',\n },\n borderColor: {\n value: '{components.searchfield.button._hover.borderColor}',\n },\n color: { value: '{components.searchfield.button._hover.color}' },\n },\n },\n },\n};\n\nexport { collection };\n","const copy = {\n fontSize: { value: '{fontSizes.xs}' },\n gap: { value: '{space.relative.medium}' },\n svg: {\n path: {\n fill: {\n value: '{colors.font.primary}',\n },\n },\n },\n toolTip: {\n bottom: { value: '{space.large}' },\n color: { value: '{colors.teal.100}' },\n fontSize: { value: '{fontSizes.xxs}' },\n },\n};\n\nexport { copy };\n","const dialcodeselect = {\n height: {\n value: '{space.relative.full.value}',\n },\n};\n\nexport { dialcodeselect };\n","const divider = {\n borderStyle: { value: 'solid' },\n borderColor: { value: '{colors.border.primary.value}' },\n borderWidth: { value: '{borderWidths.medium.value}' },\n label: {\n color: { value: '{colors.font.tertiary.value}' },\n paddingInline: { value: '{space.medium.value}' },\n fontSize: { value: '{fontSizes.small.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n },\n small: {\n borderWidth: { value: '{borderWidths.small.value}' },\n },\n large: {\n borderWidth: { value: '{borderWidths.large.value}' },\n },\n opacity: {\n value: '{opacities.60.value}',\n },\n};\n\nexport { divider };\n","const dropzone = {\n backgroundColor: { value: '{colors.background.primary}' },\n borderRadius: { value: '{radii.small}' },\n borderColor: { value: '{colors.border.primary}' },\n borderStyle: { value: 'dashed' },\n borderWidth: { value: '{borderWidths.small}' },\n color: { value: '{colors.font.primary}' },\n gap: { value: '{space.small}' },\n paddingBlock: { value: '{space.xl}' },\n paddingInline: { value: '{space.large}' },\n textAlign: { value: 'center' },\n _active: {\n backgroundColor: { value: '{colors.primary.10}' },\n borderRadius: { value: '{components.dropzone.borderRadius}' },\n borderColor: { value: '{colors.border.pressed}' },\n borderStyle: { value: '{components.dropzone.borderStyle}' },\n borderWidth: { value: '{components.dropzone.borderWidth}' },\n color: { value: '{colors.font.primary}' },\n },\n _disabled: {\n backgroundColor: { value: '{colors.background.disabled}' },\n borderRadius: { value: '{components.dropzone.borderRadius}' },\n borderColor: { value: '{colors.border.disabled}' },\n borderStyle: { value: '{components.dropzone.borderStyle}' },\n borderWidth: { value: '{components.dropzone.borderWidth}' },\n color: { value: '{colors.font.disabled}' },\n },\n accepted: {\n backgroundColor: { value: '{colors.background.success}' },\n borderRadius: { value: '{components.dropzone.borderRadius}' },\n borderColor: { value: '{colors.border.success}' },\n borderStyle: { value: '{components.dropzone.borderStyle}' },\n borderWidth: { value: '{components.dropzone.borderWidth}' },\n color: { value: '{colors.font.success}' },\n },\n rejected: {\n backgroundColor: { value: '{colors.background.error}' },\n borderRadius: { value: '{components.dropzone.borderRadius}' },\n borderColor: { value: '{colors.border.pressed}' },\n borderStyle: { value: '{components.dropzone.borderStyle}' },\n borderWidth: { value: '{components.dropzone.borderWidth}' },\n color: { value: '{colors.font.error}' },\n },\n};\n\nexport { dropzone };\n","const accordion = {\n backgroundColor: { value: '{colors.background.primary.value}' },\n item: {\n borderColor: { value: '{colors.border.secondary.value}' },\n borderWidth: { value: '{borderWidths.small.value}' },\n borderStyle: { value: 'solid' },\n borderRadius: { value: '{radii.small.value}' },\n trigger: {\n alignItems: { value: 'center' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n color: { value: 'inherit' },\n gap: { value: '{space.small.value}' },\n justifyContent: { value: 'space-between' },\n paddingBlock: { value: '{space.xs.value}' },\n paddingInline: { value: '{space.small.value}' },\n _hover: {\n color: { value: 'inherit' },\n backgroundColor: { value: '{colors.overlay.5.value}' },\n },\n _focus: {\n borderColor: { value: '{colors.border.focus.value}' },\n boxShadow: {\n value: {\n offsetX: '0',\n offsetY: '0',\n blurRadius: '0',\n spreadRadius: '2px',\n color: '{colors.border.focus.value}',\n },\n },\n },\n },\n content: {\n color: { value: 'inherit' },\n paddingInline: { value: '{space.small.value}' },\n paddingBlockEnd: { value: '{space.small.value}' },\n paddingBlockStart: { value: '{space.xxxs.value}' },\n },\n icon: {\n color: { value: '{colors.font.tertiary.value}' },\n transitionDuration: { value: '{time.medium.value}' },\n transitionTimingFunction: { value: 'cubic-bezier(0.87, 0, 0.13, 1)' },\n },\n },\n};\n\nexport { accordion };\n","const field = {\n // default styles\n gap: { value: '{space.xs.value}' },\n fontSize: { value: '{fontSizes.medium.value}' },\n flexDirection: { value: 'column' },\n // Adjust base fontSize and gap for small and large sizes\n small: {\n gap: { value: '{space.xxxs.value}' },\n fontSize: { value: '{fontSizes.small.value}' },\n },\n large: {\n gap: { value: '{space.small.value}' },\n fontSize: { value: '{fontSizes.large.value}' },\n },\n label: {\n color: { value: '{colors.font.secondary.value}' },\n },\n};\n\nexport { field };\n","const fieldcontrol = {\n borderStyle: { value: 'solid' },\n borderColor: { value: '{colors.border.primary.value}' },\n borderWidth: { value: '{borderWidths.small.value}' },\n borderRadius: { value: '{radii.small.value}' },\n color: { value: '{colors.font.primary.value}' },\n paddingBlockStart: {\n value: '{space.xs.value}',\n },\n paddingBlockEnd: {\n value: '{space.xs.value}',\n },\n paddingInlineStart: {\n value: '{space.medium.value}',\n },\n paddingInlineEnd: {\n value: '{space.medium.value}',\n },\n fontSize: { value: '{components.field.fontSize.value}' },\n lineHeight: { value: '{lineHeights.medium.value}' },\n transitionDuration: { value: '{time.medium.value}' },\n outlineColor: { value: '{colors.transparent.value}' },\n outlineStyle: { value: 'solid' },\n outlineWidth: { value: '{outlineWidths.medium.value}' },\n outlineOffset: { value: '{outlineOffsets.medium.value}' },\n small: {\n fontSize: { value: '{components.field.small.fontSize.value}' },\n paddingBlockStart: {\n value: '{space.xxs.value}',\n },\n paddingBlockEnd: {\n value: '{space.xxs.value}',\n },\n paddingInlineStart: {\n value: '{space.small.value}',\n },\n paddingInlineEnd: {\n value: '{space.small.value}',\n },\n },\n large: {\n fontSize: { value: '{components.field.large.fontSize.value}' },\n paddingBlockStart: {\n value: '{space.xs.value}',\n },\n paddingBlockEnd: {\n value: '{space.xs.value}',\n },\n paddingInlineStart: {\n value: '{space.medium.value}',\n },\n paddingInlineEnd: {\n value: '{space.medium.value}',\n },\n },\n quiet: {\n borderStyle: { value: 'none' },\n borderInlineStart: { value: 'none' },\n borderInlineEnd: { value: 'none' },\n borderBlockStart: { value: 'none' },\n borderRadius: { value: '0' },\n _focus: {\n borderBlockEndColor: { value: 'transparent' },\n boxShadow: {\n value: '{components.fieldcontrol._focus.boxShadow.value}',\n },\n },\n _error: {\n borderBlockEndColor: { value: '{colors.border.error.value}' },\n _focus: {\n borderBlockEndColor: { value: 'transparent' },\n boxShadow: {\n value: '{components.fieldcontrol._error._focus.boxShadow.value}',\n },\n },\n },\n },\n _focus: {\n // These focus styles have been calibrated to create\n // a highly visible focus indicator per WCAG 2.2 guidlines:\n // See: https://www.w3.org/TR/WCAG22/#focus-appearance\n //\n // Key features:\n // * Focus indicator area is at least the 2 CSS px perimeter around the component.\n // * Contrast between focused and unfocused area of contrast has a ratio of 3:1\n //\n // IMPORTANT: Must recalibrate if `colors.border.focus` are changed\n borderColor: { value: '{colors.border.focus.value}' },\n boxShadow: {\n value: {\n offsetX: '0px',\n offsetY: '0px',\n blurRadius: '0px',\n spreadRadius: '2px',\n color: '{colors.border.focus.value}',\n },\n },\n },\n _disabled: {\n color: { value: '{colors.font.disabled.value}' },\n cursor: { value: 'not-allowed' },\n borderColor: { value: '{colors.transparent.value}' },\n backgroundColor: { value: '{colors.background.disabled.value}' },\n },\n _error: {\n borderColor: { value: '{colors.border.error.value}' },\n color: { value: '{colors.font.error.value}' },\n _focus: {\n boxShadow: {\n value: {\n offsetX: '0px',\n offsetY: '0px',\n blurRadius: '0px',\n spreadRadius: '2px',\n color: '{colors.border.error.value}',\n },\n },\n },\n },\n info: {\n _focus: {\n boxShadow: {\n value: {\n offsetX: '0px',\n offsetY: '0px',\n blurRadius: '0px',\n spreadRadius: '2px',\n color: '{colors.blue.100.value}',\n },\n },\n },\n },\n warning: {\n _focus: {\n boxShadow: {\n value: {\n offsetX: '0px',\n offsetY: '0px',\n blurRadius: '0px',\n spreadRadius: '2px',\n color: '{colors.orange.100.value}',\n },\n },\n },\n },\n success: {\n _focus: {\n boxShadow: {\n value: {\n offsetX: '0px',\n offsetY: '0px',\n blurRadius: '0px',\n spreadRadius: '2px',\n color: '{colors.green.100.value}',\n },\n },\n },\n },\n overlay: {\n _focus: {\n boxShadow: {\n value: {\n offsetX: '0px',\n offsetY: '0px',\n blurRadius: '0px',\n spreadRadius: '2px',\n color: '{colors.overlay.90.value}',\n },\n },\n },\n },\n};\n\nexport { fieldcontrol };\n","const fieldgroup = {\n gap: { value: '{space.zero.value}' },\n vertical: {\n alignItems: { value: 'center' },\n },\n outer: {\n alignItems: { value: 'center' },\n },\n};\n\nexport { fieldgroup };\n","const fieldset = {\n backgroundColor: { value: 'transparent' },\n borderRadius: { value: '{radii.xs.value}' },\n flexDirection: {\n value: 'column',\n },\n gap: { value: '{components.field.gap.value}' },\n legend: {\n color: { value: '{colors.font.primary.value}' },\n fontSize: { value: '{components.field.fontSize.value}' },\n fontWeight: { value: '{fontWeights.bold.value}' },\n lineHeight: { value: '{lineHeights.medium.value}' },\n small: {\n fontSize: '{components.field.small.fontSize.value}',\n },\n large: {\n fontSize: '{components.field.large.fontSize.value}',\n },\n },\n outlined: {\n padding: '{space.medium.value}',\n borderColor: '{colors.neutral.40.value}',\n borderWidth: '{borderWidths.small.value}',\n borderStyle: 'solid',\n small: {\n padding: '{space.small.value}',\n },\n large: {\n padding: '{space.large.value}',\n },\n },\n small: {\n gap: '{components.field.small.gap.value}',\n },\n large: {\n gap: '{components.field.large.gap.value}',\n },\n};\n\nexport { fieldset };\n","const fieldmessages = {\n error: {\n color: { value: '{colors.font.error.value}' },\n fontSize: { value: '{fontSizes.small.value}' },\n },\n description: {\n color: { value: '{colors.font.secondary.value}' },\n fontStyle: { value: 'italic' },\n fontSize: { value: '{fontSizes.small.value}' },\n },\n};\n\nexport { fieldmessages };\n","const fileuploader = {\n dropzone: {\n backgroundColor: { value: '{colors.background.primary}' },\n borderRadius: { value: '{radii.small}' },\n borderColor: { value: '{colors.border.primary}' },\n borderStyle: { value: 'dashed' },\n borderWidth: { value: '{borderWidths.small}' },\n gap: { value: '{space.small}' },\n paddingBlock: { value: '{space.xl}' },\n paddingInline: { value: '{space.large}' },\n textAlign: { value: 'center' },\n _active: {\n backgroundColor: { value: '{colors.primary.10}' },\n borderRadius: {\n value: '{components.fileuploader.dropzone.borderRadius}',\n },\n borderColor: { value: '{colors.border.pressed}' },\n borderStyle: {\n value: '{components.fileuploader.dropzone.borderStyle}',\n },\n borderWidth: { value: '{borderWidths.medium}' },\n },\n icon: {\n color: { value: '{colors.border.primary}' },\n fontSize: { value: '{fontSizes.xxl}' },\n },\n text: {\n color: { value: '{colors.font.tertiary}' },\n fontSize: { value: '{fontSizes.medium}' },\n fontWeight: { value: '{fontWeights.bold}' },\n },\n },\n file: {\n backgroundColor: { value: '{colors.background.primary}' },\n borderRadius: { value: '{radii.small}' },\n borderColor: { value: '{colors.border.primary}' },\n borderStyle: { value: 'solid' },\n borderWidth: { value: '{borderWidths.small}' },\n paddingBlock: { value: '{space.xs}' },\n paddingInline: { value: '{space.small}' },\n gap: { value: '{space.small}' },\n alignItems: { value: 'baseline' },\n name: {\n fontSize: { value: '{fontSizes.medium}' },\n fontWeight: { value: '{fontWeights.bold}' },\n color: { value: '{colors.font.primary}' },\n },\n size: {\n fontSize: { value: '{fontSizes.small}' },\n fontWeight: { value: '{fontWeights.normal}' },\n color: { value: '{colors.font.tertiary}' },\n },\n image: {\n width: { value: '{space.xxl}' },\n height: { value: '{space.xxl}' },\n backgroundColor: { value: '{colors.background.secondary}' },\n color: { value: '{colors.font.tertiary}' },\n borderRadius: { value: '{radii.small}' },\n },\n },\n filelist: {\n flexDirection: { value: 'column' },\n gap: { value: '{space.small}' },\n },\n loader: {\n strokeLinecap: { value: 'round' },\n strokeEmpty: { value: '{colors.border.secondary}' },\n strokeFilled: { value: '{components.loader.strokeFilled}' },\n strokeWidth: { value: '{borderWidths.large}' },\n },\n previewer: {\n backgroundColor: { value: '{colors.background.primary}' },\n borderColor: { value: '{colors.border.primary}' },\n borderStyle: { value: 'solid' },\n borderWidth: { value: '{borderWidths.small}' },\n borderRadius: { value: '{radii.small}' },\n paddingBlock: { value: '{space.zero}' },\n paddingInline: { value: '{space.zero}' },\n maxHeight: { value: '40rem' },\n maxWidth: { value: 'auto' },\n text: {\n fontSize: { value: '{fontSizes.medium}' },\n fontWeight: { value: '{fontWeights.bold}' },\n color: { value: '{colors.font.primary}' },\n },\n body: {\n paddingBlock: { value: '{space.medium}' },\n paddingInline: { value: '{space.medium}' },\n gap: { value: '{space.small}' },\n },\n footer: {\n justifyContent: { value: 'flex-end' },\n },\n },\n};\n\nexport { fileuploader };\n","const flex = {\n gap: { value: '{space.medium.value}' },\n justifyContent: { value: 'normal' },\n alignItems: { value: 'stretch' },\n alignContent: { value: 'normal' },\n flexWrap: { value: 'nowrap' },\n};\n\nexport { flex };\n","const heading = {\n color: { value: '{colors.font.primary.value}' },\n lineHeight: { value: '{lineHeights.small.value}' },\n 1: {\n fontSize: { value: '{fontSizes.xxxxl.value}' },\n fontWeight: { value: '{fontWeights.light.value}' },\n },\n 2: {\n fontSize: { value: '{fontSizes.xxxl.value}' },\n fontWeight: { value: '{fontWeights.normal.value}' },\n },\n 3: {\n fontSize: { value: '{fontSizes.xxl.value}' },\n fontWeight: { value: '{fontWeights.medium.value}' },\n },\n 4: {\n fontSize: { value: '{fontSizes.xl.value}' },\n fontWeight: { value: '{fontWeights.semibold.value}' },\n },\n 5: {\n fontSize: { value: '{fontSizes.large.value}' },\n fontWeight: { value: '{fontWeights.bold.value}' },\n },\n 6: {\n fontSize: { value: '{fontSizes.medium.value}' },\n fontWeight: { value: '{fontWeights.extrabold.value}' },\n },\n};\n\nexport { heading };\n","const highlightmatch = {\n highlighted: {\n fontWeight: { value: '{fontWeights.bold}' },\n },\n};\n\nexport { highlightmatch };\n","const icon = {\n lineHeight: { value: 1 },\n height: { value: '1em' }, // Should match height of parent container font-size\n};\n\nexport { icon };\n","const input = {\n color: { value: '{components.fieldcontrol.color.value}' },\n borderColor: { value: '{components.fieldcontrol.borderColor.value}' },\n fontSize: { value: '{components.fieldcontrol.fontSize.value}' },\n _focus: {\n borderColor: {\n value: '{components.fieldcontrol._focus.borderColor.value}',\n },\n },\n};\n\nexport { input };\n","const image = {\n maxWidth: { value: '100%' },\n height: { value: 'auto' },\n objectFit: { value: 'initial' },\n objectPosition: { value: 'initial' },\n};\n\nexport { image };\n","const inappmessaging = {\n banner: {\n height: { value: '150px ' },\n width: { value: '400px ' },\n },\n button: {\n backgroundColor: { value: '#e8e8e8' },\n borderRadius: { value: '5px' },\n color: { value: 'black' },\n },\n dialog: {\n height: { value: '50vh' },\n minHeight: { value: '400px' },\n minWidth: { value: '400px' },\n width: { value: '30vw' },\n },\n header: {\n fontSize: { value: '{fontSizes.medium.value}' },\n fontWeight: { value: '{fontWeights.extrabold.value}' },\n },\n};\n\nexport { inappmessaging };\n","const link = {\n active: { color: { value: '{colors.font.active.value}' } },\n color: { value: '{colors.font.interactive.value}' },\n focus: { color: { value: '{colors.font.focus.value}' } },\n hover: { color: { value: '{colors.font.hover.value}' } },\n visited: { color: { value: '{colors.font.interactive.value}' } },\n};\n\nexport { link };\n","const liveness = {\n cameraModule: {\n backgroundColor: { value: '{colors.background.primary.value}' },\n },\n};\n\nexport { liveness };\n","const loader = {\n width: { value: '{fontSizes.medium.value}' },\n height: { value: '{fontSizes.medium.value}' },\n fontSize: { value: '{fontSizes.xs.value}' },\n strokeEmpty: { value: '{colors.neutral.20.value}' },\n strokeFilled: { value: '{colors.primary.80.value}' },\n strokeLinecap: { value: 'round' },\n animationDuration: { value: '1s' },\n small: {\n width: { value: '{fontSizes.small.value}' },\n height: { value: '{fontSizes.small.value}' },\n fontSize: { value: '{fontSizes.xxs.value}' },\n },\n large: {\n width: { value: '{fontSizes.large.value}' },\n height: { value: '{fontSizes.large.value}' },\n fontSize: { value: '{fontSizes.small.value}' },\n },\n linear: {\n width: { value: '100%' },\n minWidth: { value: '5rem' },\n fontSize: { value: '{fontSizes.xxs.value}' },\n strokeWidth: { value: '{fontSizes.xxs.value}' },\n strokeFilled: { value: '{colors.primary.80.value}' },\n strokeEmpty: { value: '{colors.neutral.20.value}' },\n strokeLinecap: { value: 'round' },\n animationDuration: { value: '1s' },\n small: {\n strokeWidth: { value: '{fontSizes.xxxs.value}' },\n fontSize: { value: '{fontSizes.xxxs.value}' },\n },\n large: {\n strokeWidth: { value: '{fontSizes.xs.value}' },\n fontSize: { value: '{fontSizes.xs.value}' },\n },\n },\n text: {\n fill: { value: '{colors.font.primary.value}' },\n },\n};\n\nexport { loader };\n","const menu = {\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderRadius: { value: '{radii.medium.value}' },\n borderWidth: { value: '{borderWidths.small.value}' },\n borderStyle: { value: 'solid' },\n borderColor: { value: '{colors.border.primary.value}' },\n boxShadow: { value: '{shadows.large.value}' },\n flexDirection: { value: 'column' },\n gap: { value: '{space.zero.value}' },\n maxWidth: { value: '30rem' },\n minWidth: { value: '14rem' },\n small: {\n width: { value: '{fontSizes.medium.value}' },\n height: { value: '{fontSizes.medium.value}' },\n },\n large: {\n width: { value: '{fontSizes.xxxl.value}' },\n height: { value: '{fontSizes.xxxl.value}' },\n },\n item: {\n minHeight: { value: '2.5rem' },\n paddingInlineStart: { value: '{space.medium.value}' },\n paddingInlineEnd: { value: '{space.medium.value}' },\n },\n};\n\nexport { menu };\n","const message = {\n // Default styles\n alignItems: { value: 'center' },\n backgroundColor: { value: '{colors.background.tertiary.value}' },\n borderColor: { value: 'transparent' },\n borderStyle: { value: 'solid' },\n borderWidth: { value: '{borderWidths.small.value}' },\n borderRadius: { value: '{radii.xs.value}' },\n color: { value: '{colors.font.primary.value}' },\n justifyContent: { value: 'flex-start' },\n paddingBlock: { value: '{space.small.value}' },\n paddingInline: { value: '{space.medium.value}' },\n lineHeight: { value: '{lineHeights.small.value}' },\n icon: {\n size: { value: '{fontSizes.xl.value}' },\n },\n heading: {\n fontSize: { value: '{fontSizes.medium.value}' },\n fontWeight: { value: '{fontWeights.bold.value}' },\n },\n dismiss: {\n gap: { value: '{space.xxs.value}' },\n },\n // Variations\n plain: {\n color: { value: '{colors.font.primary.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderColor: { value: 'transparent' },\n info: {\n color: { value: '{colors.font.info.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderColor: { value: 'transparent' },\n },\n error: {\n color: { value: '{colors.font.error.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderColor: { value: 'transparent' },\n },\n success: {\n color: { value: '{colors.font.success.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderColor: { value: 'transparent' },\n },\n warning: {\n color: { value: '{colors.font.warning.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderColor: { value: 'transparent' },\n },\n },\n outlined: {\n color: { value: '{colors.font.primary.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderColor: { value: '{colors.border.primary.value}' },\n info: {\n color: { value: '{colors.font.info.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderColor: { value: '{colors.border.info.value}' },\n },\n error: {\n color: { value: '{colors.font.error.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderColor: { value: '{colors.border.error.value}' },\n },\n success: {\n color: { value: '{colors.font.success.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderColor: { value: '{colors.border.success.value}' },\n },\n warning: {\n color: { value: '{colors.font.warning.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderColor: { value: '{colors.border.warning.value}' },\n },\n },\n filled: {\n color: { value: '{colors.font.primary.value}' },\n backgroundColor: { value: '{colors.background.secondary.value}' },\n borderColor: { value: 'transparent' },\n info: {\n color: { value: '{colors.font.info.value}' },\n backgroundColor: { value: '{colors.background.info.value}' },\n borderColor: { value: 'transparent' },\n },\n error: {\n color: { value: '{colors.font.error.value}' },\n backgroundColor: { value: '{colors.background.error.value}' },\n borderColor: { value: 'transparent' },\n },\n success: {\n color: { value: '{colors.font.success.value}' },\n backgroundColor: { value: '{colors.background.success.value}' },\n borderColor: { value: 'transparent' },\n },\n warning: {\n color: { value: '{colors.font.warning.value}' },\n backgroundColor: { value: '{colors.background.warning.value}' },\n borderColor: { value: 'transparent' },\n },\n },\n};\n\nexport { message };\n","const pagination = {\n current: {\n alignItems: { value: 'center' },\n justifyContent: { value: 'center' },\n color: { value: '{colors.font.inverse.value}' },\n fontSize: { value: '{fontSizes.small.value}' },\n backgroundColor: { value: '{colors.overlay.40.value}' },\n },\n button: {\n color: { value: '{colors.font.primary.value}' },\n paddingInlineStart: { value: '{space.xxs.value}' },\n paddingInlineEnd: { value: '{space.xxs.value}' },\n transitionProperty: { value: 'background-color' },\n transitionDuration: { value: '{time.medium.value}' },\n hover: {\n backgroundColor: { value: '{colors.overlay.10.value}' },\n color: { value: '{colors.font.primary.value}' },\n },\n disabled: {\n color: { value: '{colors.font.disabled.value}' },\n },\n },\n ellipsis: {\n alignItems: { value: 'baseline' },\n justifyContent: { value: 'center' },\n paddingInlineStart: { value: '{space.xs.value}' },\n paddingInlineEnd: { value: '{space.xs.value}' },\n },\n itemContainer: {\n marginLeft: { value: '{space.xxxs.value}' },\n marginRight: { value: '{space.xxxs.value}' },\n },\n itemShared: {\n height: { value: '{fontSizes.xxl.value}' },\n minWidth: { value: '{fontSizes.xxl.value}' },\n borderRadius: { value: '{fontSizes.medium.value}' },\n },\n};\n\nexport { pagination };\n","const passwordfield = {\n color: { value: '{components.fieldcontrol.color.value}' },\n button: {\n color: { value: '{components.button.color.value}' },\n _active: {\n backgroundColor: {\n value: '{components.button._active.backgroundColor.value}',\n },\n borderColor: { value: '{components.button._active.borderColor.value}' },\n color: { value: '{components.button._active.color.value}' },\n },\n _disabled: {\n backgroundColor: {\n value: '{components.button._disabled.backgroundColor.value}',\n },\n borderColor: {\n value: '{components.button._disabled.borderColor.value}',\n },\n color: { value: '{components.button._disabled.color.value}' },\n },\n _error: {\n color: { value: '{components.button.outlined.error.color.value}' },\n backgroundColor: {\n value: '{components.button.outlined.error.backgroundColor.value}',\n },\n borderColor: {\n value: '{components.button.outlined.error.borderColor.value}',\n },\n _active: {\n borderColor: {\n value: '{components.button.outlined.error._active.borderColor.value}',\n },\n backgroundColor: {\n value: '{components.button.outlined.error._active.backgroundColor.value}',\n },\n color: {\n value: '{components.button.outlined.error._active.color.value}',\n },\n },\n _focus: {\n borderColor: {\n value: '{components.button.outlined.error._focus.borderColor.value}',\n },\n backgroundColor: {\n value: '{components.button.outlined.error._focus.backgroundColor.value}',\n },\n color: {\n value: '{components.button.outlined.error._focus.color.value}',\n },\n boxShadow: {\n value: '{components.button.outlined.error._focus.boxShadow.value}',\n },\n },\n _hover: {\n borderColor: {\n value: '{components.button.outlined.error._hover.borderColor.value}',\n },\n backgroundColor: {\n value: '{components.button.outlined.error._hover.backgroundColor.value}',\n },\n color: {\n value: '{components.button.outlined.error._hover.color.value}',\n },\n },\n },\n _focus: {\n backgroundColor: {\n value: '{components.button._focus.backgroundColor.value}',\n },\n borderColor: { value: '{components.button._focus.borderColor.value}' },\n color: { value: '{components.button._focus.color.value}' },\n },\n _hover: {\n backgroundColor: {\n value: '{components.button._hover.backgroundColor.value}',\n },\n borderColor: { value: '{components.button._hover.borderColor.value}' },\n color: { value: '{components.button._hover.color.value}' },\n },\n },\n};\n\nexport { passwordfield };\n","const phonenumberfield = {\n color: { value: '{components.fieldcontrol.color}' },\n borderColor: { value: '{components.fieldcontrol.borderColor}' },\n fontSize: { value: '{components.fieldcontrol.fontSize}' },\n _focus: {\n borderColor: { value: '{components.fieldcontrol._focus.borderColor}' },\n },\n};\n\nexport { phonenumberfield };\n","const placeholder = {\n borderRadius: { value: '{radii.small.value}' },\n transitionDuration: { value: '{time.long.value}' },\n startColor: { value: '{colors.background.secondary.value}' },\n endColor: { value: '{colors.background.tertiary.value}' },\n // sizes\n small: {\n height: { value: '{space.small.value}' },\n },\n default: {\n height: { value: '{space.medium.value}' },\n },\n large: {\n height: { value: '{space.large.value}' },\n },\n};\n\nexport { placeholder };\n","const radio = {\n alignItems: { value: 'center' },\n justifyContent: { value: 'flex-start' },\n gap: { value: 'inherit' },\n _disabled: { cursor: { value: 'not-allowed' } },\n button: {\n alignItems: { value: 'center' },\n justifyContent: { value: 'center' },\n width: { value: '{fontSizes.medium.value}' },\n height: { value: '{fontSizes.medium.value}' },\n boxSizing: { value: 'border-box' },\n borderWidth: { value: '{borderWidths.medium.value}' },\n borderStyle: { value: 'solid' },\n borderRadius: { value: '50%' },\n borderColor: { value: '{colors.border.primary.value}' },\n color: { value: '{colors.background.primary.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n transitionProperty: { value: 'all' },\n transitionDuration: { value: '{time.medium.value}' },\n outlineColor: { value: '{colors.transparent.value}' },\n outlineStyle: { value: 'solid' },\n outlineWidth: { value: '{outlineWidths.medium.value}' },\n outlineOffset: { value: '{outlineOffsets.medium.value}' },\n // We want the dot inside the border to be a border-width from the border\n padding: { value: '{borderWidths.medium.value}' },\n small: {\n width: { value: '{fontSizes.small.value}' },\n height: { value: '{fontSizes.small.value}' },\n },\n large: {\n width: { value: '{fontSizes.large.value}' },\n height: { value: '{fontSizes.large.value}' },\n },\n _checked: {\n color: {\n value: '{colors.primary.80.value}',\n },\n _disabled: { color: { value: '{colors.background.disabled.value}' } },\n },\n _focus: {\n borderColor: { value: '{colors.border.focus.value}' },\n boxShadow: { value: '{components.fieldcontrol._focus.boxShadow.value}' },\n },\n _error: {\n borderColor: { value: '{colors.border.error.value}' },\n _focus: {\n boxShadow: {\n value: '{components.fieldcontrol._error._focus.boxShadow.value}',\n },\n },\n },\n _disabled: {\n borderColor: { value: '{colors.border.disabled.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n },\n },\n label: {\n color: { value: '{components.text.color.value}' },\n _disabled: {\n color: {\n value: '{colors.font.disabled.value}',\n },\n },\n },\n};\n\nexport { radio };\n","const radiogroup = {\n radio: {\n borderWidth: { value: '{components.radio.button.borderWidth}' },\n borderColor: { value: '{components.radio.button.borderColor}' },\n backgroundColor: { value: '{components.radio.button.backgroundColor}' },\n _checked: {\n color: { value: '{components.radio.button._checked.color}' },\n },\n label: {\n color: { value: '{components.radio.label.color}' },\n },\n },\n legend: {\n color: { value: '{components.fieldset.legend.color}' },\n fontWeight: { value: '{fontWeights.normal}' },\n },\n};\n\nexport { radiogroup };\n","const rating = {\n large: { size: { value: '{fontSizes.xxxl.value}' } },\n default: { size: { value: '{fontSizes.xl.value}' } },\n small: { size: { value: '{fontSizes.small.value}' } },\n filled: { color: { value: '{colors.secondary.80.value}' } },\n empty: { color: { value: '{colors.background.tertiary.value}' } },\n};\n\nexport { rating };\n","const searchfield = {\n color: { value: '{components.fieldcontrol.color.value}' },\n button: {\n color: { value: '{components.button.color.value}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n _active: {\n backgroundColor: {\n value: '{components.button._active.backgroundColor.value}',\n },\n borderColor: { value: '{components.button._active.borderColor.value}' },\n color: { value: '{components.button._active.color.value}' },\n },\n _disabled: {\n backgroundColor: {\n value: '{components.button._disabled.backgroundColor.value}',\n },\n borderColor: {\n value: '{components.button._disabled.borderColor.value}',\n },\n color: { value: '{components.button._disabled.color.value}' },\n },\n _focus: {\n backgroundColor: {\n value: '{components.button._focus.backgroundColor.value}',\n },\n borderColor: { value: '{components.button._focus.borderColor.value}' },\n color: { value: '{components.button._focus.color.value}' },\n },\n _hover: {\n backgroundColor: {\n value: '{components.button._hover.backgroundColor.value}',\n },\n borderColor: { value: '{components.button._hover.borderColor.value}' },\n color: { value: '{components.button._hover.color.value}' },\n },\n },\n};\n\nexport { searchfield };\n","const select = {\n color: { value: '{components.fieldcontrol.color}' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n paddingInlineEnd: { value: '{space.xxl.value}' },\n _disabled: {\n color: { value: '{colors.font.disabled.value}' },\n backgroundColor: { value: '{colors.background.disabled.value}' },\n },\n // wrappers\n wrapper: {\n flex: { value: '1' },\n display: { value: 'block' },\n position: { value: 'relative' },\n cursor: { value: 'pointer' },\n },\n iconWrapper: {\n alignItems: { value: 'center' },\n position: { value: 'absolute' },\n top: { value: '50%' },\n right: { value: '{space.medium.value}' },\n transform: { value: 'translateY(-50%)' },\n pointerEvents: { value: 'none' },\n small: {\n right: { value: '{space.xs.value}' },\n },\n large: {\n right: { value: '{space.medium.value}' },\n },\n },\n // It's important to test these option values on Chrome/FireFox/Edge\n // on Windows because they allow styling of the option element.\n // Chrome/Safari/Firefox on Mac uses the system ui.\n option: {\n backgroundColor: { value: 'transparent' },\n color: { value: '{colors.font.primary.value}' },\n _disabled: {\n color: { value: '{colors.font.disabled.value}' },\n backgroundColor: {\n value: 'transparent',\n },\n },\n },\n whiteSpace: { value: 'nowrap' },\n minWidth: { value: '6.5rem' },\n small: {\n minWidth: { value: '5.5rem' },\n paddingInlineEnd: { value: '{space.xl.value}' },\n },\n large: {\n minWidth: { value: '7.5rem' },\n paddingInlineEnd: { value: '{space.xxl.value}' },\n },\n expanded: {\n paddingBlock: { value: '{space.xs.value}' },\n paddingInline: { value: '{space.small.value}' },\n option: {\n paddingBlock: { value: '{space.xs.value}' },\n paddingInline: { value: '{space.small.value}' },\n },\n },\n};\n\nexport { select };\n","const selectfield = {\n borderColor: { value: '{components.fieldcontrol.borderColor}' },\n color: { value: '{components.fieldcontrol.color}' },\n flexDirection: {\n value: 'column',\n },\n fontSize: { value: '{components.fieldcontrol.fontSize}' },\n _focus: {\n borderColor: { value: '{components.fieldcontrol._focus.borderColor}' },\n },\n label: {\n color: { value: '{components.field.label.color}' },\n },\n};\n\nexport { selectfield };\n","const sliderfield = {\n paddingBlock: { value: '{space.xs.value}' },\n // The track is the thin background of the slider\n track: {\n backgroundColor: { value: '{colors.background.quaternary.value}' },\n borderRadius: { value: '9999px' },\n height: { value: '0.375rem' },\n minWidth: { value: '10rem' },\n },\n // The range is the filled part of the track\n range: {\n backgroundColor: { value: '{colors.primary.80.value}' },\n borderRadius: { value: '9999px' },\n _disabled: {\n backgroundColor: { value: '{colors.background.disabled.value}' },\n },\n },\n // The thumb is the circle above the track that the user drags\n thumb: {\n width: { value: '1.25rem' },\n height: { value: '1.25rem' },\n backgroundColor: { value: '{colors.background.primary.value}' },\n boxShadow: { value: '{shadows.small.value}' },\n borderRadius: { value: '50%' },\n borderWidth: { value: '{borderWidths.medium.value}' },\n borderColor: { value: '{colors.border.primary.value}' },\n borderStyle: { value: 'solid' },\n _disabled: {\n backgroundColor: { value: '{colors.background.disabled.value}' },\n borderColor: { value: 'transparent' },\n boxShadow: { value: 'none' },\n },\n _hover: {\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderColor: { value: '{colors.border.focus.value}' },\n },\n _focus: {\n borderColor: { value: '{colors.border.focus.value}' },\n boxShadow: { value: '{components.fieldcontrol._focus.boxShadow.value}' },\n },\n },\n small: {\n track: {\n height: { value: '0.25rem' },\n },\n thumb: {\n width: { value: '1rem' },\n height: { value: '1rem' },\n },\n },\n large: {\n track: {\n height: { value: '0.625rem' },\n },\n thumb: {\n width: { value: '1.5rem' },\n height: { value: '1.5rem' },\n },\n },\n};\n\nexport { sliderfield };\n","const stepperfield = {\n borderColor: { value: '{components.fieldcontrol.borderColor}' },\n flexDirection: { value: 'column' },\n input: {\n color: { value: '{components.fieldcontrol.color}' },\n fontSize: { value: '{components.fieldcontrol.fontSize}' },\n textAlign: { value: 'center' },\n },\n button: {\n color: { value: '{components.button.color}' },\n backgroundColor: { value: '{colors.transparent}' },\n _active: {\n color: { value: '{components.button._active.color}' },\n backgroundColor: { value: '{components.button._active.backgroundColor}' },\n },\n _focus: {\n color: { value: '{components.button._focus.color}' },\n backgroundColor: { value: '{components.button._focus.backgroundColor}' },\n },\n _disabled: {\n color: { value: '{components.button._disabled.color}' },\n backgroundColor: {\n value: '{components.fieldcontrol._disabled.backgroundColor}',\n },\n },\n _hover: {\n color: { value: '{components.button._hover.color}' },\n backgroundColor: { value: '{components.button._hover.backgroundColor}' },\n },\n },\n};\n\nexport { stepperfield };\n","const storagemanager = {\n dropzone: {\n backgroundColor: { value: '{colors.background.primary}' },\n borderRadius: { value: '{radii.small}' },\n borderColor: { value: '{colors.border.primary}' },\n borderStyle: { value: 'dashed' },\n borderWidth: { value: '{borderWidths.small}' },\n gap: { value: '{space.small}' },\n paddingBlock: { value: '{space.xl}' },\n paddingInline: { value: '{space.large}' },\n textAlign: { value: 'center' },\n _active: {\n backgroundColor: { value: '{colors.primary.10}' },\n borderRadius: {\n value: '{components.storagemanager.dropzone.borderRadius}',\n },\n borderColor: { value: '{colors.border.pressed}' },\n borderStyle: {\n value: '{components.storagemanager.dropzone.borderStyle}',\n },\n borderWidth: { value: '{borderWidths.medium}' },\n },\n icon: {\n color: { value: '{colors.border.primary}' },\n fontSize: { value: '{fontSizes.xxl}' },\n },\n text: {\n color: { value: '{colors.font.tertiary}' },\n fontSize: { value: '{fontSizes.medium}' },\n fontWeight: { value: '{fontWeights.bold}' },\n },\n },\n file: {\n backgroundColor: { value: '{colors.background.primary}' },\n borderRadius: { value: '{radii.small}' },\n borderColor: { value: '{colors.border.primary}' },\n borderStyle: { value: 'solid' },\n borderWidth: { value: '{borderWidths.small}' },\n paddingBlock: { value: '{space.xs}' },\n paddingInline: { value: '{space.small}' },\n gap: { value: '{space.small}' },\n alignItems: { value: 'baseline' },\n name: {\n fontSize: { value: '{fontSizes.medium}' },\n fontWeight: { value: '{fontWeights.bold}' },\n color: { value: '{colors.font.primary}' },\n },\n size: {\n fontSize: { value: '{fontSizes.small}' },\n fontWeight: { value: '{fontWeights.normal}' },\n color: { value: '{colors.font.tertiary}' },\n },\n image: {\n width: { value: '{space.xxl}' },\n height: { value: '{space.xxl}' },\n backgroundColor: { value: '{colors.background.secondary}' },\n color: { value: '{colors.font.tertiary}' },\n borderRadius: { value: '{radii.small}' },\n },\n },\n filelist: {\n flexDirection: { value: 'column' },\n gap: { value: '{space.small}' },\n },\n loader: {\n strokeLinecap: { value: 'round' },\n strokeEmpty: { value: '{colors.border.secondary}' },\n strokeFilled: { value: '{components.loader.strokeFilled}' },\n strokeWidth: { value: '{borderWidths.large}' },\n },\n previewer: {\n backgroundColor: { value: '{colors.background.primary}' },\n borderColor: { value: '{colors.border.primary}' },\n borderStyle: { value: 'solid' },\n borderWidth: { value: '{borderWidths.small}' },\n borderRadius: { value: '{radii.small}' },\n paddingBlock: { value: '{space.zero}' },\n paddingInline: { value: '{space.zero}' },\n maxHeight: { value: '40rem' },\n maxWidth: { value: 'auto' },\n text: {\n fontSize: { value: '{fontSizes.medium}' },\n fontWeight: { value: '{fontWeights.bold}' },\n color: { value: '{colors.font.primary}' },\n },\n body: {\n paddingBlock: { value: '{space.medium}' },\n paddingInline: { value: '{space.medium}' },\n gap: { value: '{space.small}' },\n },\n footer: {\n justifyContent: { value: 'flex-end' },\n },\n },\n};\n\nexport { storagemanager };\n","const switchfield = {\n // States\n _disabled: {\n opacity: { value: '{opacities.60.value}' },\n },\n _focused: {\n shadow: {\n value: '{components.fieldcontrol._focus.boxShadow.value}',\n },\n },\n // Sizes\n fontSize: { value: '{fontSizes.medium.value}' },\n large: {\n fontSize: { value: '{fontSizes.large.value}' },\n },\n small: {\n fontSize: { value: '{fontSizes.small.value}' },\n },\n // Child elements\n label: {\n padding: { value: '{space.xs.value}' },\n },\n thumb: {\n backgroundColor: { value: '{colors.background.primary.value}' },\n borderColor: { value: 'transparent' },\n borderWidth: { value: '{borderWidths.small.value}' },\n borderStyle: { value: 'solid' },\n borderRadius: { value: '{radii.xxxl.value}' },\n checked: {\n transform: { value: '{transforms.slideX.medium.value}' },\n },\n transition: {\n duration: { value: '{time.medium.value}' },\n },\n width: { value: '{space.relative.medium.value}' },\n },\n track: {\n backgroundColor: { value: '{colors.background.quaternary.value}' },\n borderRadius: { value: '{radii.xxxl.value}' },\n checked: {\n backgroundColor: { value: '{colors.primary.80.value}' },\n },\n height: { value: '{space.relative.medium.value}' },\n padding: { value: '{outlineWidths.medium.value}' },\n transition: {\n duration: { value: '{time.short.value}' },\n },\n width: { value: '{space.relative.xl.value}' },\n _error: {\n backgroundColor: { value: '{colors.background.error.value}' },\n },\n },\n};\n\nexport { switchfield };\n","const table = {\n /**\n * Default table styles\n */\n borderCollapse: { value: 'collapse' },\n display: { value: 'table' },\n width: { value: '100%' },\n /**\n * Default table head styles\n */\n head: {\n display: { value: 'table-header-group' },\n verticalAlign: { value: 'middle' },\n },\n /**\n * Default table body styles\n */\n body: {\n display: { value: 'table-row-group' },\n verticalAlign: { value: 'middle' },\n },\n /**\n * Default table foot styles\n */\n foot: {\n display: { value: 'table-footer-group' },\n verticalAlign: { value: 'middle' },\n },\n /**\n * Default table row styles\n */\n row: {\n display: { value: 'table-row' },\n verticalAlign: { value: 'middle' },\n hover: {\n backgroundColor: { value: '{colors.background.tertiary.value}' },\n },\n striped: {\n backgroundColor: { value: '{colors.background.secondary.value}' },\n },\n },\n /**\n * Default table header cell styles\n */\n header: {\n borderColor: { value: '{colors.border.tertiary.value}' },\n borderStyle: { value: 'solid' },\n borderWidth: { value: '{borderWidths.small.value}' },\n color: { value: '{colors.font.primary.value}' },\n display: { value: 'table-cell' },\n fontSize: { value: '{fontSizes.medium.value}' },\n fontWeight: { value: '{fontWeights.bold.value}' },\n padding: { value: '{space.medium.value}' },\n verticalAlign: { value: 'middle' },\n large: {\n fontSize: { value: '{fontSizes.large.value}' },\n padding: { value: '{space.large.value}' },\n },\n small: {\n fontSize: { value: '{fontSizes.small.value}' },\n padding: { value: '{space.xs.value}' },\n },\n },\n /**\n * Default table data cell styles\n */\n data: {\n borderColor: { value: '{colors.border.tertiary.value}' },\n borderStyle: { value: 'solid' },\n borderWidth: { value: '{borderWidths.small.value}' },\n color: { value: '{colors.font.primary.value}' },\n display: { value: 'table-cell' },\n fontSize: { value: '{fontSizes.medium.value}' },\n fontWeight: { value: '{fontWeights.normal.value}' },\n padding: { value: '{space.medium.value}' },\n verticalAlign: { value: 'middle' },\n large: {\n fontSize: { value: '{fontSizes.large.value}' },\n padding: { value: '{space.large.value}' },\n },\n small: {\n fontSize: { value: '{fontSizes.small.value}' },\n padding: { value: '{space.xs.value}' },\n },\n },\n /**\n * Default table caption styles\n */\n caption: {\n captionSide: { value: 'bottom' },\n color: { value: '{colors.font.primary.value}' },\n display: { value: 'table-caption' },\n fontSize: { value: '{fontSizes.medium.value}' },\n textAlign: { value: 'center' },\n wordBreak: { value: 'break-all' },\n large: {\n fontSize: { value: '{fontSizes.large.value}' },\n },\n small: {\n fontSize: { value: '{fontSizes.small.value}' },\n },\n },\n};\n\nexport { table };\n","const tabs = {\n backgroundColor: { value: 'transparent' },\n borderColor: { value: '{colors.border.secondary.value}' },\n borderStyle: { value: 'solid' },\n borderWidth: { value: '{borderWidths.medium.value}' },\n gap: { value: '0' },\n item: {\n backgroundColor: { value: 'transparent' },\n borderColor: { value: '{colors.border.secondary.value}' },\n borderStyle: { value: 'solid' },\n borderWidth: { value: '{borderWidths.medium.value}' },\n color: { value: '{colors.font.secondary.value}' },\n fontSize: { value: '{fontSizes.medium.value}' },\n fontWeight: { value: '{fontWeights.bold.value}' },\n paddingVertical: { value: '{space.small.value}' },\n paddingHorizontal: { value: '{space.medium.value}' },\n textAlign: { value: 'center' },\n transitionDuration: { value: '{time.medium.value}' },\n _hover: {\n backgroundColor: { value: 'transparent' },\n borderColor: { value: '{colors.border.focus.value}' },\n boxShadow: { value: 'none' },\n color: { value: '{colors.font.hover.value}' },\n },\n _focus: {\n backgroundColor: { value: 'transparent' },\n borderColor: { value: '{colors.border.focus.value}' },\n boxShadow: {\n value: {\n offsetX: '0px',\n offsetY: '0px',\n blurRadius: '0px',\n spreadRadius: '{borderWidths.medium}',\n color: '{colors.border.focus.value}',\n },\n },\n color: { value: '{colors.font.focus.value}' },\n },\n _active: {\n backgroundColor: { value: 'transparent' },\n borderColor: { value: '{colors.font.interactive.value}' },\n boxShadow: { value: 'none' },\n color: { value: '{colors.font.interactive.value}' },\n },\n _disabled: {\n backgroundColor: { value: 'transparent' },\n borderColor: { value: '{colors.border.tertiary.value}' },\n boxShadow: { value: 'none' },\n color: { value: '{colors.font.disabled.value}' },\n },\n },\n panel: {\n backgroundColor: { value: 'transparent' },\n paddingInline: { value: '0' },\n paddingBlock: { value: '{space.small.value}' },\n },\n};\n\nexport { tabs };\n","const text = {\n // default styles\n color: { value: '{colors.font.primary.value}' },\n // variations\n primary: {\n color: { value: '{colors.font.primary.value}' },\n },\n secondary: {\n color: { value: '{colors.font.secondary.value}' },\n },\n tertiary: {\n color: { value: '{colors.font.tertiary.value}' },\n },\n error: {\n color: { value: '{colors.font.error.value}' },\n },\n warning: {\n color: { value: '{colors.font.warning.value}' },\n },\n success: {\n color: { value: '{colors.font.success.value}' },\n },\n info: {\n color: { value: '{colors.font.info.value}' },\n },\n};\n\nexport { text };\n","const textareafield = {\n color: { value: '{components.fieldcontrol.color.value}' },\n borderColor: { value: '{components.fieldcontrol.borderColor.value}' },\n _focus: {\n borderColor: {\n value: '{components.fieldcontrol._focus.borderColor.value}',\n },\n },\n};\n\nexport { textareafield };\n","const textfield = {\n color: { value: '{components.fieldcontrol.color.value}' },\n borderColor: { value: '{components.fieldcontrol.borderColor.value}' },\n fontSize: { value: '{components.fieldcontrol.fontSize.value}' },\n _focus: {\n borderColor: {\n value: '{components.fieldcontrol._focus.borderColor.value}',\n },\n },\n};\n\nexport { textfield };\n","const togglebutton = {\n borderColor: { value: '{colors.border.primary.value}' },\n color: { value: '{colors.font.primary.value}' },\n _hover: {\n backgroundColor: { value: '{colors.overlay.10.value}' },\n },\n _focus: {\n borderColor: { value: '{colors.border.focus.value}' },\n color: { value: '{colors.font.primary.value}' },\n },\n _active: {\n backgroundColor: { value: '{colors.transparent.value}' },\n },\n _disabled: {\n backgroundColor: { value: '{colors.transparent.value}' },\n borderColor: { value: '{colors.border.disabled.value}' },\n color: { value: '{colors.font.disabled.value}' },\n },\n _pressed: {\n borderColor: { value: '{colors.border.pressed.value}' },\n color: { value: '{colors.font.primary.value}' },\n backgroundColor: { value: '{colors.overlay.20.value}' },\n _hover: {\n backgroundColor: { value: '{colors.overlay.30.value}' },\n },\n },\n primary: {\n backgroundColor: { value: '{colors.transparent.value}' },\n borderWidth: { value: '{borderWidths.small.value}' },\n _focus: {\n borderColor: { value: '{colors.border.focus.value}' },\n backgroundColor: { value: '{colors.transparent.value}' },\n boxShadow: { value: '{components.fieldcontrol._focus.boxShadow.value}' },\n color: { value: '{colors.font.primary.value}' },\n },\n _hover: {\n backgroundColor: { value: '{colors.overlay.10.value}' },\n color: { value: '{colors.font.primary.value}' },\n },\n _disabled: {\n borderColor: { value: '{colors.border.disabled.value}' },\n backgroundColor: { value: '{colors.background.disabled.value}' },\n color: { value: '{colors.font.disabled.value}' },\n },\n _pressed: {\n backgroundColor: { value: '{colors.primary.80.value}' },\n borderColor: { value: '{colors.primary.80.value}' },\n color: { value: '{colors.background.primary.value}' },\n _focus: {\n backgroundColor: {\n value: '{colors.border.focus.value}',\n },\n borderColor: { value: '{colors.border.focus.value}' },\n color: { value: '{colors.background.primary.value}' },\n },\n _hover: {\n borderColor: { value: '{colors.primary.60.value}' },\n backgroundColor: {\n value: '{colors.primary.60.value}',\n },\n boxShadow: { value: '{colors.primary.60.value}' },\n color: { value: '{colors.background.primary.value}' },\n },\n },\n },\n link: {\n backgroundColor: { value: '{colors.transparent.value}' },\n color: { value: '{colors.overlay.50.value}' },\n _hover: {\n backgroundColor: { value: '{colors.transparent.value}' },\n color: { value: '{colors.overlay.50.value}' },\n },\n _focus: {\n backgroundColor: { value: '{colors.transparent.value}' },\n color: { value: '{colors.overlay.50.value}' },\n },\n _disabled: {\n backgroundColor: { value: '{colors.transparent.value}' },\n color: { value: '{colors.font.disabled.value}' },\n },\n _pressed: {\n backgroundColor: { value: '{colors.transparent.value}' },\n color: { value: '{colors.overlay.90.value}' },\n _focus: {\n backgroundColor: { value: '{colors.transparent.value}' },\n color: { value: '{colors.overlay.90.value}' },\n },\n _hover: {\n color: { value: '{colors.overlay.90.value}' },\n backgroundColor: { value: '{colors.transparent.value}' },\n },\n },\n },\n};\n\nexport { togglebutton };\n","const togglebuttongroup = {\n alignItems: { value: 'center' },\n alignContent: { value: 'center' },\n justifyContent: { value: 'flex-start' },\n};\n\nexport { togglebuttongroup };\n","import { alert } from './alert.mjs';\nimport { aiConversation } from './aiConversation.mjs';\nimport { autocomplete } from './autocomplete.mjs';\nimport { authenticator } from './authenticator.mjs';\nimport { avatar } from './avatar.mjs';\nimport { badge } from './badge.mjs';\nimport { breadcrumbs } from './breadcrumbs.mjs';\nimport { button } from './button.mjs';\nimport { card } from './card.mjs';\nimport { checkbox } from './checkbox.mjs';\nimport { checkboxfield } from './checkboxField.mjs';\nimport { collection } from './collection.mjs';\nimport { copy } from './copy.mjs';\nimport { dialcodeselect } from './dialCodeSelect.mjs';\nimport { divider } from './divider.mjs';\nimport { dropzone } from './dropZone.mjs';\nimport { accordion } from './accordion.mjs';\nimport { field } from './field.mjs';\nimport { fieldcontrol } from './fieldControl.mjs';\nimport { fieldgroup } from './fieldGroup.mjs';\nimport { fieldset } from './fieldset.mjs';\nimport { fieldmessages } from './fieldMessages.mjs';\nimport { fileuploader } from './fileuploader.mjs';\nimport { flex } from './flex.mjs';\nimport { heading } from './heading.mjs';\nimport { highlightmatch } from './highlightMatch.mjs';\nimport { icon } from './icon.mjs';\nimport { input } from './input.mjs';\nimport { image } from './image.mjs';\nimport { inappmessaging } from './inAppMessaging.mjs';\nimport { link } from './link.mjs';\nimport { liveness } from './liveness.mjs';\nimport { loader } from './loader.mjs';\nimport { menu } from './menu.mjs';\nimport { message } from './message.mjs';\nimport { pagination } from './pagination.mjs';\nimport { passwordfield } from './passwordField.mjs';\nimport { phonenumberfield } from './phoneNumberField.mjs';\nimport { placeholder } from './placeholder.mjs';\nimport { radio } from './radio.mjs';\nimport { radiogroup } from './radioGroup.mjs';\nimport { rating } from './rating.mjs';\nimport { searchfield } from './searchField.mjs';\nimport { select } from './select.mjs';\nimport { selectfield } from './selectField.mjs';\nimport { sliderfield } from './sliderField.mjs';\nimport { stepperfield } from './stepperField.mjs';\nimport { storagemanager } from './storagemanager.mjs';\nimport { switchfield } from './switchField.mjs';\nimport { table } from './table.mjs';\nimport { tabs } from './tabs.mjs';\nimport { text } from './text.mjs';\nimport { textareafield } from './textAreaField.mjs';\nimport { textfield } from './textField.mjs';\nimport { togglebutton } from './toggleButton.mjs';\nimport { togglebuttongroup } from './toggleButtonGroup.mjs';\n\nconst components = {\n accordion,\n aiConversation,\n alert,\n authenticator,\n autocomplete,\n avatar,\n badge,\n breadcrumbs,\n button,\n card,\n checkbox,\n checkboxfield,\n collection,\n copy,\n countrycodeselect: dialcodeselect,\n divider,\n dropzone,\n field,\n fieldcontrol,\n fieldgroup,\n fieldmessages,\n fieldset,\n fileuploader,\n flex,\n heading,\n icon,\n highlightmatch,\n image,\n inappmessaging,\n input,\n link,\n liveness,\n loader,\n menu,\n message,\n pagination,\n passwordfield,\n phonenumberfield,\n placeholder,\n radio,\n radiogroup,\n rating,\n searchfield,\n select,\n selectfield,\n sliderfield,\n stepperfield,\n storagemanager,\n switchfield,\n table,\n tabs,\n text,\n textareafield,\n textfield,\n togglebutton,\n togglebuttongroup,\n};\n\nexport { components };\n","// TODO: update the design tokens to use an array\n// export interface FontDesignToken {\n// value: Array\n// }\nconst fonts = {\n default: {\n variable: {\n value: `'InterVariable', 'Inter var', 'Inter', -apple-system, BlinkMacSystemFont,\n 'Helvetica Neue', 'Segoe UI', Oxygen, Ubuntu, Cantarell, 'Open Sans',\n sans-serif`,\n },\n static: {\n value: `'Inter', -apple-system, BlinkMacSystemFont, 'Helvetica Neue',\n 'Segoe UI', Oxygen, Ubuntu, Cantarell, 'Open Sans', sans-serif`,\n },\n },\n};\n\nexport { fonts };\n","const fontSizes = {\n xxxs: { value: '0.375rem' },\n xxs: { value: '0.5rem' },\n xs: { value: '0.75rem' },\n small: { value: '0.875rem' },\n medium: { value: '1rem' },\n large: { value: '1.25rem' },\n xl: { value: '1.5rem' },\n xxl: { value: '2rem' },\n xxxl: { value: '2.5rem' },\n xxxxl: { value: '3rem' },\n};\n\nexport { fontSizes };\n","const fontWeights = {\n hairline: { value: 100 },\n thin: { value: 200 },\n light: { value: 300 },\n normal: { value: 400 },\n medium: { value: 500 },\n semibold: { value: 600 },\n bold: { value: 700 },\n extrabold: { value: 800 },\n black: { value: 900 },\n};\n\nexport { fontWeights };\n","const lineHeights = {\n small: { value: '1.25' },\n medium: { value: '1.5' },\n large: { value: '2' },\n};\n\nexport { lineHeights };\n","const opacities = {\n 0: { value: '0' },\n 10: { value: '0.1' },\n 20: { value: '0.2' },\n 30: { value: '0.3' },\n 40: { value: '0.4' },\n 50: { value: '0.5' },\n 60: { value: '0.6' },\n 70: { value: '0.7' },\n 80: { value: '0.8' },\n 90: { value: '0.9' },\n 100: { value: '1' },\n};\n\nexport { opacities };\n","const outlineOffsets = {\n small: { value: '1px' },\n medium: { value: '2px' },\n large: { value: '3px' },\n};\n\nexport { outlineOffsets };\n","const outlineWidths = {\n small: { value: '1px' },\n medium: { value: '2px' },\n large: { value: '3px' },\n};\n\nexport { outlineWidths };\n","const radii = {\n xs: { value: '0.125rem' },\n small: { value: '0.25rem' },\n medium: { value: '0.5rem' },\n large: { value: '1rem' },\n xl: { value: '2rem' },\n xxl: { value: '4rem' },\n xxxl: { value: '8rem' },\n};\n\nexport { radii };\n","const shadows = {\n small: {\n value: {\n offsetX: '0px',\n offsetY: '2px',\n blurRadius: '4px',\n color: '{colors.shadow.tertiary.value}',\n },\n },\n medium: {\n value: {\n offsetX: '0px',\n offsetY: '2px',\n blurRadius: '6px',\n color: '{colors.shadow.secondary.value}',\n },\n },\n large: {\n value: {\n offsetX: '0px',\n offsetY: '4px',\n blurRadius: '12px',\n color: '{colors.shadow.primary.value}',\n },\n },\n};\n\nexport { shadows };\n","const space = {\n zero: { value: '0' },\n xxxs: { value: '0.25rem' },\n xxs: { value: '0.375rem' },\n xs: { value: '0.5rem' },\n small: { value: '0.75rem' },\n medium: { value: '1rem' },\n large: { value: '1.5rem' },\n xl: { value: '2.0rem' },\n xxl: { value: '3.0rem' },\n xxxl: { value: '4.5rem' },\n relative: {\n //creating a second set of sizes using em which will be sized relative to a parent instead of the root\n xxxs: { value: '0.25em' },\n xxs: { value: '0.375em' },\n xs: { value: '0.5em' },\n small: { value: '0.75em' },\n medium: { value: '1em' },\n large: { value: '1.5em' },\n xl: { value: '2.0em' },\n xxl: { value: '3.0em' },\n xxxl: { value: '4.5em' },\n full: { value: '100%' },\n },\n};\n// I want to be able to pass in a Theme object that has extra tokens\n// and it returns that same object type WITH the extra tokens\n\nexport { space };\n","const time = {\n short: { value: '100ms' },\n medium: { value: '250ms' },\n long: { value: '500ms' },\n};\n\nexport { time };\n","const transforms = {\n // TODO: make this more generic and cross-platform\n slideX: {\n small: { value: 'translateX(0.5em)' },\n medium: { value: 'translateX(1em)' },\n large: { value: 'translateX(2em)' },\n },\n};\n\nexport { transforms };\n","import { borderWidths } from './borderWidths.mjs';\nimport { colors } from './colors.mjs';\nimport { components } from './components/index.mjs';\nimport { fonts } from './fonts.mjs';\nimport { fontSizes } from './fontSizes.mjs';\nimport { fontWeights } from './fontWeights.mjs';\nimport { lineHeights } from './lineHeights.mjs';\nimport { opacities } from './opacities.mjs';\nimport { outlineOffsets } from './outlineOffsets.mjs';\nimport { outlineWidths } from './outlineWidths.mjs';\nimport { radii } from './radii.mjs';\nimport { shadows } from './shadows.mjs';\nimport { space } from './space.mjs';\nimport { time } from './time.mjs';\nimport { transforms } from './transforms.mjs';\n\nconst tokens = {\n components,\n borderWidths,\n colors,\n fonts,\n fontSizes,\n fontWeights,\n lineHeights,\n opacities,\n outlineOffsets,\n outlineWidths,\n radii,\n shadows,\n space,\n time,\n transforms,\n};\nconst reactNativeTokens = {\n colors,\n borderWidths,\n fontSizes: {\n xxs: fontSizes.xxs,\n xs: fontSizes.xs,\n small: fontSizes.small,\n medium: fontSizes.medium,\n large: fontSizes.large,\n xl: fontSizes.xl,\n xxl: fontSizes.xxl,\n xxxl: fontSizes.xxxl,\n },\n fontWeights,\n opacities,\n // React Native doesn't need the relative space values\n space: {\n // use `space.xxxs` to output a value of `2` and avoid odd space numbers\n xxs: space.xxxs,\n xs: space.xs,\n small: space.small,\n medium: space.medium,\n large: space.large,\n xl: space.xl,\n xxl: space.xxl,\n xxxl: space.xxxl,\n },\n radii,\n time,\n};\n\nexport { reactNativeTokens, tokens };\n","// Breakpoint unit is in pixels\nconst breakpoints = {\n values: {\n base: 0,\n small: 480,\n medium: 768,\n large: 992,\n xl: 1280,\n xxl: 1536,\n },\n defaultBreakpoint: 'base',\n};\n\nexport { breakpoints };\n","import { tokens } from './tokens/index.mjs';\nimport { breakpoints } from './breakpoints.mjs';\n\nconst defaultTheme = {\n tokens,\n breakpoints,\n name: 'default-theme',\n};\n\nexport { defaultTheme };\n","/**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\nfunction arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n}\n\nmodule.exports = arrayReduce;\n","/**\n * The base implementation of `_.propertyOf` without support for deep paths.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyOf(object) {\n return function(key) {\n return object == null ? undefined : object[key];\n };\n}\n\nmodule.exports = basePropertyOf;\n","var basePropertyOf = require('./_basePropertyOf');\n\n/** Used to map Latin Unicode letters to basic Latin letters. */\nvar deburredLetters = {\n // Latin-1 Supplement block.\n '\\xc0': 'A', '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n '\\xe0': 'a', '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n '\\xc7': 'C', '\\xe7': 'c',\n '\\xd0': 'D', '\\xf0': 'd',\n '\\xc8': 'E', '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n '\\xe8': 'e', '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n '\\xcc': 'I', '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n '\\xec': 'i', '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n '\\xd1': 'N', '\\xf1': 'n',\n '\\xd2': 'O', '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n '\\xf2': 'o', '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n '\\xd9': 'U', '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n '\\xf9': 'u', '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n '\\xdd': 'Y', '\\xfd': 'y', '\\xff': 'y',\n '\\xc6': 'Ae', '\\xe6': 'ae',\n '\\xde': 'Th', '\\xfe': 'th',\n '\\xdf': 'ss',\n // Latin Extended-A block.\n '\\u0100': 'A', '\\u0102': 'A', '\\u0104': 'A',\n '\\u0101': 'a', '\\u0103': 'a', '\\u0105': 'a',\n '\\u0106': 'C', '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n '\\u0107': 'c', '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n '\\u010e': 'D', '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n '\\u0112': 'E', '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n '\\u0113': 'e', '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n '\\u011c': 'G', '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n '\\u011d': 'g', '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n '\\u0124': 'H', '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n '\\u0128': 'I', '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n '\\u0129': 'i', '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n '\\u0134': 'J', '\\u0135': 'j',\n '\\u0136': 'K', '\\u0137': 'k', '\\u0138': 'k',\n '\\u0139': 'L', '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n '\\u013a': 'l', '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n '\\u0143': 'N', '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n '\\u0144': 'n', '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n '\\u014c': 'O', '\\u014e': 'O', '\\u0150': 'O',\n '\\u014d': 'o', '\\u014f': 'o', '\\u0151': 'o',\n '\\u0154': 'R', '\\u0156': 'R', '\\u0158': 'R',\n '\\u0155': 'r', '\\u0157': 'r', '\\u0159': 'r',\n '\\u015a': 'S', '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n '\\u015b': 's', '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n '\\u0162': 'T', '\\u0164': 'T', '\\u0166': 'T',\n '\\u0163': 't', '\\u0165': 't', '\\u0167': 't',\n '\\u0168': 'U', '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n '\\u0169': 'u', '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n '\\u0174': 'W', '\\u0175': 'w',\n '\\u0176': 'Y', '\\u0177': 'y', '\\u0178': 'Y',\n '\\u0179': 'Z', '\\u017b': 'Z', '\\u017d': 'Z',\n '\\u017a': 'z', '\\u017c': 'z', '\\u017e': 'z',\n '\\u0132': 'IJ', '\\u0133': 'ij',\n '\\u0152': 'Oe', '\\u0153': 'oe',\n '\\u0149': \"'n\", '\\u017f': 's'\n};\n\n/**\n * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n * letters to basic Latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\nvar deburrLetter = basePropertyOf(deburredLetters);\n\nmodule.exports = deburrLetter;\n","var deburrLetter = require('./_deburrLetter'),\n toString = require('./toString');\n\n/** Used to match Latin Unicode letters (excluding mathematical operators). */\nvar reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n/** Used to compose unicode character classes. */\nvar rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;\n\n/** Used to compose unicode capture groups. */\nvar rsCombo = '[' + rsComboRange + ']';\n\n/**\n * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n */\nvar reComboMark = RegExp(rsCombo, 'g');\n\n/**\n * Deburrs `string` by converting\n * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n * letters to basic Latin letters and removing\n * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('déjà vu');\n * // => 'deja vu'\n */\nfunction deburr(string) {\n string = toString(string);\n return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n}\n\nmodule.exports = deburr;\n","/** Used to match words composed of alphanumeric characters. */\nvar reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n/**\n * Splits an ASCII `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\nfunction asciiWords(string) {\n return string.match(reAsciiWord) || [];\n}\n\nmodule.exports = asciiWords;\n","/** Used to detect strings that need a more robust regexp to match words. */\nvar reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n/**\n * Checks if `string` contains a word composed of Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a word is found, else `false`.\n */\nfunction hasUnicodeWord(string) {\n return reHasUnicodeWord.test(string);\n}\n\nmodule.exports = hasUnicodeWord;\n","/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsDingbatRange = '\\\\u2700-\\\\u27bf',\n rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n rsPunctuationRange = '\\\\u2000-\\\\u206f',\n rsSpaceRange = ' \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000',\n rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n rsVarRange = '\\\\ufe0e\\\\ufe0f',\n rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n/** Used to compose unicode capture groups. */\nvar rsApos = \"['\\u2019]\",\n rsBreak = '[' + rsBreakRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsDigits = '\\\\d+',\n rsDingbat = '[' + rsDingbatRange + ']',\n rsLower = '[' + rsLowerRange + ']',\n rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsUpper = '[' + rsUpperRange + ']',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq;\n\n/** Used to match complex or compound words. */\nvar reUnicodeWord = RegExp([\n rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n rsUpper + '+' + rsOptContrUpper,\n rsOrdUpper,\n rsOrdLower,\n rsDigits,\n rsEmoji\n].join('|'), 'g');\n\n/**\n * Splits a Unicode `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\nfunction unicodeWords(string) {\n return string.match(reUnicodeWord) || [];\n}\n\nmodule.exports = unicodeWords;\n","var asciiWords = require('./_asciiWords'),\n hasUnicodeWord = require('./_hasUnicodeWord'),\n toString = require('./toString'),\n unicodeWords = require('./_unicodeWords');\n\n/**\n * Splits `string` into an array of its words.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {RegExp|string} [pattern] The pattern to match words.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the words of `string`.\n * @example\n *\n * _.words('fred, barney, & pebbles');\n * // => ['fred', 'barney', 'pebbles']\n *\n * _.words('fred, barney, & pebbles', /[^, ]+/g);\n * // => ['fred', 'barney', '&', 'pebbles']\n */\nfunction words(string, pattern, guard) {\n string = toString(string);\n pattern = guard ? undefined : pattern;\n\n if (pattern === undefined) {\n return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);\n }\n return string.match(pattern) || [];\n}\n\nmodule.exports = words;\n","var arrayReduce = require('./_arrayReduce'),\n deburr = require('./deburr'),\n words = require('./words');\n\n/** Used to compose unicode capture groups. */\nvar rsApos = \"['\\u2019]\";\n\n/** Used to match apostrophes. */\nvar reApos = RegExp(rsApos, 'g');\n\n/**\n * Creates a function like `_.camelCase`.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\nfunction createCompounder(callback) {\n return function(string) {\n return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n };\n}\n\nmodule.exports = createCompounder;\n","var createCompounder = require('./_createCompounder');\n\n/**\n * Converts `string` to\n * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the kebab cased string.\n * @example\n *\n * _.kebabCase('Foo Bar');\n * // => 'foo-bar'\n *\n * _.kebabCase('fooBar');\n * // => 'foo-bar'\n *\n * _.kebabCase('__FOO_BAR__');\n * // => 'foo-bar'\n */\nvar kebabCase = createCompounder(function(result, word, index) {\n return result + (index ? '-' : '') + word.toLowerCase();\n});\n\nmodule.exports = kebabCase;\n","const OPTIONS = {\n openingCharacter: '{',\n closingCharacter: '}',\n separator: '.',\n};\nconst REFERENCE_REGEX = /\\{([^}]+)\\}/g;\n\nexport { OPTIONS, REFERENCE_REGEX };\n","import { has } from './utils.mjs';\nimport { OPTIONS, REFERENCE_REGEX } from '../theme/createTheme/constants.mjs';\n\n/**\n * Checks if the value uses a value reference.\n * @param {string} value\n * @returns {boolean} - True, if the value uses a value reference\n */\nfunction usesReference(value) {\n const regex = new RegExp(REFERENCE_REGEX);\n if (typeof value === 'string') {\n return regex.test(value);\n }\n if (typeof value === 'object') {\n let hasReference = false;\n // iterate over each property in the object,\n // if any element passes the regex test,\n // the whole thing should be true\n for (const key in value) {\n if (has(value, key)) {\n const element = value[key];\n let reference = usesReference(element);\n if (reference) {\n hasReference = true;\n break;\n }\n }\n }\n return hasReference;\n }\n return false;\n}\nfunction resolveReference(path, obj) {\n let ref = obj;\n if (!Array.isArray(path)) {\n return;\n }\n for (let i = 0; i < path.length; i++) {\n // Check for undefined as 0 is a valid, truthy value\n if (typeof ref[path[i]] !== 'undefined') {\n ref = ref[path[i]];\n }\n else {\n // set the reference as undefined if we don't find anything\n ref = undefined;\n break;\n }\n }\n return ref;\n}\n/**\n * Returns the path from a path name be splitting the name by a given separator.\n */\nfunction getPathFromName(pathName) {\n if (typeof pathName !== 'string') {\n throw new Error('Getting path from name failed. Name must be a string');\n }\n return pathName.split(OPTIONS.separator);\n}\n/**\n * Returns the paths name be joining its parts with a given separator.\n */\nfunction getName(path) {\n if (!path || !(path instanceof Array)) {\n throw new Error('Getting name for path failed. Path must be an array');\n }\n return path.join(OPTIONS.separator);\n}\n\nexport { getName, getPathFromName, resolveReference, usesReference };\n","import kebabCase from 'lodash/kebabCase.js';\nimport '@aws-amplify/core/internals/utils';\nimport '../../utils/setUserAgent/constants.mjs';\nimport { isObject, has, isString } from '../../utils/utils.mjs';\nimport { usesReference } from '../../utils/references.mjs';\n\nconst CSS_VARIABLE_PREFIX = 'amplify';\n/**\n * This will take an object like:\n * {paddingTop:'20px',color:'{colors.font.primary}'}\n * and turn it into a CSS string:\n * `padding-top:20px; color: var(--colors-font-primary);`\n */\nfunction propsToString(props) {\n return Object.entries(props)\n .map(([key, value]) => {\n const _value = isDesignToken(value)\n ? value.toString()\n : // @ts-ignore\n cssValue({ value });\n return `${kebabCase(key)}:${_value}; `;\n })\n .join(' ');\n}\nfunction cssNameTransform({ path = [] }) {\n return `${kebabCase([CSS_VARIABLE_PREFIX, ...path].join(' '))}`;\n}\n// Important: these properties should not be altered in\n// order to maintain the expected order of the CSS `box-shadow` property\nconst SHADOW_PROPERTIES = [\n 'offsetX',\n 'offsetY',\n 'blurRadius',\n 'spreadRadius',\n 'color',\n];\n/**\n * Will take a design token in a theme and return its value as CSS\n *\n * @param token\n * @returns\n */\nfunction cssValue(token) {\n const { value } = token;\n if (isString(value)) {\n return referenceValue(value);\n }\n if (isShadowTokenObject(value)) {\n return SHADOW_PROPERTIES.map((property) => {\n return referenceValue(\n // lookup property against `token` first for custom non-nested value, then lookup\n // property against `value` for design token value\n isShadowTokenObject(token) ? token[property] : value[property]);\n }).join(' ');\n }\n return value;\n}\n/**\n * Helper function to test if something is a design token or not.\n * Used in the React component style props.\n *\n * @param value - thing to test if it is a design token or not\n * @returns boolean\n */\nfunction isDesignToken(value) {\n return isObject(value) && has(value, 'value');\n}\nfunction isShadowTokenObject(value) {\n return isObject(value) && has(value, 'offsetX');\n}\n/**\n * Function that sees if a string contains a design token reference\n * and if so will turn that into a CSS variable.\n *\n * @param {string} value\n * @returns string\n */\nfunction referenceValue(value) {\n if (!value)\n return '';\n if (usesReference(value)) {\n const path = value.replace(/\\{|\\}/g, '').replace('.value', '').split('.');\n return `var(--${cssNameTransform({ path })})`;\n }\n return value;\n}\n/**\n * This will take a design token and add some data to it for it\n * to be used in JS/CSS. It will create its CSS var name and update\n * the value to use a CSS var if it is a reference. It will also\n * add a `.toString()` method to make it easier to use in JS.\n *\n * We should see if there is a way to share this logic with style dictionary...\n */\nconst setupToken = ({ token, path }) => {\n const name = `--${cssNameTransform({ path })}`;\n const { value: original } = token;\n const value = cssValue(token);\n return { name, original, path, value, toString: () => `var(${name})` };\n};\n/**\n * Recursive function that will walk down the token object\n * and perform the setupToken function on each token.\n * Similar to what Style Dictionary does.\n */\nfunction setupTokens({ tokens, path = [], setupToken, }) {\n if (has(tokens, 'value')) {\n return setupToken({ token: tokens, path });\n }\n const output = {};\n for (const name in tokens) {\n if (has(tokens, name)) {\n const value = tokens[name];\n const nextTokens = isObject(value) ? value : { value };\n output[name] = setupTokens({\n tokens: nextTokens,\n path: path.concat(name),\n setupToken,\n });\n }\n }\n return output;\n}\n// Internal Style Dictionary methods\n// copied from amzn/style-dictionary with the owner's permission\n/**\n * Takes an plain javascript object and will make a flat array of all the leaf nodes.\n * A leaf node in this context has a 'value' property. Potentially refactor this to\n * be more generic.\n * @private\n * @param {Object} properties - The plain object you want flattened into an array.\n * @param {Array} [to_ret=[]] - Properties array. This function is recursive therefore this is what gets passed along.\n * @return {Array}\n */\nfunction flattenProperties(properties, to_ret) {\n to_ret = to_ret || [];\n for (var name in properties) {\n if (has(properties, name)) {\n if (isObject(properties[name]) && 'value' in properties[name]) {\n to_ret.push(properties[name]);\n }\n else if (isObject(properties[name])) {\n flattenProperties(properties[name], to_ret);\n }\n }\n }\n return to_ret;\n}\n/**\n * Performs an deep extend on the objects, from right to left.\n * @private\n * @param {Object[]} objects - An array of JS objects\n * @param {Function} collision - A function to be called when a merge collision happens.\n * @param {string[]} path - (for internal use) An array of strings which is the current path down the object when this is called recursively.\n * @returns {Object}\n */\nfunction deepExtend(objects, collision, path) {\n if (objects == null)\n return {};\n var src, copyIsArray, copy, name, options, clone, target = objects[0] || {}, i = 1, length = objects.length;\n path = path || [];\n // Handle case when target is a string or something (possible in deep copy)\n if (typeof target !== 'object') {\n target = {};\n }\n for (; i < length; i++) {\n // Only deal with non-null/undefined values\n if ((options = objects[i]) != null) {\n // Extend the base object\n for (name in options) {\n if (!has(options, name))\n continue;\n if (name === '__proto__')\n continue;\n src = target[name];\n copy = options[name];\n // Prevent never-ending loop\n if (target === copy) {\n continue;\n }\n // Recurse if we're merging plain objects or arrays\n if (copy && (isObject(copy) || (copyIsArray = Array.isArray(copy)))) {\n if (copyIsArray) {\n copyIsArray = false;\n clone = src && Array.isArray(src) ? src : [];\n }\n else {\n clone = src && isObject(src) ? src : {};\n }\n var nextPath = path.slice(0);\n nextPath.push(name);\n // Never move original objects, clone them\n target[name] = deepExtend([clone, copy], collision, nextPath);\n // Don't bring in undefined values\n }\n else if (copy !== undefined) {\n if (src != null && typeof collision == 'function') {\n collision({ target: target, copy: options, path: path, key: name });\n }\n target[name] = copy;\n }\n }\n }\n }\n return target;\n}\n\nexport { CSS_VARIABLE_PREFIX, cssNameTransform, cssValue, deepExtend, flattenProperties, isDesignToken, isShadowTokenObject, propsToString, referenceValue, setupToken, setupTokens };\n","/**\n * Takes a set of keys and a color name and returns an object of design tokens,\n * used for applying a primary color at the theme level to our tokens.\n *\n * createColorPalette({keys: ['10','20',...], value: 'red'})\n * returns {\n * 10: { value: '{colors.red.10.value}' },\n * 20: { value: '{colors.red.20.value}' },\n * ...\n * }\n */\nfunction createColorPalette({ keys, value }) {\n return keys.reduce((acc, key) => {\n return {\n ...acc,\n [key]: { value: `{colors.${value}.${key}.value}` },\n };\n }, {});\n}\n\nexport { createColorPalette };\n","import '@aws-amplify/core/internals/utils';\nimport '../../utils/setUserAgent/constants.mjs';\nimport { isFunction } from '../../utils/utils.mjs';\nimport { propsToString } from './utils.mjs';\n\nfunction createAnimationCSS({ animations, tokens, }) {\n let cssText = '';\n Object.entries(animations).forEach(([key, value]) => {\n cssText += `\\n @keyframes ${key} {`;\n Object.entries(value).forEach(([step, properties]) => {\n cssText += `\\n ${step} {\\n`;\n const animationProperties = isFunction(properties)\n ? properties(tokens)\n : properties;\n cssText += propsToString(animationProperties);\n cssText += `\\n }`;\n });\n cssText += `\\n }`;\n });\n return cssText;\n}\n\nexport { createAnimationCSS };\n","import { defaultTheme } from '../defaultTheme.mjs';\nimport { deepExtend, setupTokens, setupToken, flattenProperties } from './utils.mjs';\nimport { createComponentCSS } from './createComponentCSS.mjs';\nimport '@aws-amplify/core/internals/utils';\nimport '../../utils/setUserAgent/constants.mjs';\nimport { isString } from '../../utils/utils.mjs';\nimport { createColorPalette } from './createColorPalette.mjs';\nimport { createAnimationCSS } from './createAnimationCSS.mjs';\n\n/**\n * This will be used like `const myTheme = createTheme({})`\n * `myTheme` can then be passed to a Provider or the generated CSS\n * can be passed to a stylesheet at build-time or run-time.\n * const myTheme = createTheme({})\n * const myOtherTheme = createTheme({}, myTheme);\n */\nfunction createTheme(theme, DefaultTheme = defaultTheme) {\n // merge theme and DefaultTheme to get a complete theme\n // deepExtend is an internal Style Dictionary method\n // that performs a deep merge on n objects. We could change\n // this to another 3p deep merge solution too.\n const mergedTheme = deepExtend([\n {},\n DefaultTheme,\n {\n ...theme,\n components: {},\n },\n ]);\n const { primaryColor, secondaryColor } = mergedTheme;\n // apply primaryColor and secondaryColor if present\n if (isString(primaryColor)) {\n mergedTheme.tokens.colors.primary = createColorPalette({\n keys: Object.keys(mergedTheme.tokens.colors[primaryColor]),\n value: primaryColor,\n });\n }\n if (isString(secondaryColor)) {\n mergedTheme.tokens.colors.secondary = createColorPalette({\n keys: Object.keys(mergedTheme.tokens.colors[secondaryColor]),\n value: secondaryColor,\n });\n }\n // Setting up the tokens. This is similar to what Style Dictionary\n // does. At the end of this, each token should have:\n // - CSS variable name of itself\n // - its value (reference to another CSS variable or raw value)\n const tokens = setupTokens({\n tokens: mergedTheme.tokens,\n setupToken,\n }); // Setting the type here because setupTokens is recursive\n const { breakpoints, name } = mergedTheme;\n // flattenProperties is another internal Style Dictionary function\n // that creates an array of all tokens.\n let cssText = `[data-amplify-theme=\"${name}\"] {\\n` +\n flattenProperties(tokens)\n .map((token) => `${token.name}: ${token.value};`)\n .join('\\n') +\n `\\n}\\n`;\n if (theme?.components) {\n cssText += createComponentCSS({\n theme: {\n ...mergedTheme,\n tokens,\n },\n components: theme.components,\n });\n }\n let overrides = [];\n if (mergedTheme.animations) {\n cssText += createAnimationCSS({\n animations: mergedTheme.animations,\n tokens,\n });\n }\n /**\n * For each override, we setup the tokens and then generate the CSS.\n * This allows us to have one single CSS string for all possible overrides\n * and avoid re-renders in React, but also support other frameworks as well.\n */\n if (mergedTheme.overrides) {\n overrides = mergedTheme.overrides.map((override) => {\n const overrideTokens = setupTokens({\n tokens: override.tokens,\n setupToken,\n });\n const customProperties = flattenProperties(overrideTokens)\n .map((token) => `${token.name}: ${token.value};`)\n .join('\\n');\n // Overrides can have a selector, media query, breakpoint, or color mode\n // for creating the selector\n if ('selector' in override) {\n cssText += `\\n${override.selector} {\\n${customProperties}\\n}\\n`;\n }\n if ('mediaQuery' in override) {\n cssText += `\\n@media (${override.mediaQuery}) {\n [data-amplify-theme=\"${name}\"] {\n ${customProperties}\n }\n}\\n`;\n }\n if ('breakpoint' in override) {\n const breakpoint = mergedTheme.breakpoints.values[override.breakpoint];\n cssText += `\\n@media (min-width: ${breakpoint}px) {\n [data-amplify-theme=\"${name}\"] {\n ${customProperties}\n }\n}\\n`;\n }\n if ('colorMode' in override) {\n cssText += `\\n@media (prefers-color-scheme: ${override.colorMode}) {\n [data-amplify-theme=\"${name}\"][data-amplify-color-mode=\"system\"] {\n ${customProperties}\n color-scheme: ${override.colorMode};\n }\n }\\n`;\n cssText += `\\n[data-amplify-theme=\"${name}\"][data-amplify-color-mode=\"${override.colorMode}\"] {\n ${customProperties}\n color-scheme: ${override.colorMode};\n }\\n`;\n }\n return {\n ...override,\n tokens: overrideTokens,\n };\n });\n }\n return {\n tokens,\n breakpoints,\n name,\n cssText,\n containerProps: ({ colorMode } = {}) => {\n return {\n 'data-amplify-theme': name,\n 'data-amplify-color-mode': colorMode,\n };\n },\n // keep overrides separate from base theme\n // this allows web platforms to use plain CSS scoped to a\n // selector and only override the CSS vars needed. This\n // means we could generate CSS at build-time in a postcss\n // plugin, or do it at runtime and inject the CSS into a\n // style tag.\n // This also allows RN to dynamically switch themes in a\n // provider.\n overrides,\n };\n}\n\nexport { createTheme };\n","import { isString, isObject, has } from './utils.mjs';\n\nconst classNames = (...args) => {\n const classes = [];\n for (const arg of args) {\n // skip falsey values\n if (!arg) {\n continue;\n }\n if (isString(arg)) {\n classes.push(arg);\n continue;\n }\n if (typeof arg === 'number') {\n classes.push(arg.toString());\n continue;\n }\n if (Array.isArray(arg)) {\n classes.push(classNames(...arg));\n continue;\n }\n if (isObject(arg)) {\n // check if the object has a valid .toString() method\n if (arg.toString !== Object.prototype.toString &&\n arg.toString() !== '[object Object]') {\n classes.push(arg.toString());\n continue;\n }\n for (const key in arg) {\n if (has(arg, key) && arg[key]) {\n classes.push(key);\n }\n }\n }\n }\n return classes.join(' ');\n};\n\nexport { classNames };\n","const ComponentClassName = {\n Accordion: 'amplify-accordion',\n AccordionItem: 'amplify-accordion__item',\n AccordionItemTrigger: 'amplify-accordion__item__trigger',\n AccordionItemContent: 'amplify-accordion__item__content',\n AccordionItemIcon: 'amplify-accordion__item__icon',\n Alert: 'amplify-alert',\n AlertIcon: 'amplify-alert__icon',\n AlertHeading: 'amplify-alert__heading',\n AlertBody: 'amplify-alert__body',\n AlertDismiss: 'amplify-alert__dismiss',\n Autocomplete: 'amplify-autocomplete',\n AutocompleteMenu: 'amplify-autocomplete__menu',\n AutocompleteMenuEmpty: 'amplify-autocomplete__menu--empty',\n AutocompleteMenuFooter: 'amplify-autocomplete__menu__footer',\n AutocompleteMenuHeader: 'amplify-autocomplete__menu__header',\n AutocompleteMenuLoading: 'amplify-autocomplete__menu--loading',\n AutocompleteMenuOption: 'amplify-autocomplete__menu__option',\n AutocompleteMenuOptions: 'amplify-autocomplete__menu__options',\n Avatar: 'amplify-avatar',\n AvatarIcon: 'amplify-avatar__icon',\n AvatarImage: 'amplify-avatar__image',\n AvatarLoader: 'amplify-avatar__loader',\n AIConversation: 'amplify-ai-conversation',\n AIConversationAttachment: 'amplify-ai-conversation__attachment',\n AIConversationAttachmentList: 'amplify-ai-conversation__attachment__list',\n AIConversationAttachmentImage: 'amplify-ai-conversation__attachment__image',\n AIConversationAttachmentName: 'amplify-ai-conversation__attachment__name',\n AIConversationAttachmentSize: 'amplify-ai-conversation__attachment__size',\n AIConversationAttachmentRemove: 'amplify-ai-conversation__attachment__remove',\n AIConversationForm: 'amplify-ai-conversation__form',\n AIConversationFormAttach: 'amplify-ai-conversation__form__attach',\n AIConversationFormError: 'amplify-ai-conversation__form__error',\n AIConversationFormSend: 'amplify-ai-conversation__form__send',\n AIConversationFormField: 'amplify-ai-conversation__form__field',\n AIConversationFormDropzone: 'amplify-ai-conversation__form__dropzone',\n AIConversationMessage: 'amplify-ai-conversation__message',\n AIConversationMessageAvatar: 'amplify-ai-conversation__message__avatar',\n AIConversationMessageSender: 'amplify-ai-conversation__message__sender',\n AIConversationMessageSenderUsername: 'amplify-ai-conversation__message__sender__username',\n AIConversationMessageSenderTimestamp: 'amplify-ai-conversation__message__sender__timestamp',\n AIConversationMessageBody: 'amplify-ai-conversation__message__body',\n AIConversationMessageContent: 'amplify-ai-conversation__message__content',\n AIConversationMessageActions: 'amplify-ai-conversation__message__actions',\n AIConversationMessageList: 'amplify-ai-conversation__message__list',\n AIConversationPrompt: 'amplify-ai-conversation__prompt',\n Badge: 'amplify-badge',\n Breadcrumbs: 'amplify-breadcrumbs',\n BreadcrumbsList: 'amplify-breadcrumbs__list',\n BreadcrumbsItem: 'amplify-breadcrumbs__item',\n BreadcrumbsSeparator: 'amplify-breadcrumbs__separator',\n BreadcrumbsLink: 'amplify-breadcrumbs__link',\n Button: 'amplify-button',\n ButtonGroup: 'amplify-buttongroup',\n ButtonLoaderWrapper: 'amplify-button__loader-wrapper',\n Card: 'amplify-card',\n Checkbox: 'amplify-checkbox',\n CheckboxButton: 'amplify-checkbox__button',\n CheckboxIcon: 'amplify-checkbox__icon',\n CheckboxInput: 'amplify-checkbox__input',\n CheckboxLabel: 'amplify-checkbox__label',\n CheckboxField: 'amplify-checkboxfield',\n Collection: 'amplify-collection',\n CollectionItems: 'amplify-collection-items',\n CollectionSearch: 'amplify-collection-search',\n CollectionPagination: 'amplify-collection-pagination',\n CountryCodeSelect: 'amplify-countrycodeselect',\n DialCodeSelect: 'amplify-dialcodeselect',\n Divider: 'amplify-divider',\n DividerLabel: 'amplify-divider--label',\n DropZone: 'amplify-dropzone',\n Field: 'amplify-field',\n FieldDescription: 'amplify-field__description',\n FieldErrorMessage: 'amplify-field__error-message',\n FieldGroup: 'amplify-field-group',\n FieldGroupControl: 'amplify-field-group__control',\n FieldGroupOuterEnd: 'amplify-field-group__outer-end',\n FieldGroupOuterStart: 'amplify-field-group__outer-start',\n FieldGroupInnerEnd: 'amplify-field-group__inner-end',\n FieldGroupInnerStart: 'amplify-field-group__inner-start',\n FieldGroupIcon: 'amplify-field-group__icon',\n FieldGroupIconButton: 'amplify-field-group__icon-button',\n FieldGroupHasInnerEnd: 'amplify-field-group--has-inner-end',\n FieldGroupHasInnerStart: 'amplify-field-group--has-inner-start',\n FieldShowPassword: 'amplify-field__show-password',\n FieldGroupFieldWrapper: 'amplify-field-group__field-wrapper',\n Fieldset: 'amplify-fieldset',\n FieldsetLegend: 'amplify-fieldset__legend',\n FileUploader: 'amplify-fileuploader',\n FileUploaderDropZone: 'amplify-fileuploader__dropzone',\n FileUploaderDropZoneIcon: 'amplify-fileuploader__dropzone__icon',\n FileUploaderDropZoneText: 'amplify-fileuploader__dropzone__text',\n FileUploaderFilePicker: 'amplify-fileuploader__file__picker',\n FileUploaderFile: 'amplify-fileuploader__file',\n FileUploaderFileWrapper: 'amplify-fileuploader__file__wrapper',\n FileUploaderFileList: 'amplify-fileuploader__file__list',\n FileUploaderFileName: 'amplify-fileuploader__file__name',\n FileUploaderFileSize: 'amplify-fileuploader__file__size',\n FileUploaderFileInfo: 'amplify-fileuploader__file__info',\n FileUploaderFileImage: 'amplify-fileuploader__file__image',\n FileUploaderFileMain: 'amplify-fileuploader__file__main',\n FileUploaderFileStatus: 'amplify-fileuploader__file__status',\n FileUploaderLoader: 'amplify-fileuploader__loader',\n FileUploaderPreviewer: 'amplify-fileuploader__previewer',\n FileUploaderPreviewerText: 'amplify-fileuploader__previewer__text',\n FileUploaderPreviewerActions: 'amplify-fileuploader__previewer__actions',\n FileUploaderPreviewerFooter: 'amplify-fileuploader__previewer__footer',\n Flex: 'amplify-flex',\n Grid: 'amplify-grid',\n Heading: 'amplify-heading',\n HighlightMatch: 'amplify-highlightmatch',\n HighlightMatchHighlighted: 'amplify-highlightmatch__highlighted',\n Icon: 'amplify-icon',\n Image: 'amplify-image',\n Input: 'amplify-input',\n Label: 'amplify-label',\n Link: 'amplify-link',\n Loader: 'amplify-loader',\n LoaderLabel: 'amplify-loader__label',\n MenuContent: 'amplify-menu__content',\n MenuItem: 'amplify-menu__content__item',\n MenuTrigger: 'amplify-menu__trigger',\n MenuWrapper: 'amplify-menu__wrapper',\n Message: 'amplify-message',\n MessageIcon: 'amplify-message__icon',\n MessageHeading: 'amplify-message__heading',\n MessageBody: 'amplify-message__body',\n MessageContent: 'amplify-message__content',\n MessageDismiss: 'amplify-message__dismiss',\n Pagination: 'amplify-pagination',\n PaginationItem: 'amplify-pagination__item',\n PasswordField: 'amplify-passwordfield',\n PhoneNumberField: 'amplify-phonenumberfield',\n Placeholder: 'amplify-placeholder',\n Radio: 'amplify-radio',\n RadioButton: 'amplify-radio__button',\n RadioInput: 'amplify-radio__input',\n RadioLabel: 'amplify-radio__label',\n RadioGroupField: 'amplify-radiogroupfield',\n RadioGroup: 'amplify-radiogroup',\n Rating: 'amplify-rating',\n RatingItem: 'amplify-rating__item',\n RatingIcon: 'amplify-rating__icon',\n RatingLabel: 'amplify-rating__label',\n ScrollView: 'amplify-scrollview',\n SearchField: 'amplify-searchfield',\n SearchFieldClear: 'amplify-searchfield__clear',\n SearchFieldSearch: 'amplify-searchfield__search',\n Select: 'amplify-select',\n SelectField: 'amplify-selectfield',\n SelectWrapper: 'amplify-select__wrapper',\n SelectIcon: 'amplify-select__icon',\n SliderField: 'amplify-sliderfield',\n SliderFieldGroup: 'amplify-sliderfield__group',\n SliderFieldLabel: 'amplify-sliderfield__label',\n SliderFieldRange: 'amplify-sliderfield__range',\n SliderFieldRoot: 'amplify-sliderfield__root',\n SliderFieldThumb: 'amplify-sliderfield__thumb',\n SliderFieldTrack: 'amplify-sliderfield__track',\n StepperField: 'amplify-stepperfield',\n StepperFieldButtonDecrease: 'amplify-stepperfield__button--decrease',\n StepperFieldButtonIncrease: 'amplify-stepperfield__button--increase',\n StepperFieldInput: 'amplify-stepperfield__input',\n StorageImage: 'amplify-storageimage',\n StorageManager: 'amplify-storagemanager',\n StorageManagerDropZone: 'amplify-storagemanager__dropzone',\n StorageManagerDropZoneIcon: 'amplify-storagemanager__dropzone__icon',\n StorageManagerDropZoneText: 'amplify-storagemanager__dropzone__text',\n StorageManagerFilePicker: 'amplify-storagemanager__file__picker',\n StorageManagerFile: 'amplify-storagemanager__file',\n StorageManagerFileWrapper: 'amplify-storagemanager__file__wrapper',\n StorageManagerFileList: 'amplify-storagemanager__file__list',\n StorageManagerFileName: 'amplify-storagemanager__file__name',\n StorageManagerFileSize: 'amplify-storagemanager__file__size',\n StorageManagerFileInfo: 'amplify-storagemanager__file__info',\n StorageManagerFileImage: 'amplify-storagemanager__file__image',\n StorageManagerFileMain: 'amplify-storagemanager__file__main',\n StorageManagerFileStatus: 'amplify-storagemanager__file__status',\n StorageManagerLoader: 'amplify-storagemanager__loader',\n StorageManagerPreviewer: 'amplify-storagemanager__previewer',\n StorageManagerPreviewerText: 'amplify-storagemanager__previewer__text',\n StorageManagerPreviewerActions: 'amplify-storagemanager__previewer__actions',\n StorageManagerPreviewerFooter: 'amplify-storagemanager__previewer__footer',\n SwitchField: 'amplify-switchfield',\n SwitchLabel: 'amplify-switch__label',\n SwitchThumb: 'amplify-switch__thumb',\n SwitchTrack: 'amplify-switch__track',\n SwitchWrapper: 'amplify-switch__wrapper',\n Table: 'amplify-table',\n TableCaption: 'amplify-table__caption',\n TableBody: 'amplify-table__body',\n TableTd: 'amplify-table__td',\n TableTh: 'amplify-table__th',\n TableFoot: 'amplify-table__foot',\n TableHead: 'amplify-table__head',\n TableRow: 'amplify-table__row',\n Tabs: 'amplify-tabs',\n TabsList: 'amplify-tabs__list',\n TabsItem: 'amplify-tabs__item',\n TabsPanel: 'amplify-tabs__panel',\n Text: 'amplify-text',\n Textarea: 'amplify-textarea',\n TextAreaField: 'amplify-textareafield',\n TextField: 'amplify-textfield',\n ToggleButton: 'amplify-togglebutton',\n ToggleButtonGroup: 'amplify-togglebuttongroup',\n VisuallyHidden: 'amplify-visually-hidden',\n};\n\nexport { ComponentClassName };\n","import { setCustomUserAgent } from '@aws-amplify/core/internals/utils';\nimport { STORAGE_BROWSER_INPUT_BASE, STORAGE_MANAGER_INPUT_BASE, MAP_VIEW_INPUT_BASE, LOCATION_SEARCH_INPUT_BASE, IN_APP_MESSAGING_INPUT_BASE, FILE_UPLOADER_BASE_INPUT, ACCOUNT_SETTINGS_INPUT_BASE, AUTHENTICATOR_INPUT_BASE, AI_INPUT_BASE } from './constants.mjs';\nimport { noop } from '../utils.mjs';\n\n/**\n * @example\n * ```ts\n * // set user agent options\n * const clear = setUserAgent(input);\n *\n * // clear user agent options\n * clear();\n * ```\n */\nconst setUserAgent = ({ componentName, packageName, version, }) => {\n const packageData = [`ui-${packageName}`, version];\n switch (componentName) {\n case 'AIConversation': {\n setCustomUserAgent({\n ...AI_INPUT_BASE,\n additionalDetails: [[componentName], packageData],\n });\n break;\n }\n case 'Authenticator': {\n setCustomUserAgent({\n ...AUTHENTICATOR_INPUT_BASE,\n additionalDetails: [[componentName], packageData],\n });\n break;\n }\n case 'ChangePassword':\n case 'DeleteUser': {\n setCustomUserAgent({\n ...ACCOUNT_SETTINGS_INPUT_BASE,\n additionalDetails: [['AccountSettings'], packageData],\n });\n break;\n }\n case 'FileUploader': {\n setCustomUserAgent({\n ...FILE_UPLOADER_BASE_INPUT,\n additionalDetails: [[componentName], packageData],\n });\n break;\n }\n case 'InAppMessaging': {\n setCustomUserAgent({\n ...IN_APP_MESSAGING_INPUT_BASE,\n additionalDetails: [[componentName], packageData],\n });\n break;\n }\n case 'LocationSearch': {\n setCustomUserAgent({\n ...LOCATION_SEARCH_INPUT_BASE,\n additionalDetails: [[componentName], packageData],\n });\n break;\n }\n case 'MapView': {\n setCustomUserAgent({\n ...MAP_VIEW_INPUT_BASE,\n additionalDetails: [[componentName], packageData],\n });\n break;\n }\n case 'StorageManager': {\n setCustomUserAgent({\n ...STORAGE_MANAGER_INPUT_BASE,\n additionalDetails: [[componentName], packageData],\n });\n break;\n }\n case 'StorageBrowser': {\n setCustomUserAgent({\n ...STORAGE_BROWSER_INPUT_BASE,\n additionalDetails: [[componentName], packageData],\n });\n break;\n }\n }\n return noop;\n};\n\nexport { setUserAgent };\n","import React__default from 'react';\n\n/**\n * AuthenticatorContext serves static reference to the auth machine service.\n *\n * https://xstate.js.org/docs/recipes/react.html#context-provider\n */\nconst AuthenticatorContext = React__default.createContext(null);\n\nexport { AuthenticatorContext };\n","import React__default, { useContext, useMemo, useEffect } from 'react';\nimport { useInterpret } from '@xstate/react';\nimport { getCurrentUser } from 'aws-amplify/auth';\nimport { createAuthenticatorMachine, listenToAuthHub, defaultAuthHubHandler } from '@aws-amplify/ui';\nimport { AuthenticatorContext } from './AuthenticatorContext.mjs';\n\nconst createHubHandler = (options) => (data, service) => {\n defaultAuthHubHandler(data, service, options);\n};\nfunction AuthenticatorProvider({ children, }) {\n // `authStatus` is exposed by `useAuthenticator` but should not be derived directly from the\n // state machine as the machine only updates on `Authenticator` initiated events, which\n // leads to scenarios where the state machine `authStatus` gets \"stuck\". For exmample,\n // if a user was to sign in using `Auth.signIn` directly rather than using `Authenticator`\n const [authStatus, setAuthStatus] = React__default.useState('configuring');\n // only run on first render\n React__default.useEffect(() => {\n getCurrentUser()\n .then(() => {\n setAuthStatus('authenticated');\n })\n .catch(() => {\n setAuthStatus('unauthenticated');\n });\n }, []);\n /**\n * Based on use cases, developer might already have added another Provider\n * outside Authenticator. In that case, we sync the two providers by just\n * passing the parent value.\n *\n * TODO(BREAKING): enforce only one provider in App tree\n */\n const parentProviderVal = useContext(AuthenticatorContext);\n const service = useInterpret(createAuthenticatorMachine);\n const value = useMemo(() => (!parentProviderVal ? { authStatus, service } : parentProviderVal), [authStatus, parentProviderVal, service]);\n const { service: activeService } = value;\n useEffect(() => {\n const onSignIn = () => {\n setAuthStatus('authenticated');\n };\n const onSignOut = () => {\n setAuthStatus('unauthenticated');\n };\n const unsubscribe = listenToAuthHub(activeService, createHubHandler({ onSignIn, onSignOut }));\n return unsubscribe;\n }, [activeService]);\n return (React__default.createElement(AuthenticatorContext.Provider, { value: value }, children));\n}\n\nexport { AuthenticatorProvider as default };\n","const USE_AUTHENTICATOR_ERROR = '`useAuthenticator` must be used inside an `Authenticator.Provider`.';\n\nexport { USE_AUTHENTICATOR_ERROR };\n","const COMPONENT_ROUTE_KEYS = [\n 'confirmResetPassword',\n 'confirmSignIn',\n 'confirmSignUp',\n 'confirmVerifyUser',\n 'forceNewPassword',\n 'forgotPassword',\n 'setupTotp',\n 'signIn',\n 'signUp',\n 'verifyUser',\n];\nconst COMPONENT_ROUTE_NAMES = [\n 'ConfirmResetPassword',\n 'ConfirmSignIn',\n 'ConfirmSignUp',\n 'ConfirmVerifyUser',\n 'ForceNewPassword',\n 'ForgotPassword',\n 'SetupTotp',\n 'SignIn',\n 'SignUp',\n 'VerifyUser',\n];\n\nexport { COMPONENT_ROUTE_KEYS, COMPONENT_ROUTE_NAMES };\n","import { COMPONENT_ROUTE_KEYS, COMPONENT_ROUTE_NAMES } from './constants.mjs';\n\nconst isComponentRouteKey = (route) => COMPONENT_ROUTE_KEYS.some((componentRoute) => componentRoute === route);\nfunction resolveAuthenticatorComponents(defaults, overrides) {\n if (!overrides) {\n return defaults;\n }\n return COMPONENT_ROUTE_NAMES.reduce((components, route) => {\n const Default = defaults[route];\n const Override = overrides[route];\n if (typeof Override !== 'function') {\n return { ...components, [route]: Default };\n }\n const { Footer, FormFields, Header } = Default;\n // cast to allow assigning of component slots\n const Component = Override;\n Component.Footer = Footer;\n Component.FormFields = FormFields;\n Component.Header = Header;\n return { ...components, [route]: Component };\n }, {});\n}\n\nexport { isComponentRouteKey, resolveAuthenticatorComponents };\n","import { getActorContext, getSortedFormFields, isString, areEmptyArrays, areEmptyObjects } from '@aws-amplify/ui';\nimport { isComponentRouteKey } from '../utils.mjs';\n\nconst defaultComparator = () => false;\n/**\n * Does an ordering and shallow comparison of each array value,\n * plus a value equality check for empty objects and arrays.\n */\nfunction areSelectorDepsEqual(currentDeps, nextDeps) {\n if (currentDeps.length !== nextDeps.length) {\n return false;\n }\n return currentDeps.every((currentDep, index) => {\n const nextDep = nextDeps[index];\n if (areEmptyArrays(currentDep, nextDep) ||\n areEmptyObjects(currentDep, nextDep)) {\n return true;\n }\n return currentDep === nextDep;\n });\n}\nconst getComparator = (selector) => (currentFacade, nextFacade) => {\n const currentSelectorDeps = selector(currentFacade);\n const nextSelectorDeps = selector(nextFacade);\n // Shallow compare the array values\n return areSelectorDepsEqual(currentSelectorDeps, nextSelectorDeps);\n};\nconst getQRFields = (state) => ({\n ...getActorContext(state)?.formFields?.setupTotp?.QR,\n});\nconst flattenFormFields = (fields) => fields.flatMap(([name, options]) => ({ name, ...options }));\nconst convertContactMethodsToFields = (unverifiedUserAttributes) => {\n return (unverifiedUserAttributes &&\n Object.entries(unverifiedUserAttributes).map(([name, value]) => {\n const valueIsString = isString(value);\n if (!valueIsString || !name) {\n return {};\n }\n return { name, label: value, type: 'radio', value };\n }));\n};\n/**\n * Retrieves default and custom (RWA only, to be updated) form field values from state machine\n * for subcomponent routes that render fields\n */\nconst getMachineFields = (route, state, unverifiedUserAttributes) => {\n if (isComponentRouteKey(route)) {\n return route === 'verifyUser'\n ? convertContactMethodsToFields(unverifiedUserAttributes)\n : flattenFormFields(getSortedFormFields(route, state));\n }\n return [];\n};\n\nexport { areSelectorDepsEqual, defaultComparator, getComparator, getMachineFields, getQRFields };\n","import React__default, { useCallback } from 'react';\nimport { useSelector } from '@xstate/react';\nimport { getServiceFacade } from '@aws-amplify/ui';\nimport 'aws-amplify/auth';\nimport { AuthenticatorContext } from '../../context/AuthenticatorContext.mjs';\nimport { USE_AUTHENTICATOR_ERROR } from './constants.mjs';\nimport { getQRFields, getMachineFields, getComparator, defaultComparator } from './utils.mjs';\n\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/connected-components/authenticator/headless#useauthenticator-hook)\n */\nfunction useAuthenticator(selector) {\n const context = React__default.useContext(AuthenticatorContext);\n if (!context) {\n throw new Error(USE_AUTHENTICATOR_ERROR);\n }\n const { service } = context;\n const { send } = service;\n const xstateSelector = useCallback((state) => ({ ...getServiceFacade({ send, state }) }), [send]);\n const comparator = selector ? getComparator(selector) : defaultComparator;\n // the purpose of `context.authStatus`is to intentionally override `facade.authStatus`. `facade.authStatus` does\n // not update on external sign in events (for example when a user is not using the `Authenticator`).\n const { authStatus } = context;\n const facade = useSelector(service, xstateSelector, comparator);\n const { route, totpSecretCode, unverifiedUserAttributes, user, ...rest } = facade;\n // do not memoize output. `service.getSnapshot` reference remains stable preventing\n // `fields` from updating with current form state on value changes\n const serviceSnapshot = service.getSnapshot();\n // legacy `QRFields` values only used for SetupTotp page to retrieve issuer information, will be removed in future\n const QRFields = route === 'setupTotp' ? getQRFields(serviceSnapshot) : null;\n // legacy `formFields` values required until form state is removed from state machine\n const fields = getMachineFields(route, serviceSnapshot, unverifiedUserAttributes);\n return {\n ...rest,\n authStatus,\n route,\n totpSecretCode,\n unverifiedUserAttributes,\n user,\n /** @deprecated For internal use only */\n fields,\n QRFields,\n };\n}\n\nexport { useAuthenticator as default };\n","import React from 'react';\n\nvar isCheckBoxInput = (element) => element.type === 'checkbox';\n\nvar isDateObject = (value) => value instanceof Date;\n\nvar isNullOrUndefined = (value) => value == null;\n\nconst isObjectType = (value) => typeof value === 'object';\nvar isObject = (value) => !isNullOrUndefined(value) &&\n !Array.isArray(value) &&\n isObjectType(value) &&\n !isDateObject(value);\n\nvar getEventValue = (event) => isObject(event) && event.target\n ? isCheckBoxInput(event.target)\n ? event.target.checked\n : event.target.value\n : event;\n\nvar getNodeParentName = (name) => name.substring(0, name.search(/\\.\\d+(\\.|$)/)) || name;\n\nvar isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));\n\nvar isPlainObject = (tempObject) => {\n const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;\n return (isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf'));\n};\n\nvar isWeb = typeof window !== 'undefined' &&\n typeof window.HTMLElement !== 'undefined' &&\n typeof document !== 'undefined';\n\nfunction cloneObject(data) {\n let copy;\n const isArray = Array.isArray(data);\n const isFileListInstance = typeof FileList !== 'undefined' ? data instanceof FileList : false;\n if (data instanceof Date) {\n copy = new Date(data);\n }\n else if (data instanceof Set) {\n copy = new Set(data);\n }\n else if (!(isWeb && (data instanceof Blob || isFileListInstance)) &&\n (isArray || isObject(data))) {\n copy = isArray ? [] : {};\n if (!isArray && !isPlainObject(data)) {\n copy = data;\n }\n else {\n for (const key in data) {\n if (data.hasOwnProperty(key)) {\n copy[key] = cloneObject(data[key]);\n }\n }\n }\n }\n else {\n return data;\n }\n return copy;\n}\n\nvar compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];\n\nvar isUndefined = (val) => val === undefined;\n\nvar get = (object, path, defaultValue) => {\n if (!path || !isObject(object)) {\n return defaultValue;\n }\n const result = compact(path.split(/[,[\\].]+?/)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], object);\n return isUndefined(result) || result === object\n ? isUndefined(object[path])\n ? defaultValue\n : object[path]\n : result;\n};\n\nvar isBoolean = (value) => typeof value === 'boolean';\n\nvar isKey = (value) => /^\\w*$/.test(value);\n\nvar stringToPath = (input) => compact(input.replace(/[\"|']|\\]/g, '').split(/\\.|\\[/));\n\nvar set = (object, path, value) => {\n let index = -1;\n const tempPath = isKey(path) ? [path] : stringToPath(path);\n const length = tempPath.length;\n const lastIndex = length - 1;\n while (++index < length) {\n const key = tempPath[index];\n let newValue = value;\n if (index !== lastIndex) {\n const objValue = object[key];\n newValue =\n isObject(objValue) || Array.isArray(objValue)\n ? objValue\n : !isNaN(+tempPath[index + 1])\n ? []\n : {};\n }\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return;\n }\n object[key] = newValue;\n object = object[key];\n }\n return object;\n};\n\nconst EVENTS = {\n BLUR: 'blur',\n FOCUS_OUT: 'focusout',\n CHANGE: 'change',\n};\nconst VALIDATION_MODE = {\n onBlur: 'onBlur',\n onChange: 'onChange',\n onSubmit: 'onSubmit',\n onTouched: 'onTouched',\n all: 'all',\n};\nconst INPUT_VALIDATION_RULES = {\n max: 'max',\n min: 'min',\n maxLength: 'maxLength',\n minLength: 'minLength',\n pattern: 'pattern',\n required: 'required',\n validate: 'validate',\n};\n\nconst HookFormContext = React.createContext(null);\n/**\n * This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop. To be used with {@link FormProvider}.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)\n *\n * @returns return all useForm methods\n *\n * @example\n * ```tsx\n * function App() {\n * const methods = useForm();\n * const onSubmit = data => console.log(data);\n *\n * return (\n * \n *
\n * \n * \n * \n *
\n * );\n * }\n *\n * function NestedInput() {\n * const { register } = useFormContext(); // retrieve all hook methods\n * return ;\n * }\n * ```\n */\nconst useFormContext = () => React.useContext(HookFormContext);\n/**\n * A provider component that propagates the `useForm` methods to all children components via [React Context](https://reactjs.org/docs/context.html) API. To be used with {@link useFormContext}.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)\n *\n * @param props - all useForm methods\n *\n * @example\n * ```tsx\n * function App() {\n * const methods = useForm();\n * const onSubmit = data => console.log(data);\n *\n * return (\n * \n *
\n * \n * \n * \n *
\n * );\n * }\n *\n * function NestedInput() {\n * const { register } = useFormContext(); // retrieve all hook methods\n * return ;\n * }\n * ```\n */\nconst FormProvider = (props) => {\n const { children, ...data } = props;\n return (React.createElement(HookFormContext.Provider, { value: data }, children));\n};\n\nvar getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {\n const result = {\n defaultValues: control._defaultValues,\n };\n for (const key in formState) {\n Object.defineProperty(result, key, {\n get: () => {\n const _key = key;\n if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {\n control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;\n }\n localProxyFormState && (localProxyFormState[_key] = true);\n return formState[_key];\n },\n });\n }\n return result;\n};\n\nvar isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;\n\nvar shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {\n updateFormState(formStateData);\n const { name, ...formState } = formStateData;\n return (isEmptyObject(formState) ||\n Object.keys(formState).length >= Object.keys(_proxyFormState).length ||\n Object.keys(formState).find((key) => _proxyFormState[key] ===\n (!isRoot || VALIDATION_MODE.all)));\n};\n\nvar convertToArrayPayload = (value) => (Array.isArray(value) ? value : [value]);\n\nvar shouldSubscribeByName = (name, signalName, exact) => !name ||\n !signalName ||\n name === signalName ||\n convertToArrayPayload(name).some((currentName) => currentName &&\n (exact\n ? currentName === signalName\n : currentName.startsWith(signalName) ||\n signalName.startsWith(currentName)));\n\nfunction useSubscribe(props) {\n const _props = React.useRef(props);\n _props.current = props;\n React.useEffect(() => {\n const subscription = !props.disabled &&\n _props.current.subject &&\n _props.current.subject.subscribe({\n next: _props.current.next,\n });\n return () => {\n subscription && subscription.unsubscribe();\n };\n }, [props.disabled]);\n}\n\n/**\n * This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level. It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm. Using this hook can reduce the re-render impact on large and complex form application.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)\n *\n * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}\n *\n * @example\n * ```tsx\n * function App() {\n * const { register, handleSubmit, control } = useForm({\n * defaultValues: {\n * firstName: \"firstName\"\n * }});\n * const { dirtyFields } = useFormState({\n * control\n * });\n * const onSubmit = (data) => console.log(data);\n *\n * return (\n *
\n * \n * {dirtyFields.firstName &&

Field is dirty.

}\n * \n *
\n * );\n * }\n * ```\n */\nfunction useFormState(props) {\n const methods = useFormContext();\n const { control = methods.control, disabled, name, exact } = props || {};\n const [formState, updateFormState] = React.useState(control._formState);\n const _mounted = React.useRef(true);\n const _localProxyFormState = React.useRef({\n isDirty: false,\n isLoading: false,\n dirtyFields: false,\n touchedFields: false,\n validatingFields: false,\n isValidating: false,\n isValid: false,\n errors: false,\n });\n const _name = React.useRef(name);\n _name.current = name;\n useSubscribe({\n disabled,\n next: (value) => _mounted.current &&\n shouldSubscribeByName(_name.current, value.name, exact) &&\n shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) &&\n updateFormState({\n ...control._formState,\n ...value,\n }),\n subject: control._subjects.state,\n });\n React.useEffect(() => {\n _mounted.current = true;\n _localProxyFormState.current.isValid && control._updateValid(true);\n return () => {\n _mounted.current = false;\n };\n }, [control]);\n return React.useMemo(() => getProxyFormState(formState, control, _localProxyFormState.current, false), [formState, control]);\n}\n\nvar isString = (value) => typeof value === 'string';\n\nvar generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {\n if (isString(names)) {\n isGlobal && _names.watch.add(names);\n return get(formValues, names, defaultValue);\n }\n if (Array.isArray(names)) {\n return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));\n }\n isGlobal && (_names.watchAll = true);\n return formValues;\n};\n\n/**\n * Custom hook to subscribe to field change and isolate re-rendering at the component level.\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)\n *\n * @example\n * ```tsx\n * const { control } = useForm();\n * const values = useWatch({\n * name: \"fieldName\"\n * control,\n * })\n * ```\n */\nfunction useWatch(props) {\n const methods = useFormContext();\n const { control = methods.control, name, defaultValue, disabled, exact, } = props || {};\n const _name = React.useRef(name);\n _name.current = name;\n useSubscribe({\n disabled,\n subject: control._subjects.values,\n next: (formState) => {\n if (shouldSubscribeByName(_name.current, formState.name, exact)) {\n updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));\n }\n },\n });\n const [value, updateValue] = React.useState(control._getWatch(name, defaultValue));\n React.useEffect(() => control._removeUnmounted());\n return value;\n}\n\n/**\n * Custom hook to work with controlled component, this function provide you with both form and field level state. Re-render is isolated at the hook level.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)\n *\n * @param props - the path name to the form field value, and validation rules.\n *\n * @returns field properties, field and form state. {@link UseControllerReturn}\n *\n * @example\n * ```tsx\n * function Input(props) {\n * const { field, fieldState, formState } = useController(props);\n * return (\n *
\n * \n *

{fieldState.isTouched && \"Touched\"}

\n *

{formState.isSubmitted ? \"submitted\" : \"\"}

\n *
\n * );\n * }\n * ```\n */\nfunction useController(props) {\n const methods = useFormContext();\n const { name, disabled, control = methods.control, shouldUnregister } = props;\n const isArrayField = isNameInFieldArray(control._names.array, name);\n const value = useWatch({\n control,\n name,\n defaultValue: get(control._formValues, name, get(control._defaultValues, name, props.defaultValue)),\n exact: true,\n });\n const formState = useFormState({\n control,\n name,\n exact: true,\n });\n const _registerProps = React.useRef(control.register(name, {\n ...props.rules,\n value,\n ...(isBoolean(props.disabled) ? { disabled: props.disabled } : {}),\n }));\n const fieldState = React.useMemo(() => Object.defineProperties({}, {\n invalid: {\n enumerable: true,\n get: () => !!get(formState.errors, name),\n },\n isDirty: {\n enumerable: true,\n get: () => !!get(formState.dirtyFields, name),\n },\n isTouched: {\n enumerable: true,\n get: () => !!get(formState.touchedFields, name),\n },\n isValidating: {\n enumerable: true,\n get: () => !!get(formState.validatingFields, name),\n },\n error: {\n enumerable: true,\n get: () => get(formState.errors, name),\n },\n }), [formState, name]);\n const field = React.useMemo(() => ({\n name,\n value,\n ...(isBoolean(disabled) || formState.disabled\n ? { disabled: formState.disabled || disabled }\n : {}),\n onChange: (event) => _registerProps.current.onChange({\n target: {\n value: getEventValue(event),\n name: name,\n },\n type: EVENTS.CHANGE,\n }),\n onBlur: () => _registerProps.current.onBlur({\n target: {\n value: get(control._formValues, name),\n name: name,\n },\n type: EVENTS.BLUR,\n }),\n ref: (elm) => {\n const field = get(control._fields, name);\n if (field && elm) {\n field._f.ref = {\n focus: () => elm.focus(),\n select: () => elm.select(),\n setCustomValidity: (message) => elm.setCustomValidity(message),\n reportValidity: () => elm.reportValidity(),\n };\n }\n },\n }), [\n name,\n control._formValues,\n disabled,\n formState.disabled,\n value,\n control._fields,\n ]);\n React.useEffect(() => {\n const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;\n const updateMounted = (name, value) => {\n const field = get(control._fields, name);\n if (field && field._f) {\n field._f.mount = value;\n }\n };\n updateMounted(name, true);\n if (_shouldUnregisterField) {\n const value = cloneObject(get(control._options.defaultValues, name));\n set(control._defaultValues, name, value);\n if (isUndefined(get(control._formValues, name))) {\n set(control._formValues, name, value);\n }\n }\n !isArrayField && control.register(name);\n return () => {\n (isArrayField\n ? _shouldUnregisterField && !control._state.action\n : _shouldUnregisterField)\n ? control.unregister(name)\n : updateMounted(name, false);\n };\n }, [name, control, isArrayField, shouldUnregister]);\n React.useEffect(() => {\n control._updateDisabledField({\n disabled,\n fields: control._fields,\n name,\n });\n }, [disabled, name, control]);\n return React.useMemo(() => ({\n field,\n formState,\n fieldState,\n }), [field, formState, fieldState]);\n}\n\n/**\n * Component based on `useController` hook to work with controlled component.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/usecontroller/controller) • [Demo](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) • [Video](https://www.youtube.com/watch?v=N2UNk_UCVyA)\n *\n * @param props - the path name to the form field value, and validation rules.\n *\n * @returns provide field handler functions, field and form state.\n *\n * @example\n * ```tsx\n * function App() {\n * const { control } = useForm({\n * defaultValues: {\n * test: \"\"\n * }\n * });\n *\n * return (\n *
\n * (\n * <>\n * \n *

{formState.isSubmitted ? \"submitted\" : \"\"}

\n *

{fieldState.isTouched ? \"touched\" : \"\"}

\n * \n * )}\n * />\n * \n * );\n * }\n * ```\n */\nconst Controller = (props) => props.render(useController(props));\n\nconst flatten = (obj) => {\n const output = {};\n for (const key of Object.keys(obj)) {\n if (isObjectType(obj[key]) && obj[key] !== null) {\n const nested = flatten(obj[key]);\n for (const nestedKey of Object.keys(nested)) {\n output[`${key}.${nestedKey}`] = nested[nestedKey];\n }\n }\n else {\n output[key] = obj[key];\n }\n }\n return output;\n};\n\nconst POST_REQUEST = 'post';\n/**\n * Form component to manage submission.\n *\n * @param props - to setup submission detail. {@link FormProps}\n *\n * @returns form component or headless render prop.\n *\n * @example\n * ```tsx\n * function App() {\n * const { control, formState: { errors } } = useForm();\n *\n * return (\n *
\n * \n *

{errors?.root?.server && 'Server error'}

\n * \n *
\n * );\n * }\n * ```\n */\nfunction Form(props) {\n const methods = useFormContext();\n const [mounted, setMounted] = React.useState(false);\n const { control = methods.control, onSubmit, children, action, method = POST_REQUEST, headers, encType, onError, render, onSuccess, validateStatus, ...rest } = props;\n const submit = async (event) => {\n let hasError = false;\n let type = '';\n await control.handleSubmit(async (data) => {\n const formData = new FormData();\n let formDataJson = '';\n try {\n formDataJson = JSON.stringify(data);\n }\n catch (_a) { }\n const flattenFormValues = flatten(control._formValues);\n for (const key in flattenFormValues) {\n formData.append(key, flattenFormValues[key]);\n }\n if (onSubmit) {\n await onSubmit({\n data,\n event,\n method,\n formData,\n formDataJson,\n });\n }\n if (action) {\n try {\n const shouldStringifySubmissionData = [\n headers && headers['Content-Type'],\n encType,\n ].some((value) => value && value.includes('json'));\n const response = await fetch(String(action), {\n method,\n headers: {\n ...headers,\n ...(encType ? { 'Content-Type': encType } : {}),\n },\n body: shouldStringifySubmissionData ? formDataJson : formData,\n });\n if (response &&\n (validateStatus\n ? !validateStatus(response.status)\n : response.status < 200 || response.status >= 300)) {\n hasError = true;\n onError && onError({ response });\n type = String(response.status);\n }\n else {\n onSuccess && onSuccess({ response });\n }\n }\n catch (error) {\n hasError = true;\n onError && onError({ error });\n }\n }\n })(event);\n if (hasError && props.control) {\n props.control._subjects.state.next({\n isSubmitSuccessful: false,\n });\n props.control.setError('root.server', {\n type,\n });\n }\n };\n React.useEffect(() => {\n setMounted(true);\n }, []);\n return render ? (React.createElement(React.Fragment, null, render({\n submit,\n }))) : (React.createElement(\"form\", { noValidate: mounted, action: action, method: method, encType: encType, onSubmit: submit, ...rest }, children));\n}\n\nvar appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria\n ? {\n ...errors[name],\n types: {\n ...(errors[name] && errors[name].types ? errors[name].types : {}),\n [type]: message || true,\n },\n }\n : {};\n\nvar generateId = () => {\n const d = typeof performance === 'undefined' ? Date.now() : performance.now() * 1000;\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16 + d) % 16 | 0;\n return (c == 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n};\n\nvar getFocusFieldName = (name, index, options = {}) => options.shouldFocus || isUndefined(options.shouldFocus)\n ? options.focusName ||\n `${name}.${isUndefined(options.focusIndex) ? index : options.focusIndex}.`\n : '';\n\nvar getValidationModes = (mode) => ({\n isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,\n isOnBlur: mode === VALIDATION_MODE.onBlur,\n isOnChange: mode === VALIDATION_MODE.onChange,\n isOnAll: mode === VALIDATION_MODE.all,\n isOnTouch: mode === VALIDATION_MODE.onTouched,\n});\n\nvar isWatched = (name, _names, isBlurEvent) => !isBlurEvent &&\n (_names.watchAll ||\n _names.watch.has(name) ||\n [..._names.watch].some((watchName) => name.startsWith(watchName) &&\n /^\\.\\w+/.test(name.slice(watchName.length))));\n\nconst iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {\n for (const key of fieldsNames || Object.keys(fields)) {\n const field = get(fields, key);\n if (field) {\n const { _f, ...currentField } = field;\n if (_f) {\n if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) {\n return true;\n }\n else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) {\n return true;\n }\n else {\n if (iterateFieldsByAction(currentField, action)) {\n break;\n }\n }\n }\n else if (isObject(currentField)) {\n if (iterateFieldsByAction(currentField, action)) {\n break;\n }\n }\n }\n }\n return;\n};\n\nvar updateFieldArrayRootError = (errors, error, name) => {\n const fieldArrayErrors = convertToArrayPayload(get(errors, name));\n set(fieldArrayErrors, 'root', error[name]);\n set(errors, name, fieldArrayErrors);\n return errors;\n};\n\nvar isFileInput = (element) => element.type === 'file';\n\nvar isFunction = (value) => typeof value === 'function';\n\nvar isHTMLElement = (value) => {\n if (!isWeb) {\n return false;\n }\n const owner = value ? value.ownerDocument : 0;\n return (value instanceof\n (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement));\n};\n\nvar isMessage = (value) => isString(value);\n\nvar isRadioInput = (element) => element.type === 'radio';\n\nvar isRegex = (value) => value instanceof RegExp;\n\nconst defaultResult = {\n value: false,\n isValid: false,\n};\nconst validResult = { value: true, isValid: true };\nvar getCheckboxValue = (options) => {\n if (Array.isArray(options)) {\n if (options.length > 1) {\n const values = options\n .filter((option) => option && option.checked && !option.disabled)\n .map((option) => option.value);\n return { value: values, isValid: !!values.length };\n }\n return options[0].checked && !options[0].disabled\n ? // @ts-expect-error expected to work in the browser\n options[0].attributes && !isUndefined(options[0].attributes.value)\n ? isUndefined(options[0].value) || options[0].value === ''\n ? validResult\n : { value: options[0].value, isValid: true }\n : validResult\n : defaultResult;\n }\n return defaultResult;\n};\n\nconst defaultReturn = {\n isValid: false,\n value: null,\n};\nvar getRadioValue = (options) => Array.isArray(options)\n ? options.reduce((previous, option) => option && option.checked && !option.disabled\n ? {\n isValid: true,\n value: option.value,\n }\n : previous, defaultReturn)\n : defaultReturn;\n\nfunction getValidateError(result, ref, type = 'validate') {\n if (isMessage(result) ||\n (Array.isArray(result) && result.every(isMessage)) ||\n (isBoolean(result) && !result)) {\n return {\n type,\n message: isMessage(result) ? result : '',\n ref,\n };\n }\n}\n\nvar getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData)\n ? validationData\n : {\n value: validationData,\n message: '',\n };\n\nvar validateField = async (field, disabledFieldNames, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {\n const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, } = field._f;\n const inputValue = get(formValues, name);\n if (!mount || disabledFieldNames.has(name)) {\n return {};\n }\n const inputRef = refs ? refs[0] : ref;\n const setCustomValidity = (message) => {\n if (shouldUseNativeValidation && inputRef.reportValidity) {\n inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');\n inputRef.reportValidity();\n }\n };\n const error = {};\n const isRadio = isRadioInput(ref);\n const isCheckBox = isCheckBoxInput(ref);\n const isRadioOrCheckbox = isRadio || isCheckBox;\n const isEmpty = ((valueAsNumber || isFileInput(ref)) &&\n isUndefined(ref.value) &&\n isUndefined(inputValue)) ||\n (isHTMLElement(ref) && ref.value === '') ||\n inputValue === '' ||\n (Array.isArray(inputValue) && !inputValue.length);\n const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);\n const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {\n const message = exceedMax ? maxLengthMessage : minLengthMessage;\n error[name] = {\n type: exceedMax ? maxType : minType,\n message,\n ref,\n ...appendErrorsCurry(exceedMax ? maxType : minType, message),\n };\n };\n if (isFieldArray\n ? !Array.isArray(inputValue) || !inputValue.length\n : required &&\n ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||\n (isBoolean(inputValue) && !inputValue) ||\n (isCheckBox && !getCheckboxValue(refs).isValid) ||\n (isRadio && !getRadioValue(refs).isValid))) {\n const { value, message } = isMessage(required)\n ? { value: !!required, message: required }\n : getValueAndMessage(required);\n if (value) {\n error[name] = {\n type: INPUT_VALIDATION_RULES.required,\n message,\n ref: inputRef,\n ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),\n };\n if (!validateAllFieldCriteria) {\n setCustomValidity(message);\n return error;\n }\n }\n }\n if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {\n let exceedMax;\n let exceedMin;\n const maxOutput = getValueAndMessage(max);\n const minOutput = getValueAndMessage(min);\n if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {\n const valueNumber = ref.valueAsNumber ||\n (inputValue ? +inputValue : inputValue);\n if (!isNullOrUndefined(maxOutput.value)) {\n exceedMax = valueNumber > maxOutput.value;\n }\n if (!isNullOrUndefined(minOutput.value)) {\n exceedMin = valueNumber < minOutput.value;\n }\n }\n else {\n const valueDate = ref.valueAsDate || new Date(inputValue);\n const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);\n const isTime = ref.type == 'time';\n const isWeek = ref.type == 'week';\n if (isString(maxOutput.value) && inputValue) {\n exceedMax = isTime\n ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)\n : isWeek\n ? inputValue > maxOutput.value\n : valueDate > new Date(maxOutput.value);\n }\n if (isString(minOutput.value) && inputValue) {\n exceedMin = isTime\n ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)\n : isWeek\n ? inputValue < minOutput.value\n : valueDate < new Date(minOutput.value);\n }\n }\n if (exceedMax || exceedMin) {\n getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);\n if (!validateAllFieldCriteria) {\n setCustomValidity(error[name].message);\n return error;\n }\n }\n }\n if ((maxLength || minLength) &&\n !isEmpty &&\n (isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))) {\n const maxLengthOutput = getValueAndMessage(maxLength);\n const minLengthOutput = getValueAndMessage(minLength);\n const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&\n inputValue.length > +maxLengthOutput.value;\n const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&\n inputValue.length < +minLengthOutput.value;\n if (exceedMax || exceedMin) {\n getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);\n if (!validateAllFieldCriteria) {\n setCustomValidity(error[name].message);\n return error;\n }\n }\n }\n if (pattern && !isEmpty && isString(inputValue)) {\n const { value: patternValue, message } = getValueAndMessage(pattern);\n if (isRegex(patternValue) && !inputValue.match(patternValue)) {\n error[name] = {\n type: INPUT_VALIDATION_RULES.pattern,\n message,\n ref,\n ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),\n };\n if (!validateAllFieldCriteria) {\n setCustomValidity(message);\n return error;\n }\n }\n }\n if (validate) {\n if (isFunction(validate)) {\n const result = await validate(inputValue, formValues);\n const validateError = getValidateError(result, inputRef);\n if (validateError) {\n error[name] = {\n ...validateError,\n ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message),\n };\n if (!validateAllFieldCriteria) {\n setCustomValidity(validateError.message);\n return error;\n }\n }\n }\n else if (isObject(validate)) {\n let validationResult = {};\n for (const key in validate) {\n if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {\n break;\n }\n const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);\n if (validateError) {\n validationResult = {\n ...validateError,\n ...appendErrorsCurry(key, validateError.message),\n };\n setCustomValidity(validateError.message);\n if (validateAllFieldCriteria) {\n error[name] = validationResult;\n }\n }\n }\n if (!isEmptyObject(validationResult)) {\n error[name] = {\n ref: inputRef,\n ...validationResult,\n };\n if (!validateAllFieldCriteria) {\n return error;\n }\n }\n }\n }\n setCustomValidity(true);\n return error;\n};\n\nvar appendAt = (data, value) => [\n ...data,\n ...convertToArrayPayload(value),\n];\n\nvar fillEmptyArray = (value) => Array.isArray(value) ? value.map(() => undefined) : undefined;\n\nfunction insert(data, index, value) {\n return [\n ...data.slice(0, index),\n ...convertToArrayPayload(value),\n ...data.slice(index),\n ];\n}\n\nvar moveArrayAt = (data, from, to) => {\n if (!Array.isArray(data)) {\n return [];\n }\n if (isUndefined(data[to])) {\n data[to] = undefined;\n }\n data.splice(to, 0, data.splice(from, 1)[0]);\n return data;\n};\n\nvar prependAt = (data, value) => [\n ...convertToArrayPayload(value),\n ...convertToArrayPayload(data),\n];\n\nfunction removeAtIndexes(data, indexes) {\n let i = 0;\n const temp = [...data];\n for (const index of indexes) {\n temp.splice(index - i, 1);\n i++;\n }\n return compact(temp).length ? temp : [];\n}\nvar removeArrayAt = (data, index) => isUndefined(index)\n ? []\n : removeAtIndexes(data, convertToArrayPayload(index).sort((a, b) => a - b));\n\nvar swapArrayAt = (data, indexA, indexB) => {\n [data[indexA], data[indexB]] = [data[indexB], data[indexA]];\n};\n\nfunction baseGet(object, updatePath) {\n const length = updatePath.slice(0, -1).length;\n let index = 0;\n while (index < length) {\n object = isUndefined(object) ? index++ : object[updatePath[index++]];\n }\n return object;\n}\nfunction isEmptyArray(obj) {\n for (const key in obj) {\n if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {\n return false;\n }\n }\n return true;\n}\nfunction unset(object, path) {\n const paths = Array.isArray(path)\n ? path\n : isKey(path)\n ? [path]\n : stringToPath(path);\n const childObject = paths.length === 1 ? object : baseGet(object, paths);\n const index = paths.length - 1;\n const key = paths[index];\n if (childObject) {\n delete childObject[key];\n }\n if (index !== 0 &&\n ((isObject(childObject) && isEmptyObject(childObject)) ||\n (Array.isArray(childObject) && isEmptyArray(childObject)))) {\n unset(object, paths.slice(0, -1));\n }\n return object;\n}\n\nvar updateAt = (fieldValues, index, value) => {\n fieldValues[index] = value;\n return fieldValues;\n};\n\n/**\n * A custom hook that exposes convenient methods to perform operations with a list of dynamic inputs that need to be appended, updated, removed etc. • [Demo](https://codesandbox.io/s/react-hook-form-usefieldarray-ssugn) • [Video](https://youtu.be/4MrbfGSFY2A)\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/usefieldarray) • [Demo](https://codesandbox.io/s/react-hook-form-usefieldarray-ssugn)\n *\n * @param props - useFieldArray props\n *\n * @returns methods - functions to manipulate with the Field Arrays (dynamic inputs) {@link UseFieldArrayReturn}\n *\n * @example\n * ```tsx\n * function App() {\n * const { register, control, handleSubmit, reset, trigger, setError } = useForm({\n * defaultValues: {\n * test: []\n * }\n * });\n * const { fields, append } = useFieldArray({\n * control,\n * name: \"test\"\n * });\n *\n * return (\n *
console.log(data))}>\n * {fields.map((item, index) => (\n * \n * ))}\n * \n * \n *
\n * );\n * }\n * ```\n */\nfunction useFieldArray(props) {\n const methods = useFormContext();\n const { control = methods.control, name, keyName = 'id', shouldUnregister, rules, } = props;\n const [fields, setFields] = React.useState(control._getFieldArray(name));\n const ids = React.useRef(control._getFieldArray(name).map(generateId));\n const _fieldIds = React.useRef(fields);\n const _name = React.useRef(name);\n const _actioned = React.useRef(false);\n _name.current = name;\n _fieldIds.current = fields;\n control._names.array.add(name);\n rules &&\n control.register(name, rules);\n useSubscribe({\n next: ({ values, name: fieldArrayName, }) => {\n if (fieldArrayName === _name.current || !fieldArrayName) {\n const fieldValues = get(values, _name.current);\n if (Array.isArray(fieldValues)) {\n setFields(fieldValues);\n ids.current = fieldValues.map(generateId);\n }\n }\n },\n subject: control._subjects.array,\n });\n const updateValues = React.useCallback((updatedFieldArrayValues) => {\n _actioned.current = true;\n control._updateFieldArray(name, updatedFieldArrayValues);\n }, [control, name]);\n const append = (value, options) => {\n const appendValue = convertToArrayPayload(cloneObject(value));\n const updatedFieldArrayValues = appendAt(control._getFieldArray(name), appendValue);\n control._names.focus = getFocusFieldName(name, updatedFieldArrayValues.length - 1, options);\n ids.current = appendAt(ids.current, appendValue.map(generateId));\n updateValues(updatedFieldArrayValues);\n setFields(updatedFieldArrayValues);\n control._updateFieldArray(name, updatedFieldArrayValues, appendAt, {\n argA: fillEmptyArray(value),\n });\n };\n const prepend = (value, options) => {\n const prependValue = convertToArrayPayload(cloneObject(value));\n const updatedFieldArrayValues = prependAt(control._getFieldArray(name), prependValue);\n control._names.focus = getFocusFieldName(name, 0, options);\n ids.current = prependAt(ids.current, prependValue.map(generateId));\n updateValues(updatedFieldArrayValues);\n setFields(updatedFieldArrayValues);\n control._updateFieldArray(name, updatedFieldArrayValues, prependAt, {\n argA: fillEmptyArray(value),\n });\n };\n const remove = (index) => {\n const updatedFieldArrayValues = removeArrayAt(control._getFieldArray(name), index);\n ids.current = removeArrayAt(ids.current, index);\n updateValues(updatedFieldArrayValues);\n setFields(updatedFieldArrayValues);\n !Array.isArray(get(control._fields, name)) &&\n set(control._fields, name, undefined);\n control._updateFieldArray(name, updatedFieldArrayValues, removeArrayAt, {\n argA: index,\n });\n };\n const insert$1 = (index, value, options) => {\n const insertValue = convertToArrayPayload(cloneObject(value));\n const updatedFieldArrayValues = insert(control._getFieldArray(name), index, insertValue);\n control._names.focus = getFocusFieldName(name, index, options);\n ids.current = insert(ids.current, index, insertValue.map(generateId));\n updateValues(updatedFieldArrayValues);\n setFields(updatedFieldArrayValues);\n control._updateFieldArray(name, updatedFieldArrayValues, insert, {\n argA: index,\n argB: fillEmptyArray(value),\n });\n };\n const swap = (indexA, indexB) => {\n const updatedFieldArrayValues = control._getFieldArray(name);\n swapArrayAt(updatedFieldArrayValues, indexA, indexB);\n swapArrayAt(ids.current, indexA, indexB);\n updateValues(updatedFieldArrayValues);\n setFields(updatedFieldArrayValues);\n control._updateFieldArray(name, updatedFieldArrayValues, swapArrayAt, {\n argA: indexA,\n argB: indexB,\n }, false);\n };\n const move = (from, to) => {\n const updatedFieldArrayValues = control._getFieldArray(name);\n moveArrayAt(updatedFieldArrayValues, from, to);\n moveArrayAt(ids.current, from, to);\n updateValues(updatedFieldArrayValues);\n setFields(updatedFieldArrayValues);\n control._updateFieldArray(name, updatedFieldArrayValues, moveArrayAt, {\n argA: from,\n argB: to,\n }, false);\n };\n const update = (index, value) => {\n const updateValue = cloneObject(value);\n const updatedFieldArrayValues = updateAt(control._getFieldArray(name), index, updateValue);\n ids.current = [...updatedFieldArrayValues].map((item, i) => !item || i === index ? generateId() : ids.current[i]);\n updateValues(updatedFieldArrayValues);\n setFields([...updatedFieldArrayValues]);\n control._updateFieldArray(name, updatedFieldArrayValues, updateAt, {\n argA: index,\n argB: updateValue,\n }, true, false);\n };\n const replace = (value) => {\n const updatedFieldArrayValues = convertToArrayPayload(cloneObject(value));\n ids.current = updatedFieldArrayValues.map(generateId);\n updateValues([...updatedFieldArrayValues]);\n setFields([...updatedFieldArrayValues]);\n control._updateFieldArray(name, [...updatedFieldArrayValues], (data) => data, {}, true, false);\n };\n React.useEffect(() => {\n control._state.action = false;\n isWatched(name, control._names) &&\n control._subjects.state.next({\n ...control._formState,\n });\n if (_actioned.current &&\n (!getValidationModes(control._options.mode).isOnSubmit ||\n control._formState.isSubmitted)) {\n if (control._options.resolver) {\n control._executeSchema([name]).then((result) => {\n const error = get(result.errors, name);\n const existingError = get(control._formState.errors, name);\n if (existingError\n ? (!error && existingError.type) ||\n (error &&\n (existingError.type !== error.type ||\n existingError.message !== error.message))\n : error && error.type) {\n error\n ? set(control._formState.errors, name, error)\n : unset(control._formState.errors, name);\n control._subjects.state.next({\n errors: control._formState.errors,\n });\n }\n });\n }\n else {\n const field = get(control._fields, name);\n if (field &&\n field._f &&\n !(getValidationModes(control._options.reValidateMode).isOnSubmit &&\n getValidationModes(control._options.mode).isOnSubmit)) {\n validateField(field, control._names.disabled, control._formValues, control._options.criteriaMode === VALIDATION_MODE.all, control._options.shouldUseNativeValidation, true).then((error) => !isEmptyObject(error) &&\n control._subjects.state.next({\n errors: updateFieldArrayRootError(control._formState.errors, error, name),\n }));\n }\n }\n }\n control._subjects.values.next({\n name,\n values: { ...control._formValues },\n });\n control._names.focus &&\n iterateFieldsByAction(control._fields, (ref, key) => {\n if (control._names.focus &&\n key.startsWith(control._names.focus) &&\n ref.focus) {\n ref.focus();\n return 1;\n }\n return;\n });\n control._names.focus = '';\n control._updateValid();\n _actioned.current = false;\n }, [fields, name, control]);\n React.useEffect(() => {\n !get(control._formValues, name) && control._updateFieldArray(name);\n return () => {\n (control._options.shouldUnregister || shouldUnregister) &&\n control.unregister(name);\n };\n }, [name, control, keyName, shouldUnregister]);\n return {\n swap: React.useCallback(swap, [updateValues, name, control]),\n move: React.useCallback(move, [updateValues, name, control]),\n prepend: React.useCallback(prepend, [updateValues, name, control]),\n append: React.useCallback(append, [updateValues, name, control]),\n remove: React.useCallback(remove, [updateValues, name, control]),\n insert: React.useCallback(insert$1, [updateValues, name, control]),\n update: React.useCallback(update, [updateValues, name, control]),\n replace: React.useCallback(replace, [updateValues, name, control]),\n fields: React.useMemo(() => fields.map((field, index) => ({\n ...field,\n [keyName]: ids.current[index] || generateId(),\n })), [fields, keyName]),\n };\n}\n\nvar createSubject = () => {\n let _observers = [];\n const next = (value) => {\n for (const observer of _observers) {\n observer.next && observer.next(value);\n }\n };\n const subscribe = (observer) => {\n _observers.push(observer);\n return {\n unsubscribe: () => {\n _observers = _observers.filter((o) => o !== observer);\n },\n };\n };\n const unsubscribe = () => {\n _observers = [];\n };\n return {\n get observers() {\n return _observers;\n },\n next,\n subscribe,\n unsubscribe,\n };\n};\n\nvar isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);\n\nfunction deepEqual(object1, object2) {\n if (isPrimitive(object1) || isPrimitive(object2)) {\n return object1 === object2;\n }\n if (isDateObject(object1) && isDateObject(object2)) {\n return object1.getTime() === object2.getTime();\n }\n const keys1 = Object.keys(object1);\n const keys2 = Object.keys(object2);\n if (keys1.length !== keys2.length) {\n return false;\n }\n for (const key of keys1) {\n const val1 = object1[key];\n if (!keys2.includes(key)) {\n return false;\n }\n if (key !== 'ref') {\n const val2 = object2[key];\n if ((isDateObject(val1) && isDateObject(val2)) ||\n (isObject(val1) && isObject(val2)) ||\n (Array.isArray(val1) && Array.isArray(val2))\n ? !deepEqual(val1, val2)\n : val1 !== val2) {\n return false;\n }\n }\n }\n return true;\n}\n\nvar isMultipleSelect = (element) => element.type === `select-multiple`;\n\nvar isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);\n\nvar live = (ref) => isHTMLElement(ref) && ref.isConnected;\n\nvar objectHasFunction = (data) => {\n for (const key in data) {\n if (isFunction(data[key])) {\n return true;\n }\n }\n return false;\n};\n\nfunction markFieldsDirty(data, fields = {}) {\n const isParentNodeArray = Array.isArray(data);\n if (isObject(data) || isParentNodeArray) {\n for (const key in data) {\n if (Array.isArray(data[key]) ||\n (isObject(data[key]) && !objectHasFunction(data[key]))) {\n fields[key] = Array.isArray(data[key]) ? [] : {};\n markFieldsDirty(data[key], fields[key]);\n }\n else if (!isNullOrUndefined(data[key])) {\n fields[key] = true;\n }\n }\n }\n return fields;\n}\nfunction getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) {\n const isParentNodeArray = Array.isArray(data);\n if (isObject(data) || isParentNodeArray) {\n for (const key in data) {\n if (Array.isArray(data[key]) ||\n (isObject(data[key]) && !objectHasFunction(data[key]))) {\n if (isUndefined(formValues) ||\n isPrimitive(dirtyFieldsFromValues[key])) {\n dirtyFieldsFromValues[key] = Array.isArray(data[key])\n ? markFieldsDirty(data[key], [])\n : { ...markFieldsDirty(data[key]) };\n }\n else {\n getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);\n }\n }\n else {\n dirtyFieldsFromValues[key] = !deepEqual(data[key], formValues[key]);\n }\n }\n }\n return dirtyFieldsFromValues;\n}\nvar getDirtyFields = (defaultValues, formValues) => getDirtyFieldsFromDefaultValues(defaultValues, formValues, markFieldsDirty(formValues));\n\nvar getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value)\n ? value\n : valueAsNumber\n ? value === ''\n ? NaN\n : value\n ? +value\n : value\n : valueAsDate && isString(value)\n ? new Date(value)\n : setValueAs\n ? setValueAs(value)\n : value;\n\nfunction getFieldValue(_f) {\n const ref = _f.ref;\n if (isFileInput(ref)) {\n return ref.files;\n }\n if (isRadioInput(ref)) {\n return getRadioValue(_f.refs).value;\n }\n if (isMultipleSelect(ref)) {\n return [...ref.selectedOptions].map(({ value }) => value);\n }\n if (isCheckBoxInput(ref)) {\n return getCheckboxValue(_f.refs).value;\n }\n return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);\n}\n\nvar getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {\n const fields = {};\n for (const name of fieldsNames) {\n const field = get(_fields, name);\n field && set(fields, name, field._f);\n }\n return {\n criteriaMode,\n names: [...fieldsNames],\n fields,\n shouldUseNativeValidation,\n };\n};\n\nvar getRuleValue = (rule) => isUndefined(rule)\n ? rule\n : isRegex(rule)\n ? rule.source\n : isObject(rule)\n ? isRegex(rule.value)\n ? rule.value.source\n : rule.value\n : rule;\n\nconst ASYNC_FUNCTION = 'AsyncFunction';\nvar hasPromiseValidation = (fieldReference) => !!fieldReference &&\n !!fieldReference.validate &&\n !!((isFunction(fieldReference.validate) &&\n fieldReference.validate.constructor.name === ASYNC_FUNCTION) ||\n (isObject(fieldReference.validate) &&\n Object.values(fieldReference.validate).find((validateFunction) => validateFunction.constructor.name === ASYNC_FUNCTION)));\n\nvar hasValidation = (options) => options.mount &&\n (options.required ||\n options.min ||\n options.max ||\n options.maxLength ||\n options.minLength ||\n options.pattern ||\n options.validate);\n\nfunction schemaErrorLookup(errors, _fields, name) {\n const error = get(errors, name);\n if (error || isKey(name)) {\n return {\n error,\n name,\n };\n }\n const names = name.split('.');\n while (names.length) {\n const fieldName = names.join('.');\n const field = get(_fields, fieldName);\n const foundError = get(errors, fieldName);\n if (field && !Array.isArray(field) && name !== fieldName) {\n return { name };\n }\n if (foundError && foundError.type) {\n return {\n name: fieldName,\n error: foundError,\n };\n }\n names.pop();\n }\n return {\n name,\n };\n}\n\nvar skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {\n if (mode.isOnAll) {\n return false;\n }\n else if (!isSubmitted && mode.isOnTouch) {\n return !(isTouched || isBlurEvent);\n }\n else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {\n return !isBlurEvent;\n }\n else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {\n return isBlurEvent;\n }\n return true;\n};\n\nvar unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);\n\nconst defaultOptions = {\n mode: VALIDATION_MODE.onSubmit,\n reValidateMode: VALIDATION_MODE.onChange,\n shouldFocusError: true,\n};\nfunction createFormControl(props = {}) {\n let _options = {\n ...defaultOptions,\n ...props,\n };\n let _formState = {\n submitCount: 0,\n isDirty: false,\n isLoading: isFunction(_options.defaultValues),\n isValidating: false,\n isSubmitted: false,\n isSubmitting: false,\n isSubmitSuccessful: false,\n isValid: false,\n touchedFields: {},\n dirtyFields: {},\n validatingFields: {},\n errors: _options.errors || {},\n disabled: _options.disabled || false,\n };\n let _fields = {};\n let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values)\n ? cloneObject(_options.defaultValues || _options.values) || {}\n : {};\n let _formValues = _options.shouldUnregister\n ? {}\n : cloneObject(_defaultValues);\n let _state = {\n action: false,\n mount: false,\n watch: false,\n };\n let _names = {\n mount: new Set(),\n disabled: new Set(),\n unMount: new Set(),\n array: new Set(),\n watch: new Set(),\n };\n let delayErrorCallback;\n let timer = 0;\n const _proxyFormState = {\n isDirty: false,\n dirtyFields: false,\n validatingFields: false,\n touchedFields: false,\n isValidating: false,\n isValid: false,\n errors: false,\n };\n const _subjects = {\n values: createSubject(),\n array: createSubject(),\n state: createSubject(),\n };\n const validationModeBeforeSubmit = getValidationModes(_options.mode);\n const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);\n const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;\n const debounce = (callback) => (wait) => {\n clearTimeout(timer);\n timer = setTimeout(callback, wait);\n };\n const _updateValid = async (shouldUpdateValid) => {\n if (!_options.disabled && (_proxyFormState.isValid || shouldUpdateValid)) {\n const isValid = _options.resolver\n ? isEmptyObject((await _executeSchema()).errors)\n : await executeBuiltInValidation(_fields, true);\n if (isValid !== _formState.isValid) {\n _subjects.state.next({\n isValid,\n });\n }\n }\n };\n const _updateIsValidating = (names, isValidating) => {\n if (!_options.disabled &&\n (_proxyFormState.isValidating || _proxyFormState.validatingFields)) {\n (names || Array.from(_names.mount)).forEach((name) => {\n if (name) {\n isValidating\n ? set(_formState.validatingFields, name, isValidating)\n : unset(_formState.validatingFields, name);\n }\n });\n _subjects.state.next({\n validatingFields: _formState.validatingFields,\n isValidating: !isEmptyObject(_formState.validatingFields),\n });\n }\n };\n const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {\n if (args && method && !_options.disabled) {\n _state.action = true;\n if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {\n const fieldValues = method(get(_fields, name), args.argA, args.argB);\n shouldSetValues && set(_fields, name, fieldValues);\n }\n if (shouldUpdateFieldsAndState &&\n Array.isArray(get(_formState.errors, name))) {\n const errors = method(get(_formState.errors, name), args.argA, args.argB);\n shouldSetValues && set(_formState.errors, name, errors);\n unsetEmptyArray(_formState.errors, name);\n }\n if (_proxyFormState.touchedFields &&\n shouldUpdateFieldsAndState &&\n Array.isArray(get(_formState.touchedFields, name))) {\n const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);\n shouldSetValues && set(_formState.touchedFields, name, touchedFields);\n }\n if (_proxyFormState.dirtyFields) {\n _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);\n }\n _subjects.state.next({\n name,\n isDirty: _getDirty(name, values),\n dirtyFields: _formState.dirtyFields,\n errors: _formState.errors,\n isValid: _formState.isValid,\n });\n }\n else {\n set(_formValues, name, values);\n }\n };\n const updateErrors = (name, error) => {\n set(_formState.errors, name, error);\n _subjects.state.next({\n errors: _formState.errors,\n });\n };\n const _setErrors = (errors) => {\n _formState.errors = errors;\n _subjects.state.next({\n errors: _formState.errors,\n isValid: false,\n });\n };\n const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {\n const field = get(_fields, name);\n if (field) {\n const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);\n isUndefined(defaultValue) ||\n (ref && ref.defaultChecked) ||\n shouldSkipSetValueAs\n ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f))\n : setFieldValue(name, defaultValue);\n _state.mount && _updateValid();\n }\n };\n const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {\n let shouldUpdateField = false;\n let isPreviousDirty = false;\n const output = {\n name,\n };\n if (!_options.disabled) {\n const disabledField = !!(get(_fields, name) &&\n get(_fields, name)._f &&\n get(_fields, name)._f.disabled);\n if (!isBlurEvent || shouldDirty) {\n if (_proxyFormState.isDirty) {\n isPreviousDirty = _formState.isDirty;\n _formState.isDirty = output.isDirty = _getDirty();\n shouldUpdateField = isPreviousDirty !== output.isDirty;\n }\n const isCurrentFieldPristine = disabledField || deepEqual(get(_defaultValues, name), fieldValue);\n isPreviousDirty = !!(!disabledField && get(_formState.dirtyFields, name));\n isCurrentFieldPristine || disabledField\n ? unset(_formState.dirtyFields, name)\n : set(_formState.dirtyFields, name, true);\n output.dirtyFields = _formState.dirtyFields;\n shouldUpdateField =\n shouldUpdateField ||\n (_proxyFormState.dirtyFields &&\n isPreviousDirty !== !isCurrentFieldPristine);\n }\n if (isBlurEvent) {\n const isPreviousFieldTouched = get(_formState.touchedFields, name);\n if (!isPreviousFieldTouched) {\n set(_formState.touchedFields, name, isBlurEvent);\n output.touchedFields = _formState.touchedFields;\n shouldUpdateField =\n shouldUpdateField ||\n (_proxyFormState.touchedFields &&\n isPreviousFieldTouched !== isBlurEvent);\n }\n }\n shouldUpdateField && shouldRender && _subjects.state.next(output);\n }\n return shouldUpdateField ? output : {};\n };\n const shouldRenderByError = (name, isValid, error, fieldState) => {\n const previousFieldError = get(_formState.errors, name);\n const shouldUpdateValid = _proxyFormState.isValid &&\n isBoolean(isValid) &&\n _formState.isValid !== isValid;\n if (_options.delayError && error) {\n delayErrorCallback = debounce(() => updateErrors(name, error));\n delayErrorCallback(_options.delayError);\n }\n else {\n clearTimeout(timer);\n delayErrorCallback = null;\n error\n ? set(_formState.errors, name, error)\n : unset(_formState.errors, name);\n }\n if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) ||\n !isEmptyObject(fieldState) ||\n shouldUpdateValid) {\n const updatedFormState = {\n ...fieldState,\n ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),\n errors: _formState.errors,\n name,\n };\n _formState = {\n ..._formState,\n ...updatedFormState,\n };\n _subjects.state.next(updatedFormState);\n }\n };\n const _executeSchema = async (name) => {\n _updateIsValidating(name, true);\n const result = await _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));\n _updateIsValidating(name);\n return result;\n };\n const executeSchemaAndUpdateState = async (names) => {\n const { errors } = await _executeSchema(names);\n if (names) {\n for (const name of names) {\n const error = get(errors, name);\n error\n ? set(_formState.errors, name, error)\n : unset(_formState.errors, name);\n }\n }\n else {\n _formState.errors = errors;\n }\n return errors;\n };\n const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {\n valid: true,\n }) => {\n for (const name in fields) {\n const field = fields[name];\n if (field) {\n const { _f, ...fieldValue } = field;\n if (_f) {\n const isFieldArrayRoot = _names.array.has(_f.name);\n const isPromiseFunction = field._f && hasPromiseValidation(field._f);\n if (isPromiseFunction && _proxyFormState.validatingFields) {\n _updateIsValidating([name], true);\n }\n const fieldError = await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);\n if (isPromiseFunction && _proxyFormState.validatingFields) {\n _updateIsValidating([name]);\n }\n if (fieldError[_f.name]) {\n context.valid = false;\n if (shouldOnlyCheckValid) {\n break;\n }\n }\n !shouldOnlyCheckValid &&\n (get(fieldError, _f.name)\n ? isFieldArrayRoot\n ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name)\n : set(_formState.errors, _f.name, fieldError[_f.name])\n : unset(_formState.errors, _f.name));\n }\n !isEmptyObject(fieldValue) &&\n (await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context));\n }\n }\n return context.valid;\n };\n const _removeUnmounted = () => {\n for (const name of _names.unMount) {\n const field = get(_fields, name);\n field &&\n (field._f.refs\n ? field._f.refs.every((ref) => !live(ref))\n : !live(field._f.ref)) &&\n unregister(name);\n }\n _names.unMount = new Set();\n };\n const _getDirty = (name, data) => !_options.disabled &&\n (name && data && set(_formValues, name, data),\n !deepEqual(getValues(), _defaultValues));\n const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {\n ...(_state.mount\n ? _formValues\n : isUndefined(defaultValue)\n ? _defaultValues\n : isString(names)\n ? { [names]: defaultValue }\n : defaultValue),\n }, isGlobal, defaultValue);\n const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, _options.shouldUnregister ? get(_defaultValues, name, []) : []));\n const setFieldValue = (name, value, options = {}) => {\n const field = get(_fields, name);\n let fieldValue = value;\n if (field) {\n const fieldReference = field._f;\n if (fieldReference) {\n !fieldReference.disabled &&\n set(_formValues, name, getFieldValueAs(value, fieldReference));\n fieldValue =\n isHTMLElement(fieldReference.ref) && isNullOrUndefined(value)\n ? ''\n : value;\n if (isMultipleSelect(fieldReference.ref)) {\n [...fieldReference.ref.options].forEach((optionRef) => (optionRef.selected = fieldValue.includes(optionRef.value)));\n }\n else if (fieldReference.refs) {\n if (isCheckBoxInput(fieldReference.ref)) {\n fieldReference.refs.length > 1\n ? fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) &&\n (checkboxRef.checked = Array.isArray(fieldValue)\n ? !!fieldValue.find((data) => data === checkboxRef.value)\n : fieldValue === checkboxRef.value))\n : fieldReference.refs[0] &&\n (fieldReference.refs[0].checked = !!fieldValue);\n }\n else {\n fieldReference.refs.forEach((radioRef) => (radioRef.checked = radioRef.value === fieldValue));\n }\n }\n else if (isFileInput(fieldReference.ref)) {\n fieldReference.ref.value = '';\n }\n else {\n fieldReference.ref.value = fieldValue;\n if (!fieldReference.ref.type) {\n _subjects.values.next({\n name,\n values: { ..._formValues },\n });\n }\n }\n }\n }\n (options.shouldDirty || options.shouldTouch) &&\n updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);\n options.shouldValidate && trigger(name);\n };\n const setValues = (name, value, options) => {\n for (const fieldKey in value) {\n const fieldValue = value[fieldKey];\n const fieldName = `${name}.${fieldKey}`;\n const field = get(_fields, fieldName);\n (_names.array.has(name) ||\n isObject(fieldValue) ||\n (field && !field._f)) &&\n !isDateObject(fieldValue)\n ? setValues(fieldName, fieldValue, options)\n : setFieldValue(fieldName, fieldValue, options);\n }\n };\n const setValue = (name, value, options = {}) => {\n const field = get(_fields, name);\n const isFieldArray = _names.array.has(name);\n const cloneValue = cloneObject(value);\n set(_formValues, name, cloneValue);\n if (isFieldArray) {\n _subjects.array.next({\n name,\n values: { ..._formValues },\n });\n if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) &&\n options.shouldDirty) {\n _subjects.state.next({\n name,\n dirtyFields: getDirtyFields(_defaultValues, _formValues),\n isDirty: _getDirty(name, cloneValue),\n });\n }\n }\n else {\n field && !field._f && !isNullOrUndefined(cloneValue)\n ? setValues(name, cloneValue, options)\n : setFieldValue(name, cloneValue, options);\n }\n isWatched(name, _names) && _subjects.state.next({ ..._formState });\n _subjects.values.next({\n name: _state.mount ? name : undefined,\n values: { ..._formValues },\n });\n };\n const onChange = async (event) => {\n _state.mount = true;\n const target = event.target;\n let name = target.name;\n let isFieldValueUpdated = true;\n const field = get(_fields, name);\n const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);\n const _updateIsFieldValueUpdated = (fieldValue) => {\n isFieldValueUpdated =\n Number.isNaN(fieldValue) ||\n (isDateObject(fieldValue) && isNaN(fieldValue.getTime())) ||\n deepEqual(fieldValue, get(_formValues, name, fieldValue));\n };\n if (field) {\n let error;\n let isValid;\n const fieldValue = getCurrentFieldValue();\n const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;\n const shouldSkipValidation = (!hasValidation(field._f) &&\n !_options.resolver &&\n !get(_formState.errors, name) &&\n !field._f.deps) ||\n skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);\n const watched = isWatched(name, _names, isBlurEvent);\n set(_formValues, name, fieldValue);\n if (isBlurEvent) {\n field._f.onBlur && field._f.onBlur(event);\n delayErrorCallback && delayErrorCallback(0);\n }\n else if (field._f.onChange) {\n field._f.onChange(event);\n }\n const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);\n const shouldRender = !isEmptyObject(fieldState) || watched;\n !isBlurEvent &&\n _subjects.values.next({\n name,\n type: event.type,\n values: { ..._formValues },\n });\n if (shouldSkipValidation) {\n if (_proxyFormState.isValid) {\n if (_options.mode === 'onBlur' && isBlurEvent) {\n _updateValid();\n }\n else if (!isBlurEvent) {\n _updateValid();\n }\n }\n return (shouldRender &&\n _subjects.state.next({ name, ...(watched ? {} : fieldState) }));\n }\n !isBlurEvent && watched && _subjects.state.next({ ..._formState });\n if (_options.resolver) {\n const { errors } = await _executeSchema([name]);\n _updateIsFieldValueUpdated(fieldValue);\n if (isFieldValueUpdated) {\n const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);\n const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);\n error = errorLookupResult.error;\n name = errorLookupResult.name;\n isValid = isEmptyObject(errors);\n }\n }\n else {\n _updateIsValidating([name], true);\n error = (await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];\n _updateIsValidating([name]);\n _updateIsFieldValueUpdated(fieldValue);\n if (isFieldValueUpdated) {\n if (error) {\n isValid = false;\n }\n else if (_proxyFormState.isValid) {\n isValid = await executeBuiltInValidation(_fields, true);\n }\n }\n }\n if (isFieldValueUpdated) {\n field._f.deps &&\n trigger(field._f.deps);\n shouldRenderByError(name, isValid, error, fieldState);\n }\n }\n };\n const _focusInput = (ref, key) => {\n if (get(_formState.errors, key) && ref.focus) {\n ref.focus();\n return 1;\n }\n return;\n };\n const trigger = async (name, options = {}) => {\n let isValid;\n let validationResult;\n const fieldNames = convertToArrayPayload(name);\n if (_options.resolver) {\n const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);\n isValid = isEmptyObject(errors);\n validationResult = name\n ? !fieldNames.some((name) => get(errors, name))\n : isValid;\n }\n else if (name) {\n validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {\n const field = get(_fields, fieldName);\n return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);\n }))).every(Boolean);\n !(!validationResult && !_formState.isValid) && _updateValid();\n }\n else {\n validationResult = isValid = await executeBuiltInValidation(_fields);\n }\n _subjects.state.next({\n ...(!isString(name) ||\n (_proxyFormState.isValid && isValid !== _formState.isValid)\n ? {}\n : { name }),\n ...(_options.resolver || !name ? { isValid } : {}),\n errors: _formState.errors,\n });\n options.shouldFocus &&\n !validationResult &&\n iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);\n return validationResult;\n };\n const getValues = (fieldNames) => {\n const values = {\n ...(_state.mount ? _formValues : _defaultValues),\n };\n return isUndefined(fieldNames)\n ? values\n : isString(fieldNames)\n ? get(values, fieldNames)\n : fieldNames.map((name) => get(values, name));\n };\n const getFieldState = (name, formState) => ({\n invalid: !!get((formState || _formState).errors, name),\n isDirty: !!get((formState || _formState).dirtyFields, name),\n error: get((formState || _formState).errors, name),\n isValidating: !!get(_formState.validatingFields, name),\n isTouched: !!get((formState || _formState).touchedFields, name),\n });\n const clearErrors = (name) => {\n name &&\n convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));\n _subjects.state.next({\n errors: name ? _formState.errors : {},\n });\n };\n const setError = (name, error, options) => {\n const ref = (get(_fields, name, { _f: {} })._f || {}).ref;\n const currentError = get(_formState.errors, name) || {};\n // Don't override existing error messages elsewhere in the object tree.\n const { ref: currentRef, message, type, ...restOfErrorTree } = currentError;\n set(_formState.errors, name, {\n ...restOfErrorTree,\n ...error,\n ref,\n });\n _subjects.state.next({\n name,\n errors: _formState.errors,\n isValid: false,\n });\n options && options.shouldFocus && ref && ref.focus && ref.focus();\n };\n const watch = (name, defaultValue) => isFunction(name)\n ? _subjects.values.subscribe({\n next: (payload) => name(_getWatch(undefined, defaultValue), payload),\n })\n : _getWatch(name, defaultValue, true);\n const unregister = (name, options = {}) => {\n for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {\n _names.mount.delete(fieldName);\n _names.array.delete(fieldName);\n if (!options.keepValue) {\n unset(_fields, fieldName);\n unset(_formValues, fieldName);\n }\n !options.keepError && unset(_formState.errors, fieldName);\n !options.keepDirty && unset(_formState.dirtyFields, fieldName);\n !options.keepTouched && unset(_formState.touchedFields, fieldName);\n !options.keepIsValidating &&\n unset(_formState.validatingFields, fieldName);\n !_options.shouldUnregister &&\n !options.keepDefaultValue &&\n unset(_defaultValues, fieldName);\n }\n _subjects.values.next({\n values: { ..._formValues },\n });\n _subjects.state.next({\n ..._formState,\n ...(!options.keepDirty ? {} : { isDirty: _getDirty() }),\n });\n !options.keepIsValid && _updateValid();\n };\n const _updateDisabledField = ({ disabled, name, field, fields, }) => {\n if ((isBoolean(disabled) && _state.mount) ||\n !!disabled ||\n _names.disabled.has(name)) {\n disabled ? _names.disabled.add(name) : _names.disabled.delete(name);\n updateTouchAndDirty(name, getFieldValue(field ? field._f : get(fields, name)._f), false, false, true);\n }\n };\n const register = (name, options = {}) => {\n let field = get(_fields, name);\n const disabledIsDefined = isBoolean(options.disabled) || isBoolean(_options.disabled);\n set(_fields, name, {\n ...(field || {}),\n _f: {\n ...(field && field._f ? field._f : { ref: { name } }),\n name,\n mount: true,\n ...options,\n },\n });\n _names.mount.add(name);\n if (field) {\n _updateDisabledField({\n field,\n disabled: isBoolean(options.disabled)\n ? options.disabled\n : _options.disabled,\n name,\n });\n }\n else {\n updateValidAndValue(name, true, options.value);\n }\n return {\n ...(disabledIsDefined\n ? { disabled: options.disabled || _options.disabled }\n : {}),\n ...(_options.progressive\n ? {\n required: !!options.required,\n min: getRuleValue(options.min),\n max: getRuleValue(options.max),\n minLength: getRuleValue(options.minLength),\n maxLength: getRuleValue(options.maxLength),\n pattern: getRuleValue(options.pattern),\n }\n : {}),\n name,\n onChange,\n onBlur: onChange,\n ref: (ref) => {\n if (ref) {\n register(name, options);\n field = get(_fields, name);\n const fieldRef = isUndefined(ref.value)\n ? ref.querySelectorAll\n ? ref.querySelectorAll('input,select,textarea')[0] || ref\n : ref\n : ref;\n const radioOrCheckbox = isRadioOrCheckbox(fieldRef);\n const refs = field._f.refs || [];\n if (radioOrCheckbox\n ? refs.find((option) => option === fieldRef)\n : fieldRef === field._f.ref) {\n return;\n }\n set(_fields, name, {\n _f: {\n ...field._f,\n ...(radioOrCheckbox\n ? {\n refs: [\n ...refs.filter(live),\n fieldRef,\n ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),\n ],\n ref: { type: fieldRef.type, name },\n }\n : { ref: fieldRef }),\n },\n });\n updateValidAndValue(name, false, undefined, fieldRef);\n }\n else {\n field = get(_fields, name, {});\n if (field._f) {\n field._f.mount = false;\n }\n (_options.shouldUnregister || options.shouldUnregister) &&\n !(isNameInFieldArray(_names.array, name) && _state.action) &&\n _names.unMount.add(name);\n }\n },\n };\n };\n const _focusError = () => _options.shouldFocusError &&\n iterateFieldsByAction(_fields, _focusInput, _names.mount);\n const _disableForm = (disabled) => {\n if (isBoolean(disabled)) {\n _subjects.state.next({ disabled });\n iterateFieldsByAction(_fields, (ref, name) => {\n const currentField = get(_fields, name);\n if (currentField) {\n ref.disabled = currentField._f.disabled || disabled;\n if (Array.isArray(currentField._f.refs)) {\n currentField._f.refs.forEach((inputRef) => {\n inputRef.disabled = currentField._f.disabled || disabled;\n });\n }\n }\n }, 0, false);\n }\n };\n const handleSubmit = (onValid, onInvalid) => async (e) => {\n let onValidError = undefined;\n if (e) {\n e.preventDefault && e.preventDefault();\n e.persist && e.persist();\n }\n let fieldValues = cloneObject(_formValues);\n if (_names.disabled.size) {\n for (const name of _names.disabled) {\n set(fieldValues, name, undefined);\n }\n }\n _subjects.state.next({\n isSubmitting: true,\n });\n if (_options.resolver) {\n const { errors, values } = await _executeSchema();\n _formState.errors = errors;\n fieldValues = values;\n }\n else {\n await executeBuiltInValidation(_fields);\n }\n unset(_formState.errors, 'root');\n if (isEmptyObject(_formState.errors)) {\n _subjects.state.next({\n errors: {},\n });\n try {\n await onValid(fieldValues, e);\n }\n catch (error) {\n onValidError = error;\n }\n }\n else {\n if (onInvalid) {\n await onInvalid({ ..._formState.errors }, e);\n }\n _focusError();\n setTimeout(_focusError);\n }\n _subjects.state.next({\n isSubmitted: true,\n isSubmitting: false,\n isSubmitSuccessful: isEmptyObject(_formState.errors) && !onValidError,\n submitCount: _formState.submitCount + 1,\n errors: _formState.errors,\n });\n if (onValidError) {\n throw onValidError;\n }\n };\n const resetField = (name, options = {}) => {\n if (get(_fields, name)) {\n if (isUndefined(options.defaultValue)) {\n setValue(name, cloneObject(get(_defaultValues, name)));\n }\n else {\n setValue(name, options.defaultValue);\n set(_defaultValues, name, cloneObject(options.defaultValue));\n }\n if (!options.keepTouched) {\n unset(_formState.touchedFields, name);\n }\n if (!options.keepDirty) {\n unset(_formState.dirtyFields, name);\n _formState.isDirty = options.defaultValue\n ? _getDirty(name, cloneObject(get(_defaultValues, name)))\n : _getDirty();\n }\n if (!options.keepError) {\n unset(_formState.errors, name);\n _proxyFormState.isValid && _updateValid();\n }\n _subjects.state.next({ ..._formState });\n }\n };\n const _reset = (formValues, keepStateOptions = {}) => {\n const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;\n const cloneUpdatedValues = cloneObject(updatedValues);\n const isEmptyResetValues = isEmptyObject(formValues);\n const values = isEmptyResetValues ? _defaultValues : cloneUpdatedValues;\n if (!keepStateOptions.keepDefaultValues) {\n _defaultValues = updatedValues;\n }\n if (!keepStateOptions.keepValues) {\n if (keepStateOptions.keepDirtyValues) {\n const fieldsToCheck = new Set([\n ..._names.mount,\n ...Object.keys(getDirtyFields(_defaultValues, _formValues)),\n ]);\n for (const fieldName of Array.from(fieldsToCheck)) {\n get(_formState.dirtyFields, fieldName)\n ? set(values, fieldName, get(_formValues, fieldName))\n : setValue(fieldName, get(values, fieldName));\n }\n }\n else {\n if (isWeb && isUndefined(formValues)) {\n for (const name of _names.mount) {\n const field = get(_fields, name);\n if (field && field._f) {\n const fieldReference = Array.isArray(field._f.refs)\n ? field._f.refs[0]\n : field._f.ref;\n if (isHTMLElement(fieldReference)) {\n const form = fieldReference.closest('form');\n if (form) {\n form.reset();\n break;\n }\n }\n }\n }\n }\n _fields = {};\n }\n _formValues = _options.shouldUnregister\n ? keepStateOptions.keepDefaultValues\n ? cloneObject(_defaultValues)\n : {}\n : cloneObject(values);\n _subjects.array.next({\n values: { ...values },\n });\n _subjects.values.next({\n values: { ...values },\n });\n }\n _names = {\n mount: keepStateOptions.keepDirtyValues ? _names.mount : new Set(),\n unMount: new Set(),\n array: new Set(),\n disabled: new Set(),\n watch: new Set(),\n watchAll: false,\n focus: '',\n };\n _state.mount =\n !_proxyFormState.isValid ||\n !!keepStateOptions.keepIsValid ||\n !!keepStateOptions.keepDirtyValues;\n _state.watch = !!_options.shouldUnregister;\n _subjects.state.next({\n submitCount: keepStateOptions.keepSubmitCount\n ? _formState.submitCount\n : 0,\n isDirty: isEmptyResetValues\n ? false\n : keepStateOptions.keepDirty\n ? _formState.isDirty\n : !!(keepStateOptions.keepDefaultValues &&\n !deepEqual(formValues, _defaultValues)),\n isSubmitted: keepStateOptions.keepIsSubmitted\n ? _formState.isSubmitted\n : false,\n dirtyFields: isEmptyResetValues\n ? {}\n : keepStateOptions.keepDirtyValues\n ? keepStateOptions.keepDefaultValues && _formValues\n ? getDirtyFields(_defaultValues, _formValues)\n : _formState.dirtyFields\n : keepStateOptions.keepDefaultValues && formValues\n ? getDirtyFields(_defaultValues, formValues)\n : keepStateOptions.keepDirty\n ? _formState.dirtyFields\n : {},\n touchedFields: keepStateOptions.keepTouched\n ? _formState.touchedFields\n : {},\n errors: keepStateOptions.keepErrors ? _formState.errors : {},\n isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful\n ? _formState.isSubmitSuccessful\n : false,\n isSubmitting: false,\n });\n };\n const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues)\n ? formValues(_formValues)\n : formValues, keepStateOptions);\n const setFocus = (name, options = {}) => {\n const field = get(_fields, name);\n const fieldReference = field && field._f;\n if (fieldReference) {\n const fieldRef = fieldReference.refs\n ? fieldReference.refs[0]\n : fieldReference.ref;\n if (fieldRef.focus) {\n fieldRef.focus();\n options.shouldSelect &&\n isFunction(fieldRef.select) &&\n fieldRef.select();\n }\n }\n };\n const _updateFormState = (updatedFormState) => {\n _formState = {\n ..._formState,\n ...updatedFormState,\n };\n };\n const _resetDefaultValues = () => isFunction(_options.defaultValues) &&\n _options.defaultValues().then((values) => {\n reset(values, _options.resetOptions);\n _subjects.state.next({\n isLoading: false,\n });\n });\n return {\n control: {\n register,\n unregister,\n getFieldState,\n handleSubmit,\n setError,\n _executeSchema,\n _getWatch,\n _getDirty,\n _updateValid,\n _removeUnmounted,\n _updateFieldArray,\n _updateDisabledField,\n _getFieldArray,\n _reset,\n _resetDefaultValues,\n _updateFormState,\n _disableForm,\n _subjects,\n _proxyFormState,\n _setErrors,\n get _fields() {\n return _fields;\n },\n get _formValues() {\n return _formValues;\n },\n get _state() {\n return _state;\n },\n set _state(value) {\n _state = value;\n },\n get _defaultValues() {\n return _defaultValues;\n },\n get _names() {\n return _names;\n },\n set _names(value) {\n _names = value;\n },\n get _formState() {\n return _formState;\n },\n set _formState(value) {\n _formState = value;\n },\n get _options() {\n return _options;\n },\n set _options(value) {\n _options = {\n ..._options,\n ...value,\n };\n },\n },\n trigger,\n register,\n handleSubmit,\n watch,\n setValue,\n getValues,\n reset,\n resetField,\n clearErrors,\n unregister,\n setError,\n setFocus,\n getFieldState,\n };\n}\n\n/**\n * Custom hook to manage the entire form.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)\n *\n * @param props - form configuration and validation parameters.\n *\n * @returns methods - individual functions to manage the form state. {@link UseFormReturn}\n *\n * @example\n * ```tsx\n * function App() {\n * const { register, handleSubmit, watch, formState: { errors } } = useForm();\n * const onSubmit = data => console.log(data);\n *\n * console.log(watch(\"example\"));\n *\n * return (\n *
\n * \n * \n * {errors.exampleRequired && This field is required}\n * \n *
\n * );\n * }\n * ```\n */\nfunction useForm(props = {}) {\n const _formControl = React.useRef(undefined);\n const _values = React.useRef(undefined);\n const [formState, updateFormState] = React.useState({\n isDirty: false,\n isValidating: false,\n isLoading: isFunction(props.defaultValues),\n isSubmitted: false,\n isSubmitting: false,\n isSubmitSuccessful: false,\n isValid: false,\n submitCount: 0,\n dirtyFields: {},\n touchedFields: {},\n validatingFields: {},\n errors: props.errors || {},\n disabled: props.disabled || false,\n defaultValues: isFunction(props.defaultValues)\n ? undefined\n : props.defaultValues,\n });\n if (!_formControl.current) {\n _formControl.current = {\n ...createFormControl(props),\n formState,\n };\n }\n const control = _formControl.current.control;\n control._options = props;\n useSubscribe({\n subject: control._subjects.state,\n next: (value) => {\n if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {\n updateFormState({ ...control._formState });\n }\n },\n });\n React.useEffect(() => control._disableForm(props.disabled), [control, props.disabled]);\n React.useEffect(() => {\n if (control._proxyFormState.isDirty) {\n const isDirty = control._getDirty();\n if (isDirty !== formState.isDirty) {\n control._subjects.state.next({\n isDirty,\n });\n }\n }\n }, [control, formState.isDirty]);\n React.useEffect(() => {\n if (props.values && !deepEqual(props.values, _values.current)) {\n control._reset(props.values, control._options.resetOptions);\n _values.current = props.values;\n updateFormState((state) => ({ ...state }));\n }\n else {\n control._resetDefaultValues();\n }\n }, [props.values, control]);\n React.useEffect(() => {\n if (props.errors) {\n control._setErrors(props.errors);\n }\n }, [props.errors, control]);\n React.useEffect(() => {\n if (!control._state.mount) {\n control._updateValid();\n control._state.mount = true;\n }\n if (control._state.watch) {\n control._state.watch = false;\n control._subjects.state.next({ ...control._formState });\n }\n control._removeUnmounted();\n });\n React.useEffect(() => {\n props.shouldUnregister &&\n control._subjects.values.next({\n values: control._getWatch(),\n });\n }, [props.shouldUnregister, control]);\n _formControl.current.formState = getProxyFormState(formState, control);\n return _formControl.current;\n}\n\nexport { Controller, Form, FormProvider, appendErrors, get, set, useController, useFieldArray, useForm, useFormContext, useFormState, useWatch };\n//# sourceMappingURL=index.esm.mjs.map\n","import React__default from 'react';\nimport useAuthenticator from '../useAuthenticator/useAuthenticator.mjs';\n\n// only select `route` from machine context\nconst routeSelector = ({ route }) => [route];\nfunction useAuthenticatorInitMachine(data) {\n const { route, initializeMachine } = useAuthenticator(routeSelector);\n const hasInitialized = React__default.useRef(false);\n React__default.useEffect(() => {\n if (!hasInitialized.current && route === 'setup') {\n initializeMachine(data);\n hasInitialized.current = true;\n }\n }, [initializeMachine, route, data]);\n}\n\nexport { useAuthenticatorInitMachine as default, routeSelector };\n","import * as React from 'react';\n\n/**\n * Logs a deprecation warning message.\n *\n * @important Please use the React/React Native specific platform implementations.\n * This version of the hook is a base implementation that the others extend from due\n * to env differences between running in RN or the browser\n */\nconst useDeprecationWarning = ({ shouldWarn, message, }) => {\n React.useEffect(() => {\n if (shouldWarn) {\n // eslint-disable-next-line no-console\n console.warn(message);\n }\n }, [shouldWarn, message]);\n};\n\nexport { useDeprecationWarning as default };\n","import { useEffect } from 'react';\nimport { setUserAgent } from '@aws-amplify/ui';\n\nfunction useSetUserAgent({ componentName, packageName, version, }) {\n useEffect(() => {\n const clearUserAgent = setUserAgent({\n componentName,\n packageName,\n version,\n });\n return clearUserAgent;\n }, [componentName, packageName, version]);\n}\n\nexport { useSetUserAgent as default };\n","import * as React from 'react';\nimport { createTheme } from '@aws-amplify/ui';\n\nconst ThemeContext = React.createContext({\n theme: createTheme(),\n colorMode: undefined,\n});\n\nexport { ThemeContext };\n","/**\n * @internal May be removed in a future version\n * Maps from component style props to React `style` props\n * Note: Primarily needed to map from component style props that don't match CSS Properties directly\n * such as wrap => flexWrap and direction => flexDirection\n */\nconst ComponentPropsToStylePropsMap = {\n alignContent: 'alignContent',\n alignItems: 'alignItems',\n alignSelf: 'alignSelf',\n area: 'gridArea',\n aspectRatio: 'aspectRatio',\n autoColumns: 'gridAutoColumns',\n autoFlow: 'gridAutoFlow',\n autoRows: 'gridAutoRows',\n backgroundColor: 'backgroundColor',\n backgroundImage: 'backgroundImage',\n basis: 'flexBasis',\n border: 'border',\n borderRadius: 'borderRadius',\n borderColor: 'borderColor',\n borderWidth: 'borderWidth',\n borderStyle: 'borderStyle',\n bottom: 'bottom',\n boxShadow: 'boxShadow',\n color: 'color',\n column: 'gridColumn',\n columnEnd: 'gridColumnEnd',\n columnGap: 'columnGap',\n columnSpan: 'gridColumn',\n columnStart: 'gridColumnStart',\n direction: 'flexDirection',\n display: 'display',\n flex: 'flex',\n fontFamily: 'fontFamily',\n fontSize: 'fontSize',\n fontStyle: 'fontStyle',\n fontWeight: 'fontWeight',\n gap: 'gap',\n grow: 'flexGrow',\n height: 'height',\n justifyContent: 'justifyContent',\n left: 'left',\n letterSpacing: 'letterSpacing',\n lineHeight: 'lineHeight',\n margin: 'margin',\n marginBlock: 'marginBlock',\n marginBlockEnd: 'marginBlockEnd',\n marginBlockStart: 'marginBlockStart',\n marginBottom: 'marginBlockEnd',\n marginInline: 'marginInline',\n marginInlineEnd: 'marginInlineEnd',\n marginInlineStart: 'marginInlineStart',\n marginLeft: 'marginInlineStart',\n marginRight: 'marginInlineEnd',\n marginTop: 'marginBlockStart',\n maxHeight: 'maxHeight',\n maxWidth: 'maxWidth',\n minHeight: 'minHeight',\n minWidth: 'minWidth',\n objectFit: 'objectFit',\n objectPosition: 'objectPosition',\n opacity: 'opacity',\n order: 'order',\n overflow: 'overflow',\n padding: 'padding',\n paddingBlock: 'paddingBlock',\n paddingBlockEnd: 'paddingBlockEnd',\n paddingBlockStart: 'paddingBlockStart',\n paddingBottom: 'paddingBlockEnd',\n paddingInline: 'paddingInline',\n paddingInlineEnd: 'paddingInlineEnd',\n paddingInlineStart: 'paddingInlineStart',\n paddingLeft: 'paddingInlineStart',\n paddingRight: 'paddingInlineEnd',\n paddingTop: 'paddingBlockStart',\n position: 'position',\n resize: 'resize',\n right: 'right',\n row: 'gridRow',\n rowEnd: 'gridRowEnd',\n rowGap: 'rowGap',\n rowSpan: 'gridRow',\n rowStart: 'gridRowStart',\n shrink: 'flexShrink',\n templateAreas: 'gridTemplateAreas',\n templateColumns: 'gridTemplateColumns',\n templateRows: 'gridTemplateRows',\n textAlign: 'textAlign',\n textDecoration: 'textDecoration',\n textTransform: 'textTransform',\n top: 'top',\n transform: 'transform',\n transformOrigin: 'transformOrigin',\n width: 'width',\n whiteSpace: 'whiteSpace',\n wrap: 'flexWrap',\n};\n/**\n * @internal May be removed in a future version\n */\nconst ComponentPropsToStylePropsMapKeys = Object.keys(ComponentPropsToStylePropsMap);\n\nexport { ComponentPropsToStylePropsMap, ComponentPropsToStylePropsMapKeys };\n","// For internal use, no need to export\nconst ComponentText = {\n Alert: {\n dismissButtonLabel: 'Dismiss alert',\n },\n Autocomplete: {\n emptyText: 'No options found',\n loadingText: 'Loading options...',\n },\n Collection: {\n searchButtonLabel: 'Search',\n searchNoResultsFound: 'No results found',\n },\n Fields: {\n clearButtonLabel: 'Clear input',\n },\n Message: {\n dismissLabel: 'Dismiss message',\n },\n PaginationItem: {\n currentPageLabel: 'Page',\n nextLabel: 'Go to next page',\n pageLabel: 'Go to page',\n previousLabel: 'Go to previous page',\n },\n PhoneNumberField: {\n countryCodeLabel: 'Country code',\n },\n SearchField: {\n searchButtonLabel: 'Search',\n },\n PasswordField: {\n passwordIsHidden: 'Password is hidden',\n passwordIsShown: 'Password is shown',\n showPassword: 'Show password',\n },\n StepperField: {\n increaseButtonLabel: 'Increase to',\n decreaseButtonLabel: 'Decrease to',\n },\n};\nconst stylePropsToThemeKeys = {\n backgroundColor: 'colors',\n borderColor: 'colors',\n borderWidth: 'borderWidths',\n color: 'colors',\n borderRadius: 'radii',\n fontSize: 'fontSizes',\n fontWeight: 'fontWeights',\n fontFamily: 'fonts',\n lineHeight: 'lineHeights',\n opacity: 'opacities',\n boxShadow: 'shadows',\n transform: 'transforms',\n left: 'space',\n right: 'space',\n top: 'space',\n bottom: 'space',\n height: 'space',\n width: 'space',\n letterSpacing: 'space',\n margin: 'space',\n marginBlock: 'space',\n marginBlockEnd: 'space',\n marginBlockStart: 'space',\n marginInline: 'space',\n marginInlineEnd: 'space',\n marginInlineStart: 'space',\n marginLeft: 'space',\n marginRight: 'space',\n marginTop: 'space',\n marginBottom: 'space',\n maxHeight: 'space',\n maxWidth: 'space',\n minHeight: 'space',\n minWidth: 'space',\n padding: 'space',\n paddingBlock: 'space',\n paddingBlockEnd: 'space',\n paddingBlockStart: 'space',\n paddingInline: 'space',\n paddingInlineEnd: 'space',\n paddingInlineStart: 'space',\n paddingLeft: 'space',\n paddingRight: 'space',\n paddingTop: 'space',\n paddingBottom: 'space',\n gap: 'space',\n columnGap: 'space',\n rowGap: 'space',\n};\n// key name\nconst ESCAPE_KEY = 'Escape';\nconst ENTER_KEY = 'Enter';\nconst ARROW_UP = 'ArrowUp';\nconst ARROW_DOWN = 'ArrowDown';\n\nexport { ARROW_DOWN, ARROW_UP, ComponentText, ENTER_KEY, ESCAPE_KEY, stylePropsToThemeKeys };\n","import { stylePropsToThemeKeys } from '../shared/constants.mjs';\n\nconst isThemeStylePropKey = (key) => {\n return key in stylePropsToThemeKeys;\n};\n\nexport { isThemeStylePropKey };\n","import { isDesignToken, cssNameTransform } from '@aws-amplify/ui';\nexport { classNameModifier, classNameModifierByFlag } from '@aws-amplify/ui';\nimport { isThemeStylePropKey } from '../types/theme.mjs';\nimport { stylePropsToThemeKeys } from './constants.mjs';\n\nconst strHasLength = (str) => typeof str === 'string' && str.length > 0;\nconst isEmptyString = (value) => typeof value === 'string' && value.length === 0;\nconst isNullOrEmptyString = (value) => value == null || isEmptyString(value);\n/**\n * Create a consecutive integer array from start value to end value.\n * @param start start value\n * @param end end value\n * @returns an integer array with elements from start to end consecutively\n */\nconst getConsecutiveIntArray = (start, end) => {\n const length = end - start + 1;\n return Array.from({ length }, (_, idx) => idx + start);\n};\n/**\n * TS helper function to make using Object.keys more typesafe\n */\nconst objectKeys = (obj) => {\n return Object.keys(obj);\n};\nconst getCSSVariableIfValueIsThemeKey = (propKey, value, tokens) => {\n if (typeof value !== 'string') {\n return value;\n }\n // For shorthand properties like `padding` which can accept 1, 2, 3, or 4 values\n // run this function on each value. This would not work on CSS shorthands that\n // mix types, like border which is a composite of borderWidth, borderStyle, and\n // borderColor.\n if (value.includes(' ')) {\n return value\n .split(' ')\n .map((val) => getCSSVariableIfValueIsThemeKey(propKey, val, tokens))\n .join(' ');\n }\n if (isThemeStylePropKey(propKey)) {\n const path = value.split('.');\n const tokenKey = stylePropsToThemeKeys[propKey];\n let tokenProps = tokens[tokenKey];\n for (let i = 0; i < path.length; i++) {\n if (tokenProps) {\n // overwrite tokenProps with next nested value of tokenProps\n tokenProps = tokenProps[path[i]];\n continue;\n }\n break;\n }\n return isDesignToken(tokenProps)\n ? `var(--${cssNameTransform({\n path: [stylePropsToThemeKeys[propKey], ...path],\n })})`\n : value;\n }\n return value;\n};\n\nexport { getCSSVariableIfValueIsThemeKey, getConsecutiveIntArray, isEmptyString, isNullOrEmptyString, objectKeys, strHasLength };\n","import { defaultTheme } from '@aws-amplify/ui';\nimport { objectKeys } from '../utils.mjs';\n\nconst getClosestValueByBreakpoint = ({ breakpoint, breakpoints, values, }) => {\n const value = values[breakpoint];\n // Check if breakpoint exists in values\n if (value !== undefined) {\n return value;\n }\n // Otherwise use a lower breakpoint value\n const breakpointsDesc = objectKeys(breakpoints).sort((a, b) => breakpoints[b] - breakpoints[a]);\n const lowerBreakpoints = breakpointsDesc.slice(breakpointsDesc.indexOf(breakpoint));\n for (const breakpoint of lowerBreakpoints) {\n // Check if breakpoint exists in values\n const value = values[breakpoint];\n if (value !== undefined) {\n return value;\n }\n }\n return null;\n};\n/**\n * This takes an object and will return an object that only has the\n * breakpoint keys\n * @param obj\n * @returns\n */\nconst valueObjToBreakpoints = (obj) => {\n return objectKeys(obj).reduce((acc, key) => key in defaultTheme.breakpoints.values\n ? { ...acc, [key]: obj[key] }\n : acc, {});\n};\nconst getValueAtCurrentBreakpoint = ({ breakpoint, breakpoints, values, }) => {\n let breakpointCompatValues = {};\n const breakpointsAscending = objectKeys(breakpoints).sort((a, b) => breakpoints[a] - breakpoints[b]);\n if (Array.isArray(values)) {\n values.forEach((value, index) => {\n breakpointCompatValues[breakpointsAscending[index]] = value;\n });\n }\n else if (typeof values === 'object') {\n breakpointCompatValues = valueObjToBreakpoints(values);\n }\n return getClosestValueByBreakpoint({\n breakpoint,\n breakpoints,\n values: breakpointCompatValues,\n });\n};\n\nexport { getValueAtCurrentBreakpoint };\n","import { objectKeys } from '../utils.mjs';\n\n// Inspiration for getMediaQueries and useBreakpoint\n// comes from https://github.com/iiroj/use-breakpoint/\nconst getMediaQueries = ({ breakpoints }) => {\n const sortedBreakpoints = objectKeys(breakpoints).sort((a, b) => breakpoints[b] - breakpoints[a]);\n return sortedBreakpoints.map((breakpoint, index) => {\n let query = '';\n const minWidth = breakpoints[breakpoint];\n const nextBreakpoint = sortedBreakpoints[index - 1];\n const maxWidth = nextBreakpoint ? breakpoints[nextBreakpoint] - 1 : null;\n if (minWidth >= 0) {\n query = `(min-width: ${minWidth}px)`;\n }\n if (maxWidth !== null) {\n if (query) {\n query += ' and ';\n }\n query += `(max-width: ${maxWidth}px)`;\n }\n return {\n breakpoint,\n query,\n maxWidth,\n minWidth,\n };\n });\n};\n\nexport { getMediaQueries };\n","import * as React from 'react';\nimport { getMediaQueries } from './getMediaQueries.mjs';\n\n// Inspiration for getMediaQueries and useBreakpoint\n// comes from https://github.com/iiroj/use-breakpoint/\nconst useIsomorphicEffect = typeof window === 'undefined' ? React.useEffect : React.useLayoutEffect;\nconst useBreakpoint = ({ breakpoints, defaultBreakpoint, }) => {\n const supportMatchMedia = typeof window !== 'undefined' && typeof window.matchMedia !== 'undefined';\n const matchMedia = supportMatchMedia ? window.matchMedia : null;\n const mediaQueries = React.useMemo(() => getMediaQueries({ breakpoints }), [breakpoints]);\n const [breakpoint, setBreakpoint] = React.useState(defaultBreakpoint);\n const updateBreakpoint = React.useCallback((matches, breakpoint) => {\n if (matches) {\n setBreakpoint(breakpoint);\n }\n }, [setBreakpoint]);\n useIsomorphicEffect(() => {\n if (!matchMedia)\n return;\n const unsubscribeList = mediaQueries.map(({ query, breakpoint }) => {\n const queryList = matchMedia(query);\n updateBreakpoint(queryList.matches, breakpoint);\n const handleMediaChange = (event) => {\n if (event.matches) {\n setBreakpoint(breakpoint);\n }\n };\n queryList.addEventListener('change', handleMediaChange);\n return () => queryList.removeEventListener('change', handleMediaChange);\n });\n return () => {\n unsubscribeList.forEach((unsubscribe) => unsubscribe());\n };\n }, [breakpoints, setBreakpoint, matchMedia, mediaQueries]);\n /** Print a nice debug value for React Devtools */\n React.useDebugValue(breakpoint, (breakpoint) => breakpoint);\n return breakpoint;\n};\n\nexport { useBreakpoint };\n","import * as React from 'react';\nimport { createTheme } from '@aws-amplify/ui';\nimport { ThemeContext } from '../components/ThemeProvider/ThemeContext.mjs';\n\n/**\n * Get current Theme object value from Amplify context.\n * Returns a default theme if context is not available\n */\nconst getThemeFromContext = (context) => {\n if (typeof context === 'undefined' || typeof context.theme === 'undefined') {\n return createTheme();\n }\n return context.theme;\n};\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/theming)\n */\nconst useTheme = () => {\n const context = React.useContext(ThemeContext);\n return getThemeFromContext(context);\n};\n/**\n * Internal use only\n */\nconst useColorMode = () => {\n const context = React.useContext(ThemeContext);\n return context.colorMode;\n};\n\nexport { getThemeFromContext, useColorMode, useTheme };\n","import { isDesignToken, isString } from '@aws-amplify/ui';\nimport { getCSSVariableIfValueIsThemeKey } from './utils.mjs';\n\n/**\n * This takes an unknown value, which could be a:\n * - design token: `color={tokens.colors.font.primary}`\n * - string, which could be a:\n * - theme key: `color='font.primary'`\n * - plain style: `color='red'`\n * - or a number: `padding={10}`\n * and returns the appropriate and resolved value\n */\nconst getStyleValue = ({ value, propKey, tokens, }) => {\n if (isDesignToken(value)) {\n return value.toString();\n }\n if (isString(value)) {\n return isString(propKey)\n ? getCSSVariableIfValueIsThemeKey(propKey, value, tokens)\n : value;\n }\n return null;\n};\n\nexport { getStyleValue };\n","import * as React from 'react';\nimport { isDesignToken } from '@aws-amplify/ui';\nimport { ComponentPropsToStylePropsMap } from '../types/style.mjs';\nimport { getValueAtCurrentBreakpoint } from './responsive/utils.mjs';\nimport { useBreakpoint } from './responsive/useBreakpoint.mjs';\nimport { useTheme } from '../../hooks/useTheme.mjs';\nimport { getStyleValue } from './getStyleValue.mjs';\nimport { isNullOrEmptyString, isEmptyString, getCSSVariableIfValueIsThemeKey } from './utils.mjs';\n\nconst isSpanPrimitiveValue = (spanValue) => {\n return (spanValue === 'auto' ||\n (typeof spanValue === 'number' && !isNaN(spanValue)) ||\n (typeof spanValue === 'string' && !isNaN(parseFloat(spanValue))));\n};\nconst getGridSpan = (spanValue) => {\n return spanValue === 'auto' ? 'auto' : `span ${spanValue}`;\n};\nconst convertGridSpan = (spanValue) => {\n // PropertyType\n if (isSpanPrimitiveValue(spanValue)) {\n return getGridSpan(spanValue);\n }\n // PropertyType[]\n if (Array.isArray(spanValue)) {\n return spanValue.map((value) => getGridSpan(value));\n }\n // ResponsiveObject\n if (typeof spanValue === 'object' && spanValue != null) {\n return Object.entries(spanValue).reduce((acc, [key, value]) => ({ ...acc, [key]: getGridSpan(value) }), {});\n }\n return null;\n};\n/**\n * Transforms style props to another target prop\n * where the original is a simpler API than the target.\n * This function will remove the original prop and\n * replace target prop values with calculated\n * E.g. rowSpan => row, columnSpan => column\n */\nconst useTransformStyleProps = (props) => {\n const { rowSpan, columnSpan, row, column, ...rest } = props;\n const { rowFromSpanValue, columnFromSpanValue } = React.useMemo(() => {\n return {\n rowFromSpanValue: convertGridSpan(rowSpan),\n columnFromSpanValue: convertGridSpan(columnSpan),\n };\n }, [rowSpan, columnSpan]);\n return {\n row: !isNullOrEmptyString(row) ? row : rowFromSpanValue,\n column: !isNullOrEmptyString(column) ? column : columnFromSpanValue,\n ...rest,\n };\n};\nconst isComponentStyleProp = (key) => {\n return key in ComponentPropsToStylePropsMap;\n};\n/**\n * Convert style props to CSS variables for React style prop\n * Note: Will filter out undefined, null, and empty string prop values\n */\nconst convertStylePropsToStyleObj = ({ props = {}, style = {}, breakpoint, breakpoints, tokens, }) => {\n const nonStyleProps = {};\n Object.keys(props)\n .filter((propKey) => props[propKey] !== null)\n .forEach((propKey) => {\n if (isComponentStyleProp(propKey)) {\n const values = props[propKey];\n if (!values || isEmptyString(values))\n return;\n const reactStyleProp = ComponentPropsToStylePropsMap[propKey];\n // short circuit the style prop here if it is a string or design token\n // so we don't have to call getValueAtCurrentBreakpoint every time\n let value = '';\n if (isDesignToken(values)) {\n value = values.toString();\n }\n else if (typeof values === 'string') {\n value = getCSSVariableIfValueIsThemeKey(propKey, values, tokens);\n }\n else if (typeof values === 'number') {\n value = values;\n }\n else if (typeof values === 'object') {\n // here values should be a responsive array or object\n value = getStyleValue({\n propKey,\n tokens,\n value: getValueAtCurrentBreakpoint({\n values,\n breakpoint,\n breakpoints,\n }),\n });\n }\n style = {\n ...style,\n [reactStyleProp]: value,\n };\n }\n else if (typeof props[propKey] !== 'undefined') {\n nonStyleProps[propKey] = props[propKey];\n }\n });\n return { propStyles: style, nonStyleProps };\n};\nconst useStyles = (props, style) => {\n const { breakpoints: { values: breakpoints, defaultBreakpoint }, tokens, } = useTheme();\n const breakpoint = useBreakpoint({\n breakpoints,\n defaultBreakpoint,\n });\n const propStyles = useTransformStyleProps(props);\n return React.useMemo(() => convertStylePropsToStyleObj({\n props: propStyles,\n style,\n breakpoint,\n breakpoints,\n tokens,\n }), [propStyles, style, breakpoints, breakpoint, tokens]);\n};\n\nexport { convertGridSpan, convertStylePropsToStyleObj, getGridSpan, isSpanPrimitiveValue, useStyles, useTransformStyleProps };\n","import * as React from 'react';\n\n/**\n * Updates the return type for primitives wrapped in `React.forwardRef` to\n * `React.ReactElement`. In React 18 the return type of `React.ExoticComponent`\n * was changed from `React.ReactElement` to `React.ReactNode`, which breaks\n * clients using React 16 and 17.\n *\n * @param primitive UI Primitive to be wrapped with `React.forwardRef`\n * @returns ForwaredRef wrapped UI Primitive\n */\nconst primitiveWithForwardRef = (primitive) => React.forwardRef(primitive);\n\nexport { primitiveWithForwardRef };\n","import * as React from 'react';\nimport { useStyles } from '../shared/styleUtils.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst ViewPrimitive = ({ as = 'div', children, testId, ariaLabel, isDisabled, style, inert, ...rest }, ref) => {\n const { propStyles, nonStyleProps } = useStyles(rest, style);\n return React.createElement(as, {\n 'aria-label': ariaLabel,\n 'data-testid': testId,\n disabled: isDisabled,\n ref,\n inert: inert ? '' : null,\n style: propStyles,\n ...nonStyleProps,\n }, children);\n};\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/view)\n */\nconst View = primitiveWithForwardRef(ViewPrimitive);\nView.displayName = 'View';\n\nexport { View };\n","import * as React from 'react';\nimport { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport { View } from '../View/View.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst defaultViewBox = { minX: 0, minY: 0, width: 24, height: 24 };\nconst IconPrimitive = ({ className, \n// as can be used to render other icon react components too\nas = 'svg', fill = 'currentColor', pathData, viewBox = defaultViewBox, children, paths, ...rest }, ref) => {\n const minX = viewBox.minX ? viewBox.minX : defaultViewBox.minX;\n const minY = viewBox.minY ? viewBox.minY : defaultViewBox.minY;\n const width = viewBox.width ? viewBox.width : defaultViewBox.width;\n const height = viewBox.height ? viewBox.height : defaultViewBox.height;\n // An icon can be drawn in 3 ways:\n // 1. Pass it children which should be valid SVG elements\n // 2. Pass an array of path-like objects to `paths` prop\n // 3. Supply `pathData` for a simple icons\n let _children;\n if (children) {\n _children = children;\n }\n if (paths) {\n _children = paths.map((path, index) => React.createElement(\"path\", { ...path, key: index }));\n }\n if (pathData) {\n _children = React.createElement(\"path\", { d: pathData, fill: fill });\n }\n return (React.createElement(View, { as: as, className: classNames(ComponentClassName.Icon, className), ref: ref, viewBox: `${minX} ${minY} ${width} ${height}`, ...rest }, _children));\n};\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/icon)\n */\nconst Icon = primitiveWithForwardRef(IconPrimitive);\nIcon.displayName = 'Icon';\n\nexport { Icon };\n","import * as React from 'react';\n\nconst IconsContext = React.createContext({});\n\nexport { IconsContext };\n","import * as React from 'react';\nimport { IconsContext } from './IconsContext.mjs';\n\nfunction useIcons(component) {\n const context = React.useContext(IconsContext);\n if (component && context) {\n return context[component];\n }\n return undefined;\n}\n\nexport { useIcons };\n","import * as React from 'react';\nimport { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport { View } from '../../View/View.mjs';\n\n/**\n * @internal For internal Amplify UI use only. May be removed in a future release.\n */\nconst IconCheckCircle = (props) => {\n const { className, ...rest } = props;\n return (React.createElement(View, { as: \"span\", width: \"1em\", height: \"1em\", className: classNames(ComponentClassName.Icon, className), ...rest },\n React.createElement(\"svg\", { width: \"24\", height: \"24\", viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\" },\n React.createElement(\"path\", { d: \"M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM12 20C7.59 20 4 16.41 4 12C4 7.59 7.59 4 12 4C16.41 4 20 7.59 20 12C20 16.41 16.41 20 12 20ZM16.59 7.58L10 14.17L7.41 11.59L6 13L10 17L18 9L16.59 7.58Z\", fill: \"currentColor\" }))));\n};\n\nexport { IconCheckCircle };\n","import { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport * as React from 'react';\nimport { View } from '../../View/View.mjs';\n\n/**\n * @internal For internal Amplify UI use only. May be removed in a future release.\n */\nconst IconError = (props) => {\n const { className, ...rest } = props;\n return (React.createElement(View, { as: \"span\", width: \"1em\", height: \"1em\", className: classNames(ComponentClassName.Icon, className), ...rest },\n React.createElement(\"svg\", { width: \"24\", height: \"24\", viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\" },\n React.createElement(\"path\", { d: \"M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM13 17H11V15H13V17ZM13 13H11V7H13V13Z\", fill: \"currentColor\" }))));\n};\n\nexport { IconError };\n","import { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport * as React from 'react';\nimport { View } from '../../View/View.mjs';\n\n/**\n * @internal For internal Amplify UI use only. May be removed in a future release.\n */\nconst IconInfo = (props) => {\n const { className, ...rest } = props;\n return (React.createElement(View, { as: \"span\", width: \"1em\", height: \"1em\", className: classNames(ComponentClassName.Icon, className), ...rest },\n React.createElement(\"svg\", { width: \"24\", height: \"24\", viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\" },\n React.createElement(\"path\", { d: \"M11 7H13V9H11V7ZM11 11H13V17H11V11ZM12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM12 20C7.59 20 4 16.41 4 12C4 7.59 7.59 4 12 4C16.41 4 20 7.59 20 12C20 16.41 16.41 20 12 20Z\", fill: \"currentColor\" }))));\n};\n\nexport { IconInfo };\n","import { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport * as React from 'react';\nimport { View } from '../../View/View.mjs';\n\n/**\n * @internal For internal Amplify UI use only. May be removed in a future release.\n */\nconst IconWarning = (props) => {\n const { className, ...rest } = props;\n return (React.createElement(View, { as: \"span\", width: \"1em\", height: \"1em\", className: classNames(ComponentClassName.Icon, className), ...rest },\n React.createElement(\"svg\", { width: \"24\", height: \"24\", viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\" },\n React.createElement(\"path\", { d: \"M1 21H23L12 2L1 21ZM13 18H11V16H13V18ZM13 14H11V10H13V14Z\", fill: \"currentColor\" }))));\n};\n\nexport { IconWarning };\n","import * as React from 'react';\nimport { ComponentClassName } from '@aws-amplify/ui';\nimport '../Icon/Icon.mjs';\nimport '../Icon/context/IconsContext.mjs';\nimport { useIcons } from '../Icon/context/useIcons.mjs';\nimport '../View/View.mjs';\nimport { IconCheckCircle } from '../Icon/icons/IconCheckCircle.mjs';\nimport { IconError } from '../Icon/icons/IconError.mjs';\nimport { IconInfo } from '../Icon/icons/IconInfo.mjs';\nimport { IconWarning } from '../Icon/icons/IconWarning.mjs';\n\n/**\n * @internal For internal Amplify UI use only. May be removed in a future release.\n */\nconst AlertIcon = ({ variation, ariaHidden, ariaLabel, role, }) => {\n const icons = useIcons('alert');\n let icon;\n switch (variation) {\n case 'info':\n icon = icons?.info ?? (React.createElement(IconInfo, { \"aria-hidden\": ariaHidden, \"aria-label\": ariaLabel, role: role }));\n break;\n case 'error':\n icon = icons?.error ?? (React.createElement(IconError, { \"aria-hidden\": ariaHidden, \"aria-label\": ariaLabel, role: role }));\n break;\n case 'warning':\n icon = icons?.warning ?? (React.createElement(IconWarning, { \"aria-hidden\": ariaHidden, \"aria-label\": ariaLabel, role: role }));\n break;\n case 'success':\n icon = icons?.success ?? (React.createElement(IconCheckCircle, { \"aria-hidden\": ariaHidden, \"aria-label\": ariaLabel, role: role }));\n break;\n }\n return icon ? (React.createElement(\"span\", { className: ComponentClassName.AlertIcon }, icon)) : null;\n};\nAlertIcon.displayName = 'AlertIcon';\n\nexport { AlertIcon };\n","import * as React from 'react';\n\n// Source: https://github.com/radix-ui/primitives/blob/7ae63b6cce6ea53ea5d65b6d411894c004b38f47/packages/react/use-layout-effect/src/useLayoutEffect.tsx\n/**\n * On the server, React emits a warning when calling `useLayoutEffect`.\n * This is because neither `useLayoutEffect` nor `useEffect` run on the server.\n * We use this safe version which suppresses the warning by replacing it with a noop on the server.\n *\n * See: https://reactjs.org/docs/hooks-reference.html#uselayouteffect\n */\nconst useLayoutEffect = globalThis?.document ? React.useLayoutEffect : () => { };\n\nexport { useLayoutEffect };\n","import * as React from 'react';\nimport { useLayoutEffect } from './useLayoutEffect.mjs';\n\n// Adapted from https://github.com/radix-ui/primitives/blob/main/packages/react/id/src/id.tsx#L8\n// Prefixed autogenerated id created by useStableId\nconst AUTO_GENERATED_ID_PREFIX = 'amplify-id';\n// Create a local version of React.useId which will reference React.useId for React 18\n// and fallback to noop for React 17 and below\n// Note: We use `toString()` to prevent bundlers from trying to `import { useId } from 'react';`\n// since it doesn't exist in React 17 and below (prevents https://github.com/aws-amplify/amplify-ui/issues/1154)\nconst useReactId = \n// disable eslint below to allow usage of casting React to `any`, which ensures that TS\n// does not get confused about the existence of `useId` in React 17 and below\n// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\nReact['useId'.toString()] || (() => undefined);\nlet count = 0;\n/**\n * Create a uuid to use with amplify fields unless\n * an id is provided\n * @param id user specified id\n * @returns string\n */\nconst useStableId = (id) => {\n const [stableId, setStableId] = React.useState(useReactId());\n // React versions older than 18 will have client-side ids only\n useLayoutEffect(() => {\n if (!id) {\n setStableId((reactId) => reactId ?? String(count++));\n }\n }, [id]);\n return id ?? (stableId ? `${AUTO_GENERATED_ID_PREFIX}-${stableId}` : '');\n};\n\nexport { AUTO_GENERATED_ID_PREFIX, useStableId };\n","import * as React from 'react';\n\nconst FieldsetContext = React.createContext({\n isFieldsetDisabled: false,\n});\n/**\n * @description Fieldsets in HTML can be disabled, which disables all child\n * fieldsets and input controls. `useFieldset` passes the disabled state down\n * via context.\n */\nconst useFieldset = () => React.useContext(FieldsetContext);\n\nexport { FieldsetContext, useFieldset };\n","import * as React from 'react';\nimport { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport { View } from '../View/View.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst FlexPrimitive = ({ className, children, ...rest }, ref) => (React.createElement(View, { className: classNames(ComponentClassName.Flex, className), ref: ref, ...rest }, children));\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/flex)\n */\nconst Flex = primitiveWithForwardRef(FlexPrimitive);\nFlex.displayName = 'Flex';\n\nexport { Flex };\n","import * as React from 'react';\nimport { classNames, ComponentClassName, classNameModifier, classNameModifierByFlag } from '@aws-amplify/ui';\nimport { View } from '../View/View.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst LINEAR_EMPTY = 'linear-empty';\nconst LINEAR_FILLED = 'linear-filled';\nconst CIRCULAR_EMPTY = 'circular-empty';\nconst CIRCULAR_FILLED = 'circular-filled';\n// radius + strokeWidth = 50\nconst CIRCULAR_STROKE_WIDTH = 8;\nconst RADIUS = 42;\n// circumference = 2 * r * PI (r = 42)\nconst CIRCUMFERENCE = 2 * RADIUS * Math.PI;\nconst LoaderPrimitive = ({ className, filledColor, emptyColor, size, variation, isDeterminate = false, isPercentageTextHidden = false, percentage = 0, ...rest }, ref) => {\n percentage = Math.min(percentage, 100);\n percentage = Math.max(percentage, 0);\n const percent = `${percentage}%`;\n const componentClasses = classNames(ComponentClassName.Loader, classNameModifier(ComponentClassName.Loader, size), classNameModifier(ComponentClassName.Loader, variation), classNameModifierByFlag(ComponentClassName.Loader, 'determinate', isDeterminate), className);\n const linearLoader = (React.createElement(\"g\", null,\n React.createElement(\"line\", { x1: \"0\", x2: \"100%\", y1: \"50%\", y2: \"50%\", style: { stroke: String(emptyColor) }, \"data-testid\": LINEAR_EMPTY }),\n React.createElement(\"line\", { x1: \"0\", x2: isDeterminate ? percent : '100%', y1: \"50%\", y2: \"50%\", style: {\n // To get rid of the visible stroke linecap when percentage is 0\n stroke: isDeterminate && percentage === 0\n ? 'none'\n : filledColor\n ? String(filledColor)\n : undefined,\n }, \"data-testid\": LINEAR_FILLED }),\n isDeterminate ? (React.createElement(\"text\", { \"aria-live\": \"polite\", className: classNames(ComponentClassName.LoaderLabel, isPercentageTextHidden ? ComponentClassName.VisuallyHidden : null), \n // -1% offset makes the text position look nicest\n x: `${-1 + percentage}%`, y: \"200%\" }, percent)) : null));\n // r + stroke-width should add up to 50% to avoid overflow\n const circularLoader = (React.createElement(\"g\", null,\n React.createElement(\"circle\", { cx: \"50%\", cy: \"50%\", r: `${RADIUS}%`, strokeWidth: `${CIRCULAR_STROKE_WIDTH}%`, style: { stroke: String(emptyColor) }, \"data-testid\": CIRCULAR_EMPTY }),\n React.createElement(\"circle\", { cx: \"50%\", cy: \"50%\", r: `${RADIUS}%`, strokeWidth: `${CIRCULAR_STROKE_WIDTH}%`, style: {\n stroke: String(filledColor),\n strokeDasharray: isDeterminate\n ? `${CIRCUMFERENCE}% ${CIRCUMFERENCE}%`\n : undefined,\n strokeDashoffset: isDeterminate\n ? `${CIRCUMFERENCE - (CIRCUMFERENCE * percentage) / 100}%`\n : undefined,\n }, \"data-testid\": CIRCULAR_FILLED }),\n isDeterminate ? (React.createElement(\"text\", { \"aria-live\": \"polite\", className: classNames(ComponentClassName.LoaderLabel, isPercentageTextHidden ? ComponentClassName.VisuallyHidden : null), \n // this x and y make text position look nicest\n x: \"130%\", y: \"80%\" }, percent)) : null));\n return (React.createElement(View, { as: \"svg\", className: componentClasses, ref: ref, role: \"img\", ...rest }, variation === 'linear' ? linearLoader : circularLoader));\n};\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/loader)\n */\nconst Loader = primitiveWithForwardRef(LoaderPrimitive);\nLoader.displayName = 'Loader';\n\nexport { CIRCULAR_EMPTY, CIRCULAR_FILLED, CIRCULAR_STROKE_WIDTH, CIRCUMFERENCE, LINEAR_EMPTY, LINEAR_FILLED, Loader, RADIUS };\n","import * as React from 'react';\nimport { classNames, ComponentClassName, classNameModifier, classNameModifierByFlag } from '@aws-amplify/ui';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\nimport { useFieldset } from '../Fieldset/useFieldset.mjs';\nimport { Flex } from '../Flex/Flex.mjs';\nimport { Loader } from '../Loader/Loader.mjs';\nimport { View } from '../View/View.mjs';\n\n// These variations support colorThemes. 'undefined' accounts for our\n// 'default' variation which is not named.\nconst supportedVariations = ['link', 'primary', undefined];\nconst ButtonPrimitive = ({ className, children, colorTheme, isFullWidth = false, isDisabled, isLoading, loadingText = '', size, type = 'button', variation, ...rest }, ref) => {\n // Creates our colorTheme modifier string based on if the variation\n // supports colorThemes and a colorTheme is used.\n const colorThemeModifier = supportedVariations.includes(variation) && colorTheme\n ? `${variation ?? 'outlined'}--${colorTheme}`\n : undefined;\n const { isFieldsetDisabled } = useFieldset();\n const shouldBeDisabled = isFieldsetDisabled\n ? isFieldsetDisabled\n : isDisabled ?? isLoading ?? rest['disabled'];\n const componentClasses = classNames(ComponentClassName.Button, ComponentClassName.FieldGroupControl, classNameModifier(ComponentClassName.Button, variation), classNameModifier(ComponentClassName.Button, colorThemeModifier), classNameModifier(ComponentClassName.Button, size), classNameModifierByFlag(ComponentClassName.Button, 'disabled', shouldBeDisabled), classNameModifierByFlag(ComponentClassName.Button, 'loading', isLoading), classNameModifierByFlag(ComponentClassName.Button, 'fullwidth', isFullWidth), className);\n return (React.createElement(View, { ref: ref, as: \"button\", className: componentClasses, isDisabled: shouldBeDisabled, type: type, ...rest }, isLoading ? (React.createElement(Flex, { as: \"span\", className: ComponentClassName.ButtonLoaderWrapper },\n React.createElement(Loader, { size: size }),\n loadingText ? loadingText : null)) : (children)));\n};\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/button)\n */\nconst Button = primitiveWithForwardRef(ButtonPrimitive);\nButton.displayName = 'Button';\n\nexport { Button };\n","import { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport * as React from 'react';\nimport { View } from '../../View/View.mjs';\n\n/**\n * @internal For internal Amplify UI use only. May be removed in a future release.\n */\nconst IconClose = (props) => {\n const { className, size, ...rest } = props;\n return (React.createElement(View, { as: \"span\", width: size ?? '1em', height: size ?? '1em', className: classNames(ComponentClassName.Icon, className), ...rest },\n React.createElement(\"svg\", { width: \"24\", height: \"24\", viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\", style: size ? { width: size, height: size } : undefined },\n React.createElement(\"path\", { d: \"M19 6.41L17.59 5L12 10.59L6.41 5L5 6.41L10.59 12L5 17.59L6.41 19L12 13.41L17.59 19L19 17.59L13.41 12L19 6.41Z\", fill: \"currentColor\" }))));\n};\n\nexport { IconClose };\n","import * as React from 'react';\nimport { classNames, ComponentClassName, classNameModifier, classNameModifierByFlag } from '@aws-amplify/ui';\nimport { View } from '../View/View.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst TextPrimitive = ({ as = 'p', className, children, isTruncated, variation, ...rest }, ref) => {\n const componentClasses = classNames(ComponentClassName.Text, classNameModifier(ComponentClassName.Text, variation), classNameModifierByFlag(ComponentClassName.Text, 'truncated', isTruncated), className);\n return (React.createElement(View, { as: as, className: componentClasses, ref: ref, ...rest }, children));\n};\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/text)\n */\nconst Text = primitiveWithForwardRef(TextPrimitive);\nText.displayName = 'Text';\n\nexport { Text };\n","import * as React from 'react';\nimport { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport { Text } from '../Text/Text.mjs';\n\nconst QA_FIELD_DESCRIPTION = 'qa-field-description';\nconst FieldDescription = ({ descriptiveText, labelHidden, ...rest }) => descriptiveText ? (React.createElement(Text, { \"data-testid\": QA_FIELD_DESCRIPTION, className: classNames(ComponentClassName.FieldDescription, {\n [ComponentClassName.VisuallyHidden]: labelHidden,\n }), ...rest }, descriptiveText)) : null;\nFieldDescription.displayName = 'FieldDescription';\n\nexport { FieldDescription, QA_FIELD_DESCRIPTION };\n","import * as React from 'react';\nimport { Text } from '../Text/Text.mjs';\nimport { ComponentClassName } from '@aws-amplify/ui';\n\nconst FieldErrorMessage = ({ errorMessage, hasError, ...rest }) => {\n return hasError && errorMessage ? (React.createElement(Text, { className: ComponentClassName.FieldErrorMessage, ...rest }, errorMessage)) : null;\n};\nFieldErrorMessage.displayName = 'FieldErrorMessage';\n\nexport { FieldErrorMessage };\n","import * as React from 'react';\nimport { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport { View } from '../View/View.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst LabelPrimitive = ({ children, className, visuallyHidden, ...rest }, ref) => {\n return (React.createElement(View, { as: \"label\", className: classNames(ComponentClassName.Label, className, {\n [ComponentClassName.VisuallyHidden]: visuallyHidden,\n }), ref: ref, ...rest }, children));\n};\nconst Label = primitiveWithForwardRef(LabelPrimitive);\nLabel.displayName = 'Label';\n\nexport { Label };\n","import * as React from 'react';\nimport { isFunction, classNames, ComponentClassName, classNameModifier } from '@aws-amplify/ui';\nimport { ComponentText } from '../shared/constants.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\nimport { View } from '../View/View.mjs';\nimport { Flex } from '../Flex/Flex.mjs';\nimport { Button } from '../Button/Button.mjs';\nimport { AlertIcon } from './AlertIcon.mjs';\nimport '../Icon/Icon.mjs';\nimport '../Icon/context/IconsContext.mjs';\nimport { useIcons } from '../Icon/context/useIcons.mjs';\nimport { IconClose } from '../Icon/icons/IconClose.mjs';\n\nconst AlertPrimitive = ({ buttonRef, children, className, dismissButtonLabel = ComponentText.Alert.dismissButtonLabel, hasIcon = true, heading, isDismissible = false, onDismiss, variation, ...rest }, ref) => {\n const [dismissed, setDismissed] = React.useState(false);\n const icons = useIcons('alert');\n const dismissAlert = React.useCallback(() => {\n setDismissed(!dismissed);\n if (isFunction(onDismiss)) {\n onDismiss();\n }\n }, [setDismissed, onDismiss, dismissed]);\n return !dismissed ? (React.createElement(Flex, { className: classNames(ComponentClassName.Alert, className, classNameModifier(ComponentClassName.Alert, variation)), ref: ref, role: \"alert\", ...rest },\n hasIcon && React.createElement(AlertIcon, { variation: variation, ariaHidden: true }),\n React.createElement(View, { flex: \"1\" },\n heading && (React.createElement(View, { className: ComponentClassName.AlertHeading }, heading)),\n React.createElement(View, { className: ComponentClassName.AlertBody }, children)),\n isDismissible && (React.createElement(Button, { ariaLabel: dismissButtonLabel, variation: \"link\", className: ComponentClassName.AlertDismiss, onClick: dismissAlert, ref: buttonRef }, icons?.close ?? React.createElement(IconClose, { \"aria-hidden\": \"true\" }))))) : null;\n};\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/alert)\n */\nconst Alert = primitiveWithForwardRef(AlertPrimitive);\nAlert.displayName = 'Alert';\n\nexport { Alert };\n","const getUniqueComponentId = (id, suffix) => (id && suffix ? `${id}-${suffix}` : undefined);\n\nexport { getUniqueComponentId };\n","import * as React from 'react';\nimport { ComponentClassName, classNames, classNameModifier } from '@aws-amplify/ui';\nimport { Flex } from '../Flex/Flex.mjs';\nimport { View } from '../View/View.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst FieldGroupPrimitive = ({ children, className, innerEndComponent, innerStartComponent, orientation = 'horizontal', outerEndComponent, outerStartComponent, variation, ...rest }, ref) => {\n // Don't apply hasInner classnames unless a component was provided\n const hasInnerStartComponent = innerStartComponent != null;\n const hasInnerEndComponent = innerEndComponent != null;\n const fieldGroupHasInnerStartClassName = hasInnerStartComponent\n ? ComponentClassName.FieldGroupHasInnerStart\n : null;\n const fieldGroupHasInnerEndClassName = hasInnerEndComponent\n ? ComponentClassName.FieldGroupHasInnerEnd\n : null;\n const componentClasses = classNames(ComponentClassName.FieldGroup, fieldGroupHasInnerStartClassName, fieldGroupHasInnerEndClassName, classNameModifier(ComponentClassName.FieldGroup, orientation), className);\n return (React.createElement(Flex, { className: componentClasses, ref: ref, ...rest },\n outerStartComponent && (React.createElement(View, { className: classNames(ComponentClassName.FieldGroupOuterStart, classNameModifier(ComponentClassName.FieldGroupOuterStart, variation)) }, outerStartComponent)),\n React.createElement(View, { className: classNames(ComponentClassName.FieldGroupFieldWrapper, classNameModifier(ComponentClassName.FieldGroupFieldWrapper, orientation)) },\n innerStartComponent && (React.createElement(View, { className: ComponentClassName.FieldGroupInnerStart }, innerStartComponent)),\n children,\n innerEndComponent && (React.createElement(View, { className: ComponentClassName.FieldGroupInnerEnd }, innerEndComponent))),\n outerEndComponent && (React.createElement(View, { className: classNames(ComponentClassName.FieldGroupOuterEnd, classNameModifier(ComponentClassName.FieldGroupOuterEnd, variation)) }, outerEndComponent))));\n};\nconst FieldGroup = primitiveWithForwardRef(FieldGroupPrimitive);\nFieldGroup.displayName = 'FieldGroup';\n\nexport { FieldGroup };\n","import * as React from 'react';\nimport { classNames, ComponentClassName, classNameModifier, classNameModifierByFlag } from '@aws-amplify/ui';\nimport { View } from '../View/View.mjs';\nimport { useFieldset } from '../Fieldset/useFieldset.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst InputPrimitive = ({ autoComplete, checked, className, defaultChecked, defaultValue, id, isDisabled, isReadOnly, isRequired, size, type = 'text', hasError = false, value, variation, ...rest }, ref) => {\n const componentClasses = classNames(ComponentClassName.Input, ComponentClassName.FieldGroupControl, classNameModifier(ComponentClassName.Input, variation), classNameModifierByFlag(ComponentClassName.Input, 'error', hasError), classNameModifier(ComponentClassName.Input, size), className);\n const { isFieldsetDisabled } = useFieldset();\n return (React.createElement(View, { \"aria-invalid\": hasError, as: \"input\", autoComplete: autoComplete, checked: checked, className: componentClasses, defaultChecked: defaultChecked, defaultValue: defaultValue, isDisabled: isFieldsetDisabled ? isFieldsetDisabled : isDisabled, id: id, readOnly: isReadOnly, ref: ref, required: isRequired, type: type, value: value, ...rest }));\n};\nconst Input = primitiveWithForwardRef(InputPrimitive);\nInput.displayName = 'Input';\n\nexport { Input };\n","import { ComponentPropsToStylePropsMap } from '../types/style.mjs';\n\nconst isStyleKey = (prop) => {\n return prop in ComponentPropsToStylePropsMap;\n};\n/**\n * This function splits props into style props and non-style props. This is used\n * on Field primitives so we can apply style props on the wrapper element and\n * the rest on the input.\n * @param props this should be a destructured `rest` from the component's props\n */\nconst splitPrimitiveProps = (props) => {\n const splitProps = {\n styleProps: {},\n rest: {},\n };\n Object.keys(props).forEach((prop) => {\n if (isStyleKey(prop)) {\n // we know it is a style key\n // so we know we can assign the key in styleProps\n splitProps.styleProps = {\n ...splitProps.styleProps,\n [prop]: props[prop],\n };\n }\n else {\n splitProps.rest = {\n ...splitProps.rest,\n [prop]: props[prop],\n };\n }\n });\n return splitProps;\n};\n\nexport { splitPrimitiveProps };\n","/**\n * Joins an array of strings and undefined values into a single string with spaces as separators.\n * If all elements are undefined, returns undefined.\n *\n * @param {(string | undefined)[]} ids - An array of strings or undefined values.\n * @returns {string | undefined} A single string with space-separated IDs, or undefined if all elements are undefined.\n */\nconst createSpaceSeparatedIds = (ids) => {\n const joinedIds = ids.filter((id) => id !== undefined).join(' ');\n return joinedIds.length > 0 ? joinedIds : undefined;\n};\n\nexport { createSpaceSeparatedIds };\n","import { isFunction } from '@aws-amplify/ui';\n\n(typeof Symbol !== 'undefined' && isFunction(Symbol.for)\n ? Symbol.for('amplify_default')\n : '@@amplify_default');\nconst ERROR_SUFFIX = 'error';\nconst DESCRIPTION_SUFFIX = 'description';\n\nexport { DESCRIPTION_SUFFIX, ERROR_SUFFIX };\n","import * as React from 'react';\nimport { classNames, ComponentClassName, classNameModifier } from '@aws-amplify/ui';\nimport '../Field/FieldClearButton.mjs';\nimport { FieldDescription } from '../Field/FieldDescription.mjs';\nimport { FieldErrorMessage } from '../Field/FieldErrorMessage.mjs';\nimport '../Field/Field.mjs';\nimport { FieldGroup } from '../FieldGroup/FieldGroup.mjs';\nimport { Flex } from '../Flex/Flex.mjs';\nimport { Input } from '../Input/Input.mjs';\nimport { Label } from '../Label/Label.mjs';\nimport { splitPrimitiveProps } from '../utils/splitPrimitiveProps.mjs';\nimport { useStableId } from '../utils/useStableId.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\nimport { createSpaceSeparatedIds } from '../utils/createSpaceSeparatedIds.mjs';\nimport { DESCRIPTION_SUFFIX, ERROR_SUFFIX } from '../../helpers/constants.mjs';\nimport { getUniqueComponentId } from '../utils/getUniqueComponentId.mjs';\n\nconst TextFieldPrimitive = (props, ref) => {\n const { className, descriptiveText, errorMessage, hasError = false, id, innerEndComponent, innerStartComponent, label, labelHidden = false, outerEndComponent, outerStartComponent, size, testId, variation, inputStyles, ..._rest } = props;\n const fieldId = useStableId(id);\n const stableId = useStableId();\n const descriptionId = descriptiveText\n ? getUniqueComponentId(stableId, DESCRIPTION_SUFFIX)\n : undefined;\n const errorId = hasError\n ? getUniqueComponentId(stableId, ERROR_SUFFIX)\n : undefined;\n const ariaDescribedBy = createSpaceSeparatedIds([errorId, descriptionId]);\n const { styleProps, rest } = splitPrimitiveProps(_rest);\n return (React.createElement(Flex, { className: classNames(ComponentClassName.Field, classNameModifier(ComponentClassName.Field, size), ComponentClassName.TextField, className), testId: testId, ...styleProps },\n React.createElement(Label, { htmlFor: fieldId, visuallyHidden: labelHidden }, label),\n React.createElement(FieldDescription, { id: descriptionId, labelHidden: labelHidden, descriptiveText: descriptiveText }),\n React.createElement(FieldGroup, { outerStartComponent: outerStartComponent, outerEndComponent: outerEndComponent, innerStartComponent: innerStartComponent, innerEndComponent: innerEndComponent, variation: variation },\n React.createElement(Input, { \"aria-describedby\": ariaDescribedBy, hasError: hasError, id: fieldId, ref: ref, size: size, variation: variation, ...inputStyles, ...rest })),\n React.createElement(FieldErrorMessage, { id: errorId, hasError: hasError, errorMessage: errorMessage })));\n};\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/textfield)\n */\nconst TextField = primitiveWithForwardRef(TextFieldPrimitive);\nTextField.displayName = 'TextField';\n\nexport { TextField };\n","import * as React from 'react';\nimport { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport { View } from '../View/View.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst VisuallyHiddenPrimitive = ({ as = 'span', children, className, ...rest }, ref) => (React.createElement(View, { as: as, className: classNames(ComponentClassName.VisuallyHidden, className), ref: ref, ...rest }, children));\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/visuallyhidden)\n */\nconst VisuallyHidden = primitiveWithForwardRef(VisuallyHiddenPrimitive);\nVisuallyHidden.displayName = 'VisuallyHidden';\n\nexport { VisuallyHidden };\n","var root = require('./_root');\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\nmodule.exports = now;\n","/** Used to match a single whitespace character. */\nvar reWhitespace = /\\s/;\n\n/**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\nfunction trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n}\n\nmodule.exports = trimmedEndIndex;\n","var trimmedEndIndex = require('./_trimmedEndIndex');\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\n\n/**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\nfunction baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n}\n\nmodule.exports = baseTrim;\n","var baseTrim = require('./_baseTrim'),\n isObject = require('./isObject'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = baseTrim(value);\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = toNumber;\n","var isObject = require('./isObject'),\n now = require('./now'),\n toNumber = require('./toNumber');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\nmodule.exports = debounce;\n","import { classNames, ComponentClassName, classNameModifier } from '@aws-amplify/ui';\nimport * as React from 'react';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\nimport { View } from '../View/View.mjs';\n\nconst DividerPrimitive = ({ className, orientation = 'horizontal', size, label, ...rest }, ref) => {\n const componentClasses = classNames(ComponentClassName.Divider, classNameModifier(ComponentClassName.Divider, orientation), classNameModifier(ComponentClassName.Divider, size), className);\n return (React.createElement(View, { \"aria-orientation\": orientation, as: \"hr\", className: componentClasses, \"data-label\": label, ref: ref, ...rest }));\n};\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/divider)\n */\nconst Divider = primitiveWithForwardRef(DividerPrimitive);\nDivider.displayName = 'Divider';\n\nexport { Divider };\n","import { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport * as React from 'react';\nimport { View } from '../../View/View.mjs';\n\n/**\n * @internal For internal Amplify UI use only. May be removed in a future release.\n */\nconst IconExpandMore = (props) => {\n const { className, ...rest } = props;\n return (React.createElement(View, { as: \"span\", width: \"1em\", height: \"1em\", className: classNames(ComponentClassName.Icon, className), ...rest },\n React.createElement(\"svg\", { width: \"24\", height: \"24\", viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\" },\n React.createElement(\"path\", { d: \"M16.59 8.58984L12 13.1698L7.41 8.58984L6 9.99984L12 15.9998L18 9.99984L16.59 8.58984Z\", fill: \"currentColor\" }))));\n};\n\nexport { IconExpandMore };\n","import * as React from 'react';\nimport { classNames, ComponentClassName, classNameModifier } from '@aws-amplify/ui';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\nimport { Flex } from '../Flex/Flex.mjs';\nimport { View } from '../View/View.mjs';\nimport { VisuallyHidden } from '../VisuallyHidden/VisuallyHidden.mjs';\nimport { useFieldset, FieldsetContext } from './useFieldset.mjs';\n\nconst FieldsetPrimitive = ({ children, className, isDisabled, legend, legendHidden, size, testId, variation = 'plain', ...rest }, ref) => {\n const { isFieldsetDisabled } = useFieldset();\n // Fieldsets that are nested within a disabled Fieldset should\n // also be disabled.\n const shouldBeDisabled = isFieldsetDisabled ? isFieldsetDisabled : isDisabled;\n const value = React.useMemo(() => ({\n isFieldsetDisabled: shouldBeDisabled,\n }), [shouldBeDisabled]);\n const fieldsetClasses = classNames(ComponentClassName.Fieldset, classNameModifier(ComponentClassName.Fieldset, variation), classNameModifier(ComponentClassName.Fieldset, size), className);\n const legendClasses = classNames(ComponentClassName.FieldsetLegend, classNameModifier(ComponentClassName.FieldsetLegend, size), {\n [ComponentClassName.VisuallyHidden]: legendHidden,\n });\n return (React.createElement(FieldsetContext.Provider, { value: value },\n React.createElement(Flex, { as: \"fieldset\", className: fieldsetClasses, ref: ref, disabled: shouldBeDisabled, testId: testId, ...rest },\n React.createElement(VisuallyHidden, { as: \"legend\" }, legend),\n React.createElement(View, { as: \"div\", \"aria-hidden\": \"true\", className: legendClasses }, legend),\n children)));\n};\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/fieldset)\n */\nconst Fieldset = primitiveWithForwardRef(FieldsetPrimitive);\nFieldset.displayName = 'Fieldset';\n\nexport { Fieldset };\n","import * as React from 'react';\nimport { classNames, ComponentClassName, classNameModifier, classNameModifierByFlag } from '@aws-amplify/ui';\nimport { View } from '../View/View.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst headingLevels = {\n 1: 'h1',\n 2: 'h2',\n 3: 'h3',\n 4: 'h4',\n 5: 'h5',\n 6: 'h6',\n};\nconst HeadingPrimitive = ({ className, children, isTruncated, level = 6, ...rest }, ref) => (React.createElement(View, { as: headingLevels[level], className: classNames(ComponentClassName.Heading, classNameModifier(ComponentClassName.Heading, level), classNameModifierByFlag(ComponentClassName.Heading, 'truncated', isTruncated), className), ref: ref, ...rest }, children));\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/heading)\n */\nconst Heading = primitiveWithForwardRef(HeadingPrimitive);\nHeading.displayName = 'Heading';\n\nexport { Heading };\n","function _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}\nexport { _extends as default };","import { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport * as React from 'react';\nimport { View } from '../../View/View.mjs';\n\n/**\n * @internal For internal Amplify UI use only. May be removed in a future release.\n */\nconst IconVisibilityOff = (props) => {\n const { className, ...rest } = props;\n return (React.createElement(View, { as: \"span\", width: \"1em\", height: \"1em\", className: classNames(ComponentClassName.Icon, className), ...rest },\n React.createElement(\"svg\", { width: \"24\", height: \"24\", viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\" },\n React.createElement(\"path\", { d: \"M12 6.0002C15.79 6.0002 19.17 8.1302 20.82 11.5002C20.23 12.7202 19.4 13.7702 18.41 14.6202L19.82 16.0302C21.21 14.8002 22.31 13.2602 23 11.5002C21.27 7.1102 17 4.0002 12 4.0002C10.73 4.0002 9.51 4.2002 8.36 4.5702L10.01 6.2202C10.66 6.0902 11.32 6.0002 12 6.0002ZM10.93 7.14019L13 9.2102C13.57 9.4602 14.03 9.9202 14.28 10.4902L16.35 12.5602C16.43 12.2202 16.49 11.8602 16.49 11.4902C16.5 9.0102 14.48 7.0002 12 7.0002C11.63 7.0002 11.28 7.05019 10.93 7.14019ZM2.01 3.8702L4.69 6.5502C3.06 7.8302 1.77 9.5302 1 11.5002C2.73 15.8902 7 19.0002 12 19.0002C13.52 19.0002 14.98 18.7102 16.32 18.1802L19.74 21.6002L21.15 20.1902L3.42 2.4502L2.01 3.8702ZM9.51 11.3702L12.12 13.9802C12.08 13.9902 12.04 14.0002 12 14.0002C10.62 14.0002 9.5 12.8802 9.5 11.5002C9.5 11.4502 9.51 11.4202 9.51 11.3702V11.3702ZM6.11 7.97019L7.86 9.7202C7.63 10.2702 7.5 10.8702 7.5 11.5002C7.5 13.9802 9.52 16.0002 12 16.0002C12.63 16.0002 13.23 15.8702 13.77 15.6402L14.75 16.6202C13.87 16.8602 12.95 17.0002 12 17.0002C8.21 17.0002 4.83 14.8702 3.18 11.5002C3.88 10.0702 4.9 8.89019 6.11 7.97019Z\", fill: \"currentColor\" }))));\n};\n\nexport { IconVisibilityOff };\n","import { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport * as React from 'react';\nimport { View } from '../../View/View.mjs';\n\n/**\n * @internal For internal Amplify UI use only. May be removed in a future release.\n */\nconst IconVisibility = (props) => {\n const { className, ...rest } = props;\n return (React.createElement(View, { as: \"span\", width: \"1em\", height: \"1em\", className: classNames(ComponentClassName.Icon, className), ...rest },\n React.createElement(\"svg\", { width: \"24\", height: \"24\", viewBox: \"0 0 24 24\", fill: \"none\", xmlns: \"http://www.w3.org/2000/svg\" },\n React.createElement(\"path\", { d: \"M12 6C15.79 6 19.17 8.13 20.82 11.5C19.17 14.87 15.79 17 12 17C8.21 17 4.83 14.87 3.18 11.5C4.83 8.13 8.21 6 12 6ZM12 4C7 4 2.73 7.11 1 11.5C2.73 15.89 7 19 12 19C17 19 21.27 15.89 23 11.5C21.27 7.11 17 4 12 4ZM12 9C13.38 9 14.5 10.12 14.5 11.5C14.5 12.88 13.38 14 12 14C10.62 14 9.5 12.88 9.5 11.5C9.5 10.12 10.62 9 12 9ZM12 7C9.52 7 7.5 9.02 7.5 11.5C7.5 13.98 9.52 16 12 16C14.48 16 16.5 13.98 16.5 11.5C16.5 9.02 14.48 7 12 7Z\", fill: \"currentColor\" }))));\n};\n\nexport { IconVisibility };\n","import * as React from 'react';\nimport { classNames, ComponentClassName, classNameModifierByFlag } from '@aws-amplify/ui';\nimport { Button } from '../Button/Button.mjs';\nimport { VisuallyHidden } from '../VisuallyHidden/VisuallyHidden.mjs';\nimport { ComponentText } from '../shared/constants.mjs';\nimport '../Icon/Icon.mjs';\nimport '../Icon/context/IconsContext.mjs';\nimport { useIcons } from '../Icon/context/useIcons.mjs';\nimport '../View/View.mjs';\nimport { IconVisibilityOff } from '../Icon/icons/IconVisibilityOff.mjs';\nimport { IconVisibility } from '../Icon/icons/IconVisibility.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst { passwordIsHidden, passwordIsShown, showPassword } = ComponentText.PasswordField;\nconst ShowPasswordButtonPrimitive = ({ fieldType, passwordIsHiddenLabel = passwordIsHidden, passwordIsShownLabel = passwordIsShown, showPasswordButtonLabel = showPassword, size, hasError, ...rest }, ref) => {\n const icons = useIcons('passwordField');\n const showPasswordButtonClass = classNames(ComponentClassName.FieldShowPassword, classNameModifierByFlag(ComponentClassName.FieldShowPassword, 'error', hasError));\n const icon = fieldType === 'password'\n ? icons?.visibility ?? React.createElement(IconVisibility, { \"aria-hidden\": \"true\" })\n : icons?.visibilityOff ?? React.createElement(IconVisibilityOff, { \"aria-hidden\": \"true\" });\n return (React.createElement(Button, { \"aria-checked\": fieldType !== 'password', ariaLabel: showPasswordButtonLabel, className: showPasswordButtonClass, colorTheme: hasError ? 'error' : undefined, ref: ref, role: \"switch\", size: size, ...rest },\n React.createElement(VisuallyHidden, { \"aria-live\": \"polite\" }, fieldType === 'password'\n ? passwordIsHiddenLabel\n : passwordIsShownLabel),\n icon));\n};\nconst ShowPasswordButton = primitiveWithForwardRef(ShowPasswordButtonPrimitive);\nShowPasswordButton.displayName = 'ShowPasswordButton';\n\nexport { ShowPasswordButton };\n","import { classNames, ComponentClassName } from '@aws-amplify/ui';\nimport * as React from 'react';\nimport { ShowPasswordButton } from './ShowPasswordButton.mjs';\nimport { TextField } from '../TextField/TextField.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst PasswordFieldPrimitive = ({ autoComplete = 'current-password', label, className, hideShowPassword = false, passwordIsHiddenLabel, passwordIsShownLabel, showPasswordButtonLabel, showPasswordButtonRef, size, hasError, ...rest }, ref) => {\n const [type, setType] = React.useState('password');\n const showPasswordOnClick = React.useCallback(() => {\n if (type === 'password') {\n setType('text');\n }\n else {\n setType('password');\n }\n }, [setType, type]);\n return (React.createElement(TextField, { autoComplete: autoComplete, outerEndComponent: hideShowPassword ? null : (React.createElement(ShowPasswordButton, { fieldType: type, onClick: showPasswordOnClick, passwordIsHiddenLabel: passwordIsHiddenLabel, passwordIsShownLabel: passwordIsShownLabel, ref: showPasswordButtonRef, size: size, showPasswordButtonLabel: showPasswordButtonLabel, hasError: hasError })), size: size, type: type, label: label, className: classNames(ComponentClassName.PasswordField, className), ref: ref, hasError: hasError, ...rest }));\n};\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/passwordfield)\n */\nconst PasswordField = primitiveWithForwardRef(PasswordFieldPrimitive);\nPasswordField.displayName = 'PasswordField';\n\nexport { PasswordField };\n","import * as React from 'react';\nimport { classNames, ComponentClassName, classNameModifier, classNameModifierByFlag } from '@aws-amplify/ui';\nimport { Flex } from '../Flex/Flex.mjs';\nimport '../Icon/Icon.mjs';\nimport '../Icon/context/IconsContext.mjs';\nimport { useIcons } from '../Icon/context/useIcons.mjs';\nimport { View } from '../View/View.mjs';\nimport { IconExpandMore } from '../Icon/icons/IconExpandMore.mjs';\nimport { useFieldset } from '../Fieldset/useFieldset.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst SelectPrimitive = ({ autoComplete, className, size, variation, value, defaultValue, hasError, icon, iconColor, children, placeholder, isDisabled, isRequired, isMultiple = false, selectSize = 1, ...rest }, ref) => {\n const DEFAULT_PLACEHOLDER_VALUE = '';\n // value === undefined is to make sure that component is used in uncontrolled way so that setting defaultValue is valid\n const shouldSetDefaultPlaceholderValue = value === undefined && defaultValue === undefined && placeholder;\n const isExpanded = isMultiple || selectSize > 1;\n const componentClasses = classNames(ComponentClassName.Select, ComponentClassName.FieldGroupControl, classNameModifier(ComponentClassName.Select, size), classNameModifier(ComponentClassName.Select, variation), classNameModifierByFlag(ComponentClassName.Select, 'error', hasError), classNameModifierByFlag(ComponentClassName.Select, 'expanded', isExpanded), className);\n const icons = useIcons('select');\n const { isFieldsetDisabled } = useFieldset();\n return (React.createElement(View, { className: ComponentClassName.SelectWrapper },\n React.createElement(View, { \"aria-invalid\": hasError, as: \"select\", autoComplete: autoComplete, value: value, defaultValue: shouldSetDefaultPlaceholderValue\n ? DEFAULT_PLACEHOLDER_VALUE\n : defaultValue, isDisabled: isFieldsetDisabled ? isFieldsetDisabled : isDisabled, multiple: isMultiple, size: selectSize, required: isRequired, className: componentClasses, ref: ref, ...rest },\n placeholder && React.createElement(\"option\", { value: \"\" }, placeholder),\n children),\n isExpanded ? null : (React.createElement(Flex, { className: classNames(ComponentClassName.SelectIcon, classNameModifier(ComponentClassName.SelectIcon, size)), color: iconColor, \"aria-hidden\": \"true\" }, icon ?? icons?.expand ?? React.createElement(IconExpandMore, null)))));\n};\nconst Select = primitiveWithForwardRef(SelectPrimitive);\nSelect.displayName = 'Select';\n\nexport { Select };\n","import * as React from 'react';\nimport { classNames, ComponentClassName, classNameModifier } from '@aws-amplify/ui';\nimport '../Field/FieldClearButton.mjs';\nimport { FieldDescription } from '../Field/FieldDescription.mjs';\nimport { FieldErrorMessage } from '../Field/FieldErrorMessage.mjs';\nimport '../Field/Field.mjs';\nimport { Flex } from '../Flex/Flex.mjs';\nimport { Label } from '../Label/Label.mjs';\nimport { Select } from '../Select/Select.mjs';\nimport { splitPrimitiveProps } from '../utils/splitPrimitiveProps.mjs';\nimport { useStableId } from '../utils/useStableId.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\nimport { createSpaceSeparatedIds } from '../utils/createSpaceSeparatedIds.mjs';\nimport { DESCRIPTION_SUFFIX, ERROR_SUFFIX } from '../../helpers/constants.mjs';\nimport { getUniqueComponentId } from '../utils/getUniqueComponentId.mjs';\n\nconst selectFieldChildren = ({ children, options, }) => {\n if (children) {\n if (options?.length) {\n // eslint-disable-next-line no-console\n console.warn('Amplify UI: component defaults to rendering children over `options`. When using the `options` prop, omit children.');\n }\n return children;\n }\n return options?.map((option, index) => (React.createElement(\"option\", { label: option, value: option, key: `${option}-${index}` }, option)));\n};\nconst SelectFieldPrimitive = (props, ref) => {\n const { children, className, descriptiveText, errorMessage, hasError = false, id, label, labelHidden = false, options, size, testId, inputStyles, ..._rest } = props;\n const fieldId = useStableId(id);\n const stableId = useStableId();\n const descriptionId = descriptiveText\n ? getUniqueComponentId(stableId, DESCRIPTION_SUFFIX)\n : undefined;\n const errorId = hasError\n ? getUniqueComponentId(stableId, ERROR_SUFFIX)\n : undefined;\n const ariaDescribedBy = createSpaceSeparatedIds([errorId, descriptionId]);\n const { styleProps, rest } = splitPrimitiveProps(_rest);\n return (React.createElement(Flex, { className: classNames(ComponentClassName.Field, classNameModifier(ComponentClassName.Field, size), ComponentClassName.SelectField, className), testId: testId, ...styleProps },\n React.createElement(Label, { htmlFor: fieldId, visuallyHidden: labelHidden }, label),\n React.createElement(FieldDescription, { id: descriptionId, labelHidden: labelHidden, descriptiveText: descriptiveText }),\n React.createElement(Select, { \"aria-describedby\": ariaDescribedBy, hasError: hasError, id: fieldId, ref: ref, size: size, ...rest, ...inputStyles }, selectFieldChildren({ children, options })),\n React.createElement(FieldErrorMessage, { id: errorId, hasError: hasError, errorMessage: errorMessage })));\n};\n/**\n * [📖 Docs](https://ui.docs.amplify.aws/react/components/selectfield)\n */\nconst SelectField = primitiveWithForwardRef(SelectFieldPrimitive);\nSelectField.displayName = 'SelectField';\n\nexport { SelectField };\n","import * as React from 'react';\nimport { classNames, ComponentClassName, countryDialCodes } from '@aws-amplify/ui';\nimport { SelectField } from '../SelectField/SelectField.mjs';\nimport { primitiveWithForwardRef } from '../utils/primitiveWithForwardRef.mjs';\n\nconst DialCodeSelectPrimitive = ({ className, dialCodeList, isReadOnly, ...props }, ref) => {\n const dialList = dialCodeList ?? countryDialCodes;\n const dialCodeOptions = React.useMemo(() => dialList.map((dialCode) => (\n // Regarding the `disabled` attribute, see comment in SelectField below\n React.createElement(\"option\", { key: dialCode, value: dialCode, disabled: isReadOnly }, dialCode))), [dialList, isReadOnly]);\n return (React.createElement(SelectField\n /*\n Since \n * We'll never share your email.\n * \n * ```\n *\n * ⚠️ Only one `InputBase` can be used within a FormControl because it creates visual inconsistencies.\n * For instance, only one input can be focused at the same time, the state shouldn't be shared.\n */\nconst FormControl = /*#__PURE__*/React.forwardRef(function FormControl(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiFormControl'\n });\n const {\n children,\n className,\n color = 'primary',\n component = 'div',\n disabled = false,\n error = false,\n focused: visuallyFocused,\n fullWidth = false,\n hiddenLabel = false,\n margin = 'none',\n required = false,\n size = 'medium',\n variant = 'outlined'\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const ownerState = _extends({}, props, {\n color,\n component,\n disabled,\n error,\n fullWidth,\n hiddenLabel,\n margin,\n required,\n size,\n variant\n });\n const classes = useUtilityClasses(ownerState);\n const [adornedStart, setAdornedStart] = React.useState(() => {\n // We need to iterate through the children and find the Input in order\n // to fully support server-side rendering.\n let initialAdornedStart = false;\n if (children) {\n React.Children.forEach(children, child => {\n if (!isMuiElement(child, ['Input', 'Select'])) {\n return;\n }\n const input = isMuiElement(child, ['Select']) ? child.props.input : child;\n if (input && isAdornedStart(input.props)) {\n initialAdornedStart = true;\n }\n });\n }\n return initialAdornedStart;\n });\n const [filled, setFilled] = React.useState(() => {\n // We need to iterate through the children and find the Input in order\n // to fully support server-side rendering.\n let initialFilled = false;\n if (children) {\n React.Children.forEach(children, child => {\n if (!isMuiElement(child, ['Input', 'Select'])) {\n return;\n }\n if (isFilled(child.props, true) || isFilled(child.props.inputProps, true)) {\n initialFilled = true;\n }\n });\n }\n return initialFilled;\n });\n const [focusedState, setFocused] = React.useState(false);\n if (disabled && focusedState) {\n setFocused(false);\n }\n const focused = visuallyFocused !== undefined && !disabled ? visuallyFocused : focusedState;\n let registerEffect;\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const registeredInput = React.useRef(false);\n registerEffect = () => {\n if (registeredInput.current) {\n console.error(['MUI: There are multiple `InputBase` components inside a FormControl.', 'This creates visual inconsistencies, only use one `InputBase`.'].join('\\n'));\n }\n registeredInput.current = true;\n return () => {\n registeredInput.current = false;\n };\n };\n }\n const childContext = React.useMemo(() => {\n return {\n adornedStart,\n setAdornedStart,\n color,\n disabled,\n error,\n filled,\n focused,\n fullWidth,\n hiddenLabel,\n size,\n onBlur: () => {\n setFocused(false);\n },\n onEmpty: () => {\n setFilled(false);\n },\n onFilled: () => {\n setFilled(true);\n },\n onFocus: () => {\n setFocused(true);\n },\n registerEffect,\n required,\n variant\n };\n }, [adornedStart, color, disabled, error, filled, focused, fullWidth, hiddenLabel, registerEffect, required, size, variant]);\n return /*#__PURE__*/_jsx(FormControlContext.Provider, {\n value: childContext,\n children: /*#__PURE__*/_jsx(FormControlRoot, _extends({\n as: component,\n ownerState: ownerState,\n className: clsx(classes.root, className),\n ref: ref\n }, other, {\n children: children\n }))\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? FormControl.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The color of the component.\n * It supports both default and custom theme colors, which can be added as shown in the\n * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).\n * @default 'primary'\n */\n color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * If `true`, the label, input and helper text should be displayed in a disabled state.\n * @default false\n */\n disabled: PropTypes.bool,\n /**\n * If `true`, the label is displayed in an error state.\n * @default false\n */\n error: PropTypes.bool,\n /**\n * If `true`, the component is displayed in focused state.\n */\n focused: PropTypes.bool,\n /**\n * If `true`, the component will take up the full width of its container.\n * @default false\n */\n fullWidth: PropTypes.bool,\n /**\n * If `true`, the label is hidden.\n * This is used to increase density for a `FilledInput`.\n * Be sure to add `aria-label` to the `input` element.\n * @default false\n */\n hiddenLabel: PropTypes.bool,\n /**\n * If `dense` or `normal`, will adjust vertical spacing of this and contained components.\n * @default 'none'\n */\n margin: PropTypes.oneOf(['dense', 'none', 'normal']),\n /**\n * If `true`, the label will indicate that the `input` is required.\n * @default false\n */\n required: PropTypes.bool,\n /**\n * The size of the component.\n * @default 'medium'\n */\n size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The variant to use.\n * @default 'outlined'\n */\n variant: PropTypes.oneOf(['filled', 'outlined', 'standard'])\n} : void 0;\nexport default FormControl;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getFormHelperTextUtilityClasses(slot) {\n return generateUtilityClass('MuiFormHelperText', slot);\n}\nconst formHelperTextClasses = generateUtilityClasses('MuiFormHelperText', ['root', 'error', 'disabled', 'sizeSmall', 'sizeMedium', 'contained', 'focused', 'filled', 'required']);\nexport default formHelperTextClasses;","'use client';\n\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nvar _span;\nconst _excluded = [\"children\", \"className\", \"component\", \"disabled\", \"error\", \"filled\", \"focused\", \"margin\", \"required\", \"variant\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport formControlState from '../FormControl/formControlState';\nimport useFormControl from '../FormControl/useFormControl';\nimport styled from '../styles/styled';\nimport capitalize from '../utils/capitalize';\nimport formHelperTextClasses, { getFormHelperTextUtilityClasses } from './formHelperTextClasses';\nimport { useDefaultProps } from '../DefaultPropsProvider';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n contained,\n size,\n disabled,\n error,\n filled,\n focused,\n required\n } = ownerState;\n const slots = {\n root: ['root', disabled && 'disabled', error && 'error', size && `size${capitalize(size)}`, contained && 'contained', focused && 'focused', filled && 'filled', required && 'required']\n };\n return composeClasses(slots, getFormHelperTextUtilityClasses, classes);\n};\nconst FormHelperTextRoot = styled('p', {\n name: 'MuiFormHelperText',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.size && styles[`size${capitalize(ownerState.size)}`], ownerState.contained && styles.contained, ownerState.filled && styles.filled];\n }\n})(({\n theme,\n ownerState\n}) => _extends({\n color: (theme.vars || theme).palette.text.secondary\n}, theme.typography.caption, {\n textAlign: 'left',\n marginTop: 3,\n marginRight: 0,\n marginBottom: 0,\n marginLeft: 0,\n [`&.${formHelperTextClasses.disabled}`]: {\n color: (theme.vars || theme).palette.text.disabled\n },\n [`&.${formHelperTextClasses.error}`]: {\n color: (theme.vars || theme).palette.error.main\n }\n}, ownerState.size === 'small' && {\n marginTop: 4\n}, ownerState.contained && {\n marginLeft: 14,\n marginRight: 14\n}));\nconst FormHelperText = /*#__PURE__*/React.forwardRef(function FormHelperText(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiFormHelperText'\n });\n const {\n children,\n className,\n component = 'p'\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const muiFormControl = useFormControl();\n const fcs = formControlState({\n props,\n muiFormControl,\n states: ['variant', 'size', 'disabled', 'error', 'filled', 'focused', 'required']\n });\n const ownerState = _extends({}, props, {\n component,\n contained: fcs.variant === 'filled' || fcs.variant === 'outlined',\n variant: fcs.variant,\n size: fcs.size,\n disabled: fcs.disabled,\n error: fcs.error,\n filled: fcs.filled,\n focused: fcs.focused,\n required: fcs.required\n });\n const classes = useUtilityClasses(ownerState);\n return /*#__PURE__*/_jsx(FormHelperTextRoot, _extends({\n as: component,\n ownerState: ownerState,\n className: clsx(classes.root, className),\n ref: ref\n }, other, {\n children: children === ' ' ? // notranslate needed while Google Translate will not fix zero-width space issue\n _span || (_span = /*#__PURE__*/_jsx(\"span\", {\n className: \"notranslate\",\n children: \"\\u200B\"\n })) : children\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? FormHelperText.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n *\n * If `' '` is provided, the component reserves one line height for displaying a future message.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * If `true`, the helper text should be displayed in a disabled state.\n */\n disabled: PropTypes.bool,\n /**\n * If `true`, helper text should be displayed in an error state.\n */\n error: PropTypes.bool,\n /**\n * If `true`, the helper text should use filled classes key.\n */\n filled: PropTypes.bool,\n /**\n * If `true`, the helper text should use focused classes key.\n */\n focused: PropTypes.bool,\n /**\n * If `dense`, will adjust vertical spacing. This is normally obtained via context from\n * FormControl.\n */\n margin: PropTypes.oneOf(['dense']),\n /**\n * If `true`, the helper text should use required classes key.\n */\n required: PropTypes.bool,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The variant to use.\n */\n variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['filled', 'outlined', 'standard']), PropTypes.string])\n} : void 0;\nexport default FormHelperText;","export const reflow = node => node.scrollTop;\nexport function getTransitionProps(props, options) {\n var _style$transitionDura, _style$transitionTimi;\n const {\n timeout,\n easing,\n style = {}\n } = props;\n return {\n duration: (_style$transitionDura = style.transitionDuration) != null ? _style$transitionDura : typeof timeout === 'number' ? timeout : timeout[options.mode] || 0,\n easing: (_style$transitionTimi = style.transitionTimingFunction) != null ? _style$transitionTimi : typeof easing === 'object' ? easing[options.mode] : easing,\n delay: style.transitionDelay\n };\n}","'use client';\n\nimport _extends from \"@babel/runtime/helpers/esm/extends\";\nimport _objectWithoutPropertiesLoose from \"@babel/runtime/helpers/esm/objectWithoutPropertiesLoose\";\nconst _excluded = [\"addEndListener\", \"appear\", \"children\", \"easing\", \"in\", \"onEnter\", \"onEntered\", \"onEntering\", \"onExit\", \"onExited\", \"onExiting\", \"style\", \"timeout\", \"TransitionComponent\"];\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport useTimeout from '@mui/utils/useTimeout';\nimport elementAcceptingRef from '@mui/utils/elementAcceptingRef';\nimport getReactElementRef from '@mui/utils/getReactElementRef';\nimport { Transition } from 'react-transition-group';\nimport useTheme from '../styles/useTheme';\nimport { getTransitionProps, reflow } from '../transitions/utils';\nimport useForkRef from '../utils/useForkRef';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction getScale(value) {\n return `scale(${value}, ${value ** 2})`;\n}\nconst styles = {\n entering: {\n opacity: 1,\n transform: getScale(1)\n },\n entered: {\n opacity: 1,\n transform: 'none'\n }\n};\n\n/*\n TODO v6: remove\n Conditionally apply a workaround for the CSS transition bug in Safari 15.4 / WebKit browsers.\n */\nconst isWebKit154 = typeof navigator !== 'undefined' && /^((?!chrome|android).)*(safari|mobile)/i.test(navigator.userAgent) && /(os |version\\/)15(.|_)4/i.test(navigator.userAgent);\n\n/**\n * The Grow transition is used by the [Tooltip](/material-ui/react-tooltip/) and\n * [Popover](/material-ui/react-popover/) components.\n * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.\n */\nconst Grow = /*#__PURE__*/React.forwardRef(function Grow(props, ref) {\n const {\n addEndListener,\n appear = true,\n children,\n easing,\n in: inProp,\n onEnter,\n onEntered,\n onEntering,\n onExit,\n onExited,\n onExiting,\n style,\n timeout = 'auto',\n // eslint-disable-next-line react/prop-types\n TransitionComponent = Transition\n } = props,\n other = _objectWithoutPropertiesLoose(props, _excluded);\n const timer = useTimeout();\n const autoTimeout = React.useRef();\n const theme = useTheme();\n const nodeRef = React.useRef(null);\n const handleRef = useForkRef(nodeRef, getReactElementRef(children), ref);\n const normalizedTransitionCallback = callback => maybeIsAppearing => {\n if (callback) {\n const node = nodeRef.current;\n\n // onEnterXxx and onExitXxx callbacks have a different arguments.length value.\n if (maybeIsAppearing === undefined) {\n callback(node);\n } else {\n callback(node, maybeIsAppearing);\n }\n }\n };\n const handleEntering = normalizedTransitionCallback(onEntering);\n const handleEnter = normalizedTransitionCallback((node, isAppearing) => {\n reflow(node); // So the animation always start from the start.\n\n const {\n duration: transitionDuration,\n delay,\n easing: transitionTimingFunction\n } = getTransitionProps({\n style,\n timeout,\n easing\n }, {\n mode: 'enter'\n });\n let duration;\n if (timeout === 'auto') {\n duration = theme.transitions.getAutoHeightDuration(node.clientHeight);\n autoTimeout.current = duration;\n } else {\n duration = transitionDuration;\n }\n node.style.transition = [theme.transitions.create('opacity', {\n duration,\n delay\n }), theme.transitions.create('transform', {\n duration: isWebKit154 ? duration : duration * 0.666,\n delay,\n easing: transitionTimingFunction\n })].join(',');\n if (onEnter) {\n onEnter(node, isAppearing);\n }\n });\n const handleEntered = normalizedTransitionCallback(onEntered);\n const handleExiting = normalizedTransitionCallback(onExiting);\n const handleExit = normalizedTransitionCallback(node => {\n const {\n duration: transitionDuration,\n delay,\n easing: transitionTimingFunction\n } = getTransitionProps({\n style,\n timeout,\n easing\n }, {\n mode: 'exit'\n });\n let duration;\n if (timeout === 'auto') {\n duration = theme.transitions.getAutoHeightDuration(node.clientHeight);\n autoTimeout.current = duration;\n } else {\n duration = transitionDuration;\n }\n node.style.transition = [theme.transitions.create('opacity', {\n duration,\n delay\n }), theme.transitions.create('transform', {\n duration: isWebKit154 ? duration : duration * 0.666,\n delay: isWebKit154 ? delay : delay || duration * 0.333,\n easing: transitionTimingFunction\n })].join(',');\n node.style.opacity = 0;\n node.style.transform = getScale(0.75);\n if (onExit) {\n onExit(node);\n }\n });\n const handleExited = normalizedTransitionCallback(onExited);\n const handleAddEndListener = next => {\n if (timeout === 'auto') {\n timer.start(autoTimeout.current || 0, next);\n }\n if (addEndListener) {\n // Old call signature before `react-transition-group` implemented `nodeRef`\n addEndListener(nodeRef.current, next);\n }\n };\n return /*#__PURE__*/_jsx(TransitionComponent, _extends({\n appear: appear,\n in: inProp,\n nodeRef: nodeRef,\n onEnter: handleEnter,\n onEntered: handleEntered,\n onEntering: handleEntering,\n onExit: handleExit,\n onExited: handleExited,\n onExiting: handleExiting,\n addEndListener: handleAddEndListener,\n timeout: timeout === 'auto' ? null : timeout\n }, other, {\n children: (state, childProps) => {\n return /*#__PURE__*/React.cloneElement(children, _extends({\n style: _extends({\n opacity: 0,\n transform: getScale(0.75),\n visibility: state === 'exited' && !inProp ? 'hidden' : undefined\n }, styles[state], style, children.props.style),\n ref: handleRef\n }, childProps));\n }\n }));\n});\nprocess.env.NODE_ENV !== \"production\" ? Grow.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Add a custom transition end trigger. Called with the transitioning DOM\n * node and a done callback. Allows for more fine grained transition end\n * logic. Note: Timeouts are still used as a fallback if provided.\n */\n addEndListener: PropTypes.func,\n /**\n * Perform the enter transition when it first mounts if `in` is also `true`.\n * Set this to `false` to disable this behavior.\n * @default true\n */\n appear: PropTypes.bool,\n /**\n * A single child content element.\n */\n children: elementAcceptingRef.isRequired,\n /**\n * The transition timing function.\n * You may specify a single easing or a object containing enter and exit values.\n */\n easing: PropTypes.oneOfType([PropTypes.shape({\n enter: PropTypes.string,\n exit: PropTypes.string\n }), PropTypes.string]),\n /**\n * If `true`, the component will transition in.\n */\n in: PropTypes.bool,\n /**\n * @ignore\n */\n onEnter: PropTypes.func,\n /**\n * @ignore\n */\n onEntered: PropTypes.func,\n /**\n * @ignore\n */\n onEntering: PropTypes.func,\n /**\n * @ignore\n */\n onExit: PropTypes.func,\n /**\n * @ignore\n */\n onExited: PropTypes.func,\n /**\n * @ignore\n */\n onExiting: PropTypes.func,\n /**\n * @ignore\n */\n style: PropTypes.object,\n /**\n * The duration for the transition, in milliseconds.\n * You may specify a single timeout for all transitions, or individually with an object.\n *\n * Set to 'auto' to automatically calculate transition time based on height.\n * @default 'auto'\n */\n timeout: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })])\n} : void 0;\nGrow.muiSupportAuto = true;\nexport default Grow;","import { unstable_ownerWindow as ownerWindow, unstable_ownerDocument as ownerDocument, unstable_getScrollbarSize as getScrollbarSize } from '@mui/utils';\n// Is a vertical scrollbar displayed?\nfunction isOverflowing(container) {\n const doc = ownerDocument(container);\n if (doc.body === container) {\n return ownerWindow(container).innerWidth > doc.documentElement.clientWidth;\n }\n return container.scrollHeight > container.clientHeight;\n}\nexport function ariaHidden(element, show) {\n if (show) {\n element.setAttribute('aria-hidden', 'true');\n } else {\n element.removeAttribute('aria-hidden');\n }\n}\nfunction getPaddingRight(element) {\n return parseInt(ownerWindow(element).getComputedStyle(element).paddingRight, 10) || 0;\n}\nfunction isAriaHiddenForbiddenOnElement(element) {\n // The forbidden HTML tags are the ones from ARIA specification that\n // can be children of body and can't have aria-hidden attribute.\n // cf. https://www.w3.org/TR/html-aria/#docconformance\n const forbiddenTagNames = ['TEMPLATE', 'SCRIPT', 'STYLE', 'LINK', 'MAP', 'META', 'NOSCRIPT', 'PICTURE', 'COL', 'COLGROUP', 'PARAM', 'SLOT', 'SOURCE', 'TRACK'];\n const isForbiddenTagName = forbiddenTagNames.indexOf(element.tagName) !== -1;\n const isInputHidden = element.tagName === 'INPUT' && element.getAttribute('type') === 'hidden';\n return isForbiddenTagName || isInputHidden;\n}\nfunction ariaHiddenSiblings(container, mountElement, currentElement, elementsToExclude, show) {\n const blacklist = [mountElement, currentElement, ...elementsToExclude];\n [].forEach.call(container.children, element => {\n const isNotExcludedElement = blacklist.indexOf(element) === -1;\n const isNotForbiddenElement = !isAriaHiddenForbiddenOnElement(element);\n if (isNotExcludedElement && isNotForbiddenElement) {\n ariaHidden(element, show);\n }\n });\n}\nfunction findIndexOf(items, callback) {\n let idx = -1;\n items.some((item, index) => {\n if (callback(item)) {\n idx = index;\n return true;\n }\n return false;\n });\n return idx;\n}\nfunction handleContainer(containerInfo, props) {\n const restoreStyle = [];\n const container = containerInfo.container;\n if (!props.disableScrollLock) {\n if (isOverflowing(container)) {\n // Compute the size before applying overflow hidden to avoid any scroll jumps.\n const scrollbarSize = getScrollbarSize(ownerDocument(container));\n restoreStyle.push({\n value: container.style.paddingRight,\n property: 'padding-right',\n el: container\n });\n // Use computed style, here to get the real padding to add our scrollbar width.\n container.style.paddingRight = `${getPaddingRight(container) + scrollbarSize}px`;\n\n // .mui-fixed is a global helper.\n const fixedElements = ownerDocument(container).querySelectorAll('.mui-fixed');\n [].forEach.call(fixedElements, element => {\n restoreStyle.push({\n value: element.style.paddingRight,\n property: 'padding-right',\n el: element\n });\n element.style.paddingRight = `${getPaddingRight(element) + scrollbarSize}px`;\n });\n }\n let scrollContainer;\n if (container.parentNode instanceof DocumentFragment) {\n scrollContainer = ownerDocument(container).body;\n } else {\n // Support html overflow-y: auto for scroll stability between pages\n // https://css-tricks.com/snippets/css/force-vertical-scrollbar/\n const parent = container.parentElement;\n const containerWindow = ownerWindow(container);\n scrollContainer = (parent == null ? void 0 : parent.nodeName) === 'HTML' && containerWindow.getComputedStyle(parent).overflowY === 'scroll' ? parent : container;\n }\n\n // Block the scroll even if no scrollbar is visible to account for mobile keyboard\n // screensize shrink.\n restoreStyle.push({\n value: scrollContainer.style.overflow,\n property: 'overflow',\n el: scrollContainer\n }, {\n value: scrollContainer.style.overflowX,\n property: 'overflow-x',\n el: scrollContainer\n }, {\n value: scrollContainer.style.overflowY,\n property: 'overflow-y',\n el: scrollContainer\n });\n scrollContainer.style.overflow = 'hidden';\n }\n const restore = () => {\n restoreStyle.forEach(({\n value,\n el,\n property\n }) => {\n if (value) {\n el.style.setProperty(property, value);\n } else {\n el.style.removeProperty(property);\n }\n });\n };\n return restore;\n}\nfunction getHiddenSiblings(container) {\n const hiddenSiblings = [];\n [].forEach.call(container.children, element => {\n if (element.getAttribute('aria-hidden') === 'true') {\n hiddenSiblings.push(element);\n }\n });\n return hiddenSiblings;\n}\n/**\n * @ignore - do not document.\n *\n * Proper state management for containers and the modals in those containers.\n * Simplified, but inspired by react-overlay's ModalManager class.\n * Used by the Modal to ensure proper styling of containers.\n */\nexport class ModalManager {\n constructor() {\n this.containers = void 0;\n this.modals = void 0;\n this.modals = [];\n this.containers = [];\n }\n add(modal, container) {\n let modalIndex = this.modals.indexOf(modal);\n if (modalIndex !== -1) {\n return modalIndex;\n }\n modalIndex = this.modals.length;\n this.modals.push(modal);\n\n // If the modal we are adding is already in the DOM.\n if (modal.modalRef) {\n ariaHidden(modal.modalRef, false);\n }\n const hiddenSiblings = getHiddenSiblings(container);\n ariaHiddenSiblings(container, modal.mount, modal.modalRef, hiddenSiblings, true);\n const containerIndex = findIndexOf(this.containers, item => item.container === container);\n if (containerIndex !== -1) {\n this.containers[containerIndex].modals.push(modal);\n return modalIndex;\n }\n this.containers.push({\n modals: [modal],\n container,\n restore: null,\n hiddenSiblings\n });\n return modalIndex;\n }\n mount(modal, props) {\n const containerIndex = findIndexOf(this.containers, item => item.modals.indexOf(modal) !== -1);\n const containerInfo = this.containers[containerIndex];\n if (!containerInfo.restore) {\n containerInfo.restore = handleContainer(containerInfo, props);\n }\n }\n remove(modal, ariaHiddenState = true) {\n const modalIndex = this.modals.indexOf(modal);\n if (modalIndex === -1) {\n return modalIndex;\n }\n const containerIndex = findIndexOf(this.containers, item => item.modals.indexOf(modal) !== -1);\n const containerInfo = this.containers[containerIndex];\n containerInfo.modals.splice(containerInfo.modals.indexOf(modal), 1);\n this.modals.splice(modalIndex, 1);\n\n // If that was the last modal in a container, clean up the container.\n if (containerInfo.modals.length === 0) {\n // The modal might be closed before it had the chance to be mounted in the DOM.\n if (containerInfo.restore) {\n containerInfo.restore();\n }\n if (modal.modalRef) {\n // In case the modal wasn't in the DOM yet.\n ariaHidden(modal.modalRef, ariaHiddenState);\n }\n ariaHiddenSiblings(containerInfo.container, modal.mount, modal.modalRef, containerInfo.hiddenSiblings, false);\n this.containers.splice(containerIndex, 1);\n } else {\n // Otherwise make sure the next top modal is visible to a screen reader.\n const nextTop = containerInfo.modals[containerInfo.modals.length - 1];\n // as soon as a modal is adding its modalRef is undefined. it can't set\n // aria-hidden because the dom element doesn't exist either\n // when modal was unmounted before modalRef gets null\n if (nextTop.modalRef) {\n ariaHidden(nextTop.modalRef, false);\n }\n }\n return modalIndex;\n }\n isTopModal(modal) {\n return this.modals.length > 0 && this.modals[this.modals.length - 1] === modal;\n }\n}","'use client';\n\n/* eslint-disable consistent-return, jsx-a11y/no-noninteractive-tabindex */\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { exactProp, elementAcceptingRef, unstable_useForkRef as useForkRef, unstable_ownerDocument as ownerDocument, unstable_getReactElementRef as getReactElementRef } from '@mui/utils';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nimport { jsxs as _jsxs } from \"react/jsx-runtime\";\n// Inspired by https://github.com/focus-trap/tabbable\nconst candidatesSelector = ['input', 'select', 'textarea', 'a[href]', 'button', '[tabindex]', 'audio[controls]', 'video[controls]', '[contenteditable]:not([contenteditable=\"false\"])'].join(',');\nfunction getTabIndex(node) {\n const tabindexAttr = parseInt(node.getAttribute('tabindex') || '', 10);\n if (!Number.isNaN(tabindexAttr)) {\n return tabindexAttr;\n }\n\n // Browsers do not return `tabIndex` correctly for contentEditable nodes;\n // https://bugs.chromium.org/p/chromium/issues/detail?id=661108&q=contenteditable%20tabindex&can=2\n // so if they don't have a tabindex attribute specifically set, assume it's 0.\n // in Chrome,
,
\\`/\\`\\` and will default to \"${defaultEncType}\"`\n );\n return null;\n }\n return encType;\n}\nfunction getFormSubmissionInfo(target, basename) {\n let method;\n let action;\n let encType;\n let formData;\n let body;\n if (isFormElement(target)) {\n let attr = target.getAttribute(\"action\");\n action = attr ? stripBasename(attr, basename) : null;\n method = target.getAttribute(\"method\") || defaultMethod;\n encType = getFormEncType(target.getAttribute(\"enctype\")) || defaultEncType;\n formData = new FormData(target);\n } else if (isButtonElement(target) || isInputElement(target) && (target.type === \"submit\" || target.type === \"image\")) {\n let form = target.form;\n if (form == null) {\n throw new Error(\n `Cannot submit a \n * );\n * };\n */\nexport var NotificationContext = createContext({\n notifications: [],\n addNotification: function () { },\n takeNotification: function () { },\n resetNotifications: function () { },\n setNotifications: function () { },\n});\n//# sourceMappingURL=NotificationContext.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport * as React from 'react';\nimport { useState, useCallback, useMemo } from 'react';\nimport { NotificationContext } from './NotificationContext';\nimport { AddNotificationContext } from './AddNotificationContext';\nexport var NotificationContextProvider = function (_a) {\n var children = _a.children;\n var _b = useState([]), notifications = _b[0], setNotifications = _b[1];\n var addNotification = useCallback(function (notification) {\n setNotifications(function (notifications) { return __spreadArray(__spreadArray([], notifications, true), [notification], false); });\n }, []);\n var takeNotification = useCallback(function () {\n if (notifications.length === 0)\n return;\n var notification = notifications[0], rest = notifications.slice(1);\n setNotifications(rest);\n return notification;\n }, [notifications]);\n var resetNotifications = useCallback(function () {\n setNotifications([]);\n }, []);\n var contextValue = useMemo(function () { return ({\n notifications: notifications,\n addNotification: addNotification,\n takeNotification: takeNotification,\n resetNotifications: resetNotifications,\n setNotifications: setNotifications,\n }); }, [notifications] // eslint-disable-line react-hooks/exhaustive-deps\n );\n // we separate the addNotification context to avoid rerendering all components\n // that depend on useNotify when a notification is dispatched\n return (React.createElement(NotificationContext.Provider, { value: contextValue },\n React.createElement(AddNotificationContext.Provider, { value: addNotification }, children)));\n};\n//# sourceMappingURL=NotificationContextProvider.js.map","import { useContext } from 'react';\nimport { AddNotificationContext } from './AddNotificationContext';\nexport var useAddNotificationContext = function () {\n return useContext(AddNotificationContext);\n};\n//# sourceMappingURL=useAddNotificationContext.js.map","import { useContext } from 'react';\nimport { NotificationContext } from './NotificationContext';\nexport var useNotificationContext = function () { return useContext(NotificationContext); };\n//# sourceMappingURL=useNotificationContext.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useCallback } from 'react';\nimport { useAddNotificationContext } from './useAddNotificationContext';\n/**\n * Hook for Notification Side Effect\n *\n * @example\n *\n * const notify = useNotify();\n * // simple message (info level)\n * notify('Level complete');\n * // specify level\n * notify('A problem occurred', { type: 'error' })\n * // pass arguments to the translation function\n * notify('Deleted %{count} elements', { type: 'info', messageArgs: { smart_count: 23 } })\n * // show the action as undoable in the notification\n * notify('Post renamed', { type: 'info', undoable: true })\n */\nexport var useNotify = function () {\n var addNotification = useAddNotificationContext();\n return useCallback(function (message, options) {\n if (options === void 0) { options = {}; }\n var _a = options.type, messageType = _a === void 0 ? 'info' : _a, notificationOptions = __rest(options, [\"type\"]);\n addNotification({\n message: message,\n type: messageType,\n notificationOptions: notificationOptions,\n });\n }, [addNotification]);\n};\n//# sourceMappingURL=useNotify.js.map","import * as React from 'react';\nimport { useEffect, useState } from 'react';\nimport { I18nContext } from './I18nContext';\nimport { useStore } from '../store/useStore';\nimport { useNotify } from '../notification';\n/**\n * Store the i18nProvider in a context, and rerender children when the locale changes\n */\nexport var I18nContextProvider = function (_a) {\n var _b = _a.value, value = _b === void 0 ? defaulti18nContext : _b, children = _a.children;\n var locale = useStore('locale')[0];\n var notify = useNotify();\n var _c = useState(0), key = _c[0], setKey = _c[1];\n // to avoid blinking effect, delay first render if the user has a non-default locale\n var _d = useState(locale === value.getLocale()), isInitialized = _d[0], setInitialized = _d[1];\n // watch store for locale changes\n useEffect(function () {\n if (locale && value.getLocale() !== locale) {\n new Promise(function (resolve) {\n // so we systematically return a Promise for the messages\n // i18nProvider may return a Promise for language changes,\n resolve(value.changeLocale(locale));\n })\n .then(function () {\n // Force full page re-render.\n // This is slow on locale change, but it's a good way\n // to avoid having one subscription to the locale\n // for each call to translate()\n setKey(function (key) { return key + 1; });\n setInitialized(true);\n })\n .catch(function (error) {\n setInitialized(true);\n notify('ra.notification.i18n_error', { type: 'error' });\n console.error(error);\n });\n }\n else {\n setInitialized(true);\n }\n }, [value, locale, notify]);\n return isInitialized ? (React.createElement(I18nContext.Provider, { value: value, key: key }, children)) : null;\n};\nvar defaulti18nContext = {\n translate: function (x) { return x; },\n changeLocale: function () { return Promise.resolve(); },\n getLocale: function () { return 'en'; },\n};\n//# sourceMappingURL=I18nContextProvider.js.map","import { useContext } from 'react';\nimport { I18nContext } from './I18nContext';\n/**\n * Get the i18nProvider instance declared in the component\n *\n * @example\n *\n * const CurrentLanguage = () => {\n * const i18nProvider = useI18nProvider();\n * const locale = i18nProvider.getLocale();\n * return {locale};\n * };\n */\nexport var useI18nProvider = function () { return useContext(I18nContext); };\n//# sourceMappingURL=useI18nProvider.js.map","import { useMemo } from 'react';\nimport { useI18nProvider } from './useI18nProvider';\nimport { useStore } from '../store/useStore';\n/**\n * Get the current locale and the ability to change it\n *\n * @example\n *\n * import { useLocaleState } from 'react-admin';\n *\n * const availableLanguages = {\n * en: 'English',\n * fr: 'Français',\n * }\n * const LocaleSwitcher = () => {\n * const [locale, setLocale] = useLocaleState();\n * return (\n *
\n *
Language
\n * \n * \n *
\n * );\n * };\n */\nexport var useLocaleState = function () {\n var i18nProvider = useI18nProvider();\n var defaultLocale = useMemo(function () { return i18nProvider.getLocale(); }, [i18nProvider]);\n return useStore('locale', defaultLocale);\n};\n//# sourceMappingURL=useLocaleState.js.map","import { useLocaleState } from './useLocaleState';\n/**\n * Get the current locale\n *\n * @example\n *\n * import { useLocale } from 'react-admin';\n *\n * const availableLanguages = {\n * en: 'English',\n * fr: 'Français',\n * }\n * const CurrentLanguage = () => {\n * const locale = useLocale();\n * return {availableLanguages[locale]};\n * }\n */\nexport var useLocale = function () {\n var locale = useLocaleState()[0];\n return locale;\n};\n//# sourceMappingURL=useLocale.js.map","import { useMemo } from 'react';\nimport { useI18nProvider } from './useI18nProvider';\n/**\n * A hook that gets the available locales from the i18nProvider.\n * @example\n *\n * import { useLocales } from 'react-admin';\n *\n * const LocaleSelector = () => {\n * const locales = useLocales();\n * const [currentLocale, setCurrentLocale] = useLocaleState();\n *\n * return (\n * \n * );\n * }\n */\nexport var useLocales = function (options) {\n var _a;\n var i18nProvider = useI18nProvider();\n var locales = useMemo(function () { return ((i18nProvider === null || i18nProvider === void 0 ? void 0 : i18nProvider.getLocales) ? i18nProvider === null || i18nProvider === void 0 ? void 0 : i18nProvider.getLocales() : []); }, [i18nProvider]);\n return (_a = options === null || options === void 0 ? void 0 : options.locales) !== null && _a !== void 0 ? _a : locales;\n};\n//# sourceMappingURL=useLocales.js.map","/**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\nfunction arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n}\n\nmodule.exports = arrayEach;\n","var copyObject = require('./_copyObject'),\n keys = require('./keys');\n\n/**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n}\n\nmodule.exports = baseAssign;\n","var copyObject = require('./_copyObject'),\n keysIn = require('./keysIn');\n\n/**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\nfunction baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n}\n\nmodule.exports = baseAssignIn;\n","var copyObject = require('./_copyObject'),\n getSymbols = require('./_getSymbols');\n\n/**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n}\n\nmodule.exports = copySymbols;\n","var copyObject = require('./_copyObject'),\n getSymbolsIn = require('./_getSymbolsIn');\n\n/**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\nfunction copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n}\n\nmodule.exports = copySymbolsIn;\n","/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\nfunction initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n}\n\nmodule.exports = initCloneArray;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer');\n\n/**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\nfunction cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n}\n\nmodule.exports = cloneDataView;\n","/** Used to match `RegExp` flags from their coerced string values. */\nvar reFlags = /\\w*$/;\n\n/**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\nfunction cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n}\n\nmodule.exports = cloneRegExp;\n","var Symbol = require('./_Symbol');\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\nfunction cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n}\n\nmodule.exports = cloneSymbol;\n","var cloneArrayBuffer = require('./_cloneArrayBuffer'),\n cloneDataView = require('./_cloneDataView'),\n cloneRegExp = require('./_cloneRegExp'),\n cloneSymbol = require('./_cloneSymbol'),\n cloneTypedArray = require('./_cloneTypedArray');\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n}\n\nmodule.exports = initCloneByTag;\n","var getTag = require('./_getTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]';\n\n/**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\nfunction baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n}\n\nmodule.exports = baseIsMap;\n","var baseIsMap = require('./_baseIsMap'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsMap = nodeUtil && nodeUtil.isMap;\n\n/**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\nvar isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\nmodule.exports = isMap;\n","var getTag = require('./_getTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar setTag = '[object Set]';\n\n/**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\nfunction baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n}\n\nmodule.exports = baseIsSet;\n","var baseIsSet = require('./_baseIsSet'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsSet = nodeUtil && nodeUtil.isSet;\n\n/**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\nvar isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\nmodule.exports = isSet;\n","var Stack = require('./_Stack'),\n arrayEach = require('./_arrayEach'),\n assignValue = require('./_assignValue'),\n baseAssign = require('./_baseAssign'),\n baseAssignIn = require('./_baseAssignIn'),\n cloneBuffer = require('./_cloneBuffer'),\n copyArray = require('./_copyArray'),\n copySymbols = require('./_copySymbols'),\n copySymbolsIn = require('./_copySymbolsIn'),\n getAllKeys = require('./_getAllKeys'),\n getAllKeysIn = require('./_getAllKeysIn'),\n getTag = require('./_getTag'),\n initCloneArray = require('./_initCloneArray'),\n initCloneByTag = require('./_initCloneByTag'),\n initCloneObject = require('./_initCloneObject'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isMap = require('./isMap'),\n isObject = require('./isObject'),\n isSet = require('./isSet'),\n keys = require('./keys'),\n keysIn = require('./keysIn');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values supported by `_.clone`. */\nvar cloneableTags = {};\ncloneableTags[argsTag] = cloneableTags[arrayTag] =\ncloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\ncloneableTags[boolTag] = cloneableTags[dateTag] =\ncloneableTags[float32Tag] = cloneableTags[float64Tag] =\ncloneableTags[int8Tag] = cloneableTags[int16Tag] =\ncloneableTags[int32Tag] = cloneableTags[mapTag] =\ncloneableTags[numberTag] = cloneableTags[objectTag] =\ncloneableTags[regexpTag] = cloneableTags[setTag] =\ncloneableTags[stringTag] = cloneableTags[symbolTag] =\ncloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\ncloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\ncloneableTags[errorTag] = cloneableTags[funcTag] =\ncloneableTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\nfunction baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n}\n\nmodule.exports = baseClone;\n","var baseClone = require('./_baseClone');\n\n/** Used to compose bitmasks for cloning. */\nvar CLONE_DEEP_FLAG = 1,\n CLONE_SYMBOLS_FLAG = 4;\n\n/**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\nfunction cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n}\n\nmodule.exports = cloneDeep;\n","import { useCallback } from 'react';\nimport { useI18nProvider } from './useI18nProvider';\n/**\n * Translate a string using the current locale and the translations from the i18nProvider\n *\n * @see Polyglot.t()\n * @link https://airbnb.io/polyglot.js/#polyglotprototypetkey-interpolationoptions\n *\n * @return {Function} A translation function, accepting two arguments\n * - a string used as key in the translations\n * - an interpolationOptions object\n *\n * @example\n *\n * import { useTranslate } from 'react-admin';\n *\n * const SettingsMenu = () => {\n * const translate = useTranslate();\n * return {translate('settings')};\n * }\n */\nexport var useTranslate = function () {\n var i18nProvider = useI18nProvider();\n var translate = useCallback(function (key, options) {\n return i18nProvider.translate(key, options);\n }, \n // update the hook each time the locale changes\n [i18nProvider] // eslint-disable-line react-hooks/exhaustive-deps\n );\n return i18nProvider ? translate : identity;\n};\nvar identity = function (key) { return key; };\n//# sourceMappingURL=useTranslate.js.map","import { createContext } from 'react';\nexport var BasenameContext = createContext('');\n//# sourceMappingURL=BasenameContext.js.map","import * as React from 'react';\nimport { BasenameContext } from './BasenameContext';\n/**\n * Set the string to append to all links to the admin app.\n *\n * Useful when the app is mounted on a sub path, e.g. '/admin'.\n * Used internally by the `` component.\n *\n * @see useBasename\n */\nexport var BasenameContextProvider = function (_a) {\n var children = _a.children, basename = _a.basename;\n return (React.createElement(BasenameContext.Provider, { value: basename }, children));\n};\n//# sourceMappingURL=BasenameContextProvider.js.map","import * as React from 'react';\nimport { useInRouterContext, createHashRouter, RouterProvider, } from 'react-router-dom';\nimport { BasenameContextProvider } from './BasenameContextProvider';\n/**\n * Creates a react-router Router unless the app is already inside existing router.\n * Also creates a BasenameContext with the basename prop\n */\nexport var AdminRouter = function (_a) {\n var _b = _a.basename, basename = _b === void 0 ? '' : _b, children = _a.children;\n var isInRouter = useInRouterContext();\n var Router = isInRouter ? DummyRouter : InternalRouter;\n return (React.createElement(BasenameContextProvider, { basename: isInRouter ? basename : '' },\n React.createElement(Router, { basename: basename }, children)));\n};\nvar DummyRouter = function (_a) {\n var children = _a.children;\n return React.createElement(React.Fragment, null, children);\n};\nvar routerProviderFuture = { v7_startTransition: false, v7_relativeSplatPath: false };\nvar InternalRouter = function (_a) {\n var children = _a.children, basename = _a.basename;\n var router = createHashRouter([{ path: '*', element: React.createElement(React.Fragment, null, children) }], {\n basename: basename,\n future: {\n v7_fetcherPersist: false,\n v7_normalizeFormMethod: false,\n v7_partialHydration: false,\n v7_relativeSplatPath: false,\n v7_skipActionErrorRevalidation: false,\n },\n });\n return React.createElement(RouterProvider, { router: router, future: routerProviderFuture });\n};\n//# sourceMappingURL=AdminRouter.js.map","import { useEffect } from 'react';\nimport { useLocation } from 'react-router';\nimport debounce from 'lodash/debounce';\nimport { useStore } from '../store';\n/**\n * A hook that tracks the scroll position and restores it when the component mounts.\n * @param storeKey The key under which to store the scroll position in the store\n * @param debounceMs The debounce time in milliseconds\n *\n * @example\n * import { useRestoreScrollPosition } from 'ra-core';\n *\n * const MyCustomPage = () => {\n * useRestoreScrollPosition('my-list');\n *\n * return (\n *
\n *

My Custom Page

\n * \n *
\n * );\n * };\n */\nexport var useRestoreScrollPosition = function (storeKey, debounceMs) {\n if (debounceMs === void 0) { debounceMs = 250; }\n var _a = useTrackScrollPosition(storeKey, debounceMs), position = _a[0], setPosition = _a[1];\n var location = useLocation();\n useEffect(function () {\n var _a;\n if (position != null && ((_a = location.state) === null || _a === void 0 ? void 0 : _a._scrollToTop) !== true) {\n setPosition(undefined);\n window.scrollTo(0, position);\n }\n // We only want to run this effect on mount\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n};\n/**\n * A hook that tracks the scroll position and stores it.\n * @param storeKey The key under which to store the scroll position in the store\n * @param debounceMs The debounce time in milliseconds\n *\n * @example\n * import { useTrackScrollPosition } from 'ra-core';\n *\n * const MyCustomPage = () => {\n * useTrackScrollPosition('my-list');\n *\n * return (\n *
\n *

My Custom Page

\n * \n *
\n * );\n * };\n */\nexport var useTrackScrollPosition = function (storeKey, debounceMs) {\n if (debounceMs === void 0) { debounceMs = 250; }\n var _a = useStore(storeKey), position = _a[0], setPosition = _a[1];\n useEffect(function () {\n if (typeof window === 'undefined') {\n return;\n }\n var handleScroll = debounce(function () {\n setPosition(window.scrollY);\n }, debounceMs);\n window.addEventListener('scroll', handleScroll);\n return function () {\n window.removeEventListener('scroll', handleScroll);\n };\n }, [debounceMs, setPosition]);\n return [position, setPosition];\n};\n//# sourceMappingURL=useRestoreScrollPosition.js.map","import { useRestoreScrollPosition } from './useRestoreScrollPosition';\n/**\n * A component that tracks the scroll position and restores it when the component mounts.\n * @param children The content to render\n * @param key The key under which to store the scroll position in the store\n * @param debounceMs The debounce time in milliseconds\n *\n * @example\n * import { RestoreScrollPosition } from 'ra-core';\n *\n * const MyCustomPage = () => {\n * \n *
\n *

My Custom Page

\n * \n *
\n *
\n * };\n */\nexport var RestoreScrollPosition = function (_a) {\n var children = _a.children, storeKey = _a.storeKey, _b = _a.debounce, debounce = _b === void 0 ? 250 : _b;\n useRestoreScrollPosition(storeKey, debounce);\n return children;\n};\n//# sourceMappingURL=RestoreScrollPosition.js.map","import { useContext } from 'react';\nimport { BasenameContext } from './BasenameContext';\n/**\n * Get the string to append to all links to the admin app.\n *\n * Useful when the app is mounted on a sub path, e.g. '/admin'.\n *\n * This hook is used internally by all react-admin components that\n * contain a link, and requires that the basename is set via the\n * `` component (or via the `` component,\n * which calls BasenameContextProvider internally).\n *\n * @see BasenameContextProvider\n *\n * @example\n * import { useBasename } from 'react-admin';\n *\n * const ArticleLink = ({ title, id }) => {\n * const basename = useBasename();\n * return
{title};\n * };\n */\nexport var useBasename = function () { return useContext(BasenameContext); };\n//# sourceMappingURL=useBasename.js.map","import { useCallback } from 'react';\nimport { useBasename } from './useBasename';\n/**\n * Get a callback to create a link to a given page in the admin app.\n *\n * The callback expects an object as parameter, containing the following properties:\n * - type: 'list', 'edit', 'show' or 'create'\n * - resource\n * - id (optional), for 'edit' or 'show' pages\n *\n * This is used internally by react-admin to allow default components to work\n * in applications that are mounted on a sub path, e.g. '/admin'. If your app\n * is mounted in the root path, you don't need it, and you can create links by\n * hand, e.g. '/articles/1/show'.\n *\n * @example\n * import { useCreatePath, useRecordContext } from 'react-admin';\n * import { useNavigate } from 'react-router-dom';\n *\n * const PostEditButton = () => {\n * const createPath = useCreatePath();\n * const record = useRecordContext();\n * const navigate = useNavigate();\n *\n * const handleClick = () => {\n * const link = createPath({\n * type: 'edit',\n * resource: 'posts',\n * id: record.id\n * });\n * navigate(link);\n * };\n *\n * return ;\n * };\n */\nexport var useCreatePath = function () {\n var basename = useBasename();\n return useCallback(function (_a) {\n var resource = _a.resource, id = _a.id, type = _a.type;\n if (['list', 'create', 'edit', 'show'].includes(type) &&\n !resource) {\n throw new Error('Cannot create a link without a resource. You must provide the resource name.');\n }\n switch (type) {\n case 'list':\n return removeDoubleSlashes(\"\".concat(basename, \"/\").concat(resource));\n case 'create':\n return removeDoubleSlashes(\"\".concat(basename, \"/\").concat(resource, \"/create\"));\n case 'edit': {\n if (id == null) {\n // maybe the id isn't defined yet\n // instead of throwing an error, fallback to list link\n return removeDoubleSlashes(\"\".concat(basename, \"/\").concat(resource));\n }\n return removeDoubleSlashes(\"\".concat(basename, \"/\").concat(resource, \"/\").concat(encodeURIComponent(id)));\n }\n case 'show': {\n if (id == null) {\n // maybe the id isn't defined yet\n // instead of throwing an error, fallback to list link\n return removeDoubleSlashes(\"\".concat(basename, \"/\").concat(resource));\n }\n return removeDoubleSlashes(\"\".concat(basename, \"/\").concat(resource, \"/\").concat(encodeURIComponent(id), \"/show\"));\n }\n default:\n return type;\n }\n }, [basename]);\n};\nexport var removeDoubleSlashes = function (path) { return path.replace('//', '/'); };\n//# sourceMappingURL=useCreatePath.js.map","import { createContext } from 'react';\n/**\n * Context to store the current resource name.\n *\n * Use the useResource() hook to read the context. That's what most components do in react-admin.\n *\n * @example\n *\n * import { useResourceContext, useTranslate } from 'ra-core';\n *\n * const MyCustomEditTitle = props => {\n * const name = useResourceContext(props);\n *\n * return (\n *

{translate(`${name}.name`)}

\n * );\n * };\n */\nexport var ResourceContext = createContext(undefined);\n//# sourceMappingURL=ResourceContext.js.map","import { useContext } from 'react';\nimport { ResourceContext } from './ResourceContext';\n/**\n * Hook to read the resource from the ResourceContext.\n *\n * Must be used within a (e.g. as a descendent of \n * or any reference related components), or called with a resource prop.\n *\n * @example\n *\n * const ResourceName = (props) => {\n * const resource = useResourceContext(props);\n * const getResourceLabel = useGetResourceLabel();\n * return <>{getResourceLabel(resource, 1)};\n * }\n *\n * // use it in a resource context\n * const MyComponent = () => (\n * \n * \n * ...\n * \n * );\n *\n * // override resource via props\n * const MyComponent = () => (\n * <>\n * \n * ...\n * \n * );\n *\n * @returns {ResourceContextValue} The resource name, e.g. 'posts'\n */\nexport var useResourceContext = function (props) {\n var context = useContext(ResourceContext);\n return (props && props.resource) || context;\n};\n//# sourceMappingURL=useResourceContext.js.map","import * as React from 'react';\nimport { createContext } from 'react';\n/**\n * Context to store a record.\n *\n * @see RecordContextProvider\n * @see useRecordContext\n */\nexport var RecordContext = createContext(undefined);\nRecordContext.displayName = 'RecordContext';\n/**\n * Provider for the Record Context, to store a record.\n *\n * Use the useRecordContext() hook to read the context.\n * That's what the Edit and Show components do in react-admin.\n *\n * Many react-admin components read the RecordContext, including all Field\n * components.\n *\n * @example\n *\n * import { useGetOne, RecordContextProvider } from 'ra-core';\n *\n * const Show = ({ resource, id }) => {\n * const { data } = useGetOne(resource, { id });\n * return (\n * \n * ...\n * \n * );\n * };\n */\nexport var RecordContextProvider = function (_a) {\n var children = _a.children, value = _a.value;\n return (React.createElement(RecordContext.Provider, { value: value }, children));\n};\n//# sourceMappingURL=RecordContext.js.map","import { useContext } from 'react';\nimport { RecordContext } from './RecordContext';\n/**\n * Hook to read the record from a RecordContext.\n *\n * Must be used within a such as provided by the \n * (e.g. as a descendent of or ) or within a \n * (e.g. as a descendent of or )\n *\n * @example // basic usage\n *\n * import { useRecordContext } from 'ra-core';\n *\n * const TitleField = () => {\n * const record = useRecordContext();\n * return {record && record.title};\n * };\n *\n * @example // allow record override via props\n *\n * import { useRecordContext } from 'ra-core';\n *\n * const TitleField = (props) => {\n * const record = useRecordContext(props);\n * return {record && record.title};\n * };\n * render();\n *\n * @returns {RaRecord} A record object\n */\nexport var useRecordContext = function (props) {\n // Can't find a way to specify the RecordType when CreateContext is declared\n // @ts-ignore\n var context = useContext(RecordContext);\n return (props && props.record) || context;\n};\n//# sourceMappingURL=useRecordContext.js.map","import { useState, useEffect } from 'react';\nimport { useResourceContext } from '../core/useResourceContext';\nimport { useRecordContext } from '../controller/record/useRecordContext';\nimport { useCanAccess } from '../auth';\nimport { useResourceDefinition } from '../core';\nimport { useCreatePath } from './useCreatePath';\n/**\n * Get a path for a record, based on the current resource and the link type.\n *\n * Accepted link types are 'edit', 'show', a route string, false, or a function returning one of these types.\n *\n * @example\n * // basic usage (leverages RecordContext, ResourceContext and ResourceDefinitionContext)\n * const EditLink = () => {\n * const path = useGetPathForRecord();\n * return path ? Edit : null;\n * };\n *\n * // controlled mode\n * const EditLink = ({ record, resource }) => {\n * const path = useGetPathForRecord({ record, resource, link: 'edit' });\n * return path ? Edit : null;\n * };\n *\n * // the link option can be a function\n * const EditLink = ({ record, resource }) => {\n * const path = useGetPathForRecord({ record, resource, link: (record, resource) => record.canEdit ? 'edit' : false });\n * return path ? Edit : null;\n * };\n *\n * // the link option can be a function returning a promise\n * const EditLink = ({ record, resource }) => {\n * const path = useGetPathForRecord({ record, resource, link: async (record, resource) => {\n * const canEdit = await canEditRecord(record, resource);\n * return canEdit ? 'edit' : false;\n * }});\n * return path ? Edit : null;\n * };\n */\nexport var useGetPathForRecord = function (options) {\n if (options === void 0) { options = {}; }\n var link = (options || {}).link;\n var record = useRecordContext(options);\n var resource = useResourceContext(options);\n if (!resource) {\n throw new Error('Cannot generate a link for a record without a resource. You must use useGetPathForRecord within a ResourceContextProvider, or pass a resource prop.');\n }\n var resourceDefinition = useResourceDefinition(options);\n var createPath = useCreatePath();\n var _a = useState(link && typeof link !== 'function' && record != null\n ? createPath({\n resource: resource,\n id: record.id,\n type: link,\n })\n : false), path = _a[0], setPath = _a[1];\n // in preparation for the default value, does the user have access to the show and edit pages?\n // (we can't run hooks conditionally, so we need to run them even though the link is specified)\n var canAccessShow = useCanAccess({\n action: 'show',\n resource: resource,\n record: record,\n enabled: link == null && resourceDefinition.hasShow,\n }).canAccess;\n var canAccessEdit = useCanAccess({\n action: 'edit',\n resource: resource,\n record: record,\n enabled: link == null && resourceDefinition.hasEdit,\n }).canAccess;\n useEffect(function () {\n if (!record)\n return;\n if (link === false) {\n setPath(false);\n return;\n }\n // Handle the inferred link type case\n if (link == null) {\n // We must check whether the resource has an edit view because if there is no\n // authProvider, canAccessShow will always be true\n if (resourceDefinition.hasShow && canAccessShow) {\n setPath(createPath({\n resource: resource,\n id: record.id,\n type: 'show',\n }));\n return;\n }\n // We must check whether the resource has an edit view because if there is no\n // authProvider, canAccessEdit will always be true\n if (resourceDefinition.hasEdit && canAccessEdit) {\n setPath(createPath({\n resource: resource,\n id: record.id,\n type: 'edit',\n }));\n return;\n }\n }\n // Handle the link function case\n if (typeof link === 'function') {\n var linkResult = link(record, resource);\n if (linkResult instanceof Promise) {\n linkResult.then(function (resolvedPath) { return setPath(resolvedPath); });\n return;\n }\n setPath(linkResult\n ? createPath({\n resource: resource,\n id: record.id,\n type: linkResult,\n })\n : false);\n return;\n }\n // handle string case\n if (link) {\n setPath(createPath({\n resource: resource,\n id: record.id,\n type: link,\n }));\n }\n }, [\n createPath,\n canAccessShow,\n canAccessEdit,\n link,\n record,\n resource,\n resourceDefinition.hasEdit,\n resourceDefinition.hasShow,\n ]);\n return path;\n};\n//# sourceMappingURL=useGetPathForRecord.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport * as React from 'react';\nimport { createContext, useCallback, useState, useMemo } from 'react';\nimport isEqual from 'lodash/isEqual';\nexport var ResourceDefinitionContext = createContext({\n definitions: {},\n register: function () { },\n unregister: function () { },\n});\n/**\n * Context to store the current resource Definition.\n *\n * Use the useResourceDefinition() hook to read the context.\n *\n * @example\n *\n * import { useResourceDefinition, useTranslate } from 'ra-core';\n *\n * const PostMenuItem = () => {\n * const { name, icon } = useResourceDefinition({ resource: 'posts' });\n *\n * return (\n * \n * {icon}\n * {name}\n * \n * );\n * };\n */\nexport var ResourceDefinitionContextProvider = function (_a) {\n var _b = _a.definitions, defaultDefinitions = _b === void 0 ? {} : _b, children = _a.children;\n var _c = useState(defaultDefinitions), definitions = _c[0], setState = _c[1];\n var register = useCallback(function (config) {\n setState(function (prev) {\n var _a;\n return isEqual(prev[config.name], config)\n ? prev\n : __assign(__assign({}, prev), (_a = {}, _a[config.name] = config, _a));\n });\n }, []);\n var unregister = useCallback(function (config) {\n setState(function (prev) {\n var _a = prev, _b = config.name, _ = _a[_b], rest = __rest(_a, [typeof _b === \"symbol\" ? _b : _b + \"\"]);\n return rest;\n });\n }, []);\n var contextValue = useMemo(function () { return ({ definitions: definitions, register: register, unregister: unregister }); }, [definitions] // eslint-disable-line react-hooks/exhaustive-deps\n );\n return (React.createElement(ResourceDefinitionContext.Provider, { value: contextValue }, children));\n};\n//# sourceMappingURL=ResourceDefinitionContext.js.map","import { useContext } from 'react';\nimport { ResourceDefinitionContext } from './ResourceDefinitionContext';\nexport var useResourceDefinitionContext = function () {\n return useContext(ResourceDefinitionContext);\n};\n//# sourceMappingURL=useResourceDefinitionContext.js.map","import { useResourceDefinitionContext } from './useResourceDefinitionContext';\n/**\n * Get the definition of the all resources\n *\n * @example\n *\n * const definitions = useResourceDefinitions();\n * console.log(definitions.posts);\n * // {\n * // name: 'posts',\n * // hasList: true,\n * // hasEdit: true,\n * // hasShow: true,\n * // hasCreate: true,\n * // options: {},\n * // icon: PostIcon,\n * // recordRepresentation: 'title',\n * // }\n */\nexport var useResourceDefinitions = function () {\n return useResourceDefinitionContext().definitions;\n};\n//# sourceMappingURL=useResourceDefinitions.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nimport { useMutation, } from '@tanstack/react-query';\nimport useAuthProvider from './useAuthProvider';\n/**\n * A hook that returns a function you can call to determine whether user has access to the given resource\n *\n * @example\n * import { Datagrid, List, TextField, useCanAccessCallback } from 'react-admin';\n *\n * const UserList = () => {\n * const checkAccess = useCanAccessCallback();\n *\n * const handleRowClick = (id: Identifier, resource: string, record: Record) => {\n * try {\n * const canAccess = checkAccess({ resource: 'users', action: 'edit', record });\n * return canAccess ? \"edit\" : \"show\";\n * } catch (error) {\n * console.error(error);\n * }\n * };\n *\n * return (\n * \n * \n * \n * \n * \n * \n * \n * );\n * };\n */\nexport var useCanAccessCallback = function (options) {\n if (options === void 0) { options = {}; }\n var authProvider = useAuthProvider();\n var mutateAsync = useMutation(__assign({ mutationFn: function (params) { return __awaiter(void 0, void 0, void 0, function () {\n return __generator(this, function (_a) {\n if (!authProvider || !authProvider.canAccess) {\n return [2 /*return*/, true];\n }\n return [2 /*return*/, authProvider.canAccess(params)];\n });\n }); }, retry: false }, options)).mutateAsync;\n return mutateAsync;\n};\n//# sourceMappingURL=useCanAccessCallback.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nimport { useCallback } from 'react';\nimport { useResourceContext } from '../core/useResourceContext';\nimport { useResourceDefinitions } from '../core/useResourceDefinitions';\nimport { useCanAccessCallback } from '../auth/useCanAccessCallback';\nimport { useCreatePath } from './useCreatePath';\nexport var useGetPathForRecordCallback = function (options) {\n if (options === void 0) { options = {}; }\n var resource = useResourceContext(options);\n var resourceDefinitions = useResourceDefinitions();\n var createPath = useCreatePath();\n var canAccess = useCanAccessCallback();\n return useCallback(function (params) { return __awaiter(void 0, void 0, void 0, function () {\n var _a, link, record, finalResource, resourceDefinition, _b, canAccessShow, canAccessEdit, linkFunc, linkResult, linkResultIsPromise, resolvedLink;\n var _c, _d;\n return __generator(this, function (_e) {\n switch (_e.label) {\n case 0:\n _a = params || {}, link = _a.link, record = _a.record;\n finalResource = (_c = params.resource) !== null && _c !== void 0 ? _c : resource;\n if (!finalResource) {\n throw new Error('Cannot generate a link for a record without a resource. You must use useGetPathForRecordCallback within a ResourceContextProvider, or pass a resource parameter.');\n }\n resourceDefinition = (_d = resourceDefinitions[finalResource]) !== null && _d !== void 0 ? _d : {};\n if (record == null || link === false) {\n return [2 /*return*/, false];\n }\n if (!(link == null)) return [3 /*break*/, 2];\n return [4 /*yield*/, Promise.all([\n resourceDefinition.hasShow\n ? canAccess({\n action: 'show',\n resource: finalResource,\n record: record,\n })\n : Promise.resolve(false),\n resourceDefinition.hasEdit\n ? canAccess({\n action: 'edit',\n resource: finalResource,\n record: record,\n })\n : Promise.resolve(false),\n ])];\n case 1:\n _b = _e.sent(), canAccessShow = _b[0], canAccessEdit = _b[1];\n if (canAccessShow) {\n return [2 /*return*/, createPath({\n resource: finalResource,\n id: record.id,\n type: 'show',\n })];\n }\n if (canAccessEdit) {\n return [2 /*return*/, createPath({\n resource: finalResource,\n id: record.id,\n type: 'edit',\n })];\n }\n return [2 /*return*/, false];\n case 2:\n linkFunc = typeof link === 'function' ? link : function () { return link; };\n linkResult = linkFunc(record, finalResource);\n if (linkResult === false) {\n return [2 /*return*/, false];\n }\n linkResultIsPromise = isPromise(linkResult);\n if (!linkResultIsPromise) return [3 /*break*/, 4];\n return [4 /*yield*/, linkResult];\n case 3:\n resolvedLink = _e.sent();\n if (resolvedLink === false) {\n // already set to false by default\n return [2 /*return*/];\n }\n return [2 /*return*/, createPath({\n resource: finalResource,\n id: record.id,\n type: resolvedLink,\n })];\n case 4: return [2 /*return*/, createPath({\n resource: finalResource,\n id: record.id,\n type: linkResult,\n })];\n }\n });\n }); }, [canAccess, createPath, resourceDefinitions, resource]);\n};\nvar isPromise = function (value) {\n return value && typeof value.then === 'function';\n};\n//# sourceMappingURL=useGetPathForRecordCallback.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport { useCallback } from 'react';\nimport { useNavigate } from 'react-router-dom';\nimport { useBasename } from './useBasename';\nimport { useCreatePath } from './useCreatePath';\n/**\n * Hook for Redirection Side Effect\n *\n * @example\n *\n * const redirect = useRedirect();\n * // redirect to list view\n * redirect('list', 'posts');\n * // redirect to edit view\n * redirect('edit', 'posts', 123);\n * // redirect to edit view with state data\n * redirect('edit', 'comments', 123, {}, { record: { post_id: record.id } });\n * // do not redirect\n * redirect(false);\n * // redirect to the result of a function\n * redirect((resource, id, data) => ...)\n */\nexport var useRedirect = function () {\n var navigate = useNavigate();\n var basename = useBasename();\n var createPath = useCreatePath();\n return useCallback(function (redirectTo, resource, id, data, state) {\n if (resource === void 0) { resource = ''; }\n if (state === void 0) { state = {}; }\n if (!redirectTo) {\n return;\n }\n else if (typeof redirectTo === 'function') {\n var target = redirectTo(resource, id, data);\n var absoluteTarget = typeof target === 'string'\n ? \"\".concat(basename, \"/\").concat(target)\n : __assign({ pathname: \"\".concat(basename, \"/\").concat(target.pathname) }, target);\n navigate(absoluteTarget, {\n state: __assign({ _scrollToTop: true }, state),\n });\n return;\n }\n else if (typeof redirectTo === 'string' &&\n redirectTo.startsWith('http') &&\n window) {\n // redirection to an absolute url\n // history doesn't handle that case, so we handle it by hand\n window.location.href = redirectTo;\n return;\n }\n else {\n // redirection to an internal link\n navigate(createPath({ resource: resource, id: id, type: redirectTo }), {\n state: \n // We force the scrollToTop except when navigating to a list\n // where this is already done by in \n redirectTo === 'list'\n ? state\n : __assign({ _scrollToTop: true }, state),\n });\n return;\n }\n }, [navigate, basename, createPath]);\n};\n//# sourceMappingURL=useRedirect.js.map","import { useEffect, useRef } from 'react';\nimport { useLocation } from 'react-router';\n/**\n * A hook to use inside the component passed to FallbackComponent\n * of react-error-boundary. It resets the error boundary state whenever\n * the location changes\n * @param {Function} resetErrorBoundary\n */\nexport var useResetErrorBoundaryOnLocationChange = function (resetErrorBoundary) {\n var pathname = useLocation().pathname;\n var originalPathname = useRef(pathname);\n useEffect(function () {\n if (pathname !== originalPathname.current) {\n resetErrorBoundary();\n }\n }, [pathname, resetErrorBoundary]);\n};\n//# sourceMappingURL=useResetErrorBoundaryOnLocationChange.js.map","import { useEffect } from 'react';\nimport { useLocation } from 'react-router-dom';\n/**\n * Scroll the window to top when the target location contains the _scrollToTop state\n *\n * @see CoreAdminRouter where it's enabled by default\n *\n * @example // usage in buttons\n * import { Link } from 'react-router-dom';\n * import { Button } from '@mui/material';\n *\n * const FooButton = () => (\n * \n * Go to foo\n * \n * );\n */\nexport var useScrollToTop = function () {\n var location = useLocation();\n useEffect(function () {\n var _a;\n if (((_a = location.state) === null || _a === void 0 ? void 0 : _a._scrollToTop) &&\n typeof window != 'undefined' &&\n typeof window.scrollTo === 'function') {\n window.scrollTo(0, 0);\n }\n }, [location]);\n};\n//# sourceMappingURL=useScrollToTop.js.map","import { useLocation, useParams } from 'react-router-dom';\n/**\n * Utility hook to get the base path of a splat path.\n * Compatible both with react-router v6 and v7.\n *\n * Example:\n * If a splat path is defined as `/posts/:id/show/*`,\n * and the current location is `/posts/12/show/3`,\n * this hook will return `/posts/12/show`.\n *\n * Solution inspired by\n * https://github.com/remix-run/react-router/issues/11052#issuecomment-1828470203\n */\nexport var useSplatPathBase = function () {\n var location = useLocation();\n var params = useParams();\n var splatPathRelativePart = params['*'];\n var splatPathBase = location.pathname.replace(new RegExp(\"/\".concat(splatPathRelativePart, \"$\")), '');\n return splatPathBase;\n};\n//# sourceMappingURL=useSplatPathBase.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nexport var GET_LIST = 'GET_LIST';\nexport var GET_ONE = 'GET_ONE';\nexport var GET_MANY = 'GET_MANY';\nexport var GET_MANY_REFERENCE = 'GET_MANY_REFERENCE';\nexport var CREATE = 'CREATE';\nexport var UPDATE = 'UPDATE';\nexport var UPDATE_MANY = 'UPDATE_MANY';\nexport var DELETE = 'DELETE';\nexport var DELETE_MANY = 'DELETE_MANY';\nexport var fetchActionsWithRecordResponse = ['getOne', 'create', 'update'];\nexport var fetchActionsWithArrayOfIdentifiedRecordsResponse = [\n 'getList',\n 'getMany',\n 'getManyReference',\n];\nexport var fetchActionsWithArrayOfRecordsResponse = __spreadArray(__spreadArray([], fetchActionsWithArrayOfIdentifiedRecordsResponse, true), [\n 'updateMany',\n 'deleteMany',\n], false);\nexport var fetchActionsWithTotalResponse = ['getList', 'getManyReference'];\nexport var reactAdminFetchActions = __spreadArray(__spreadArray([], fetchActionsWithRecordResponse, true), fetchActionsWithArrayOfRecordsResponse, true);\nexport var sanitizeFetchType = function (fetchType) {\n switch (fetchType) {\n case GET_LIST:\n return 'getList';\n case GET_ONE:\n return 'getOne';\n case GET_MANY:\n return 'getMany';\n case GET_MANY_REFERENCE:\n return 'getManyReference';\n case CREATE:\n return 'create';\n case UPDATE:\n return 'update';\n case UPDATE_MANY:\n return 'updateMany';\n case DELETE:\n return 'delete';\n case DELETE_MANY:\n return 'deleteMany';\n default:\n return fetchType;\n }\n};\n//# sourceMappingURL=dataFetchActions.js.map","// avoids adding a context in tests\nexport var defaultDataProvider = {\n create: function () { return Promise.resolve({ data: null }); },\n delete: function () { return Promise.resolve({ data: null }); },\n deleteMany: function () { return Promise.resolve({ data: [] }); },\n getList: function () { return Promise.resolve({ data: [], total: 0 }); },\n getMany: function () { return Promise.resolve({ data: [] }); },\n getManyReference: function () { return Promise.resolve({ data: [], total: 0 }); },\n getOne: function () { return Promise.resolve({ data: null }); },\n update: function () { return Promise.resolve({ data: null }); },\n updateMany: function () { return Promise.resolve({ data: [] }); },\n};\n//# sourceMappingURL=defaultDataProvider.js.map","import { CREATE, DELETE, DELETE_MANY, GET_LIST, GET_MANY, GET_MANY_REFERENCE, GET_ONE, UPDATE, UPDATE_MANY, } from './dataFetchActions';\nimport { defaultDataProvider } from './defaultDataProvider';\nvar fetchMap = {\n create: CREATE,\n delete: DELETE,\n deleteMany: DELETE_MANY,\n getList: GET_LIST,\n getMany: GET_MANY,\n getManyReference: GET_MANY_REFERENCE,\n getOne: GET_ONE,\n update: UPDATE,\n updateMany: UPDATE_MANY,\n};\n/**\n * Turn a function-based dataProvider to an object-based one\n *\n * Allows using legacy dataProviders transparently.\n *\n * @param {Function} legacyDataProvider A legacy dataProvider (type, resource, params) => Promise\n *\n * @returns {Object} A dataProvider that react-admin can use\n */\nvar convertLegacyDataProvider = function (legacyDataProvider) {\n var proxy = new Proxy(defaultDataProvider, {\n get: function (_, name) {\n return function (resource, params) {\n if (Object.keys(fetchMap).includes(name.toString())) {\n var fetchType = fetchMap[name.toString()];\n return legacyDataProvider(fetchType, resource, params);\n }\n return legacyDataProvider(name.toString(), resource, params);\n };\n },\n apply: function (_, __, args) {\n return legacyDataProvider.apply(legacyDataProvider, args);\n },\n });\n return proxy;\n};\nexport default convertLegacyDataProvider;\n//# sourceMappingURL=convertLegacyDataProvider.js.map","import { createContext } from 'react';\nvar DataProviderContext = createContext(null);\nDataProviderContext.displayName = 'DataProviderContext';\nexport default DataProviderContext;\n//# sourceMappingURL=DataProviderContext.js.map","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar HttpError = /** @class */ (function (_super) {\n __extends(HttpError, _super);\n function HttpError(message, status, body) {\n if (body === void 0) { body = null; }\n var _this = _super.call(this, message) || this;\n _this.message = message;\n _this.status = status;\n _this.body = body;\n Object.setPrototypeOf(_this, HttpError.prototype);\n _this.name = _this.constructor.name;\n if (typeof Error.captureStackTrace === 'function') {\n Error.captureStackTrace(_this, _this.constructor);\n }\n else {\n _this.stack = new Error(message).stack;\n }\n _this.stack = new Error().stack;\n return _this;\n }\n return HttpError;\n}(Error));\nexport default HttpError;\n//# sourceMappingURL=HttpError.js.map","'use strict';\nmodule.exports = str => encodeURIComponent(str).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`);\n","'use strict';\nvar token = '%[a-f0-9]{2}';\nvar singleMatcher = new RegExp('(' + token + ')|([^%]+?)', 'gi');\nvar multiMatcher = new RegExp('(' + token + ')+', 'gi');\n\nfunction decodeComponents(components, split) {\n\ttry {\n\t\t// Try to decode the entire string first\n\t\treturn [decodeURIComponent(components.join(''))];\n\t} catch (err) {\n\t\t// Do nothing\n\t}\n\n\tif (components.length === 1) {\n\t\treturn components;\n\t}\n\n\tsplit = split || 1;\n\n\t// Split the array in 2 parts\n\tvar left = components.slice(0, split);\n\tvar right = components.slice(split);\n\n\treturn Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));\n}\n\nfunction decode(input) {\n\ttry {\n\t\treturn decodeURIComponent(input);\n\t} catch (err) {\n\t\tvar tokens = input.match(singleMatcher) || [];\n\n\t\tfor (var i = 1; i < tokens.length; i++) {\n\t\t\tinput = decodeComponents(tokens, i).join('');\n\n\t\t\ttokens = input.match(singleMatcher) || [];\n\t\t}\n\n\t\treturn input;\n\t}\n}\n\nfunction customDecodeURIComponent(input) {\n\t// Keep track of all the replacements and prefill the map with the `BOM`\n\tvar replaceMap = {\n\t\t'%FE%FF': '\\uFFFD\\uFFFD',\n\t\t'%FF%FE': '\\uFFFD\\uFFFD'\n\t};\n\n\tvar match = multiMatcher.exec(input);\n\twhile (match) {\n\t\ttry {\n\t\t\t// Decode as big chunks as possible\n\t\t\treplaceMap[match[0]] = decodeURIComponent(match[0]);\n\t\t} catch (err) {\n\t\t\tvar result = decode(match[0]);\n\n\t\t\tif (result !== match[0]) {\n\t\t\t\treplaceMap[match[0]] = result;\n\t\t\t}\n\t\t}\n\n\t\tmatch = multiMatcher.exec(input);\n\t}\n\n\t// Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else\n\treplaceMap['%C2'] = '\\uFFFD';\n\n\tvar entries = Object.keys(replaceMap);\n\n\tfor (var i = 0; i < entries.length; i++) {\n\t\t// Replace all decoded components\n\t\tvar key = entries[i];\n\t\tinput = input.replace(new RegExp(key, 'g'), replaceMap[key]);\n\t}\n\n\treturn input;\n}\n\nmodule.exports = function (encodedURI) {\n\tif (typeof encodedURI !== 'string') {\n\t\tthrow new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');\n\t}\n\n\ttry {\n\t\tencodedURI = encodedURI.replace(/\\+/g, ' ');\n\n\t\t// Try the built in decoder first\n\t\treturn decodeURIComponent(encodedURI);\n\t} catch (err) {\n\t\t// Fallback to a more advanced decoder\n\t\treturn customDecodeURIComponent(encodedURI);\n\t}\n};\n","'use strict';\n\nmodule.exports = (string, separator) => {\n\tif (!(typeof string === 'string' && typeof separator === 'string')) {\n\t\tthrow new TypeError('Expected the arguments to be of type `string`');\n\t}\n\n\tif (separator === '') {\n\t\treturn [string];\n\t}\n\n\tconst separatorIndex = string.indexOf(separator);\n\n\tif (separatorIndex === -1) {\n\t\treturn [string];\n\t}\n\n\treturn [\n\t\tstring.slice(0, separatorIndex),\n\t\tstring.slice(separatorIndex + separator.length)\n\t];\n};\n","'use strict';\nmodule.exports = function (obj, predicate) {\n\tvar ret = {};\n\tvar keys = Object.keys(obj);\n\tvar isArr = Array.isArray(predicate);\n\n\tfor (var i = 0; i < keys.length; i++) {\n\t\tvar key = keys[i];\n\t\tvar val = obj[key];\n\n\t\tif (isArr ? predicate.indexOf(key) !== -1 : predicate(key, val, obj)) {\n\t\t\tret[key] = val;\n\t\t}\n\t}\n\n\treturn ret;\n};\n","'use strict';\nconst strictUriEncode = require('strict-uri-encode');\nconst decodeComponent = require('decode-uri-component');\nconst splitOnFirst = require('split-on-first');\nconst filterObject = require('filter-obj');\n\nconst isNullOrUndefined = value => value === null || value === undefined;\n\nconst encodeFragmentIdentifier = Symbol('encodeFragmentIdentifier');\n\nfunction encoderForArrayFormat(options) {\n\tswitch (options.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn key => (result, value) => {\n\t\t\t\tconst index = result.length;\n\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, [encode(key, options), '[', index, ']'].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [\n\t\t\t\t\t...result,\n\t\t\t\t\t[encode(key, options), '[', encode(index, options), ']=', encode(value, options)].join('')\n\t\t\t\t];\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, [encode(key, options), '[]'].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [...result, [encode(key, options), '[]=', encode(value, options)].join('')];\n\t\t\t};\n\n\t\tcase 'colon-list-separator':\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, [encode(key, options), ':list='].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [...result, [encode(key, options), ':list=', encode(value, options)].join('')];\n\t\t\t};\n\n\t\tcase 'comma':\n\t\tcase 'separator':\n\t\tcase 'bracket-separator': {\n\t\t\tconst keyValueSep = options.arrayFormat === 'bracket-separator' ?\n\t\t\t\t'[]=' :\n\t\t\t\t'=';\n\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\t// Translate null to an empty string so that it doesn't serialize as 'null'\n\t\t\t\tvalue = value === null ? '' : value;\n\n\t\t\t\tif (result.length === 0) {\n\t\t\t\t\treturn [[encode(key, options), keyValueSep, encode(value, options)].join('')];\n\t\t\t\t}\n\n\t\t\t\treturn [[result, encode(value, options)].join(options.arrayFormatSeparator)];\n\t\t\t};\n\t\t}\n\n\t\tdefault:\n\t\t\treturn key => (result, value) => {\n\t\t\t\tif (\n\t\t\t\t\tvalue === undefined ||\n\t\t\t\t\t(options.skipNull && value === null) ||\n\t\t\t\t\t(options.skipEmptyString && value === '')\n\t\t\t\t) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\n\t\t\t\tif (value === null) {\n\t\t\t\t\treturn [...result, encode(key, options)];\n\t\t\t\t}\n\n\t\t\t\treturn [...result, [encode(key, options), '=', encode(value, options)].join('')];\n\t\t\t};\n\t}\n}\n\nfunction parserForArrayFormat(options) {\n\tlet result;\n\n\tswitch (options.arrayFormat) {\n\t\tcase 'index':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tresult = /\\[(\\d*)\\]$/.exec(key);\n\n\t\t\t\tkey = key.replace(/\\[\\d*\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = {};\n\t\t\t\t}\n\n\t\t\t\taccumulator[key][result[1]] = value;\n\t\t\t};\n\n\t\tcase 'bracket':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tresult = /(\\[\\])$/.exec(key);\n\t\t\t\tkey = key.replace(/\\[\\]$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = [value];\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\n\t\tcase 'colon-list-separator':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tresult = /(:list)$/.exec(key);\n\t\t\t\tkey = key.replace(/:list$/, '');\n\n\t\t\t\tif (!result) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = [value];\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\n\t\tcase 'comma':\n\t\tcase 'separator':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tconst isArray = typeof value === 'string' && value.includes(options.arrayFormatSeparator);\n\t\t\t\tconst isEncodedArray = (typeof value === 'string' && !isArray && decode(value, options).includes(options.arrayFormatSeparator));\n\t\t\t\tvalue = isEncodedArray ? decode(value, options) : value;\n\t\t\t\tconst newValue = isArray || isEncodedArray ? value.split(options.arrayFormatSeparator).map(item => decode(item, options)) : value === null ? value : decode(value, options);\n\t\t\t\taccumulator[key] = newValue;\n\t\t\t};\n\n\t\tcase 'bracket-separator':\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tconst isArray = /(\\[\\])$/.test(key);\n\t\t\t\tkey = key.replace(/\\[\\]$/, '');\n\n\t\t\t\tif (!isArray) {\n\t\t\t\t\taccumulator[key] = value ? decode(value, options) : value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst arrayValue = value === null ?\n\t\t\t\t\t[] :\n\t\t\t\t\tvalue.split(options.arrayFormatSeparator).map(item => decode(item, options));\n\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = arrayValue;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], arrayValue);\n\t\t\t};\n\n\t\tdefault:\n\t\t\treturn (key, value, accumulator) => {\n\t\t\t\tif (accumulator[key] === undefined) {\n\t\t\t\t\taccumulator[key] = value;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\taccumulator[key] = [].concat(accumulator[key], value);\n\t\t\t};\n\t}\n}\n\nfunction validateArrayFormatSeparator(value) {\n\tif (typeof value !== 'string' || value.length !== 1) {\n\t\tthrow new TypeError('arrayFormatSeparator must be single character string');\n\t}\n}\n\nfunction encode(value, options) {\n\tif (options.encode) {\n\t\treturn options.strict ? strictUriEncode(value) : encodeURIComponent(value);\n\t}\n\n\treturn value;\n}\n\nfunction decode(value, options) {\n\tif (options.decode) {\n\t\treturn decodeComponent(value);\n\t}\n\n\treturn value;\n}\n\nfunction keysSorter(input) {\n\tif (Array.isArray(input)) {\n\t\treturn input.sort();\n\t}\n\n\tif (typeof input === 'object') {\n\t\treturn keysSorter(Object.keys(input))\n\t\t\t.sort((a, b) => Number(a) - Number(b))\n\t\t\t.map(key => input[key]);\n\t}\n\n\treturn input;\n}\n\nfunction removeHash(input) {\n\tconst hashStart = input.indexOf('#');\n\tif (hashStart !== -1) {\n\t\tinput = input.slice(0, hashStart);\n\t}\n\n\treturn input;\n}\n\nfunction getHash(url) {\n\tlet hash = '';\n\tconst hashStart = url.indexOf('#');\n\tif (hashStart !== -1) {\n\t\thash = url.slice(hashStart);\n\t}\n\n\treturn hash;\n}\n\nfunction extract(input) {\n\tinput = removeHash(input);\n\tconst queryStart = input.indexOf('?');\n\tif (queryStart === -1) {\n\t\treturn '';\n\t}\n\n\treturn input.slice(queryStart + 1);\n}\n\nfunction parseValue(value, options) {\n\tif (options.parseNumbers && !Number.isNaN(Number(value)) && (typeof value === 'string' && value.trim() !== '')) {\n\t\tvalue = Number(value);\n\t} else if (options.parseBooleans && value !== null && (value.toLowerCase() === 'true' || value.toLowerCase() === 'false')) {\n\t\tvalue = value.toLowerCase() === 'true';\n\t}\n\n\treturn value;\n}\n\nfunction parse(query, options) {\n\toptions = Object.assign({\n\t\tdecode: true,\n\t\tsort: true,\n\t\tarrayFormat: 'none',\n\t\tarrayFormatSeparator: ',',\n\t\tparseNumbers: false,\n\t\tparseBooleans: false\n\t}, options);\n\n\tvalidateArrayFormatSeparator(options.arrayFormatSeparator);\n\n\tconst formatter = parserForArrayFormat(options);\n\n\t// Create an object with no prototype\n\tconst ret = Object.create(null);\n\n\tif (typeof query !== 'string') {\n\t\treturn ret;\n\t}\n\n\tquery = query.trim().replace(/^[?#&]/, '');\n\n\tif (!query) {\n\t\treturn ret;\n\t}\n\n\tfor (const param of query.split('&')) {\n\t\tif (param === '') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlet [key, value] = splitOnFirst(options.decode ? param.replace(/\\+/g, ' ') : param, '=');\n\n\t\t// Missing `=` should be `null`:\n\t\t// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters\n\t\tvalue = value === undefined ? null : ['comma', 'separator', 'bracket-separator'].includes(options.arrayFormat) ? value : decode(value, options);\n\t\tformatter(decode(key, options), value, ret);\n\t}\n\n\tfor (const key of Object.keys(ret)) {\n\t\tconst value = ret[key];\n\t\tif (typeof value === 'object' && value !== null) {\n\t\t\tfor (const k of Object.keys(value)) {\n\t\t\t\tvalue[k] = parseValue(value[k], options);\n\t\t\t}\n\t\t} else {\n\t\t\tret[key] = parseValue(value, options);\n\t\t}\n\t}\n\n\tif (options.sort === false) {\n\t\treturn ret;\n\t}\n\n\treturn (options.sort === true ? Object.keys(ret).sort() : Object.keys(ret).sort(options.sort)).reduce((result, key) => {\n\t\tconst value = ret[key];\n\t\tif (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) {\n\t\t\t// Sort object keys, not values\n\t\t\tresult[key] = keysSorter(value);\n\t\t} else {\n\t\t\tresult[key] = value;\n\t\t}\n\n\t\treturn result;\n\t}, Object.create(null));\n}\n\nexports.extract = extract;\nexports.parse = parse;\n\nexports.stringify = (object, options) => {\n\tif (!object) {\n\t\treturn '';\n\t}\n\n\toptions = Object.assign({\n\t\tencode: true,\n\t\tstrict: true,\n\t\tarrayFormat: 'none',\n\t\tarrayFormatSeparator: ','\n\t}, options);\n\n\tvalidateArrayFormatSeparator(options.arrayFormatSeparator);\n\n\tconst shouldFilter = key => (\n\t\t(options.skipNull && isNullOrUndefined(object[key])) ||\n\t\t(options.skipEmptyString && object[key] === '')\n\t);\n\n\tconst formatter = encoderForArrayFormat(options);\n\n\tconst objectCopy = {};\n\n\tfor (const key of Object.keys(object)) {\n\t\tif (!shouldFilter(key)) {\n\t\t\tobjectCopy[key] = object[key];\n\t\t}\n\t}\n\n\tconst keys = Object.keys(objectCopy);\n\n\tif (options.sort !== false) {\n\t\tkeys.sort(options.sort);\n\t}\n\n\treturn keys.map(key => {\n\t\tconst value = object[key];\n\n\t\tif (value === undefined) {\n\t\t\treturn '';\n\t\t}\n\n\t\tif (value === null) {\n\t\t\treturn encode(key, options);\n\t\t}\n\n\t\tif (Array.isArray(value)) {\n\t\t\tif (value.length === 0 && options.arrayFormat === 'bracket-separator') {\n\t\t\t\treturn encode(key, options) + '[]';\n\t\t\t}\n\n\t\t\treturn value\n\t\t\t\t.reduce(formatter(key), [])\n\t\t\t\t.join('&');\n\t\t}\n\n\t\treturn encode(key, options) + '=' + encode(value, options);\n\t}).filter(x => x.length > 0).join('&');\n};\n\nexports.parseUrl = (url, options) => {\n\toptions = Object.assign({\n\t\tdecode: true\n\t}, options);\n\n\tconst [url_, hash] = splitOnFirst(url, '#');\n\n\treturn Object.assign(\n\t\t{\n\t\t\turl: url_.split('?')[0] || '',\n\t\t\tquery: parse(extract(url), options)\n\t\t},\n\t\toptions && options.parseFragmentIdentifier && hash ? {fragmentIdentifier: decode(hash, options)} : {}\n\t);\n};\n\nexports.stringifyUrl = (object, options) => {\n\toptions = Object.assign({\n\t\tencode: true,\n\t\tstrict: true,\n\t\t[encodeFragmentIdentifier]: true\n\t}, options);\n\n\tconst url = removeHash(object.url).split('?')[0] || '';\n\tconst queryFromUrl = exports.extract(object.url);\n\tconst parsedQueryFromUrl = exports.parse(queryFromUrl, {sort: false});\n\n\tconst query = Object.assign(parsedQueryFromUrl, object.query);\n\tlet queryString = exports.stringify(query, options);\n\tif (queryString) {\n\t\tqueryString = `?${queryString}`;\n\t}\n\n\tlet hash = getHash(object.url);\n\tif (object.fragmentIdentifier) {\n\t\thash = `#${options[encodeFragmentIdentifier] ? encode(object.fragmentIdentifier, options) : object.fragmentIdentifier}`;\n\t}\n\n\treturn `${url}${queryString}${hash}`;\n};\n\nexports.pick = (input, filter, options) => {\n\toptions = Object.assign({\n\t\tparseFragmentIdentifier: true,\n\t\t[encodeFragmentIdentifier]: false\n\t}, options);\n\n\tconst {url, query, fragmentIdentifier} = exports.parseUrl(input, options);\n\treturn exports.stringifyUrl({\n\t\turl,\n\t\tquery: filterObject(query, filter),\n\t\tfragmentIdentifier\n\t}, options);\n};\n\nexports.exclude = (input, filter, options) => {\n\tconst exclusionFilter = Array.isArray(filter) ? key => !filter.includes(key) : (key, value) => !filter(key, value);\n\n\treturn exports.pick(input, exclusionFilter, options);\n};\n","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport HttpError from './HttpError';\nimport { stringify } from 'query-string';\nexport var createHeadersFromOptions = function (options) {\n var requestHeaders = (options.headers ||\n new Headers({\n Accept: 'application/json',\n }));\n var hasBody = options && options.body;\n var isContentTypeSet = requestHeaders.has('Content-Type');\n var isGetMethod = !(options === null || options === void 0 ? void 0 : options.method) || (options === null || options === void 0 ? void 0 : options.method) === 'GET';\n var isFormData = (options === null || options === void 0 ? void 0 : options.body) instanceof FormData;\n var shouldSetContentType = hasBody && !isContentTypeSet && !isGetMethod && !isFormData;\n if (shouldSetContentType) {\n requestHeaders.set('Content-Type', 'application/json');\n }\n if (options.user && options.user.authenticated && options.user.token) {\n requestHeaders.set('Authorization', options.user.token);\n }\n return requestHeaders;\n};\n/**\n * Utility function to make HTTP calls. It's similar to the HTML5 `fetch()`, except it handles JSON decoding and HTTP error codes automatically.\n *\n * @param url the URL to call\n * @param options the options to pass to the HTTP call\n * @param options.user the user object, used for the Authorization header\n * @param options.user.token the token to pass as the Authorization header\n * @param options.user.authenticated whether the user is authenticated or not (the Authorization header will be set only if this is true)\n * @param options.headers the headers to pass to the HTTP call\n *\n * @returns {Promise} the Promise for a response object containing the following properties:\n * - status: the HTTP status code\n * - headers: the HTTP headers\n * - body: the response body\n * - json: the response body parsed as JSON\n */\nexport var fetchJson = function (url, options) {\n if (options === void 0) { options = {}; }\n var requestHeaders = createHeadersFromOptions(options);\n return fetch(url, __assign(__assign({}, options), { headers: requestHeaders }))\n .then(function (response) {\n return response.text().then(function (text) { return ({\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n body: text,\n }); });\n })\n .then(function (_a) {\n var status = _a.status, statusText = _a.statusText, headers = _a.headers, body = _a.body;\n var json;\n try {\n json = JSON.parse(body);\n }\n catch (e) {\n // not json, no big deal\n }\n if (status < 200 || status >= 300) {\n return Promise.reject(new HttpError((json && json.message) || statusText, status, json));\n }\n return Promise.resolve({ status: status, headers: headers, body: body, json: json });\n });\n};\nexport var queryParameters = stringify;\nvar isValidObject = function (value) {\n if (!value) {\n return false;\n }\n var isArray = Array.isArray(value);\n var isBuffer = typeof Buffer !== 'undefined' && Buffer.isBuffer(value);\n var isObject = Object.prototype.toString.call(value) === '[object Object]';\n var hasKeys = !!Object.keys(value).length;\n return !isArray && !isBuffer && isObject && hasKeys;\n};\nexport var flattenObject = function (value, path) {\n var _a;\n if (path === void 0) { path = []; }\n if (isValidObject(value)) {\n return Object.assign.apply(Object, __spreadArray([{}], Object.keys(value).map(function (key) {\n return flattenObject(value[key], path.concat([key]));\n }), false));\n }\n else {\n return path.length ? (_a = {}, _a[path.join('.')] = value, _a) : value;\n }\n};\n//# sourceMappingURL=fetch.js.map","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","import EventEmitter from 'eventemitter3';\nexport default new EventEmitter();\n//# sourceMappingURL=undoableEventEmitter.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { defaultDataProvider } from './defaultDataProvider';\n/**\n * Combine multiple data providers into one.\n *\n * @param dataProviderMatcher A function that returns a data provider for a given resource.\n *\n * @example\n * const dataProvider = combineDataProviders(resource => {\n * switch(resource) {\n * case 'posts':\n * case 'comments':\n * return dataProvider1;\n * case 'users':\n * return dataProvider2;\n * default:\n * throw new Error('Unknown resource');\n * }\n * });\n */\nexport var combineDataProviders = function (dataProviderMatcher) {\n return new Proxy(defaultDataProvider, {\n get: function (target, name) {\n if (name === 'then') {\n return null;\n }\n return function (resource) {\n var _a;\n var params = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n params[_i - 1] = arguments[_i];\n }\n if (typeof name === 'symbol') {\n return;\n }\n return (_a = dataProviderMatcher(resource))[name].apply(_a, __spreadArray([resource], params, false));\n };\n },\n });\n};\n//# sourceMappingURL=combineDataProviders.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nimport { useCallback } from 'react';\nimport useAuthProvider from './useAuthProvider';\nimport useLogout from './useLogout';\nimport { useNotify } from '../notification';\nimport { useNavigate } from 'react-router';\nvar timer;\n/**\n * Returns a callback used to call the authProvider.checkError() method\n * and an error from the dataProvider. If the authProvider rejects the call,\n * the hook logs the user out and shows a logged out notification.\n *\n * Used in the useDataProvider hook to check for access denied responses\n * (e.g. 401 or 403 responses) and trigger a logout.\n *\n * @see useLogout\n * @see useDataProvider\n *\n * @returns {Function} logoutIfAccessDenied callback\n *\n * @example\n *\n * import { useLogoutIfAccessDenied, useNotify, DataProviderContext } from 'react-admin';\n *\n * const FetchRestrictedResource = () => {\n * const dataProvider = useContext(DataProviderContext);\n * const logoutIfAccessDenied = useLogoutIfAccessDenied();\n * const notify = useNotify()\n * useEffect(() => {\n * dataProvider.getOne('secret', { id: 123 })\n * .catch(error => {\n * logoutIfAccessDenied(error);\n * notify('server error', { type: 'error' });\n * })\n * }, []);\n * // ...\n * }\n */\nvar useLogoutIfAccessDenied = function () {\n var authProvider = useAuthProvider();\n var logout = useLogout();\n var notify = useNotify();\n var navigate = useNavigate();\n var logoutIfAccessDenied = useCallback(function (error) {\n if (!authProvider) {\n return logoutIfAccessDeniedWithoutProvider();\n }\n return authProvider\n .checkError(error)\n .then(function () { return false; })\n .catch(function (e) { return __awaiter(void 0, void 0, void 0, function () {\n var logoutUser, redirectTo, shouldNotify;\n var _a;\n return __generator(this, function (_b) {\n logoutUser = (_a = e === null || e === void 0 ? void 0 : e.logoutUser) !== null && _a !== void 0 ? _a : true;\n //manual debounce\n if (timer) {\n // side effects already triggered in this tick, exit\n return [2 /*return*/, true];\n }\n timer = setTimeout(function () {\n timer = undefined;\n }, 0);\n redirectTo = e && e.redirectTo != null\n ? e.redirectTo\n : error && error.redirectTo\n ? error.redirectTo\n : undefined;\n shouldNotify = !((e && e.message === false) ||\n (error && error.message === false) ||\n (redirectTo === null || redirectTo === void 0 ? void 0 : redirectTo.startsWith('http')));\n if (shouldNotify) {\n // notify only if not yet logged out\n authProvider\n .checkAuth({})\n .then(function () {\n if (logoutUser) {\n notify(getErrorMessage(e, 'ra.notification.logged_out'), { type: 'error' });\n }\n else {\n notify(getErrorMessage(e, 'ra.notification.not_authorized'), { type: 'error' });\n }\n })\n .catch(function () { });\n }\n if (logoutUser) {\n logout({}, redirectTo);\n }\n else {\n if (redirectTo.startsWith('http')) {\n // absolute link (e.g. https://my.oidc.server/login)\n window.location.href = redirectTo;\n }\n else {\n // internal location\n navigate(redirectTo);\n }\n }\n return [2 /*return*/, true];\n });\n }); });\n }, [authProvider, logout, notify, navigate]);\n return logoutIfAccessDenied;\n};\nvar logoutIfAccessDeniedWithoutProvider = function () { return Promise.resolve(false); };\nvar getErrorMessage = function (error, defaultMessage) {\n return typeof error === 'string'\n ? error\n : typeof error === 'undefined' || !error.message\n ? defaultMessage\n : error.message;\n};\nexport default useLogoutIfAccessDenied;\n//# sourceMappingURL=useLogoutIfAccessDenied.js.map","/**\n * Populate react-query's query cache with a data dictionary\n *\n * @example\n * const data = {\n * posts: [{ id: 1, title: 'Hello, world' }, { id: 2, title: 'FooBar' }],\n * comments: [{ id: 1, post_id: 1, body: 'Nice post!' }],\n * };\n * populateQueryCache({ data, queryClient });\n * // setQueryData(['posts', 'getOne', { id: '1' }], { id: 1, title: 'Hello, world' });\n * // setQueryData(['posts', 'getOne', { id: '2' }], { id: 2, title: 'FooBar' });\n * // setQueryData(['posts', 'getMany', { ids: ['1', '2'] }], [{ id: 1, title: 'Hello, world' }, { id: 2, title: 'FooBar' }]);\n * // setQueryData(['comments', 'getOne', { id: '1' }], { id: 1, post_id: 1, body: 'Nice post!' });\n * // setQueryData(['comments', 'getMany', { ids: ['1'] }], [{ id: 1, post_id: 1, body: 'Nice post!' });\n */\nexport var populateQueryCache = function (_a) {\n var data = _a.data, queryClient = _a.queryClient, _b = _a.staleTime, staleTime = _b === void 0 ? 1000 : _b;\n // setQueryData doesn't accept a stale time option\n // So we set an updatedAt in the future to make sure the data isn't considered stale\n var updatedAt = Date.now() + staleTime;\n Object.keys(data).forEach(function (resource) {\n data[resource].forEach(function (record) {\n if (!record || record.id == null)\n return;\n queryClient.setQueryData([resource, 'getOne', { id: String(record.id) }], record, { updatedAt: updatedAt });\n });\n var recordIds = data[resource].map(function (record) { return String(record.id); });\n queryClient.setQueryData([resource, 'getMany', { ids: recordIds }], data[resource], { updatedAt: updatedAt });\n });\n};\n//# sourceMappingURL=populateQueryCache.js.map","import { useContext, useMemo } from 'react';\nimport { useQueryClient } from '@tanstack/react-query';\nimport DataProviderContext from './DataProviderContext';\nimport { defaultDataProvider } from './defaultDataProvider';\nimport validateResponseFormat from './validateResponseFormat';\nimport useLogoutIfAccessDenied from '../auth/useLogoutIfAccessDenied';\nimport { reactAdminFetchActions } from './dataFetchActions';\nimport { populateQueryCache } from './populateQueryCache';\n/**\n * Hook for getting a dataProvider\n *\n * Gets a dataProvider object, which behaves just like the real dataProvider\n * (same methods returning a Promise). But it's actually a Proxy object,\n * which validates the response format, and logs the user out upon error\n * if authProvider.checkError() rejects.\n *\n * @return dataProvider\n *\n * @example Basic usage\n *\n * import * as React from 'react';\n * import { useState } from 'react';\n * import { useDataProvider } from 'react-admin';\n *\n * const PostList = () => {\n * const [posts, setPosts] = useState([])\n * const dataProvider = useDataProvider();\n * useEffect(() => {\n * dataProvider.getList('posts', { filter: { status: 'pending' }})\n * .then(({ data }) => setPosts(data));\n * }, [])\n *\n * return (\n * \n * {posts.map((post, key) => )}\n * \n * );\n * }\n *\n * @example Handling all states (loading, error, success)\n *\n * import { useState, useEffect } from 'react';\n * import { useDataProvider } from 'react-admin';\n *\n * const UserProfile = ({ userId }) => {\n * const dataProvider = useDataProvider();\n * const [user, setUser] = useState();\n * const [loading, setLoading] = useState(true);\n * const [error, setError] = useState();\n * useEffect(() => {\n * dataProvider.getOne('users', { id: userId })\n * .then(({ data }) => {\n * setUser(data);\n * setLoading(false);\n * })\n * .catch(error => {\n * setError(error);\n * setLoading(false);\n * })\n * }, []);\n *\n * if (loading) return ;\n * if (error) return \n * if (!user) return null;\n *\n * return (\n *
    \n *
  • Name: {user.name}
  • \n *
  • Email: {user.email}
  • \n *
\n * )\n * }\n */\nvar arrayReturnTypes = ['getList', 'getMany', 'getManyReference'];\nexport var useDataProvider = function () {\n var dataProvider = (useContext(DataProviderContext) ||\n defaultDataProvider);\n var queryClient = useQueryClient();\n var logoutIfAccessDenied = useLogoutIfAccessDenied();\n var dataProviderProxy = useMemo(function () {\n return new Proxy(dataProvider, {\n get: function (_, name) {\n if (typeof name === 'symbol' || name === 'then') {\n return;\n }\n if (name === 'supportAbortSignal') {\n return dataProvider.supportAbortSignal;\n }\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var type = name.toString();\n if (typeof dataProvider[type] !== 'function') {\n throw new Error(\"Unknown dataProvider function: \".concat(type));\n }\n try {\n return dataProvider[type]\n .apply(dataProvider, args)\n .then(function (response) {\n var _a;\n if (process.env.NODE_ENV !== 'production' &&\n reactAdminFetchActions.includes(type)) {\n validateResponseFormat(response, type);\n }\n if ((_a = response === null || response === void 0 ? void 0 : response.meta) === null || _a === void 0 ? void 0 : _a.prefetched) {\n populateQueryCache({\n data: response === null || response === void 0 ? void 0 : response.meta.prefetched,\n queryClient: queryClient,\n });\n }\n return response;\n })\n .catch(function (error) {\n if (process.env.NODE_ENV !== 'production' &&\n // do not log AbortErrors\n !isAbortError(error)) {\n console.error(error);\n }\n return logoutIfAccessDenied(error).then(function (loggedOut) {\n if (loggedOut)\n return {\n data: arrayReturnTypes.includes(type)\n ? []\n : {},\n };\n throw error;\n });\n });\n }\n catch (e) {\n if (process.env.NODE_ENV !== 'production') {\n console.error(e);\n }\n throw new Error('The dataProvider threw an error. It should return a rejected Promise instead.');\n }\n };\n },\n });\n }, [dataProvider, logoutIfAccessDenied, queryClient]);\n return dataProviderProxy;\n};\nvar isAbortError = function (error) {\n return error instanceof DOMException &&\n error.name === 'AbortError';\n};\n//# sourceMappingURL=useDataProvider.js.map","import React from 'react';\nimport { notifyManager, useQueryClient } from '@tanstack/react-query';\n/**\n * Get the state of the dataProvider connection.\n *\n * Returns true if a query or a mutation is pending.\n *\n * Custom implementation because react-query's useIsFetching and useIsMutating\n * render each time the number of active queries changes, which is too often.\n *\n * @see useIsFetching\n * @see useIsMutating\n */\nexport var useLoading = function () {\n var client = useQueryClient();\n var mountedRef = React.useRef(false);\n var isFetchingRef = React.useRef(client.isFetching() > 0);\n var isMutatingRef = React.useRef(client.isMutating() > 0);\n var _a = React.useState(isFetchingRef.current || isMutatingRef.current), isLoading = _a[0], setIsLoading = _a[1];\n React.useEffect(function () {\n mountedRef.current = true;\n var unsubscribeQueryCache = client.getQueryCache().subscribe(notifyManager.batchCalls(function () {\n if (mountedRef.current) {\n isFetchingRef.current = client.isFetching() > 0;\n setIsLoading(isFetchingRef.current || isMutatingRef.current);\n }\n }));\n var unsubscribeMutationCache = client.getMutationCache().subscribe(notifyManager.batchCalls(function () {\n if (mountedRef.current) {\n isMutatingRef.current = client.isMutating() > 0;\n setIsLoading(isFetchingRef.current || isMutatingRef.current);\n }\n }));\n return function () {\n mountedRef.current = false;\n unsubscribeQueryCache();\n unsubscribeMutationCache();\n };\n }, [client]);\n return isLoading;\n};\n//# sourceMappingURL=useLoading.js.map","import { useCallback } from 'react';\nimport { useQueryClient } from '@tanstack/react-query';\n/**\n * Hook for triggering a page refresh. Returns a callback function.\n *\n * The callback invalidates all queries and refetches the active ones.\n * Any component depending on react-query data will be re-rendered.\n *\n * @example\n *\n * const refresh = useRefresh();\n * const handleClick = () => {\n * refresh();\n * };\n */\nexport var useRefresh = function () {\n var queryClient = useQueryClient();\n return useCallback(function () {\n queryClient.invalidateQueries();\n }, [queryClient]);\n};\n//# sourceMappingURL=useRefresh.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useQuery, } from '@tanstack/react-query';\nimport { useDataProvider } from './useDataProvider';\nimport { useEffect } from 'react';\nimport { useEvent } from '../util';\n/**\n * Call the dataProvider.getOne() method and return the resolved value\n * as well as the loading state.\n *\n * The return value updates according to the request state:\n *\n * - start: { isPending: true, isFetching: true, refetch }\n * - success: { data: [data from response], isPending: false, refetch }\n * - error: { error: [error from response], isPending: false, refetch }\n *\n * This hook will return the cached result when called a second time\n * with the same parameters, until the response arrives.\n *\n * @param resource The resource name, e.g. 'posts'\n * @param {Params} params The getOne parameters { id, meta }, e.g. { id: 123 }\n * @param {Options} options Options object to pass to the react-query queryClient.\n *\n * @typedef Params\n * @prop id a resource identifier, e.g. 123\n *\n * @typedef Options\n * @prop enabled Flag to conditionally run the query. If it's false, the query will not run\n * @prop onSuccess Side effect function to be executed upon success, e.g. { onSuccess: { refresh: true } }\n * @prop onError Side effect function to be executed upon failure, e.g. { onError: error => notify(error.message) }\n *\n * @returns The current request state. Destructure as { data, error, isPending, refetch }.\n *\n * @example\n *\n * import { useGetOne, useRecordContext } from 'react-admin';\n *\n * const UserProfile = () => {\n * const record = useRecordContext();\n * const { data, isPending, error } = useGetOne('users', { id: record.id });\n * if (isPending) { return ; }\n * if (error) { return

ERROR

; }\n * return
User {data.username}
;\n * };\n */\nexport var useGetOne = function (resource, _a, options) {\n var id = _a.id, meta = _a.meta;\n if (options === void 0) { options = {}; }\n var dataProvider = useDataProvider();\n var _b = options.onError, onError = _b === void 0 ? noop : _b, _c = options.onSuccess, onSuccess = _c === void 0 ? noop : _c, _d = options.onSettled, onSettled = _d === void 0 ? noop : _d, enabled = options.enabled, queryOptions = __rest(options, [\"onError\", \"onSuccess\", \"onSettled\", \"enabled\"]);\n var onSuccessEvent = useEvent(onSuccess);\n var onErrorEvent = useEvent(onError);\n var onSettledEvent = useEvent(onSettled);\n var result = useQuery(__assign({ \n // Sometimes the id comes as a string (e.g. when read from the URL in a Show view).\n // Sometimes the id comes as a number (e.g. when read from a Record in useGetList response).\n // As the react-query cache is type-sensitive, we always stringify the identifier to get a match\n queryKey: [resource, 'getOne', { id: String(id), meta: meta }], queryFn: function (queryParams) {\n return id == null\n ? new Promise(function () { })\n : dataProvider\n .getOne(resource, {\n id: id,\n meta: meta,\n signal: dataProvider.supportAbortSignal === true\n ? queryParams.signal\n : undefined,\n })\n .then(function (_a) {\n var data = _a.data;\n return data;\n });\n }, enabled: enabled !== null && enabled !== void 0 ? enabled : id != null }, queryOptions));\n useEffect(function () {\n if (result.data === undefined ||\n result.error != null ||\n result.isFetching)\n return;\n onSuccessEvent(result.data);\n }, [onSuccessEvent, result.data, result.error, result.isFetching]);\n useEffect(function () {\n if (result.error == null || result.isFetching)\n return;\n onErrorEvent(result.error);\n }, [onErrorEvent, result.error, result.isFetching]);\n useEffect(function () {\n if (result.status === 'pending' || result.isFetching)\n return;\n onSettledEvent(result.data, result.error);\n }, [\n onSettledEvent,\n result.data,\n result.error,\n result.status,\n result.isFetching,\n ]);\n return result;\n};\nvar noop = function () { return undefined; };\n//# sourceMappingURL=useGetOne.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useEffect, useMemo, useRef } from 'react';\nimport { useQuery, useQueryClient, } from '@tanstack/react-query';\nimport { useDataProvider } from './useDataProvider';\nimport { useEvent } from '../util';\nvar MAX_DATA_LENGTH_TO_CACHE = 100;\n/**\n * Call the dataProvider.getList() method and return the resolved result\n * as well as the loading state.\n *\n * The return value updates according to the request state:\n *\n * - start: { isPending: true, refetch }\n * - success: { data: [data from store], total: [total from response], isPending: false, refetch }\n * - error: { error: [error from response], isPending: false, refetch }\n *\n * This hook will return the cached result when called a second time\n * with the same parameters, until the response arrives.\n *\n * @param {string} resource The resource name, e.g. 'posts'\n * @param {Params} params The getList parameters { pagination, sort, filter, meta }\n * @param {Object} options Options object to pass to the queryClient.\n * May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } }\n *\n * @typedef Params\n * @prop params.pagination The request pagination { page, perPage }, e.g. { page: 1, perPage: 10 }\n * @prop params.sort The request sort { field, order }, e.g. { field: 'id', order: 'DESC' }\n * @prop params.filter The request filters, e.g. { title: 'hello, world' }\n * @prop params.meta Optional meta parameters\n *\n * @returns The current request state. Destructure as { data, total, error, isPending, refetch }.\n *\n * @example\n *\n * import { useGetList } from 'react-admin';\n *\n * const LatestNews = () => {\n * const { data, total, isPending, error } = useGetList(\n * 'posts',\n * { pagination: { page: 1, perPage: 10 }, sort: { field: 'published_at', order: 'DESC' } }\n * );\n * if (isPending) { return ; }\n * if (error) { return

ERROR

; }\n * return
    {data.map(item =>\n *
  • {item.title}
  • \n * )}
;\n * };\n */\nexport var useGetList = function (resource, params, options) {\n if (params === void 0) { params = {}; }\n if (options === void 0) { options = {}; }\n var _a = params.pagination, pagination = _a === void 0 ? { page: 1, perPage: 25 } : _a, _b = params.sort, sort = _b === void 0 ? { field: 'id', order: 'DESC' } : _b, _c = params.filter, filter = _c === void 0 ? {} : _c, meta = params.meta;\n var dataProvider = useDataProvider();\n var queryClient = useQueryClient();\n var _d = options.onError, onError = _d === void 0 ? noop : _d, _e = options.onSuccess, onSuccess = _e === void 0 ? noop : _e, _f = options.onSettled, onSettled = _f === void 0 ? noop : _f, queryOptions = __rest(options, [\"onError\", \"onSuccess\", \"onSettled\"]);\n var onSuccessEvent = useEvent(onSuccess);\n var onErrorEvent = useEvent(onError);\n var onSettledEvent = useEvent(onSettled);\n var result = useQuery(__assign({ queryKey: [resource, 'getList', { pagination: pagination, sort: sort, filter: filter, meta: meta }], queryFn: function (queryParams) {\n return dataProvider\n .getList(resource, {\n pagination: pagination,\n sort: sort,\n filter: filter,\n meta: meta,\n signal: dataProvider.supportAbortSignal === true\n ? queryParams.signal\n : undefined,\n })\n .then(function (_a) {\n var data = _a.data, total = _a.total, pageInfo = _a.pageInfo, meta = _a.meta;\n return ({\n data: data,\n total: total,\n pageInfo: pageInfo,\n meta: meta,\n });\n });\n } }, queryOptions));\n var metaValue = useRef(meta);\n var resourceValue = useRef(resource);\n useEffect(function () {\n metaValue.current = meta;\n }, [meta]);\n useEffect(function () {\n resourceValue.current = resource;\n }, [resource]);\n useEffect(function () {\n var _a;\n if (result.data === undefined ||\n result.error != null ||\n result.isFetching)\n return;\n // optimistically populate the getOne cache\n if (((_a = result.data) === null || _a === void 0 ? void 0 : _a.data) &&\n result.data.data.length <= MAX_DATA_LENGTH_TO_CACHE) {\n result.data.data.forEach(function (record) {\n queryClient.setQueryData([\n resourceValue.current,\n 'getOne',\n { id: String(record.id), meta: metaValue.current },\n ], function (oldRecord) { return oldRecord !== null && oldRecord !== void 0 ? oldRecord : record; });\n });\n }\n onSuccessEvent(result.data);\n }, [\n onSuccessEvent,\n queryClient,\n result.data,\n result.error,\n result.isFetching,\n ]);\n useEffect(function () {\n if (result.error == null || result.isFetching)\n return;\n onErrorEvent(result.error);\n }, [onErrorEvent, result.error, result.isFetching]);\n useEffect(function () {\n if (result.status === 'pending' || result.isFetching)\n return;\n onSettledEvent(result.data, result.error);\n }, [\n onSettledEvent,\n result.data,\n result.error,\n result.status,\n result.isFetching,\n ]);\n return useMemo(function () {\n return result.data\n ? __assign(__assign({}, result), result.data) : result;\n }, [result]);\n};\nvar noop = function () { return undefined; };\n//# sourceMappingURL=useGetList.js.map","var Symbol = require('./_Symbol'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray');\n\n/** Built-in value references. */\nvar spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;\n\n/**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\nfunction isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n}\n\nmodule.exports = isFlattenable;\n","var arrayPush = require('./_arrayPush'),\n isFlattenable = require('./_isFlattenable');\n\n/**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\nfunction baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n}\n\nmodule.exports = baseFlatten;\n","/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = baseFindIndex;\n","/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nmodule.exports = baseIsNaN;\n","/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = strictIndexOf;\n","var baseFindIndex = require('./_baseFindIndex'),\n baseIsNaN = require('./_baseIsNaN'),\n strictIndexOf = require('./_strictIndexOf');\n\n/**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n}\n\nmodule.exports = baseIndexOf;\n","var baseIndexOf = require('./_baseIndexOf');\n\n/**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\nmodule.exports = arrayIncludes;\n","/**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n}\n\nmodule.exports = arrayIncludesWith;\n","/**\n * This method returns `undefined`.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Util\n * @example\n *\n * _.times(2, _.noop);\n * // => [undefined, undefined]\n */\nfunction noop() {\n // No operation performed.\n}\n\nmodule.exports = noop;\n","var Set = require('./_Set'),\n noop = require('./noop'),\n setToArray = require('./_setToArray');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\nvar createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n};\n\nmodule.exports = createSet;\n","var SetCache = require('./_SetCache'),\n arrayIncludes = require('./_arrayIncludes'),\n arrayIncludesWith = require('./_arrayIncludesWith'),\n cacheHas = require('./_cacheHas'),\n createSet = require('./_createSet'),\n setToArray = require('./_setToArray');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\nfunction baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n}\n\nmodule.exports = baseUniq;\n","var baseFlatten = require('./_baseFlatten'),\n baseRest = require('./_baseRest'),\n baseUniq = require('./_baseUniq'),\n isArrayLikeObject = require('./isArrayLikeObject');\n\n/**\n * Creates an array of unique values, in order, from all given arrays using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.union([2], [1, 2]);\n * // => [2, 1]\n */\nvar union = baseRest(function(arrays) {\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));\n});\n\nmodule.exports = union;\n","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { useEffect, useMemo, useRef } from 'react';\nimport { useQueryClient, useQuery, } from '@tanstack/react-query';\nimport union from 'lodash/union';\nimport { useDataProvider } from './useDataProvider';\nimport { useEvent } from '../util';\n/**\n * Call the dataProvider.getMany() method and return the resolved result\n * as well as the loading state.\n *\n * The return value updates according to the request state:\n *\n * - start: { isPending: true, isFetching: true, refetch }\n * - success: { data: [data from response], isPending: false, isFetching: false, refetch }\n * - error: { error: [error from response], isPending: false, isFetching: false, refetch }\n *\n * This hook will return the cached result when called a second time\n * with the same parameters, until the response arrives.\n *\n * This hook aggregates and deduplicates calls to the same resource, so for instance, if an app calls:\n *\n * useGetManyAggregate('tags', [1, 2, 3]);\n * useGetManyAggregate('tags', [3, 4]);\n *\n * during the same tick, the hook will only call the dataProvider once with the following parameters:\n *\n * dataProvider.getMany('tags', [1, 2, 3, 4])\n *\n * @param resource The resource name, e.g. 'posts'\n * @param {Params} params The getMany parameters { ids, meta }\n * @param {Object} options Options object to pass to the dataProvider.\n * @param {boolean} options.enabled Flag to conditionally run the query. If it's false, the query will not run\n * @param {Function} options.onSuccess Side effect function to be executed upon success, e.g. { onSuccess: { refresh: true } }\n * @param {Function} options.onError Side effect function to be executed upon failure, e.g. { onError: error => notify(error.message) }\n *\n * @typedef Params\n * @prop params.ids The ids to get, e.g. [123, 456, 789]\n * @prop params.meta Optional meta parameters\n\n * @returns The current request state. Destructure as { data, error, isPending, isFetching, refetch }.\n *\n * @example\n *\n * import { useGetManyAggregate, useRecordContext } from 'react-admin';\n *\n * const PostTags = () => {\n * const record = useRecordContext();\n * const { data, isPending, error } = useGetManyAggregate('tags', { ids: record.tagIds });\n * if (isPending) { return ; }\n * if (error) { return

ERROR

; }\n * return (\n *
    \n * {data.map(tag => (\n *
  • {tag.name}
  • \n * ))}\n *
\n * );\n * };\n */\nexport var useGetManyAggregate = function (resource, params, options) {\n if (options === void 0) { options = {}; }\n var dataProvider = useDataProvider();\n var queryClient = useQueryClient();\n var _a = options.onError, onError = _a === void 0 ? noop : _a, _b = options.onSuccess, onSuccess = _b === void 0 ? noop : _b, _c = options.onSettled, onSettled = _c === void 0 ? noop : _c, enabled = options.enabled, queryOptions = __rest(options, [\"onError\", \"onSuccess\", \"onSettled\", \"enabled\"]);\n var onSuccessEvent = useEvent(onSuccess);\n var onErrorEvent = useEvent(onError);\n var onSettledEvent = useEvent(onSettled);\n var ids = params.ids, meta = params.meta;\n var placeholderData = useMemo(function () {\n var records = (Array.isArray(ids) ? ids : [ids]).map(function (id) {\n return queryClient.getQueryData([\n resource,\n 'getOne',\n { id: String(id), meta: meta },\n ]);\n });\n if (records.some(function (record) { return record === undefined; })) {\n return undefined;\n }\n else {\n return records;\n }\n }, [ids, queryClient, resource, meta]);\n var result = useQuery(__assign({ queryKey: [\n resource,\n 'getMany',\n {\n ids: (Array.isArray(ids) ? ids : [ids]).map(function (id) { return String(id); }),\n meta: meta,\n },\n ], queryFn: function (queryParams) {\n return new Promise(function (resolve, reject) {\n if (!ids || ids.length === 0) {\n // no need to call the dataProvider\n return resolve([]);\n }\n // debounced / batched fetch\n return callGetManyQueries({\n resource: resource,\n ids: ids,\n meta: meta,\n resolve: resolve,\n reject: reject,\n dataProvider: dataProvider,\n queryClient: queryClient,\n signal: dataProvider.supportAbortSignal === true\n ? queryParams.signal\n : undefined,\n });\n });\n }, placeholderData: placeholderData, enabled: enabled !== null && enabled !== void 0 ? enabled : ids != null, retry: false }, queryOptions));\n var metaValue = useRef(meta);\n var resourceValue = useRef(resource);\n useEffect(function () {\n metaValue.current = meta;\n }, [meta]);\n useEffect(function () {\n resourceValue.current = resource;\n }, [resource]);\n useEffect(function () {\n var _a;\n if (result.data === undefined ||\n result.error != null ||\n result.isFetching)\n return;\n // optimistically populate the getOne cache\n ((_a = result.data) !== null && _a !== void 0 ? _a : []).forEach(function (record) {\n queryClient.setQueryData([\n resourceValue.current,\n 'getOne',\n { id: String(record.id), meta: metaValue.current },\n ], function (oldRecord) { return oldRecord !== null && oldRecord !== void 0 ? oldRecord : record; });\n });\n onSuccessEvent(result.data);\n }, [\n queryClient,\n onSuccessEvent,\n result.data,\n result.error,\n result.isFetching,\n ]);\n useEffect(function () {\n if (result.error == null || result.isFetching)\n return;\n onErrorEvent(result.error);\n }, [onErrorEvent, result.error, result.isFetching]);\n useEffect(function () {\n if (result.status === 'pending' || result.isFetching)\n return;\n onSettledEvent(result.data, result.error);\n }, [\n onSettledEvent,\n result.data,\n result.error,\n result.status,\n result.isFetching,\n ]);\n return result;\n};\n/**\n * Batch all calls to a function into one single call with the arguments of all the calls.\n *\n * @example\n * let sum = 0;\n * const add = (args) => { sum = args.reduce((arg, total) => total + arg, 0); };\n * const addBatched = batch(add);\n * addBatched(2);\n * addBatched(8);\n * // add will be called once with arguments [2, 8]\n * // and sum will be equal to 10\n */\nvar batch = function (fn) {\n var capturedArgs = [];\n var timeout = null;\n return function (arg) {\n capturedArgs.push(arg);\n if (timeout)\n clearTimeout(timeout);\n timeout = setTimeout(function () {\n timeout = null;\n fn(__spreadArray([], capturedArgs, true));\n capturedArgs = [];\n }, 0);\n };\n};\n/**\n * Group and execute all calls to the dataProvider.getMany() method for the current tick\n *\n * Thanks to batch(), this function executes at most once per tick,\n * whatever the number of calls to useGetManyAggregate().\n */\nvar callGetManyQueries = batch(function (calls) {\n var dataProvider = calls[0].dataProvider;\n var queryClient = calls[0].queryClient;\n /**\n * Aggregate calls by resource\n *\n * callsByResource will look like:\n * {\n * posts: [{ resource, ids, resolve, reject, dataProvider, queryClient }, ...],\n * tags: [{ resource, ids, resolve, reject, dataProvider, queryClient }, ...],\n * }\n */\n var callsByResource = calls.reduce(function (acc, callArgs) {\n if (!acc[callArgs.resource]) {\n acc[callArgs.resource] = [];\n }\n acc[callArgs.resource].push(callArgs);\n return acc;\n }, {});\n /**\n * For each resource, aggregate ids and call dataProvider.getMany() once\n */\n Object.keys(callsByResource).forEach(function (resource) {\n var callsForResource = callsByResource[resource];\n /**\n * Extract ids from queries, aggregate and deduplicate them\n *\n * @example from [[1, 2], [2, null, 3], [4, null]] to [1, 2, 3, 4]\n */\n var aggregatedIds = callsForResource\n .reduce(function (acc, _a) {\n var ids = _a.ids;\n return union(acc, ids);\n }, []) // concat + unique\n .filter(function (v) { return v != null && v !== ''; }); // remove null values\n var uniqueMeta = callsForResource.reduce(function (acc, _a) {\n var meta = _a.meta;\n return meta || acc;\n }, undefined);\n if (aggregatedIds.length === 0) {\n // no need to call the data provider if all the ids are null\n callsForResource.forEach(function (_a) {\n var resolve = _a.resolve;\n resolve([]);\n });\n return;\n }\n var callThatHasAllAggregatedIds = callsForResource.find(function (_a) {\n var ids = _a.ids, signal = _a.signal;\n return JSON.stringify(ids) === JSON.stringify(aggregatedIds) &&\n !(signal === null || signal === void 0 ? void 0 : signal.aborted);\n });\n if (callThatHasAllAggregatedIds) {\n // There is only one call (no aggregation), or one of the calls has the same ids as the sum of all calls.\n // Either way, we can't trigger a new fetchQuery with the same signature, as it's already pending.\n // Therefore, we reply with the dataProvider\n var dataProvider_1 = callThatHasAllAggregatedIds.dataProvider, resource_1 = callThatHasAllAggregatedIds.resource, ids = callThatHasAllAggregatedIds.ids, meta = callThatHasAllAggregatedIds.meta, signal = callThatHasAllAggregatedIds.signal;\n dataProvider_1\n .getMany(resource_1, { ids: ids, meta: meta, signal: signal })\n .then(function (_a) {\n var data = _a.data;\n return data;\n })\n .then(function (data) {\n // We must then resolve all the pending calls with the data they requested\n callsForResource.forEach(function (_a) {\n var ids = _a.ids, resolve = _a.resolve;\n resolve(data.filter(function (record) {\n return ids\n .map(function (id) { return String(id); })\n .includes(String(record.id));\n }));\n });\n }, function (error) {\n // All pending calls must also receive the error\n callsForResource.forEach(function (_a) {\n var reject = _a.reject;\n reject(error);\n });\n });\n return;\n }\n /**\n * Call dataProvider.getMany() with the aggregatedIds,\n * and resolve each of the promises using the results\n */\n queryClient\n .fetchQuery({\n queryKey: [\n resource,\n 'getMany',\n {\n ids: aggregatedIds.map(function (id) { return String(id); }),\n meta: uniqueMeta,\n },\n ],\n queryFn: function (queryParams) {\n return dataProvider\n .getMany(resource, {\n ids: aggregatedIds,\n meta: uniqueMeta,\n signal: dataProvider.supportAbortSignal === true\n ? queryParams.signal\n : undefined,\n })\n .then(function (_a) {\n var data = _a.data;\n return data;\n });\n },\n })\n .then(function (data) {\n callsForResource.forEach(function (_a) {\n var ids = _a.ids, resolve = _a.resolve;\n resolve(data.filter(function (record) {\n return ids\n .map(function (id) { return String(id); })\n .includes(String(record.id));\n }));\n });\n })\n .catch(function (error) {\n return callsForResource.forEach(function (_a) {\n var reject = _a.reject;\n return reject(error);\n });\n });\n });\n});\nvar noop = function () { return undefined; };\n//# sourceMappingURL=useGetManyAggregate.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useEffect, useMemo } from 'react';\nimport { useQuery, useQueryClient, } from '@tanstack/react-query';\nimport { useDataProvider } from './useDataProvider';\nimport { useEvent } from '../util';\n/**\n * Call the dataProvider.getManyReference() method and return the resolved result\n * as well as the loading state.\n *\n * The return value updates according to the request state:\n *\n * - start: { isPending: true, refetch }\n * - success: { data: [data from store], total: [total from response], isPending: false, refetch }\n * - error: { error: [error from response], isPending: false, refetch }\n *\n * This hook will return the cached result when called a second time\n * with the same parameters, until the response arrives.\n *\n * @param {string} resource The resource name, e.g. 'posts'\n * @param {Params} params The getManyReference parameters { target, id, pagination, sort, filter, meta }\n * @param {Object} options Options object to pass to the queryClient.\n * May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } }\n *\n * @typedef Params\n * @prop params.target The target resource key, e.g. 'post_id'\n * @prop params.id The identifier of the record to look for in target, e.g. '123'\n * @prop params.pagination The request pagination { page, perPage }, e.g. { page: 1, perPage: 10 }\n * @prop params.sort The request sort { field, order }, e.g. { field: 'id', order: 'DESC' }\n * @prop params.filter The request filters, e.g. { title: 'hello, world' }\n * @prop params.meta Optional meta parameters\n *\n * @returns The current request state. Destructure as { data, total, error, isPending, refetch }.\n *\n * @example\n *\n * import { useGetManyReference, useRecordContext } from 'react-admin';\n *\n * const PostComments = () => {\n * const record = useRecordContext();\n * // fetch all comments related to the current record\n * const { data, isPending, error } = useGetManyReference(\n * 'comments',\n * { target: 'post_id', id: record.id, pagination: { page: 1, perPage: 10 }, sort: { field: 'published_at', order: 'DESC' } }\n * );\n * if (isPending) { return ; }\n * if (error) { return

ERROR

; }\n * return
    {data.map(comment =>\n *
  • {comment.body}
  • \n * )}
;\n * };\n */\nexport var useGetManyReference = function (resource, params, options) {\n if (params === void 0) { params = {}; }\n if (options === void 0) { options = {}; }\n var target = params.target, id = params.id, _a = params.pagination, pagination = _a === void 0 ? { page: 1, perPage: 25 } : _a, _b = params.sort, sort = _b === void 0 ? { field: 'id', order: 'DESC' } : _b, _c = params.filter, filter = _c === void 0 ? {} : _c, meta = params.meta;\n var dataProvider = useDataProvider();\n var queryClient = useQueryClient();\n var _d = options.onError, onError = _d === void 0 ? noop : _d, _e = options.onSuccess, onSuccess = _e === void 0 ? noop : _e, _f = options.onSettled, onSettled = _f === void 0 ? noop : _f, queryOptions = __rest(options, [\"onError\", \"onSuccess\", \"onSettled\"]);\n var onSuccessEvent = useEvent(onSuccess);\n var onErrorEvent = useEvent(onError);\n var onSettledEvent = useEvent(onSettled);\n var result = useQuery(__assign({ queryKey: [\n resource,\n 'getManyReference',\n { target: target, id: id, pagination: pagination, sort: sort, filter: filter, meta: meta },\n ], queryFn: function (queryParams) {\n if (!target || id == null) {\n // check at runtime to support partial parameters with the enabled option\n return Promise.reject(new Error('target and id are required'));\n }\n return dataProvider\n .getManyReference(resource, {\n target: target,\n id: id,\n pagination: pagination,\n sort: sort,\n filter: filter,\n meta: meta,\n signal: dataProvider.supportAbortSignal === true\n ? queryParams.signal\n : undefined,\n })\n .then(function (_a) {\n var data = _a.data, total = _a.total, pageInfo = _a.pageInfo, meta = _a.meta;\n return ({\n data: data,\n total: total,\n pageInfo: pageInfo,\n meta: meta,\n });\n });\n } }, queryOptions));\n useEffect(function () {\n var _a, _b;\n if (result.data === undefined)\n return;\n // optimistically populate the getOne cache\n (_b = (_a = result.data) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.forEach(function (record) {\n queryClient.setQueryData([resource, 'getOne', { id: String(record.id), meta: meta }], function (oldRecord) { return oldRecord !== null && oldRecord !== void 0 ? oldRecord : record; });\n });\n onSuccessEvent(result.data);\n }, [queryClient, meta, onSuccessEvent, resource, result.data]);\n useEffect(function () {\n if (result.error == null)\n return;\n onErrorEvent(result.error);\n }, [onErrorEvent, result.error]);\n useEffect(function () {\n if (result.status === 'pending')\n return;\n onSettledEvent(result.data, result.error);\n }, [onSettledEvent, result.data, result.error, result.status]);\n return useMemo(function () {\n return result.data\n ? __assign(__assign({}, result), result.data) : result;\n }, [result]);\n};\nvar noop = function () { return undefined; };\n//# sourceMappingURL=useGetManyReference.js.map","function is(x, y) {\n if (x === y) {\n return x !== 0 || y !== 0 || 1 / x === 1 / y;\n }\n else {\n // eslint-disable-next-line no-self-compare\n return x !== x && y !== y;\n }\n}\nexport var shallowEqual = function (objA, objB) {\n if (is(objA, objB))\n return true;\n if (typeof objA !== 'object' ||\n objA === null ||\n typeof objB !== 'object' ||\n objB === null) {\n return false;\n }\n var keysA = Object.keys(objA);\n var keysB = Object.keys(objB);\n if (keysA.length !== keysB.length)\n return false;\n for (var i = 0; i < keysA.length; i++) {\n if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) ||\n !is(objA[keysA[i]], objB[keysA[i]])) {\n return false;\n }\n }\n return true;\n};\n//# sourceMappingURL=shallowEqual.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport { shallowEqual } from './shallowEqual';\nvar isObject = function (obj) {\n return obj && Object.prototype.toString.call(obj) === '[object Object]';\n};\nvar isEmpty = function (obj) {\n return obj instanceof Date\n ? false\n : obj === '' ||\n obj === null ||\n obj === undefined ||\n shallowEqual(obj, {});\n};\nvar removeEmpty = function (object) {\n return Object.keys(object).reduce(function (acc, key) {\n var _a;\n var child = object[key];\n if (isObject(object[key])) {\n child = removeEmpty(object[key]);\n }\n return isEmpty(child) ? acc : __assign(__assign({}, acc), (_a = {}, _a[key] = child, _a));\n }, {});\n};\nexport default removeEmpty;\n//# sourceMappingURL=removeEmpty.js.map","var removeKey = function (target, path) {\n return Object.keys(target).reduce(function (acc, key) {\n var _a;\n if (key !== path) {\n return Object.assign({}, acc, (_a = {}, _a[key] = target[key], _a));\n }\n return acc;\n }, {});\n};\nvar deepRemoveKey = function (target, path) {\n var _a;\n var paths = path.split('.');\n if (paths.length === 1) {\n return removeKey(target, path);\n }\n var deepKey = paths[0];\n if (target[deepKey] === undefined) {\n return target;\n }\n var deep = deepRemoveKey(target[deepKey], paths.slice(1).join('.'));\n if (Object.keys(deep).length === 0) {\n return removeKey(target, deepKey);\n }\n return Object.assign({}, target, (_a = {}, _a[deepKey] = deep, _a));\n};\nexport default deepRemoveKey;\n//# sourceMappingURL=removeKey.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport set from 'lodash/set';\nimport removeEmpty from '../../util/removeEmpty';\nimport removeKey from '../../util/removeKey';\nexport var SET_SORT = 'SET_SORT';\nexport var SORT_ASC = 'ASC';\nexport var SORT_DESC = 'DESC';\nexport var SET_PAGE = 'SET_PAGE';\nexport var SET_PER_PAGE = 'SET_PER_PAGE';\nexport var SET_FILTER = 'SET_FILTER';\nexport var SHOW_FILTER = 'SHOW_FILTER';\nexport var HIDE_FILTER = 'HIDE_FILTER';\nvar oppositeOrder = function (direction) {\n return direction === SORT_DESC ? SORT_ASC : SORT_DESC;\n};\n/**\n * This reducer is for the react-router query string.\n */\nexport var queryReducer = function (previousState, action) {\n var _a;\n var _b;\n switch (action.type) {\n case SET_SORT:\n if (action.payload.field === previousState.sort) {\n return __assign(__assign({}, previousState), { order: (_b = action.payload.order) !== null && _b !== void 0 ? _b : oppositeOrder(previousState.order), page: 1 });\n }\n return __assign(__assign({}, previousState), { sort: action.payload.field, order: action.payload.order || SORT_ASC, page: 1 });\n case SET_PAGE:\n return __assign(__assign({}, previousState), { page: action.payload });\n case SET_PER_PAGE:\n return __assign(__assign({}, previousState), { page: 1, perPage: action.payload });\n case SET_FILTER: {\n return __assign(__assign({}, previousState), { page: 1, filter: action.payload.filter, displayedFilters: action.payload.displayedFilters\n ? action.payload.displayedFilters\n : previousState.displayedFilters });\n }\n case SHOW_FILTER: {\n if (previousState.displayedFilters &&\n previousState.displayedFilters[action.payload.filterName]) {\n // the filter is already shown\n return previousState;\n }\n return __assign(__assign({}, previousState), { filter: typeof action.payload.defaultValue !== 'undefined'\n ? set(previousState.filter, action.payload.filterName, action.payload.defaultValue)\n : previousState.filter, \n // we don't use lodash.set() for displayed filters\n // to avoid problems with compound filter names (e.g. 'author.name')\n displayedFilters: __assign(__assign({}, previousState.displayedFilters), (_a = {}, _a[action.payload.filterName] = true, _a)) });\n }\n case HIDE_FILTER: {\n return __assign(__assign({}, previousState), { filter: removeEmpty(removeKey(previousState.filter, action.payload)), \n // we don't use lodash.set() for displayed filters\n // to avoid problems with compound filter names (e.g. 'author.name')\n displayedFilters: previousState.displayedFilters\n ? Object.keys(previousState.displayedFilters).reduce(function (filters, filter) {\n var _a;\n return filter !== action.payload\n ? __assign(__assign({}, filters), (_a = {}, _a[filter] = true, _a)) : filters;\n }, {})\n : previousState.displayedFilters });\n }\n default:\n return previousState;\n }\n};\nexport default queryReducer;\n//# sourceMappingURL=queryReducer.js.map","import { useReducer, useEffect, useRef, useCallback } from 'react';\nimport { SORT_ASC, SORT_DESC } from './list/queryReducer';\nvar sortReducer = function (state, action) {\n switch (action.type) {\n case 'SET_SORT':\n return action.payload;\n case 'SET_SORT_FIELD': {\n var field = action.payload;\n var order = state.field === field\n ? state.order === SORT_ASC\n ? SORT_DESC\n : SORT_ASC\n : SORT_ASC;\n return { field: field, order: order };\n }\n case 'SET_SORT_ORDER': {\n var order = action.payload;\n if (!state.field) {\n throw new Error('cannot change the order on an undefined sort field');\n }\n return {\n field: state.field,\n order: order,\n };\n }\n default:\n return state;\n }\n};\nexport var defaultSort = { field: '', order: 'ASC' };\n/**\n * Set the sort { field, order }\n * @name setSort\n * @function\n * @param {SortPayload} sort the sort object\n */\n/**\n * Set the sort field, swap the order if the field is the same\n * @name setSortField\n * @function\n * @param {string} field the sort field\n */\n/**\n * Set the sort order\n * @name setSortOrder\n * @function\n * @param {string} order The sort order, either ASC or DESC\n */\n/**\n * @typedef SortProps\n * @type {Object}\n * @property {Object} sort: the sort object.\n * @property {string} sort.field: the sort object.\n * @property {'ASC' | 'DESC'} sort.order: the sort object.\n * @property {setSort} setSort\n * @property {setSortField} setSortField\n * @property {setSortOrder} setSortOrder\n */\n/**\n * Hooks to provide sort state\n *\n * @example\n *\n * const { sort, setSort, setSortField, setSortOrder } = useSort({\n * field: 'name',\n * order: 'ASC',\n * });\n *\n * setSort({ field: 'name', order: 'ASC' });\n * // is the same as\n * setSortField('name');\n * setSortOrder('ASC');\n *\n * @param {Object} initialSort\n * @param {string} initialSort.field The initial sort field\n * @param {string} initialSort.order The initial sort order\n * @returns {SortProps} The sort props\n */\nvar useSortState = function (initialSort) {\n if (initialSort === void 0) { initialSort = defaultSort; }\n var _a = useReducer(sortReducer, initialSort), sort = _a[0], dispatch = _a[1];\n var isFirstRender = useRef(true);\n useEffect(function () {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n dispatch({ type: 'SET_SORT', payload: initialSort });\n }, [initialSort.field, initialSort.order]); // eslint-disable-line react-hooks/exhaustive-deps\n return {\n setSort: useCallback(function (sort) {\n return dispatch({ type: 'SET_SORT', payload: sort });\n }, [dispatch]),\n setSortField: useCallback(function (field) {\n return dispatch({ type: 'SET_SORT_FIELD', payload: field });\n }, [dispatch]),\n setSortOrder: useCallback(function (order) {\n return dispatch({ type: 'SET_SORT_ORDER', payload: order });\n }, [dispatch]),\n sort: sort,\n };\n};\nexport default useSortState;\n//# sourceMappingURL=useSortState.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport { useEffect, useReducer, useCallback, useRef } from 'react';\nvar paginationReducer = function (prevState, nextState) {\n return __assign(__assign({}, prevState), nextState);\n};\nvar defaultPagination = {\n page: 1,\n perPage: 25,\n};\n/**\n * Hooks to provide pagination state (page and perPage)\n *\n * @example\n *\n * const { page, setPage, perPage, setPerPage } = usePagination(initialPerPage);\n *\n * @param {number} initialPagination the initial value per page\n * @returns {PaginationHookResult} The pagination props\n */\nexport default (function (initialPagination) {\n if (initialPagination === void 0) { initialPagination = {}; }\n var _a = useReducer(paginationReducer, __assign(__assign({}, defaultPagination), initialPagination)), pagination = _a[0], setPagination = _a[1];\n var isFirstRender = useRef(true);\n var setPerPage = useCallback(function (perPage) { return setPagination({ perPage: perPage, page: 1 }); }, []);\n var setPage = useCallback(function (page) { return setPagination({ page: page }); }, []);\n useEffect(function () {\n if (isFirstRender.current) {\n isFirstRender.current = false;\n return;\n }\n setPerPage(initialPagination.perPage || 25);\n }, [initialPagination.perPage, setPerPage]);\n return {\n page: pagination.page,\n perPage: pagination.perPage,\n pagination: pagination,\n setPage: setPage,\n setPerPage: setPerPage,\n setPagination: setPagination,\n };\n});\n//# sourceMappingURL=usePaginationState.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport * as React from 'react';\nvar checkMinimumRequiredProps = function (displayName, requiredProps) {\n return function (WrappedComponent) {\n return function (props) {\n useCheckMinimumRequiredProps(displayName, requiredProps, props);\n return React.createElement(WrappedComponent, __assign({}, props));\n };\n };\n};\nexport default checkMinimumRequiredProps;\n// Not a hook but named that way to avoid conflicts with the old one\nexport var useCheckMinimumRequiredProps = function (displayName, requiredProps, props) {\n var propNames = Object.keys(props);\n var missingProps = requiredProps.filter(function (prop) { return !propNames.includes(prop); });\n if (missingProps.length > 0) {\n throw new Error(\"<\".concat(displayName, \"> component is not properly configured, some essential props are missing.\\nBe sure to pass the props from the parent. Example:\\n\\nconst My\").concat(displayName, \" = props => (\\n <\").concat(displayName, \" {...props}>\\n);\\n\\nThe missing props are: \").concat(missingProps.join(', ')));\n }\n};\n//# sourceMappingURL=checkMinimumRequiredProps.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useCallback } from 'react';\nimport { useDelete } from '../../dataProvider';\nimport { useUnselect } from '../../controller';\nimport { useRedirect } from '../../routing';\nimport { useNotify } from '../../notification';\nimport { useResourceContext } from '../../core';\nimport { useTranslate } from '../../i18n';\n/**\n * Prepare callback for a Delete button with undo support\n *\n * @example\n *\n * import React from 'react';\n * import ActionDelete from '@mui/icons-material/Delete';\n * import { Button, useDeleteWithUndoController } from 'react-admin';\n *\n * const DeleteButton = ({\n * resource,\n * record,\n * redirect,\n * onClick,\n * ...rest\n * }) => {\n * const { isPending, handleDelete } = useDeleteWithUndoController({\n * resource,\n * record,\n * redirect,\n * onClick,\n * });\n *\n * return (\n * \n * \n * \n * );\n * };\n */\nvar useDeleteWithUndoController = function (props) {\n var record = props.record, _a = props.redirect, redirectTo = _a === void 0 ? 'list' : _a, onClick = props.onClick, _b = props.mutationOptions, mutationOptions = _b === void 0 ? {} : _b, successMessage = props.successMessage;\n var mutationMeta = mutationOptions.meta, otherMutationOptions = __rest(mutationOptions, [\"meta\"]);\n var resource = useResourceContext(props);\n var notify = useNotify();\n var unselect = useUnselect(resource);\n var redirect = useRedirect();\n var translate = useTranslate();\n var _c = useDelete(resource, undefined, {\n onSuccess: function () {\n notify(successMessage !== null && successMessage !== void 0 ? successMessage : \"resources.\".concat(resource, \".notifications.deleted\"), {\n type: 'info',\n messageArgs: {\n smart_count: 1,\n _: translate('ra.notification.deleted', {\n smart_count: 1,\n }),\n },\n undoable: true,\n });\n record && unselect([record.id]);\n redirect(redirectTo, resource);\n },\n onError: function (error) {\n notify(typeof error === 'string'\n ? error\n : (error === null || error === void 0 ? void 0 : error.message) ||\n 'ra.notification.http_error', {\n type: 'error',\n messageArgs: {\n _: typeof error === 'string'\n ? error\n : (error === null || error === void 0 ? void 0 : error.message)\n ? error.message\n : undefined,\n },\n });\n },\n }), deleteOne = _c[0], isPending = _c[1].isPending;\n var handleDelete = useCallback(function (event) {\n event.stopPropagation();\n if (!record) {\n throw new Error('The record cannot be deleted because no record has been passed');\n }\n deleteOne(resource, {\n id: record.id,\n previousData: record,\n meta: mutationMeta,\n }, __assign({ mutationMode: 'undoable' }, otherMutationOptions));\n if (typeof onClick === 'function') {\n onClick(event);\n }\n }, [\n deleteOne,\n mutationMeta,\n otherMutationOptions,\n onClick,\n record,\n resource,\n ]);\n return { isPending: isPending, isLoading: isPending, handleDelete: handleDelete };\n};\nexport default useDeleteWithUndoController;\n//# sourceMappingURL=useDeleteWithUndoController.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useState, useCallback, } from 'react';\nimport { useDelete } from '../../dataProvider';\nimport { useUnselect } from '../../controller';\nimport { useRedirect } from '../../routing';\nimport { useNotify } from '../../notification';\nimport { useResourceContext } from '../../core';\nimport { useTranslate } from '../../i18n';\n/**\n * Prepare a set of callbacks for a delete button guarded by confirmation dialog\n *\n * @example\n *\n * const DeleteButton = ({\n * resource,\n * record,\n * redirect,\n * onClick,\n * ...rest\n * }) => {\n * const {\n * open,\n * isPending,\n * handleDialogOpen,\n * handleDialogClose,\n * handleDelete,\n * } = useDeleteWithConfirmController({\n * resource,\n * record,\n * redirect,\n * onClick,\n * });\n *\n * return (\n * \n * \n * {icon}\n * \n * \n * \n * );\n * };\n */\nvar useDeleteWithConfirmController = function (props) {\n var record = props.record, _a = props.redirect, redirectTo = _a === void 0 ? 'list' : _a, mutationMode = props.mutationMode, onClick = props.onClick, _b = props.mutationOptions, mutationOptions = _b === void 0 ? {} : _b, successMessage = props.successMessage;\n var mutationMeta = mutationOptions.meta, otherMutationOptions = __rest(mutationOptions, [\"meta\"]);\n var resource = useResourceContext(props);\n var _c = useState(false), open = _c[0], setOpen = _c[1];\n var notify = useNotify();\n var unselect = useUnselect(resource);\n var redirect = useRedirect();\n var translate = useTranslate();\n var _d = useDelete(resource, undefined, {\n onSuccess: function () {\n setOpen(false);\n notify(successMessage !== null && successMessage !== void 0 ? successMessage : \"resources.\".concat(resource, \".notifications.deleted\"), {\n type: 'info',\n messageArgs: {\n smart_count: 1,\n _: translate('ra.notification.deleted', {\n smart_count: 1,\n }),\n },\n undoable: mutationMode === 'undoable',\n });\n record && unselect([record.id]);\n redirect(redirectTo, resource);\n },\n onError: function (error) {\n setOpen(false);\n notify(typeof error === 'string'\n ? error\n : (error === null || error === void 0 ? void 0 : error.message) ||\n 'ra.notification.http_error', {\n type: 'error',\n messageArgs: {\n _: typeof error === 'string'\n ? error\n : (error === null || error === void 0 ? void 0 : error.message)\n ? error.message\n : undefined,\n },\n });\n },\n }), deleteOne = _d[0], isPending = _d[1].isPending;\n var handleDialogOpen = function (e) {\n setOpen(true);\n e.stopPropagation();\n };\n var handleDialogClose = function (e) {\n setOpen(false);\n e.stopPropagation();\n };\n var handleDelete = useCallback(function (event) {\n event.stopPropagation();\n if (!record) {\n throw new Error('The record cannot be deleted because no record has been passed');\n }\n deleteOne(resource, {\n id: record.id,\n previousData: record,\n meta: mutationMeta,\n }, __assign({ mutationMode: mutationMode }, otherMutationOptions));\n if (typeof onClick === 'function') {\n onClick(event);\n }\n }, [\n deleteOne,\n mutationMeta,\n mutationMode,\n otherMutationOptions,\n onClick,\n record,\n resource,\n ]);\n return {\n open: open,\n isPending: isPending,\n isLoading: isPending,\n handleDialogOpen: handleDialogOpen,\n handleDialogClose: handleDialogClose,\n handleDelete: handleDelete,\n };\n};\nexport default useDeleteWithConfirmController;\n//# sourceMappingURL=useDeleteWithConfirmController.js.map","import { createContext } from 'react';\nexport var SaveContext = createContext({});\n//# sourceMappingURL=SaveContext.js.map","import * as React from 'react';\nimport { SaveContext } from './SaveContext';\nexport var SaveContextProvider = function (_a) {\n var children = _a.children, value = _a.value;\n return (React.createElement(SaveContext.Provider, { value: value }, children));\n};\n//# sourceMappingURL=SaveContextProvider.js.map","var basePickBy = require('./_basePickBy'),\n hasIn = require('./hasIn');\n\n/**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @returns {Object} Returns the new object.\n */\nfunction basePick(object, paths) {\n return basePickBy(object, paths, function(value, path) {\n return hasIn(object, path);\n });\n}\n\nmodule.exports = basePick;\n","var baseFlatten = require('./_baseFlatten');\n\n/**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\nfunction flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n}\n\nmodule.exports = flatten;\n","var flatten = require('./flatten'),\n overRest = require('./_overRest'),\n setToString = require('./_setToString');\n\n/**\n * A specialized version of `baseRest` which flattens the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\nfunction flatRest(func) {\n return setToString(overRest(func, undefined, flatten), func + '');\n}\n\nmodule.exports = flatRest;\n","var basePick = require('./_basePick'),\n flatRest = require('./_flatRest');\n\n/**\n * Creates an object composed of the picked `object` properties.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pick(object, ['a', 'c']);\n * // => { 'a': 1, 'c': 3 }\n */\nvar pick = flatRest(function(object, paths) {\n return object == null ? {} : basePick(object, paths);\n});\n\nmodule.exports = pick;\n","import { useMemo } from 'react';\nimport pick from 'lodash/pick';\n/**\n * This hook extracts the `save`, `saving` and mutationMode properties from either the `CreateContext` or `EditContext`. This ensures the `SaveContext` doesn't rerender when those two contexts have other properties changes.\n */\nexport var usePickSaveContext = function (context) {\n var value = useMemo(function () {\n return pick(context, [\n 'save',\n 'saving',\n 'mutationMode',\n 'registerMutationMiddleware',\n 'unregisterMutationMiddleware',\n ]);\n }, \n /* eslint-disable react-hooks/exhaustive-deps */\n [\n context.save,\n context.saving,\n context.mutationMode,\n context.registerMutationMiddleware,\n context.unregisterMutationMiddleware,\n ]\n /* eslint-enable react-hooks/exhaustive-deps */\n );\n return value;\n};\n//# sourceMappingURL=usePickSaveContext.js.map","import { useContext } from 'react';\nimport { SaveContext } from './SaveContext';\n/**\n * Get the save() function and its status\n *\n * Used in forms.\n *\n * @example\n *\n * const {\n * save,\n * saving\n * } = useSaveContext();\n */\nexport var useSaveContext = function (_props) {\n return useContext(SaveContext);\n};\n//# sourceMappingURL=useSaveContext.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { useCallback, useMemo, useRef } from 'react';\n/**\n * Internal hook used to handle mutation middlewares.\n *\n * @example\n * // We have a form creating an order for a new customer.\n * // The form contains the customer fields in addition to the order fields\n * // but they should be saved as a new customer resource record\n * // and the order should only reference this new customer\n * type Order = { id: string; reference: string };\n * type OrderCreateFormData = { id: string; reference: string; customer: Customer };\n * type Customer = { id: string; email: string; firstName: string; lastName: string };\n *\n * const CustomerForm = props => {\n * const [createCustomer] = useCreate();\n * const middleware: Middleware[0]> = useCallback(async (resource, params, next) => {\n * const { data } = params;\n * const { user, ...orderData } = data;\n * const { data = newCustomer } = await createCustomer('customers', { data: user });\n * const orderDataWithCustomer = { ...orderData, customerId: newCustomer.id };\n * next(resource, { data: orderDataWithCustomer });\n * }, [createCustomer]);\n * useRegisterMutationMiddleware(middleware);\n *\n * return (\n * <>\n * \n * \n * \n * \n * );\n * }\n */\nexport var useMutationMiddlewares = function () {\n var callbacks = useRef([]);\n var registerMutationMiddleware = useCallback(function (callback) {\n callbacks.current.push(callback);\n }, []);\n var unregisterMutationMiddleware = useCallback(function (callback) {\n callbacks.current = callbacks.current.filter(function (cb) { return cb !== callback; });\n }, []);\n var getMutateWithMiddlewares = useCallback(function (fn) {\n // Stores the current callbacks in a closure to avoid losing them if the calling component is unmounted\n var currentCallbacks = __spreadArray([], callbacks.current, true);\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n var index = currentCallbacks.length - 1;\n // Called by middlewares to call the next middleware function\n // Should take the same arguments as the original mutation function\n var next = function () {\n var newArgs = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n newArgs[_i] = arguments[_i];\n }\n // Decrement the middlewares counter so that when next is called again, we\n // call the next middleware\n index--;\n // If there are no more middlewares, we call the original mutation function\n if (index >= 0) {\n return currentCallbacks[index].apply(currentCallbacks, __spreadArray(__spreadArray([], newArgs, false), [next], false));\n }\n else {\n return fn.apply(void 0, newArgs);\n }\n };\n if (currentCallbacks.length > 0) {\n // Call the first middleware with the same args as the original mutation function\n // with an additional next function\n return currentCallbacks[index].apply(currentCallbacks, __spreadArray(__spreadArray([], args, false), [next], false));\n }\n return fn.apply(void 0, args);\n };\n }, []);\n var functions = useMemo(function () { return ({\n registerMutationMiddleware: registerMutationMiddleware,\n getMutateWithMiddlewares: getMutateWithMiddlewares,\n unregisterMutationMiddleware: unregisterMutationMiddleware,\n }); }, [\n registerMutationMiddleware,\n getMutateWithMiddlewares,\n unregisterMutationMiddleware,\n ]);\n return functions;\n};\n//# sourceMappingURL=useMutationMiddlewares.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useCallback } from 'react';\nimport { useAuthenticated, useRequireAccess } from '../../auth';\nimport { HttpError, useCreate, } from '../../dataProvider';\nimport { useRedirect } from '../../routing';\nimport { useNotify } from '../../notification';\nimport { useMutationMiddlewares, } from '../saveContext';\nimport { useTranslate } from '../../i18n';\nimport { useResourceContext, useResourceDefinition, useGetResourceLabel, } from '../../core';\n/**\n * Prepare data for the Create view\n *\n * @param {Object} props The props passed to the Create component.\n *\n * @return {Object} controllerProps Fetched data and callbacks for the Create view\n *\n * @example\n *\n * import { useCreateController } from 'react-admin';\n * import CreateView from './CreateView';\n *\n * const MyCreate = props => {\n * const controllerProps = useCreateController(props);\n * return ;\n * }\n */\nexport var useCreateController = function (props) {\n if (props === void 0) { props = {}; }\n var disableAuthentication = props.disableAuthentication, record = props.record, redirectTo = props.redirect, transform = props.transform, _a = props.mutationOptions, mutationOptions = _a === void 0 ? {} : _a;\n var resource = useResourceContext(props);\n if (!resource) {\n throw new Error('useCreateController requires a non-empty resource prop or context');\n }\n var isPendingAuthenticated = useAuthenticated({\n enabled: !disableAuthentication,\n }).isPending;\n var isPendingCanAccess = useRequireAccess({\n action: 'create',\n resource: resource,\n // If disableAuthentication is true then isPendingAuthenticated will always be true so this hook is disabled\n enabled: !isPendingAuthenticated,\n }).isPending;\n var _b = useResourceDefinition(props), hasEdit = _b.hasEdit, hasShow = _b.hasShow;\n var finalRedirectTo = redirectTo !== null && redirectTo !== void 0 ? redirectTo : getDefaultRedirectRoute(hasShow, hasEdit);\n var translate = useTranslate();\n var notify = useNotify();\n var redirect = useRedirect();\n var onSuccess = mutationOptions.onSuccess, onError = mutationOptions.onError, meta = mutationOptions.meta, otherMutationOptions = __rest(mutationOptions, [\"onSuccess\", \"onError\", \"meta\"]);\n var _c = useMutationMiddlewares(), registerMutationMiddleware = _c.registerMutationMiddleware, getMutateWithMiddlewares = _c.getMutateWithMiddlewares, unregisterMutationMiddleware = _c.unregisterMutationMiddleware;\n var _d = useCreate(resource, undefined, __assign(__assign({ onSuccess: function (data, variables, context) { return __awaiter(void 0, void 0, void 0, function () {\n return __generator(this, function (_a) {\n if (onSuccess) {\n return [2 /*return*/, onSuccess(data, variables, context)];\n }\n notify(\"resources.\".concat(resource, \".notifications.created\"), {\n type: 'info',\n messageArgs: {\n smart_count: 1,\n _: translate(\"ra.notification.created\", {\n smart_count: 1,\n }),\n },\n });\n redirect(finalRedirectTo, resource, data.id, data);\n return [2 /*return*/];\n });\n }); }, onError: function (error, variables, context) {\n var _a;\n if (onError) {\n return onError(error, variables, context);\n }\n // Don't trigger a notification if this is a validation error\n // (notification will be handled by the useNotifyIsFormInvalid hook)\n var validationErrors = (_a = error === null || error === void 0 ? void 0 : error.body) === null || _a === void 0 ? void 0 : _a.errors;\n var hasValidationErrors = !!validationErrors && Object.keys(validationErrors).length > 0;\n if (!hasValidationErrors) {\n notify(typeof error === 'string'\n ? error\n : error.message ||\n 'ra.notification.http_error', {\n type: 'error',\n messageArgs: {\n _: typeof error === 'string'\n ? error\n : error instanceof Error ||\n (typeof error === 'object' &&\n error !== null &&\n error.hasOwnProperty('message'))\n ? // @ts-ignore\n error.message\n : undefined,\n },\n });\n }\n } }, otherMutationOptions), { returnPromise: true, getMutateWithMiddlewares: getMutateWithMiddlewares })), create = _d[0], saving = _d[1].isPending;\n var save = useCallback(function (data, _a) {\n if (_a === void 0) { _a = {}; }\n var transformFromSave = _a.transform, metaFromSave = _a.meta, callTimeOptions = __rest(_a, [\"transform\", \"meta\"]);\n return Promise.resolve(transformFromSave\n ? transformFromSave(data)\n : transform\n ? transform(data)\n : data).then(function (data) { return __awaiter(void 0, void 0, void 0, function () {\n var error_1;\n var _a;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n _b.trys.push([0, 2, , 3]);\n return [4 /*yield*/, create(resource, { data: data, meta: metaFromSave !== null && metaFromSave !== void 0 ? metaFromSave : meta }, callTimeOptions)];\n case 1:\n _b.sent();\n return [3 /*break*/, 3];\n case 2:\n error_1 = _b.sent();\n if ((error_1 instanceof HttpError ||\n (typeof error_1 === 'object' &&\n error_1 !== null &&\n error_1.hasOwnProperty('body'))) &&\n ((_a = error_1.body) === null || _a === void 0 ? void 0 : _a.errors) != null) {\n return [2 /*return*/, error_1.body.errors];\n }\n return [3 /*break*/, 3];\n case 3: return [2 /*return*/];\n }\n });\n }); });\n }, [create, meta, resource, transform]);\n var getResourceLabel = useGetResourceLabel();\n var defaultTitle = translate('ra.page.create', {\n name: getResourceLabel(resource, 1),\n });\n return {\n isFetching: false,\n isLoading: false,\n isPending: disableAuthentication ? false : isPendingCanAccess,\n saving: saving,\n defaultTitle: defaultTitle,\n save: save,\n record: record,\n resource: resource,\n redirect: finalRedirectTo,\n registerMutationMiddleware: registerMutationMiddleware,\n unregisterMutationMiddleware: unregisterMutationMiddleware,\n };\n};\nvar getDefaultRedirectRoute = function (hasShow, hasEdit) {\n if (hasEdit) {\n return 'edit';\n }\n if (hasShow) {\n return 'show';\n }\n return 'list';\n};\n//# sourceMappingURL=useCreateController.js.map","import { createContext } from 'react';\n/**\n * Context to store the result of the useCreateController() hook.\n *\n * Use the useCreateContext() hook to read the context. That's what the Create components do in react-admin.\n *\n * @example\n *\n * import { useCreateController, CreateContextProvider } from 'ra-core';\n *\n * const Create = props => {\n * const controllerProps = useCreateController(props);\n * return (\n * \n * ...\n * \n * );\n * };\n */\nexport var CreateContext = createContext(null);\nCreateContext.displayName = 'CreateContext';\n//# sourceMappingURL=CreateContext.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport * as React from 'react';\nimport { RecordContextProvider } from '../record/RecordContext';\nimport { CreateContext } from './CreateContext';\nimport { SaveContextProvider, usePickSaveContext } from '../saveContext';\n/**\n * Create a Create Context.\n *\n * @example\n *\n * const MyCreate = (props) => {\n * const controllerProps = useCreateController(props);\n * return (\n * \n * \n * \n * );\n * };\n *\n * const MyCreateView = () => {\n * const record = useRecordContext();\n * // or, to rerender only when the save operation change but not data\n * const { saving } = useCreateContext();\n * }\n *\n * @see CreateContext\n * @see RecordContext\n */\nexport var CreateContextProvider = function (_a) {\n var children = _a.children, value = _a.value;\n return (React.createElement(CreateContext.Provider, { value: value },\n React.createElement(SaveContextProvider, { value: __assign(__assign({}, usePickSaveContext(value)), { mutationMode: 'pessimistic' }) },\n React.createElement(RecordContextProvider, { value: value && value.record }, children))));\n};\n//# sourceMappingURL=CreateContextProvider.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport * as React from 'react';\nimport { useCreateController, } from './useCreateController';\nimport { CreateContextProvider } from './CreateContextProvider';\nimport { OptionalResourceContextProvider } from '../../core';\nimport { useIsAuthPending } from '../../auth';\n/**\n * Call useCreateController and put the value in a CreateContext\n *\n * Base class for components, without UI.\n *\n * Accepts any props accepted by useCreateController:\n * - id: The record identifier\n * - resource: The resource\n *\n * @example // Custom edit layout\n *\n * const PostCreate = () => (\n * \n * \n * \n * \n * ...\n * \n * \n * \n * Create instructions...\n * \n * \n *
\n * Post related links...\n *
\n *
\n * );\n */\nexport var CreateBase = function (_a) {\n var children = _a.children, _b = _a.loading, loading = _b === void 0 ? null : _b, props = __rest(_a, [\"children\", \"loading\"]);\n var controllerProps = useCreateController(props);\n var isAuthPending = useIsAuthPending({\n resource: controllerProps.resource,\n action: 'create',\n });\n if (isAuthPending && !props.disableAuthentication) {\n return loading;\n }\n return (\n // We pass props.resource here as we don't need to create a new ResourceContext if the props is not provided\n React.createElement(OptionalResourceContextProvider, { value: props.resource },\n React.createElement(CreateContextProvider, { value: controllerProps }, children)));\n};\n//# sourceMappingURL=CreateBase.js.map","import { useContext } from 'react';\nimport { CreateContext } from './CreateContext';\n/**\n * Hook to read the create controller props from the CreateContext.\n *\n * Used within a (e.g. as a descendent of ).\n *\n * @returns {CreateControllerResult} create controller props\n *\n * @see useCreateController for how it is filled\n */\nexport var useCreateContext = function () {\n var context = useContext(CreateContext);\n if (!context) {\n throw new Error('useCreateContext must be used inside a CreateContextProvider');\n }\n return context;\n};\n//# sourceMappingURL=useCreateContext.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useCallback } from 'react';\nimport { useParams } from 'react-router-dom';\nimport { useAuthenticated, useRequireAccess } from '../../auth';\nimport { useRedirect } from '../../routing';\nimport { useNotify } from '../../notification';\nimport { useGetOne, useUpdate, useRefresh, } from '../../dataProvider';\nimport { useTranslate } from '../../i18n';\nimport { useResourceContext, useGetResourceLabel, useGetRecordRepresentation, } from '../../core';\nimport { useMutationMiddlewares, } from '../saveContext';\n/**\n * Prepare data for the Edit view.\n *\n * useEditController does a few things:\n * - it grabs the id from the URL and the resource name from the ResourceContext,\n * - it fetches the record via useGetOne,\n * - it prepares the page title.\n *\n * @param {Object} props The props passed to the Edit component.\n *\n * @return {Object} controllerProps Fetched data and callbacks for the Edit view\n *\n * @example\n *\n * import { useEditController } from 'react-admin';\n * import EditView from './EditView';\n *\n * const MyEdit = () => {\n * const controllerProps = useEditController({ resource: 'posts', id: 123 });\n * return ;\n * }\n */\nexport var useEditController = function (props) {\n if (props === void 0) { props = {}; }\n var _a = props.disableAuthentication, disableAuthentication = _a === void 0 ? false : _a, propsId = props.id, _b = props.mutationMode, mutationMode = _b === void 0 ? 'undoable' : _b, _c = props.mutationOptions, mutationOptions = _c === void 0 ? {} : _c, _d = props.queryOptions, queryOptions = _d === void 0 ? {} : _d, _e = props.redirect, redirectTo = _e === void 0 ? DefaultRedirect : _e, transform = props.transform;\n var resource = useResourceContext(props);\n if (!resource) {\n throw new Error('useEditController requires a non-empty resource prop or context');\n }\n var isPendingAuthenticated = useAuthenticated({\n enabled: !disableAuthentication,\n }).isPending;\n var isPendingCanAccess = useRequireAccess({\n action: 'edit',\n resource: resource,\n // If disableAuthentication is true then isPendingAuthenticated will always be true so this hook is disabled\n enabled: !isPendingAuthenticated,\n }).isPending;\n var getRecordRepresentation = useGetRecordRepresentation(resource);\n var translate = useTranslate();\n var notify = useNotify();\n var redirect = useRedirect();\n var refresh = useRefresh();\n var routeId = useParams().id;\n if (!routeId && !propsId) {\n throw new Error('useEditController requires an id prop or a route with an /:id? parameter.');\n }\n var id = propsId !== null && propsId !== void 0 ? propsId : routeId;\n var queryMeta = queryOptions.meta, otherQueryOptions = __rest(queryOptions, [\"meta\"]);\n var mutationMeta = mutationOptions.meta, onSuccess = mutationOptions.onSuccess, onError = mutationOptions.onError, otherMutationOptions = __rest(mutationOptions, [\"meta\", \"onSuccess\", \"onError\"]);\n var _f = useMutationMiddlewares(), registerMutationMiddleware = _f.registerMutationMiddleware, getMutateWithMiddlewares = _f.getMutateWithMiddlewares, unregisterMutationMiddleware = _f.unregisterMutationMiddleware;\n var _g = useGetOne(resource, { id: id, meta: queryMeta }, __assign({ enabled: (!isPendingAuthenticated && !isPendingCanAccess) ||\n disableAuthentication, onError: function () {\n notify('ra.notification.item_doesnt_exist', {\n type: 'error',\n });\n redirect('list', resource);\n refresh();\n }, refetchOnReconnect: false, refetchOnWindowFocus: false, retry: false }, otherQueryOptions)), record = _g.data, error = _g.error, isLoading = _g.isLoading, isFetching = _g.isFetching, isPending = _g.isPending, refetch = _g.refetch;\n // eslint-disable-next-line eqeqeq\n if (record && record.id && record.id != id) {\n throw new Error(\"useEditController: Fetched record's id attribute (\".concat(record.id, \") must match the requested 'id' (\").concat(id, \")\"));\n }\n var getResourceLabel = useGetResourceLabel();\n var recordRepresentation = getRecordRepresentation(record);\n var defaultTitle = translate('ra.page.edit', {\n name: getResourceLabel(resource, 1),\n id: id,\n record: record,\n recordRepresentation: typeof recordRepresentation === 'string'\n ? recordRepresentation\n : '',\n });\n var recordCached = { id: id, previousData: record };\n var _h = useUpdate(resource, recordCached, __assign(__assign({ onSuccess: function (data, variables, context) { return __awaiter(void 0, void 0, void 0, function () {\n return __generator(this, function (_a) {\n if (onSuccess) {\n return [2 /*return*/, onSuccess(data, variables, context)];\n }\n notify(\"resources.\".concat(resource, \".notifications.updated\"), {\n type: 'info',\n messageArgs: {\n smart_count: 1,\n _: translate('ra.notification.updated', {\n smart_count: 1,\n }),\n },\n undoable: mutationMode === 'undoable',\n });\n redirect(redirectTo, resource, data.id, data);\n return [2 /*return*/];\n });\n }); }, onError: function (error, variables, context) {\n var _a;\n if (onError) {\n return onError(error, variables, context);\n }\n // Don't trigger a notification if this is a validation error\n // (notification will be handled by the useNotifyIsFormInvalid hook)\n var validationErrors = (_a = error === null || error === void 0 ? void 0 : error.body) === null || _a === void 0 ? void 0 : _a.errors;\n var hasValidationErrors = !!validationErrors &&\n Object.keys(validationErrors).length > 0;\n if (!hasValidationErrors || mutationMode !== 'pessimistic') {\n notify(typeof error === 'string'\n ? error\n : error.message ||\n 'ra.notification.http_error', {\n type: 'error',\n messageArgs: {\n _: typeof error === 'string'\n ? error\n : error instanceof Error ||\n (typeof error === 'object' &&\n error !== null &&\n error.hasOwnProperty('message'))\n ? // @ts-ignore\n error.message\n : undefined,\n },\n });\n }\n } }, otherMutationOptions), { mutationMode: mutationMode, returnPromise: mutationMode === 'pessimistic', getMutateWithMiddlewares: getMutateWithMiddlewares })), update = _h[0], saving = _h[1].isPending;\n var save = useCallback(function (data, _a) {\n var _b = _a === void 0 ? {} : _a, onSuccessFromSave = _b.onSuccess, onErrorFromSave = _b.onError, transformFromSave = _b.transform, metaFromSave = _b.meta;\n return Promise.resolve(transformFromSave\n ? transformFromSave(data, {\n previousData: recordCached.previousData,\n })\n : transform\n ? transform(data, {\n previousData: recordCached.previousData,\n })\n : data).then(function (data) { return __awaiter(void 0, void 0, void 0, function () {\n var error_1;\n var _a;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n _b.trys.push([0, 2, , 3]);\n return [4 /*yield*/, update(resource, {\n id: id,\n data: data,\n meta: metaFromSave !== null && metaFromSave !== void 0 ? metaFromSave : mutationMeta,\n }, {\n onError: onErrorFromSave,\n onSuccess: onSuccessFromSave,\n })];\n case 1:\n _b.sent();\n return [3 /*break*/, 3];\n case 2:\n error_1 = _b.sent();\n if (((_a = error_1.body) === null || _a === void 0 ? void 0 : _a.errors) != null) {\n return [2 /*return*/, error_1.body.errors];\n }\n return [3 /*break*/, 3];\n case 3: return [2 /*return*/];\n }\n });\n }); });\n }, [\n id,\n mutationMeta,\n resource,\n transform,\n update,\n recordCached.previousData,\n ]);\n return {\n defaultTitle: defaultTitle,\n error: error,\n isFetching: isFetching,\n isLoading: isLoading,\n isPending: isPending,\n mutationMode: mutationMode,\n record: record,\n redirect: redirectTo,\n refetch: refetch,\n registerMutationMiddleware: registerMutationMiddleware,\n resource: resource,\n save: save,\n saving: saving,\n unregisterMutationMiddleware: unregisterMutationMiddleware,\n };\n};\nvar DefaultRedirect = 'list';\n//# sourceMappingURL=useEditController.js.map","import * as React from 'react';\nimport { RecordContextProvider } from './RecordContext';\n/**\n * Wrap children with a RecordContext provider only if the value is defined.\n *\n * Allows a component to work outside of a record context.\n *\n * @example\n *\n * import { OptionalRecordContextProvider, TextField } from 'react-admin';\n *\n * const RecordTitle = ({ record }) => (\n * \n * \n * \n * );\n */\nexport var OptionalRecordContextProvider = function (_a) {\n var value = _a.value, children = _a.children;\n return value ? (React.createElement(RecordContextProvider, { value: value }, children)) : (children);\n};\n//# sourceMappingURL=OptionalRecordContextProvider.js.map","import * as React from 'react';\nimport { useGetRecordRepresentation, useResourceContext } from '../../core';\nimport { useRecordContext } from './useRecordContext';\n/**\n * Render the record representation as specified on its parent .\n * @param props The component props\n * @param {string} props.resource The resource name\n * @param {RaRecord} props.record The record to render\n */\nexport var RecordRepresentation = function (props) {\n var record = useRecordContext(props);\n var resource = useResourceContext(props);\n var getRecordRepresentation = useGetRecordRepresentation(resource);\n return React.createElement(React.Fragment, null, getRecordRepresentation(record));\n};\n//# sourceMappingURL=RecordRepresentation.js.map","import { createContext } from 'react';\n/**\n * Context to store the result of the useEditController() hook.\n *\n * Use the useEditContext() hook to read the context. That's what the Edit components do in react-admin.\n *\n * @example\n *\n * import { useEditController, EditContextProvider } from 'ra-core';\n *\n * const Edit = props => {\n * const controllerProps = useEditController(props);\n * return (\n * \n * ...\n * \n * );\n * };\n */\nexport var EditContext = createContext(null);\nEditContext.displayName = 'EditContext';\n//# sourceMappingURL=EditContext.js.map","import * as React from 'react';\nimport { RecordContextProvider } from '../record';\nimport { SaveContextProvider, usePickSaveContext } from '../saveContext';\nimport { EditContext } from './EditContext';\n/**\n * Create an Edit Context.\n *\n * @example\n *\n * const MyEdit = (props) => {\n * const controllerProps = useEditController(props);\n * return (\n * \n * \n * \n * );\n * };\n *\n * const MyEditView = () => {\n * const record = useRecordContext();\n * // or, to rerender only when the save operation change but not data\n * const { saving } = useEditContext();\n * }\n *\n * @see EditContext\n * @see RecordContext\n */\nexport var EditContextProvider = function (_a) {\n var children = _a.children, value = _a.value;\n return (React.createElement(EditContext.Provider, { value: value },\n React.createElement(SaveContextProvider, { value: usePickSaveContext(value) },\n React.createElement(RecordContextProvider, { value: value && value.record }, children))));\n};\n//# sourceMappingURL=EditContextProvider.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport * as React from 'react';\nimport { useEditController } from './useEditController';\nimport { EditContextProvider } from './EditContextProvider';\nimport { OptionalResourceContextProvider } from '../../core';\nimport { useIsAuthPending } from '../../auth';\n/**\n * Call useEditController and put the value in a EditContext\n *\n * Base class for components, without UI.\n *\n * Accepts any props accepted by useEditController:\n * - id: The record identifier\n * - resource: The resource\n *\n * @example // Custom edit layout\n *\n * const PostEdit = () => (\n * \n * \n * \n * \n * ...\n * \n * \n * \n * Edit instructions...\n * \n * \n *
\n * Post related links...\n *
\n *
\n * );\n */\nexport var EditBase = function (_a) {\n var children = _a.children, _b = _a.loading, loading = _b === void 0 ? null : _b, props = __rest(_a, [\"children\", \"loading\"]);\n var controllerProps = useEditController(props);\n var isAuthPending = useIsAuthPending({\n resource: controllerProps.resource,\n action: 'edit',\n });\n if (isAuthPending && !props.disableAuthentication) {\n return loading;\n }\n return (\n // We pass props.resource here as we don't need to create a new ResourceContext if the props is not provided\n React.createElement(OptionalResourceContextProvider, { value: props.resource },\n React.createElement(EditContextProvider, { value: controllerProps }, children)));\n};\n//# sourceMappingURL=EditBase.js.map","import { useContext } from 'react';\nimport { EditContext } from './EditContext';\n/**\n * Hook to read the edit controller props from the EditContext.\n *\n * Used within a (e.g. as a descendent of ).\n *\n * @returns {EditControllerResult} edit controller props\n *\n * @see useEditController for how it is filled\n */\nexport var useEditContext = function () {\n var context = useContext(EditContext);\n if (!context) {\n throw new Error('useEditContext must be used inside an EditContextProvider');\n }\n return context;\n};\n//# sourceMappingURL=useEditContext.js.map","import { createContext, useContext } from 'react';\nexport var ReferenceFieldContext = createContext(null);\nexport var ReferenceFieldContextProvider = ReferenceFieldContext.Provider;\nexport var useReferenceFieldContext = function () {\n var context = useContext(ReferenceFieldContext);\n if (!context) {\n throw new Error('useReferenceFieldContext must be used inside a ReferenceFieldContextProvider');\n }\n return context;\n};\n//# sourceMappingURL=ReferenceFieldContext.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useGetManyAggregate } from '../dataProvider';\n/**\n * @typedef UseReferenceResult\n * @type {Object}\n * @property {boolean} isFetching: boolean indicating if the reference is loading\n * @property {boolean} isLoading: boolean indicating if the reference has loaded at least once\n * @property {Object} referenceRecord: the referenced record.\n */\n/**\n * Fetch reference record, and return it when available\n *\n * The reference prop should be the name of one of the components\n * added as child.\n *\n * @example\n *\n * const { isLoading, referenceRecord } = useReference({\n * id: 7,\n * reference: 'users',\n * });\n *\n * @param {Object} option\n * @param {string} option.reference The linked resource name\n * @param {string} option.id The id of the reference\n * @param {Object} option.options Options passed to the dataProvider\n *\n * @returns {UseReferenceResult} The reference record\n */\nexport var useReference = function (_a) {\n var reference = _a.reference, id = _a.id, _b = _a.options, options = _b === void 0 ? {} : _b;\n var meta = options.meta, otherQueryOptions = __rest(options, [\"meta\"]);\n var _c = useGetManyAggregate(reference, { ids: [id], meta: meta }, otherQueryOptions), data = _c.data, error = _c.error, isLoading = _c.isLoading, isFetching = _c.isFetching, isPending = _c.isPending, refetch = _c.refetch;\n return {\n referenceRecord: error ? undefined : data ? data[0] : undefined,\n refetch: refetch,\n error: error,\n isLoading: isLoading,\n isFetching: isFetching,\n isPending: isPending,\n };\n};\n//# sourceMappingURL=useReference.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport { useMemo } from 'react';\nimport { useGetPathForRecord } from '../../routing';\nimport { useReference } from '../useReference';\nimport { useFieldValue } from '../../util';\nexport var useReferenceFieldController = function (options) {\n var link = options.link, reference = options.reference, queryOptions = options.queryOptions;\n if (!reference) {\n throw new Error('useReferenceFieldController: missing reference prop. You must provide a reference, e.g. reference=\"posts\".');\n }\n var id = useFieldValue(options);\n var referenceRecordQuery = useReference({\n reference: reference,\n id: id,\n options: __assign(__assign({}, queryOptions), { enabled: ((queryOptions === null || queryOptions === void 0 ? void 0 : queryOptions.enabled) == null ||\n (queryOptions === null || queryOptions === void 0 ? void 0 : queryOptions.enabled) === true) &&\n id != null }),\n });\n var path = useGetPathForRecord({\n record: referenceRecordQuery.referenceRecord,\n resource: reference,\n link: link,\n });\n var result = useMemo(function () {\n return (__assign(__assign({}, referenceRecordQuery), { link: path }));\n }, [path, referenceRecordQuery]);\n return result;\n};\n//# sourceMappingURL=useReferenceFieldController.js.map","import * as React from 'react';\nimport { ReferenceFieldContextProvider } from './ReferenceFieldContext';\nimport { useReferenceFieldController } from './useReferenceFieldController';\nimport { ResourceContextProvider } from '../../core';\nimport { RecordContextProvider } from '../record';\n/**\n * Fetch reference record, and render its representation, or delegate rendering to child component.\n *\n * The reference prop should be the name of one of the components\n * added as child.\n *\n * @example // using recordRepresentation\n * \n *\n * @example // using a Field component to represent the record\n * \n * \n * \n *\n * @example // By default, includes a link to the page of the related record\n * // (`/users/:userId` in the previous example).\n * // Set the `link` prop to \"show\" to link to the page instead.\n * \n *\n * @example // You can also prevent `` from adding link to children\n * // by setting `link` to false.\n * \n *\n * @example // Alternatively, you can also pass a custom function to `link`.\n * // It must take reference and record as arguments and return a string\n * \"/path/to/${reference}/${record}\"} />\n *\n * @default\n * In previous versions of React-Admin, the prop `linkType` was used. It is now deprecated and replaced with `link`. However\n * backward-compatibility is still kept\n */\nexport var ReferenceFieldBase = function (props) {\n var children = props.children;\n var controllerProps = useReferenceFieldController(props);\n return (React.createElement(ResourceContextProvider, { value: props.reference },\n React.createElement(ReferenceFieldContextProvider, { value: controllerProps },\n React.createElement(RecordContextProvider, { value: controllerProps.referenceRecord }, children))));\n};\n//# sourceMappingURL=ReferenceFieldBase.js.map","/* jshint node:true */\n 'use strict';\n\n module.exports = \"\\n\";\n ","'use strict';\n\nmodule.exports.isFunction = function (fn) {\n var getType = {};\n return fn && getType.toString.call(fn) === '[object Function]';\n};\n\nmodule.exports.isArray = function (arr) {\n return Array.isArray(arr);\n};\n\nmodule.exports.isObject = function (obj) {\n return obj instanceof Object;\n};\n\nmodule.exports.isString = function (str) {\n return typeof str === 'string';\n};\n\nmodule.exports.isNumber = function (num) {\n return typeof num === 'number';\n};\n\nmodule.exports.isBoolean = function (bool) {\n return typeof bool === 'boolean';\n};\n\nmodule.exports.isDate = function (date) {\n return date instanceof Date;\n};","'use strict';\n\nvar EOL = require('./eol');\nvar helper = require('./helper');\n\nmodule.exports = function joinRows(rows, join) {\n if (!rows || !helper.isArray(rows)) {\n throw new TypeError('Invalid params \"rows\" for joinRows.' + ' Must be an array of string.');\n }\n //Merge all rows in a single output with the correct End of Line string\n var r = rows.join(join || EOL || '\\n');\n return r;\n};","/* jshint node:true */\n'use strict';\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar helper = require('../core/helper');\n\nvar Handler = function () {\n function Handler(options) {\n _classCallCheck(this, Handler);\n\n this._options = options;\n\n // an object of {typeName:(value,index,parent)=>any}\n this._options.typeHandlers = this._options.typeHandlers || {};\n }\n\n /**\n * Check if results needing mapping to alternate value\n *\n * @returns [{item, value}] result\n */\n\n\n _createClass(Handler, [{\n key: '_setHeaders',\n value: function _setHeaders(result, item) {\n var self = this;\n if (!item) return result;\n return result.map(function (element) {\n element.item = element.item ? item + self._options.headerPathString + element.item : item;\n return element;\n });\n }\n }, {\n key: 'castValue',\n value: function castValue(element, item, index, parent) {\n //cast by matching constructor\n var types = this._options.typeHandlers;\n for (var type in types) {\n if (isInstanceOfTypeName(element, type)) {\n element = types[type].call(types, element, index, parent);\n break; //first match we move on\n }\n }\n\n return element;\n }\n }, {\n key: 'checkComplex',\n value: function checkComplex(element, item) {\n //Check if element is a Date\n if (helper.isDate(element)) {\n return [{\n item: item,\n value: (this._options.handleDate || this._handleDate)(element, item)\n }];\n }\n //Check if element is an Array\n else if (helper.isArray(element)) {\n var resultArray = this._handleArray(element, item);\n return this._setHeaders(resultArray, item);\n }\n //Check if element is a Object\n else if (helper.isObject(element)) {\n var resultObject = this._handleObject(element);\n return this._setHeaders(resultObject, item);\n }\n\n return [{\n item: item,\n value: ''\n }];\n }\n\n /**\n * Check the element type of the element call the correct handle function\n *\n * @param element Element that will be checked\n * @param item Used to make the headers/path breadcrumb\n * @returns [{item, value}] result\n */\n\n }, {\n key: 'check',\n value: function check(element, item, index, parent) {\n element = this.castValue(element, item, index, parent);\n // try simple value by highier performance switch\n switch (typeof element === 'undefined' ? 'undefined' : _typeof(element)) {\n case 'string':\n return [{\n item: item,\n value: this._handleString(element, item)\n }];\n\n case 'number':\n return [{\n item: item,\n value: this._handleNumber(element, item)\n }];\n\n case 'boolean':\n return [{\n item: item,\n value: this._handleBoolean.bind(this)(element, item)\n }];\n }\n\n return this.checkComplex(element, item);\n }\n\n /**\n * Handle all Objects\n *\n * @param {Object} obj\n * @returns [{item, value}] result\n */\n\n }, {\n key: '_handleObject',\n value: function _handleObject(obj) {\n var result = [];\n //Look every object props\n for (var prop in obj) {\n var propData = obj[prop];\n //Check the propData type\n var resultCheckType = this.check(propData, prop, prop, obj);\n //Append to results aka merge results aka array-append-array\n result = result.concat(resultCheckType);\n }\n return result;\n }\n\n /**\n * Handle all Arrays, merges arrays with primitive types in a single value\n *\n * @param {Array} array\n * @returns [{item, value}] result\n */\n\n }, {\n key: '_handleArray',\n value: function _handleArray(array) {\n var self = this;\n var result = [];\n var firstElementWithoutItem;\n for (var aIndex = 0; aIndex < array.length; ++aIndex) {\n var element = array[aIndex];\n //Check the propData type\n var resultCheckType = self.check(element, null, aIndex, array);\n //Check for results without itens, merge all itens with the first occurrence\n if (resultCheckType.length === 0) continue;\n var firstResult = resultCheckType[0];\n if (!firstResult.item && firstElementWithoutItem !== undefined) {\n firstElementWithoutItem.value += self._options.arrayPathString + firstResult.value;\n continue;\n } else if (resultCheckType.length > 0 && !firstResult.item && firstElementWithoutItem === undefined) {\n firstElementWithoutItem = firstResult;\n }\n //Append to results\n result = result.concat(resultCheckType);\n }\n return result;\n }\n /**\n * Handle all Boolean variables, can be replaced with options.handleBoolean\n *\n * @param {Boolean} boolean\n * @returns {String} result\n */\n\n }, {\n key: '_handleBoolean',\n value: function _handleBoolean(boolean) {\n var result;\n //Check for booolean options\n if (boolean) {\n result = this._options.booleanTrueString || 'true';\n } else {\n result = this._options.booleanFalseString || 'false';\n }\n return result;\n }\n /**\n * Handle all String variables, can be replaced with options.handleString\n *\n * @param {String} string\n * @returns {String} string\n */\n\n }, {\n key: '_handleString',\n value: function _handleString(string) {\n return string;\n }\n /**\n * Handle all Number variables, can be replaced with options.handleNumber\n *\n * @param {Number} number\n * @returns {Number} number\n */\n\n }, {\n key: '_handleNumber',\n value: function _handleNumber(number) {\n return number;\n }\n /**\n * Handle all Date variables, can be replaced with options.handleDate\n *\n * @param {Date} number\n * @returns {string} result\n */\n\n }, {\n key: '_handleDate',\n value: function _handleDate(date) {\n return date.toLocaleDateString();\n }\n }]);\n\n return Handler;\n}();\n\nmodule.exports = Handler;\n\nvar globalScope = typeof window === \"undefined\" ? global : window;\nfunction isInstanceOfTypeName(element, typeName) {\n if (element instanceof globalScope[typeName]) {\n return true; //Buffer and complex objects\n }\n\n //literals in javascript cannot be checked by instance of\n switch (typeof element === 'undefined' ? 'undefined' : _typeof(element)) {\n case 'string':\n return typeName === \"String\";\n case 'boolean':\n return typeName === \"Boolean\";\n case 'number':\n return typeName === \"Number\";\n }\n\n return false;\n}","/* jshint node:true */\n'use strict';\n\n// Escape the textDelimiters contained in the field\n/*(https://tools.ietf.org/html/rfc4180)\n 7. If double-quotes are used to enclose fields, then a double-quote\n appearing inside a field must be escaped by preceding it with\n another double quote.\n For example: \"aaa\",\"b\"\"bb\",\"ccc\"\n*/\n\nmodule.exports = function escapedDelimiters(textDelimiter, rowDelimiter, forceTextDelimiter) {\n var endOfLine = '\\n';\n\n if (typeof textDelimiter !== 'string') {\n throw new TypeError('Invalid param \"textDelimiter\", must be a string.');\n }\n\n if (typeof rowDelimiter !== 'string') {\n throw new TypeError('Invalid param \"rowDelimiter\", must be a string.');\n }\n\n var textDelimiterRegex = new RegExp(\"\\\\\" + textDelimiter, 'g');\n var escapedDelimiter = textDelimiter + textDelimiter;\n\n var enclosingCondition = textDelimiter === '\"' ? function (value) {\n return value.indexOf(rowDelimiter) >= 0 || value.indexOf(endOfLine) >= 0 || value.indexOf('\"') >= 0;\n } : function (value) {\n return value.indexOf(rowDelimiter) >= 0 || value.indexOf(endOfLine) >= 0;\n };\n\n return function (value) {\n if (forceTextDelimiter) value = \"\" + value;\n\n if (!value.replace) return value;\n // Escape the textDelimiters contained in the field\n value = value.replace(textDelimiterRegex, escapedDelimiter);\n\n // Escape the whole field if it contains a rowDelimiter or a linebreak or double quote\n if (forceTextDelimiter || enclosingCondition(value)) {\n value = textDelimiter + value + textDelimiter;\n }\n\n return value;\n };\n};","/* jshint node:true */\n'use strict';\n\n/**\n * Module dependencies.\n */\n\nvar _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar joinRows = require('../core/join-rows');\nvar Handler = require('./handler');\nvar helper = require('../core/helper');\n\nvar Parser = function () {\n function Parser(options) {\n _classCallCheck(this, Parser);\n\n this._options = options || {};\n this._handler = new Handler(this._options);\n this._headers = this._options.headers || [];\n this._escape = require('../core/escape-delimiters')(this._options.textDelimiter, this._options.rowDelimiter, this._options.forceTextDelimiter);\n }\n\n /**\n * Generates a CSV file with optional headers based on the passed JSON,\n * with can be an Object or Array.\n *\n * @param {Object|Array} json\n * @param {Function} done(err,csv) - Callback function\n * if error, returning error in call back.\n * if csv is created successfully, returning csv output to callback.\n */\n\n\n _createClass(Parser, [{\n key: 'parse',\n value: function parse(json, done, stream) {\n if (helper.isArray(json)) return done(null, this._parseArray(json, stream));else if (helper.isObject(json)) return done(null, this._parseObject(json));\n return done(new Error('Unable to parse the JSON object, its not an Array or Object.'));\n }\n }, {\n key: '_checkRows',\n value: function _checkRows(rows) {\n var lastRow = null;\n var finalRows = [];\n var fillGaps = function fillGaps(col, index) {\n return col === '' || col === undefined ? lastRow[index] : col;\n };\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = rows[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var row = _step.value;\n\n var missing = this._headers.length - row.length;\n if (missing > 0) row = row.concat(Array(missing).join(\".\").split(\".\"));\n if (lastRow && this._options.fillGaps) row = row.map(fillGaps);\n finalRows.push(row.join(this._options.rowDelimiter));\n lastRow = row;\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n return finalRows;\n }\n }, {\n key: '_parseArray',\n value: function _parseArray(json, stream) {\n var self = this;\n this._headers = this._headers || [];\n var fileRows = [];\n var outputFile = void 0;\n var fillRows = void 0;\n\n var getHeaderIndex = function getHeaderIndex(header) {\n var index = self._headers.indexOf(header);\n if (index === -1) {\n self._headers.push(header);\n index = self._headers.indexOf(header);\n }\n return index;\n };\n\n //Generate the csv output\n fillRows = function fillRows(result) {\n var rows = [];\n var fillAndPush = function fillAndPush(row) {\n return rows.push(row.map(function (col) {\n return col != null ? col : '';\n }));\n };\n // initialize the array with empty strings to handle 'unpopular' headers\n var newRow = function newRow() {\n return new Array(self._headers.length).fill(null);\n };\n var emptyRowIndexByHeader = {};\n var currentRow = newRow();\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = result[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var element = _step2.value;\n\n var elementHeaderIndex = getHeaderIndex(element.item);\n if (currentRow[elementHeaderIndex] != undefined) {\n fillAndPush(currentRow);\n currentRow = newRow();\n }\n emptyRowIndexByHeader[elementHeaderIndex] = emptyRowIndexByHeader[elementHeaderIndex] || 0;\n // make sure there isn't a empty row for this header\n if (self._options.fillTopRow && emptyRowIndexByHeader[elementHeaderIndex] < rows.length) {\n rows[emptyRowIndexByHeader[elementHeaderIndex]][elementHeaderIndex] = self._escape(element.value);\n emptyRowIndexByHeader[elementHeaderIndex] += 1;\n continue;\n }\n currentRow[elementHeaderIndex] = self._escape(element.value);\n emptyRowIndexByHeader[elementHeaderIndex] += 1;\n }\n // push last row\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n\n if (currentRow.length > 0) {\n fillAndPush(currentRow);\n }\n fileRows = fileRows.concat(self._checkRows(rows));\n };\n var _iteratorNormalCompletion3 = true;\n var _didIteratorError3 = false;\n var _iteratorError3 = undefined;\n\n try {\n for (var _iterator3 = json[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {\n var item = _step3.value;\n\n //Call checkType to list all items inside this object\n //Items are returned as a object {item: 'Prop Value, Item Name', value: 'Prop Data Value'}\n var itemResult = self._handler.check(item, self._options.mainPathItem, item, json);\n fillRows(itemResult);\n }\n } catch (err) {\n _didIteratorError3 = true;\n _iteratorError3 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion3 && _iterator3.return) {\n _iterator3.return();\n }\n } finally {\n if (_didIteratorError3) {\n throw _iteratorError3;\n }\n }\n }\n\n if (!stream && self._options.includeHeaders) {\n //Add the headers to the first line\n fileRows.unshift(this.headers);\n }\n\n return joinRows(fileRows, self._options.endOfLine);\n }\n }, {\n key: '_parseObject',\n value: function _parseObject(json) {\n var self = this;\n var fileRows = [];\n var parseResult = [];\n var outputFile = void 0;\n var fillRows = void 0;\n var horizontalRows = [[], []];\n\n fillRows = function fillRows(result) {\n var value = result.value || result.value === 0 ? result.value.toString() : self._options.undefinedString;\n value = self._escape(value);\n\n //Type header;value\n if (self._options.verticalOutput) {\n var row = [result.item, value];\n fileRows.push(row.join(self._options.rowDelimiter));\n } else {\n horizontalRows[0].push(result.item);\n horizontalRows[1].push(value);\n }\n };\n for (var prop in json) {\n var prefix = \"\";\n if (this._options.mainPathItem) prefix = this._options.mainPathItem + this._options.headerPathString;\n parseResult = this._handler.check(json[prop], prefix + prop, prop, json);\n\n parseResult.forEach(fillRows);\n }\n if (!this._options.verticalOutput) {\n fileRows.push(horizontalRows[0].join(this._options.rowDelimiter));\n fileRows.push(horizontalRows[1].join(this._options.rowDelimiter));\n }\n return joinRows(fileRows, this._options.endOfLine);\n }\n }, {\n key: 'headers',\n get: function get() {\n var _this = this;\n\n var headers = this._headers;\n\n if (this._options.rename && this._options.rename.length > 0) headers = headers.map(function (header) {\n return _this._options.rename[_this._options.headers.indexOf(header)] || header;\n });\n\n if (this._options.forceTextDelimiter) {\n headers = headers.map(function (header) {\n return '' + _this._options.textDelimiter + header + _this._options.textDelimiter;\n });\n }\n\n if (this._options.mapHeaders) headers = headers.map(this._options.mapHeaders);\n\n return headers.join(this._options.rowDelimiter);\n }\n }]);\n\n return Parser;\n}();\n\nmodule.exports = Parser;","/* jshint node:true */\n 'use strict';\n\n var Stream = function (_Transform) {\n throw new Error(\"jsonexport called without third argument as a callback and is required\")\n }\n\n module.exports = Stream;\n ","/* jshint node:true */\n'use strict';\n/**\n * Module dependencies.\n */\n//const _ = require('underscore');\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nvar Parser = require('./parser/csv');\nvar Stream = require('./core/stream');\nvar helper = require('./core/helper');\nvar EOL = require('./core/eol');\n\n/**\n * Main function that converts json to csv\n *\n * @param {Object|Array} json\n * @param {Object} [options]\n * @param {Function} callback(err, csv) - Callback function\n * if error, returning error in call back.\n * if csv is created successfully, returning csv output to callback.\n */\nmodule.exports = function () {\n var DEFAULT_OPTIONS = {\n headers: [], // Array\n rename: [], // Array\n headerPathString: '.', // String\n rowDelimiter: ',', // String\n textDelimiter: '\"', // String\n arrayPathString: ';', // String\n undefinedString: '', // String\n endOfLine: EOL || '\\n', // String\n mainPathItem: null, // String\n booleanTrueString: null, // String\n booleanFalseString: null, // String\n includeHeaders: true, // Boolean\n fillGaps: false, // Boolean\n verticalOutput: true, // Boolean\n forceTextDelimiter: false //Boolean\n };\n // argument parsing\n var json = void 0,\n userOptions = void 0,\n callback = void 0;\n if (arguments.length === 3) {\n var _arguments = Array.prototype.slice.call(arguments);\n\n json = _arguments[0];\n userOptions = _arguments[1];\n callback = _arguments[2];\n } else if (arguments.length === 2) {\n var any = void 0;\n\n var _arguments2 = Array.prototype.slice.call(arguments);\n\n json = _arguments2[0];\n any = _arguments2[1];\n\n if (typeof any === 'function') {\n callback = any;\n } else if ((typeof any === 'undefined' ? 'undefined' : _typeof(any)) === 'object') {\n userOptions = any;\n }\n } else if (arguments.length === 1) {\n var _arguments3 = Array.prototype.slice.call(arguments),\n _any = _arguments3[0];\n\n if ((typeof _any === 'undefined' ? 'undefined' : _typeof(_any)) === 'object') {\n var defaultKeys = Object.keys(DEFAULT_OPTIONS);\n var objectKeys = Object.keys(_any);\n var isOptions = objectKeys.every(function (key) {\n return defaultKeys.includes(key);\n });\n if (objectKeys.length > 0 && isOptions) {\n userOptions = _any;\n } else {\n json = _any;\n }\n } else {\n json = _any;\n }\n } else {\n return new Stream(new Parser(DEFAULT_OPTIONS));\n }\n var options = Object.assign({}, DEFAULT_OPTIONS, userOptions);\n var parser = new Parser(options);\n // if no json is provided Stream API will be used\n if (!json) {\n return new Stream(parser);\n }\n // always return an promise\n return new Promise(function (resolve, reject) {\n parser.parse(json, function (err, result) {\n if (callback) return callback(err, result);\n if (err) return reject(err);\n if (reject) return resolve(result);\n });\n });\n};","export var downloadCSV = function (csv, filename) {\n if (filename === void 0) { filename = 'export'; }\n var fakeLink = document.createElement('a');\n fakeLink.style.display = 'none';\n document.body.appendChild(fakeLink);\n var blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });\n // @ts-ignore\n if (window.navigator && window.navigator.msSaveOrOpenBlob) {\n // Manage IE11+ & Edge\n // @ts-ignore\n window.navigator.msSaveOrOpenBlob(blob, \"\".concat(filename, \".csv\"));\n }\n else {\n fakeLink.setAttribute('href', URL.createObjectURL(blob));\n fakeLink.setAttribute('download', \"\".concat(filename, \".csv\"));\n fakeLink.click();\n }\n};\n//# sourceMappingURL=downloadCSV.js.map","import jsonExport from 'jsonexport/dist';\nimport { downloadCSV } from './downloadCSV';\nexport var defaultExporter = function (data, _, __, resource) {\n return jsonExport(data, function (err, csv) { return downloadCSV(csv, resource); });\n};\n//# sourceMappingURL=defaultExporter.js.map","/**\n * Extracts, aggregates and deduplicates the ids of related records\n *\n * @example\n * const books = [\n * { id: 1, author_id: 123, title: 'Pride and Prejudice' },\n * { id: 2, author_id: 123, title: 'Sense and Sensibility' },\n * { id: 3, author_id: 456, title: 'War and Peace' },\n * ];\n * getRelatedIds(books, 'author_id'); => [123, 456]\n *\n * @example\n * const books = [\n * { id: 1, tag_ids: [1, 2], title: 'Pride and Prejudice' },\n * { id: 2, tag_ids: [2, 3], title: 'Sense and Sensibility' },\n * { id: 3, tag_ids: [4], title: 'War and Peace' },\n * ];\n * getRelatedIds(records, 'tag_ids'); => [1, 2, 3, 4]\n *\n * @param {Object[]} records An array of records\n * @param {string} field the identifier of the record field to use\n */\nexport var getRelatedIds = function (records, field) {\n return Array.from(new Set(records\n .filter(function (record) { return record[field] != null; })\n .map(function (record) { return record[field]; })\n .reduce(function (ids, value) { return ids.concat(value); }, [])));\n};\n//# sourceMappingURL=getRelatedIds.js.map","import { getRelatedIds } from './getRelatedIds';\n/**\n * Helper function for calling the dataProvider.getMany() method,\n * and getting a Promise for the records indexed by id in return.\n *\n * @example\n * fetchRelatedRecords(dataProvider)(records, 'post_id', 'posts').then(posts =>\n * posts.map(record => ({\n * ...record,\n * post_title: posts[record.post_id].title,\n * }))\n * );\n */\nexport var fetchRelatedRecords = function (dataProvider) {\n return function (data, field, resource) {\n return dataProvider\n .getMany(resource, { ids: getRelatedIds(data, field) })\n .then(function (_a) {\n var data = _a.data;\n return data.reduce(function (acc, post) {\n acc[post.id] = post;\n return acc;\n }, {});\n });\n };\n};\n//# sourceMappingURL=fetchRelatedRecords.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { useCallback, useMemo, useState } from 'react';\nimport { useStore, useRemoveFromStore } from '../../store';\n/**\n * Get the list of selected items for a resource, and callbacks to change the selection\n *\n * @param args.resource The resource name, e.g. 'posts'\n * @param args.disableSyncWithStore Controls the selection syncronization with the store\n *\n * @returns {Object} Destructure as [selectedIds, { select, toggle, clearSelection }].\n */\nexport var useRecordSelection = function (args) {\n var _a = args.resource, resource = _a === void 0 ? '' : _a, _b = args.disableSyncWithStore, disableSyncWithStore = _b === void 0 ? false : _b;\n var storeKey = \"\".concat(resource, \".selectedIds\");\n var _c = useState(defaultSelection), localIds = _c[0], setLocalIds = _c[1];\n // As we can't conditionally call a hook, if the storeKey is false,\n // we'll ignore the params variable later on and won't call setParams either.\n var _d = useStore(storeKey, defaultSelection), storeIds = _d[0], setStoreIds = _d[1];\n var resetStore = useRemoveFromStore(storeKey);\n var ids = disableSyncWithStore ? localIds : storeIds;\n var setIds = disableSyncWithStore ? setLocalIds : setStoreIds;\n var reset = useCallback(function () {\n if (disableSyncWithStore) {\n setLocalIds(defaultSelection);\n }\n else {\n resetStore();\n }\n }, [disableSyncWithStore, resetStore]);\n var selectionModifiers = useMemo(function () { return ({\n select: function (idsToAdd) {\n if (!idsToAdd)\n return;\n setIds(__spreadArray([], idsToAdd, true));\n },\n unselect: function (idsToRemove) {\n if (!idsToRemove || idsToRemove.length === 0)\n return;\n setIds(function (ids) {\n if (!Array.isArray(ids))\n return [];\n return ids.filter(function (id) { return !idsToRemove.includes(id); });\n });\n },\n toggle: function (id) {\n if (typeof id === 'undefined')\n return;\n setIds(function (ids) {\n if (!Array.isArray(ids))\n return __spreadArray([], ids, true);\n var index = ids.indexOf(id);\n return index > -1\n ? __spreadArray(__spreadArray([], ids.slice(0, index), true), ids.slice(index + 1), true) : __spreadArray(__spreadArray([], ids, true), [id], false);\n });\n },\n clearSelection: function () {\n reset();\n },\n }); }, [setIds, reset]);\n return [ids, selectionModifiers];\n};\nvar defaultSelection = [];\n//# sourceMappingURL=useRecordSelection.js.map","import { useRef, useEffect, useState, useCallback } from 'react';\nimport isEqual from 'lodash/isEqual';\n// thanks Kent C Dodds for the following helpers\n/**\n * @deprecated use `useState` instead, since React no longer\n * issues warnings when calling setState on unmounted components.\n */\nexport function useSafeSetState(initialState) {\n var _a = useState(initialState), state = _a[0], setState = _a[1];\n var mountedRef = useRef(false);\n useEffect(function () {\n mountedRef.current = true;\n return function () {\n mountedRef.current = false;\n };\n }, []);\n var safeSetState = useCallback(function (args) {\n if (mountedRef.current) {\n return setState(args);\n }\n }, [mountedRef, setState]);\n return [state, safeSetState];\n}\nexport function usePrevious(value) {\n var ref = useRef();\n useEffect(function () {\n ref.current = value;\n });\n return ref.current;\n}\nexport function useDeepCompareEffect(callback, inputs) {\n var cleanupRef = useRef();\n useEffect(function () {\n if (!isEqual(previousInputs, inputs)) {\n cleanupRef.current = callback();\n }\n return cleanupRef.current;\n });\n var previousInputs = usePrevious(inputs);\n}\n/**\n * A hook that returns true once a delay has expired.\n * @param ms The delay in milliseconds\n * @param key A key that can be used to reset the timer\n * @returns true if the delay has expired, false otherwise\n */\nexport function useTimeout(ms, key) {\n if (ms === void 0) { ms = 0; }\n if (key === void 0) { key = ''; }\n var _a = useState(false), ready = _a[0], setReady = _a[1];\n useEffect(function () {\n setReady(false);\n var timer = setTimeout(function () {\n setReady(true);\n }, ms);\n return function () {\n clearTimeout(timer);\n };\n }, [key, ms, setReady]);\n return ready;\n}\nexport function useIsMounted() {\n var isMounted = useRef(true);\n useEffect(function () {\n isMounted.current = true;\n return function () {\n isMounted.current = false;\n };\n }, []);\n return isMounted;\n}\n//# sourceMappingURL=hooks.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { useCallback, useMemo, useEffect, useState, useRef } from 'react';\nimport { parse, stringify } from 'query-string';\nimport lodashDebounce from 'lodash/debounce';\nimport { useNavigate, useLocation } from 'react-router-dom';\nimport { useStore } from '../../store';\nimport queryReducer, { SET_FILTER, HIDE_FILTER, SHOW_FILTER, SET_PAGE, SET_PER_PAGE, SET_SORT, SORT_ASC, } from './queryReducer';\nimport removeEmpty from '../../util/removeEmpty';\nimport { useIsMounted } from '../../util/hooks';\n/**\n * Get the list parameters (page, sort, filters) and modifiers.\n *\n * These parameters are merged from 3 sources:\n * - the query string from the URL\n * - the params stored in the state (from previous navigation)\n * - the options passed to the hook (including the filter defaultValues)\n *\n * @returns {Array} A tuple [parameters, modifiers].\n * Destructure as [\n * { page, perPage, sort, order, filter, filterValues, displayedFilters, requestSignature },\n * { setFilters, hideFilter, showFilter, setPage, setPerPage, setSort }\n * ]\n *\n * @example\n *\n * const [listParams, listParamsActions] = useListParams({\n * resource: 'posts',\n * location: location // From react-router. Injected to your component by react-admin inside a List\n * filterDefaultValues: {\n * published: true\n * },\n * sort: {\n * field: 'published_at',\n * order: 'DESC'\n * },\n * perPage: 25\n * });\n *\n * const {\n * page,\n * perPage,\n * sort,\n * order,\n * filter,\n * filterValues,\n * displayedFilters,\n * requestSignature\n * } = listParams;\n *\n * const {\n * setFilters,\n * hideFilter,\n * showFilter,\n * setPage,\n * setPerPage,\n * setSort,\n * } = listParamsActions;\n */\nexport var useListParams = function (_a) {\n var _b = _a.debounce, debounce = _b === void 0 ? 500 : _b, _c = _a.disableSyncWithLocation, disableSyncWithLocation = _c === void 0 ? false : _c, filterDefaultValues = _a.filterDefaultValues, _d = _a.perPage, perPage = _d === void 0 ? 10 : _d, resource = _a.resource, _e = _a.sort, sort = _e === void 0 ? defaultSort : _e, _f = _a.storeKey, storeKey = _f === void 0 ? disableSyncWithLocation ? false : \"\".concat(resource, \".listParams\") : _f;\n var location = useLocation();\n var navigate = useNavigate();\n var _g = useState(defaultParams), localParams = _g[0], setLocalParams = _g[1];\n // As we can't conditionally call a hook, if the storeKey is false,\n // we'll ignore the params variable later on and won't call setParams either.\n var _h = useStore(storeKey || \"\".concat(resource, \".listParams\"), defaultParams), params = _h[0], setParams = _h[1];\n var tempParams = useRef();\n var isMounted = useIsMounted();\n var requestSignature = [\n location.search,\n resource,\n storeKey,\n JSON.stringify(!storeKey ? localParams : params),\n JSON.stringify(filterDefaultValues),\n JSON.stringify(sort),\n perPage,\n disableSyncWithLocation,\n ];\n var queryFromLocation = disableSyncWithLocation\n ? {}\n : parseQueryFromLocation(location);\n var query = useMemo(function () {\n return getQuery({\n queryFromLocation: queryFromLocation,\n params: !storeKey ? localParams : params,\n filterDefaultValues: filterDefaultValues,\n sort: sort,\n perPage: perPage,\n });\n }, requestSignature // eslint-disable-line react-hooks/exhaustive-deps\n );\n // if the location includes params (for example from a link like\n // the categories products on the demo), we need to persist them in the\n // store as well so that we don't lose them after a redirection back\n // to the list\n useEffect(function () {\n if (Object.keys(queryFromLocation).length > 0) {\n setParams(query);\n }\n }, [location.search]); // eslint-disable-line\n var changeParams = useCallback(function (action) {\n // do not change params if the component is already unmounted\n // this is necessary because changeParams can be debounced, and therefore\n // executed after the component is unmounted\n if (!isMounted.current)\n return;\n if (!tempParams.current) {\n // no other changeParams action dispatched this tick\n tempParams.current = queryReducer(query, action);\n // schedule side effects for next tick\n setTimeout(function () {\n if (!tempParams.current) {\n // the side effects were already processed by another changeParams\n return;\n }\n if (disableSyncWithLocation && !storeKey) {\n setLocalParams(tempParams.current);\n }\n else if (disableSyncWithLocation && !!storeKey) {\n setParams(tempParams.current);\n }\n else {\n // the useEffect above will apply the changes to the params in the store\n navigate({\n search: \"?\".concat(stringify(__assign(__assign({}, tempParams.current), { filter: JSON.stringify(tempParams.current.filter), displayedFilters: JSON.stringify(tempParams.current.displayedFilters) }))),\n }, {\n state: {\n _scrollToTop: action.type === SET_PAGE,\n },\n });\n }\n tempParams.current = undefined;\n }, 0);\n }\n else {\n // side effects already scheduled, just change the params\n tempParams.current = queryReducer(tempParams.current, action);\n }\n }, __spreadArray(__spreadArray([], requestSignature, true), [navigate], false));\n var setSort = useCallback(function (sort) {\n return changeParams({\n type: SET_SORT,\n payload: sort,\n });\n }, [changeParams]);\n var setPage = useCallback(function (newPage) { return changeParams({ type: SET_PAGE, payload: newPage }); }, [changeParams]);\n var setPerPage = useCallback(function (newPerPage) {\n return changeParams({ type: SET_PER_PAGE, payload: newPerPage });\n }, [changeParams]);\n var filterValues = query.filter || emptyObject;\n var displayedFilterValues = query.displayedFilters || emptyObject;\n var debouncedSetFilters = lodashDebounce(function (filter, displayedFilters) {\n changeParams({\n type: SET_FILTER,\n payload: {\n filter: removeEmpty(filter),\n displayedFilters: displayedFilters,\n },\n });\n }, debounce);\n var setFilters = useCallback(function (filter, displayedFilters, debounce) {\n if (displayedFilters === void 0) { displayedFilters = undefined; }\n if (debounce === void 0) { debounce = false; }\n return debounce\n ? debouncedSetFilters(filter, displayedFilters)\n : changeParams({\n type: SET_FILTER,\n payload: {\n filter: removeEmpty(filter),\n displayedFilters: displayedFilters,\n },\n });\n }, [changeParams] // eslint-disable-line react-hooks/exhaustive-deps\n );\n var hideFilter = useCallback(function (filterName) {\n changeParams({\n type: HIDE_FILTER,\n payload: filterName,\n });\n }, [changeParams]);\n var showFilter = useCallback(function (filterName, defaultValue) {\n changeParams({\n type: SHOW_FILTER,\n payload: {\n filterName: filterName,\n defaultValue: defaultValue,\n },\n });\n }, [changeParams]);\n return [\n __assign(__assign({ filterValues: filterValues, requestSignature: requestSignature }, query), { displayedFilters: displayedFilterValues }),\n {\n changeParams: changeParams,\n setPage: setPage,\n setPerPage: setPerPage,\n setSort: setSort,\n setFilters: setFilters,\n hideFilter: hideFilter,\n showFilter: showFilter,\n },\n ];\n};\nvar parseObject = function (query, field) {\n if (query[field] && typeof query[field] === 'string') {\n try {\n query[field] = JSON.parse(query[field]);\n }\n catch (err) {\n delete query[field];\n }\n }\n};\nexport var parseQueryFromLocation = function (_a) {\n var search = _a.search;\n var query = parse(search);\n parseObject(query, 'filter');\n parseObject(query, 'displayedFilters');\n return query;\n};\n/**\n * Check if user has already set custom sort, page, or filters for this list\n *\n * User params come from the store as the params props. By default,\n * this object is:\n *\n * { filter: {}, order: null, page: 1, perPage: null, sort: null }\n *\n * To check if the user has custom params, we must compare the params\n * to these initial values.\n *\n * @param {Object} params\n */\nexport var hasCustomParams = function (params) {\n return (params &&\n params.filter &&\n (Object.keys(params.filter).length > 0 ||\n params.order != null ||\n params.page !== 1 ||\n params.perPage != null ||\n params.sort != null));\n};\n/**\n * Merge list params from 3 different sources:\n * - the query string\n * - the params stored in the state (from previous navigation)\n * - the props passed to the List component (including the filter defaultValues)\n */\nexport var getQuery = function (_a) {\n var queryFromLocation = _a.queryFromLocation, params = _a.params, filterDefaultValues = _a.filterDefaultValues, sort = _a.sort, perPage = _a.perPage;\n var query = Object.keys(queryFromLocation).length > 0\n ? queryFromLocation\n : hasCustomParams(params)\n ? __assign({}, params) : { filter: filterDefaultValues || {} };\n if (!query.sort) {\n query.sort = sort.field;\n query.order = sort.order;\n }\n if (query.perPage == null) {\n query.perPage = perPage;\n }\n if (query.page == null) {\n query.page = 1;\n }\n return __assign(__assign({}, query), { page: getNumberOrDefault(query.page, 1), perPage: getNumberOrDefault(query.perPage, 10) });\n};\nexport var getNumberOrDefault = function (possibleNumber, defaultValue) {\n if (typeof possibleNumber === 'undefined') {\n return defaultValue;\n }\n var parsedNumber = typeof possibleNumber === 'string'\n ? parseInt(possibleNumber, 10)\n : possibleNumber;\n return isNaN(parsedNumber) ? defaultValue : parsedNumber;\n};\nvar emptyObject = {};\nvar defaultSort = {\n field: 'id',\n order: SORT_ASC,\n};\nvar defaultParams = {};\n//# sourceMappingURL=useListParams.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useNotify } from '../../notification';\nimport { useDataProvider } from '../../dataProvider';\nimport { useRecordSelection } from './useRecordSelection';\nimport { useResourceContext } from '../../core';\nimport { useEvent } from '../../util';\n/**\n * Get a callback to select all records of a resource (capped by the limit parameter)\n *\n * @param {Object} params The hook parameters { resource, sort, filter }\n * @returns {Function} handleSelectAll A function to select all items of a list\n *\n * @example\n * import { List, Datagrid, BulkActionsToolbar, BulkDeleteButton, useListContext, useSelectAll } from 'react-admin';\n *\n * const MySelectAllButton = () => {\n * const { sort, filter } = useListContext();\n * const handleSelectAll = useSelectAll({ resource: 'posts', sort, filter });\n * const handleClick = () => handleSelectAll({\n * queryOptions: { meta: { foo: 'bar' } },\n * limit: 250,\n * });\n * return ;\n * };\n *\n * const PostBulkActionsToolbar = () => (\n * }>\n * \n * \n * );\n *\n * export const PostList = () => (\n * \n * }>\n * ...\n * \n * \n * );\n */\nexport var useSelectAll = function (params) {\n var sort = params.sort, filter = params.filter;\n var resource = useResourceContext(params);\n if (!resource) {\n throw new Error('useSelectAll should be used inside a ResourceContextProvider or passed a resource prop');\n }\n var dataProvider = useDataProvider();\n var queryClient = useQueryClient();\n var _a = useRecordSelection({ resource: resource }), select = _a[1].select;\n var notify = useNotify();\n var handleSelectAll = useEvent(function (_a) {\n var _b = _a === void 0 ? {} : _a, _c = _b.queryOptions, queryOptions = _c === void 0 ? {} : _c, _d = _b.limit, limit = _d === void 0 ? 250 : _d;\n return __awaiter(void 0, void 0, void 0, function () {\n var meta, onSuccess, onError, otherQueryOptions, results, allIds, error_1;\n var _e;\n return __generator(this, function (_f) {\n switch (_f.label) {\n case 0:\n meta = queryOptions.meta, onSuccess = queryOptions.onSuccess, onError = queryOptions.onError, otherQueryOptions = __rest(queryOptions, [\"meta\", \"onSuccess\", \"onError\"]);\n _f.label = 1;\n case 1:\n _f.trys.push([1, 3, , 4]);\n return [4 /*yield*/, queryClient.fetchQuery(__assign({ queryKey: [\n resource,\n 'getList',\n {\n pagination: { page: 1, perPage: limit },\n sort: sort,\n filter: filter,\n meta: meta,\n },\n ], queryFn: function () {\n return dataProvider.getList(resource, {\n pagination: {\n page: 1,\n perPage: limit,\n },\n sort: sort,\n filter: filter,\n meta: meta,\n });\n } }, otherQueryOptions))];\n case 2:\n results = _f.sent();\n allIds = ((_e = results.data) === null || _e === void 0 ? void 0 : _e.map(function (_a) {\n var id = _a.id;\n return id;\n })) || [];\n select(allIds);\n if (allIds.length === limit) {\n notify('ra.message.select_all_limit_reached', {\n messageArgs: { max: limit },\n type: 'warning',\n });\n }\n if (onSuccess) {\n onSuccess(results);\n }\n return [2 /*return*/, results.data];\n case 3:\n error_1 = _f.sent();\n if (onError) {\n onError(error_1);\n }\n else {\n notify('ra.notification.http_error', { type: 'warning' });\n }\n return [3 /*break*/, 4];\n case 4: return [2 /*return*/];\n }\n });\n });\n });\n return handleSelectAll;\n};\n//# sourceMappingURL=useSelectAll.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { isValidElement, useEffect, useMemo } from 'react';\nimport { useAuthenticated, useRequireAccess } from '../../auth';\nimport { useTranslate } from '../../i18n';\nimport { useNotify } from '../../notification';\nimport { useInfiniteGetList } from '../../dataProvider';\nimport { defaultExporter } from '../../export';\nimport { useResourceContext, useGetResourceLabel } from '../../core';\nimport { useRecordSelection } from './useRecordSelection';\nimport { useListParams } from './useListParams';\nimport { useSelectAll } from './useSelectAll';\n/**\n * Prepare data for the InfiniteList view\n *\n * @param {Object} props The props passed to the InfiniteList component.\n *\n * @return {Object} controllerProps Fetched and computed data for the List view\n *\n * @example\n *\n * import { useInfiniteListController } from 'react-admin';\n * import ListView from './ListView';\n *\n * const MyList = props => {\n * const controllerProps = useInfiniteListController(props);\n * return ;\n * }\n */\nexport var useInfiniteListController = function (props) {\n if (props === void 0) { props = {}; }\n var _a = props.debounce, debounce = _a === void 0 ? 500 : _a, _b = props.disableAuthentication, disableAuthentication = _b === void 0 ? false : _b, _c = props.disableSyncWithLocation, disableSyncWithLocation = _c === void 0 ? false : _c, _d = props.exporter, exporter = _d === void 0 ? defaultExporter : _d, filter = props.filter, filterDefaultValues = props.filterDefaultValues, _e = props.perPage, perPage = _e === void 0 ? 10 : _e, queryOptions = props.queryOptions, sort = props.sort, storeKey = props.storeKey;\n var resource = useResourceContext(props);\n var _f = queryOptions !== null && queryOptions !== void 0 ? queryOptions : {}, meta = _f.meta, otherQueryOptions = __rest(_f, [\"meta\"]);\n if (!resource) {\n throw new Error(\" was called outside of a ResourceContext and without a resource prop. You must set the resource prop.\");\n }\n if (filter && isValidElement(filter)) {\n throw new Error(' received a React element as `filter` props. If you intended to set the list filter elements, use the `filters` (with an s) prop instead. The `filter` prop is internal and should not be set by the developer.');\n }\n var isPendingAuthenticated = useAuthenticated({\n enabled: !disableAuthentication,\n }).isPending;\n var isPendingCanAccess = useRequireAccess({\n action: 'list',\n resource: resource,\n // If disableAuthentication is true then isPendingAuthenticated will always be true so this hook is disabled\n enabled: !isPendingAuthenticated,\n }).isPending;\n var translate = useTranslate();\n var notify = useNotify();\n var _g = useListParams({\n debounce: debounce,\n disableSyncWithLocation: disableSyncWithLocation,\n filterDefaultValues: filterDefaultValues,\n perPage: perPage,\n resource: resource,\n sort: sort,\n storeKey: storeKey,\n }), query = _g[0], queryModifiers = _g[1];\n var _h = useRecordSelection({ resource: resource }), selectedIds = _h[0], selectionModifiers = _h[1];\n var _j = useInfiniteGetList(resource, {\n pagination: {\n page: query.page,\n perPage: query.perPage,\n },\n sort: { field: query.sort, order: query.order },\n filter: __assign(__assign({}, query.filter), filter),\n meta: meta,\n }, __assign({ enabled: (!isPendingAuthenticated && !isPendingCanAccess) ||\n disableAuthentication, placeholderData: function (previousData) { return previousData; }, retry: false, onError: function (error) {\n return notify((error === null || error === void 0 ? void 0 : error.message) || 'ra.notification.http_error', {\n type: 'error',\n messageArgs: {\n _: error === null || error === void 0 ? void 0 : error.message,\n },\n });\n } }, otherQueryOptions)), data = _j.data, total = _j.total, error = _j.error, isLoading = _j.isLoading, isPending = _j.isPending, isFetching = _j.isFetching, hasNextPage = _j.hasNextPage, hasPreviousPage = _j.hasPreviousPage, fetchNextPage = _j.fetchNextPage, isFetchingNextPage = _j.isFetchingNextPage, fetchPreviousPage = _j.fetchPreviousPage, isFetchingPreviousPage = _j.isFetchingPreviousPage, refetch = _j.refetch;\n var onSelectAll = useSelectAll({\n resource: resource,\n sort: { field: query.sort, order: query.order },\n filter: __assign(__assign({}, query.filter), filter),\n });\n // change page if there is no data\n useEffect(function () {\n if (query.page <= 0 ||\n (!isFetching &&\n query.page > 1 &&\n (data == null || (data === null || data === void 0 ? void 0 : data.pages.length) === 0))) {\n // Query for a page that doesn't exist, set page to 1\n queryModifiers.setPage(1);\n return;\n }\n if (total == null) {\n return;\n }\n var totalPages = Math.ceil(total / query.perPage) || 1;\n if (!isFetching && query.page > totalPages) {\n // Query for a page out of bounds, set page to the last existing page\n // It occurs when deleting the last element of the last page\n queryModifiers.setPage(totalPages);\n }\n }, [isFetching, query.page, query.perPage, data, queryModifiers, total]);\n var currentSort = useMemo(function () { return ({\n field: query.sort,\n order: query.order,\n }); }, [query.sort, query.order]);\n var getResourceLabel = useGetResourceLabel();\n var defaultTitle = translate('ra.page.list', {\n name: getResourceLabel(resource, 2),\n });\n var unwrappedData = useMemo(function () { var _a; return (_a = data === null || data === void 0 ? void 0 : data.pages) === null || _a === void 0 ? void 0 : _a.reduce(function (acc, page) { return __spreadArray(__spreadArray([], acc, true), page.data, true); }, []); }, [data]);\n return {\n sort: currentSort,\n data: unwrappedData,\n defaultTitle: defaultTitle,\n displayedFilters: query.displayedFilters,\n error: error,\n exporter: exporter,\n filter: filter,\n filterValues: query.filterValues,\n hideFilter: queryModifiers.hideFilter,\n isFetching: isFetching,\n isLoading: isLoading,\n isPending: isPending,\n onSelect: selectionModifiers.select,\n onSelectAll: onSelectAll,\n onToggleItem: selectionModifiers.toggle,\n onUnselectItems: selectionModifiers.clearSelection,\n page: query.page,\n perPage: query.perPage,\n refetch: refetch,\n resource: resource,\n selectedIds: selectedIds,\n setFilters: queryModifiers.setFilters,\n setPage: queryModifiers.setPage,\n setPerPage: queryModifiers.setPerPage,\n setSort: queryModifiers.setSort,\n showFilter: queryModifiers.showFilter,\n total: total,\n hasNextPage: hasNextPage,\n hasPreviousPage: hasPreviousPage,\n fetchNextPage: fetchNextPage,\n isFetchingNextPage: isFetchingNextPage,\n fetchPreviousPage: fetchPreviousPage,\n isFetchingPreviousPage: isFetchingPreviousPage,\n };\n};\n//# sourceMappingURL=useInfiniteListController.js.map","import { createContext } from 'react';\n/**\n * Context to store the result of the useListController() hook.\n *\n * Use the useListContext() hook to read the context. That's what many\n * List components do in react-admin (e.g. , , ).\n *\n * @typedef {Object} ListControllerProps\n * @prop {Array} data an array of the list records, e.g. [{ id: 123, title: 'hello world' }, { ... }]\n * @prop {integer} total the total number of results for the current filters, excluding pagination. Useful to build the pagination controls. e.g. 23\n * @prop {boolean} isFetching boolean that is true on mount, and false once the data was fetched\n * @prop {boolean} isLoading boolean that is false until the data is available\n * @prop {integer} page the current page. Starts at 1\n * @prop {Function} setPage a callback to change the page, e.g. setPage(3)\n * @prop {integer} perPage the number of results per page. Defaults to 25\n * @prop {Function} setPerPage a callback to change the number of results per page, e.g. setPerPage(25)\n * @prop {Object} sort a sort object { field, order }, e.g. { field: 'date', order: 'DESC' }\n * @prop {Function} setSort a callback to change the sort, e.g. setSort({ field: 'name', order: 'ASC' })\n * @prop {Object} filterValues a dictionary of filter values, e.g. { title: 'lorem', nationality: 'fr' }\n * @prop {Function} setFilters a callback to update the filters, e.g. setFilters(filters, displayedFilters)\n * @prop {Object} displayedFilters a dictionary of the displayed filters, e.g. { title: true, nationality: true }\n * @prop {Function} showFilter a callback to show one of the filters, e.g. showFilter('title', defaultValue)\n * @prop {Function} hideFilter a callback to hide one of the filters, e.g. hideFilter('title')\n * @prop {Array} selectedIds an array listing the ids of the selected rows, e.g. [123, 456]\n * @prop {Function} onSelect callback to change the list of selected rows, e.g. onSelect([456, 789])\n * @prop {Function} onSelectAll callback to select all the records, e.g. onSelectAll()\n * @prop {Function} onToggleItem callback to toggle the selection of a given record based on its id, e.g. onToggleItem(456)\n * @prop {Function} onUnselectItems callback to clear the selection, e.g. onUnselectItems();\n * @prop {string} defaultTitle the translated title based on the resource, e.g. 'Posts'\n * @prop {string} resource the resource name, deduced from the location. e.g. 'posts'\n * @prop {Function} refetch a function for triggering a refetch of the list data\n *\n * @typedef Props\n * @prop {ListControllerResult} value\n *\n * @param {Props}\n *\n * @see useListController\n * @see useListContext\n *\n * @example\n *\n * import { useListController, ListContext } from 'ra-core';\n *\n * const List = props => {\n * const controllerProps = useListController(props);\n * return (\n * \n * ...\n * \n * );\n * };\n */\nexport var ListContext = createContext(null);\nListContext.displayName = 'ListContext';\n//# sourceMappingURL=ListContext.js.map","import { createContext, useMemo } from 'react';\nimport pick from 'lodash/pick';\n/**\n * Context to store the filter part of the useListController() result.\n *\n * Use the useListFilterContext() hook to read the context. That's what many\n * List components do in react-admin (e.g. , ).\n *\n * @typedef {Object} ListFilterContextValue\n * @prop {Object} filterValues a dictionary of filter values, e.g. { title: 'lorem', nationality: 'fr' }\n * @prop {Function} setFilters a callback to update the filters, e.g. setFilters(filters, displayedFilters)\n * @prop {Object} displayedFilters a dictionary of the displayed filters, e.g. { title: true, nationality: true }\n * @prop {Function} showFilter a callback to show one of the filters, e.g. showFilter('title', defaultValue)\n * @prop {Function} hideFilter a callback to hide one of the filters, e.g. hideFilter('title')\n * @prop {string} resource the resource name, deduced from the location. e.g. 'posts'\n *\n * @typedef Props\n * @prop {ListFilterContextValue} value\n *\n * @param {Props}\n *\n * @see useListController\n * @see useListFilterContext\n *\n * @example\n *\n * import { useListController, usePickFilterContext, ListFilterContext } from 'ra-core';\n *\n * const List = props => {\n * const controllerProps = useListController(props);\n * return (\n * \n * ...\n * \n * );\n * };\n */\nexport var ListFilterContext = createContext(undefined);\nexport var usePickFilterContext = function (context) {\n return useMemo(function () {\n return pick(context, [\n 'displayedFilters',\n 'filterValues',\n 'hideFilter',\n 'setFilters',\n 'showFilter',\n 'resource',\n ]);\n }, \n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n context.displayedFilters,\n context.filterValues,\n context.hideFilter,\n context.setFilters,\n context.showFilter,\n ]);\n};\nListFilterContext.displayName = 'ListFilterContext';\n//# sourceMappingURL=ListFilterContext.js.map","import { createContext, useMemo } from 'react';\nimport pick from 'lodash/pick';\n/**\n * Context to store the sort part of the useListController() result.\n *\n * Use the useListSortContext() hook to read the context. That's what many\n * List components do in react-admin (e.g. ).\n *\n * @typedef {Object} ListSortContextValue\n * @prop {Object} sort a sort object { field, order }, e.g. { field: 'date', order: 'DESC' }\n * @prop {Function} setSort a callback to change the sort, e.g. setSort({ field: 'name', order: 'ASC' })\n * @prop {string} resource the resource name, deduced from the location. e.g. 'posts'\n *\n * @typedef Props\n * @prop {ListSortContextValue} value\n *\n * @param {Props}\n *\n * @see useListController\n * @see useListSortContext\n *\n * @example\n *\n * import { useListController, usePickSortContext, ListSortContext } from 'ra-core';\n *\n * const List = props => {\n * const controllerProps = useListController(props);\n * return (\n * \n * ...\n * \n * );\n * };\n */\nexport var ListSortContext = createContext(undefined);\nexport var usePickSortContext = function (context) {\n return useMemo(function () { return pick(context, ['sort', 'setSort', 'resource']); }, \n // eslint-disable-next-line react-hooks/exhaustive-deps\n [context.sort, context.setSort]);\n};\nListSortContext.displayName = 'ListSortContext';\n//# sourceMappingURL=ListSortContext.js.map","import { createContext, useMemo } from 'react';\nimport pick from 'lodash/pick';\n/**\n * Context to store the pagination part of the useListController() result.\n *\n * Use the useListPaginationContext() hook to read the pagination information.\n * That's what List components do in react-admin (e.g. ).\n *\n * @typedef {Object} ListPaginationContextValue\n * @prop {boolean} isLoading boolean that is false until the data is available\n * @prop {integer} total the total number of results for the current filters, excluding pagination. Useful to build the pagination controls. e.g. 23\n * @prop {integer} page the current page. Starts at 1\n * @prop {Function} setPage a callback to change the page, e.g. setPage(3)\n * @prop {integer} perPage the number of results per page. Defaults to 25\n * @prop {Function} setPerPage a callback to change the number of results per page, e.g. setPerPage(25)\n * @prop {Boolean} hasPreviousPage true if the current page is not the first one\n * @prop {Boolean} hasNextPage true if the current page is not the last one\n\n * @prop {string} resource the resource name, deduced from the location. e.g. 'posts'\n *\n * @typedef Props\n * @prop {ListPaginationContextValue} value\n *\n * @param {Props}\n *\n * @see useListController\n * @see useListContext\n *\n * @example\n *\n * import { useListController, ListPaginationContext } from 'ra-core';\n *\n * const List = props => {\n * const controllerProps = useListController(props);\n * return (\n * \n * ...\n * \n * );\n * };\n */\nexport var ListPaginationContext = createContext(undefined);\nListPaginationContext.displayName = 'ListPaginationContext';\nexport var usePickPaginationContext = function (context) {\n return useMemo(function () {\n return pick(context, [\n 'isLoading',\n 'isPending',\n 'hasPreviousPage',\n 'hasNextPage',\n 'page',\n 'perPage',\n 'setPage',\n 'setPerPage',\n 'total',\n 'resource',\n ]);\n }, \n // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n context.isLoading,\n context.isPending,\n context.hasPreviousPage,\n context.hasNextPage,\n context.page,\n context.perPage,\n context.setPage,\n context.setPerPage,\n context.total,\n ]);\n};\n//# sourceMappingURL=ListPaginationContext.js.map","import * as React from 'react';\nimport { ListContext } from './ListContext';\nimport { ListFilterContext, usePickFilterContext } from './ListFilterContext';\nimport { ListSortContext, usePickSortContext } from './ListSortContext';\nimport { ListPaginationContext, usePickPaginationContext, } from './ListPaginationContext';\n/**\n * Create a List Context and several thematic List subcontext.\n *\n * Allows children to subscribe to part of the ListContext, and bail out of\n * rendering when some parts of the context that they don't depend on change\n * (because unfortunately React doesn't allow to use context selectors yet).\n *\n * @example\n *\n * const MyList = (props) => {\n * const controllerProps = useListController(props);\n * return (\n * \n * \n * \n * );\n * };\n *\n * const MyListView = () => {\n * const { data, filterValues, setFilters } = useListContext();\n * // or, to rerender only when filters change but not data\n * const { filterValues, setFilters } = useListFilterContext();\n * }\n *\n * @see ListContext\n * @see ListFilterContext\n */\nexport var ListContextProvider = function (_a) {\n var value = _a.value, children = _a.children;\n return (React.createElement(ListContext.Provider, { value: value },\n React.createElement(ListFilterContext.Provider, { value: usePickFilterContext(value) },\n React.createElement(ListSortContext.Provider, { value: usePickSortContext(value) },\n React.createElement(ListPaginationContext.Provider, { value: usePickPaginationContext(value) }, children)))));\n};\n//# sourceMappingURL=ListContextProvider.js.map","import { createContext } from 'react';\n/**\n * Context to store the pagination callbacks from the useInfiniteListController() result.\n *\n * Use the useInfinitePaginationContext() hook to read the pagination callbacks.\n *\n * @typedef {Object} InfinitePaginationContextValue\n * @prop {Function} fetchNextPage a callback to fetch the next page\n * @prop {Function} fetchPreviousPage a callback to fetch the previous page\n\n * @example\n *\n * import { useListController, ListPaginationContext } from 'ra-core';\n *\n * const List = props => {\n * const { fetchNextPage, fetchPreviousPage } = useInfiniteListController(props);\n * return (\n * \n * ...\n * \n * );\n * };\n */\nexport var InfinitePaginationContext = createContext({\n hasNextPage: false,\n fetchNextPage: function () { return Promise.reject('not implemented'); },\n isFetchingNextPage: false,\n hasPreviousPage: false,\n fetchPreviousPage: function () { return Promise.reject('not implemented'); },\n isFetchingPreviousPage: false,\n});\nInfinitePaginationContext.displayName = 'InfinitePaginationContext';\n//# sourceMappingURL=InfinitePaginationContext.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport * as React from 'react';\nimport { useInfiniteListController, } from './useInfiniteListController';\nimport { OptionalResourceContextProvider } from '../../core';\nimport { ListContextProvider } from './ListContextProvider';\nimport { InfinitePaginationContext } from './InfinitePaginationContext';\nimport { useIsAuthPending } from '../../auth';\n/**\n * Call useInfiniteListController and put the value in a ListContext\n *\n * Base class for components, without UI.\n *\n * Accepts any props accepted by useInfiniteListController:\n * - filter: permanent filter applied to the list\n * - filters: Filter element, to display the filters\n * - filterDefaultValues: object;\n * - perPage: Number of results per page\n * - sort: Default sort\n * - exporter: exported function\n *\n * @example // Custom list layout\n *\n * const PostList = () => (\n * \n *
\n * List metrics...\n *
\n * \n * \n * record.title} />\n * \n * \n * List instructions...\n * \n * \n *
\n * Post related links...\n *
\n * \n * );\n */\nexport var InfiniteListBase = function (_a) {\n var children = _a.children, _b = _a.loading, loading = _b === void 0 ? null : _b, props = __rest(_a, [\"children\", \"loading\"]);\n var controllerProps = useInfiniteListController(props);\n var isAuthPending = useIsAuthPending({\n resource: controllerProps.resource,\n action: 'list',\n });\n if (isAuthPending && !props.disableAuthentication) {\n return loading;\n }\n return (\n // We pass props.resource here as we don't need to create a new ResourceContext if the props is not provided\n React.createElement(OptionalResourceContextProvider, { value: props.resource },\n React.createElement(ListContextProvider, { value: controllerProps },\n React.createElement(InfinitePaginationContext.Provider, { value: {\n hasNextPage: controllerProps.hasNextPage,\n fetchNextPage: controllerProps.fetchNextPage,\n isFetchingNextPage: controllerProps.isFetchingNextPage,\n hasPreviousPage: controllerProps.hasPreviousPage,\n fetchPreviousPage: controllerProps.fetchPreviousPage,\n isFetchingPreviousPage: controllerProps.isFetchingPreviousPage,\n } }, children))));\n};\n//# sourceMappingURL=InfiniteListBase.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { isValidElement, useEffect, useMemo } from 'react';\nimport { useAuthenticated, useRequireAccess } from '../../auth';\nimport { useTranslate } from '../../i18n';\nimport { useNotify } from '../../notification';\nimport { useGetList, } from '../../dataProvider';\nimport { useResourceContext, useGetResourceLabel } from '../../core';\nimport { useRecordSelection } from './useRecordSelection';\nimport { useListParams } from './useListParams';\nimport { useSelectAll } from './useSelectAll';\nimport { defaultExporter } from '../../export';\nimport { SORT_ASC } from './queryReducer';\n/**\n * Prepare data for the List view\n *\n * @param {Object} props The props passed to the List component.\n *\n * @return {Object} controllerProps Fetched and computed data for the List view\n *\n * @example\n *\n * import { useListController } from 'react-admin';\n * import ListView from './ListView';\n *\n * const MyList = props => {\n * const controllerProps = useListController(props);\n * return ;\n * }\n */\nexport var useListController = function (props) {\n if (props === void 0) { props = {}; }\n var _a = props.debounce, debounce = _a === void 0 ? 500 : _a, _b = props.disableAuthentication, disableAuthentication = _b === void 0 ? false : _b, _c = props.disableSyncWithLocation, disableSyncWithLocation = _c === void 0 ? false : _c, _d = props.exporter, exporter = _d === void 0 ? defaultExporter : _d, filter = props.filter, filterDefaultValues = props.filterDefaultValues, _e = props.perPage, perPage = _e === void 0 ? 10 : _e, _f = props.queryOptions, queryOptions = _f === void 0 ? {} : _f, _g = props.sort, sort = _g === void 0 ? defaultSort : _g, storeKey = props.storeKey;\n var resource = useResourceContext(props);\n var meta = queryOptions.meta, otherQueryOptions = __rest(queryOptions, [\"meta\"]);\n if (!resource) {\n throw new Error(\"useListController requires a non-empty resource prop or context\");\n }\n if (filter &&\n (isValidElement(filter) ||\n (Array.isArray(filter) && filter.some(isValidElement)))) {\n throw new Error('useListController received a React element as `filter` props. If you intended to set the list filter elements, use the `filters` (with an s) prop instead. The `filter` prop is internal and should not be set by the developer.');\n }\n var isPendingAuthenticated = useAuthenticated({\n enabled: !disableAuthentication,\n }).isPending;\n var isPendingCanAccess = useRequireAccess({\n action: 'list',\n resource: resource,\n // If disableAuthentication is true then isPendingAuthenticated will always be true so this hook is disabled\n enabled: !isPendingAuthenticated,\n }).isPending;\n var translate = useTranslate();\n var notify = useNotify();\n var _h = useListParams({\n debounce: debounce,\n disableSyncWithLocation: disableSyncWithLocation,\n filterDefaultValues: filterDefaultValues,\n perPage: perPage,\n resource: resource,\n sort: sort,\n storeKey: storeKey,\n }), query = _h[0], queryModifiers = _h[1];\n var _j = useRecordSelection({\n resource: resource,\n disableSyncWithStore: storeKey === false,\n }), selectedIds = _j[0], selectionModifiers = _j[1];\n var _k = useGetList(resource, {\n pagination: {\n page: query.page,\n perPage: query.perPage,\n },\n sort: { field: query.sort, order: query.order },\n filter: __assign(__assign({}, query.filter), filter),\n meta: meta,\n }, __assign({ enabled: (!isPendingAuthenticated && !isPendingCanAccess) ||\n disableAuthentication, placeholderData: function (previousData) { return previousData; }, retry: false, onError: function (error) {\n return notify((error === null || error === void 0 ? void 0 : error.message) || 'ra.notification.http_error', {\n type: 'error',\n messageArgs: {\n _: error === null || error === void 0 ? void 0 : error.message,\n },\n });\n } }, otherQueryOptions)), data = _k.data, pageInfo = _k.pageInfo, total = _k.total, responseMeta = _k.meta, error = _k.error, isLoading = _k.isLoading, isFetching = _k.isFetching, isPending = _k.isPending, refetch = _k.refetch;\n // change page if there is no data\n useEffect(function () {\n if (query.page <= 0 ||\n (!isFetching &&\n query.page > 1 &&\n (data == null || (data === null || data === void 0 ? void 0 : data.length) === 0))) {\n // Query for a page that doesn't exist, set page to 1\n queryModifiers.setPage(1);\n return;\n }\n if (total == null) {\n return;\n }\n var totalPages = Math.ceil(total / query.perPage) || 1;\n if (!isFetching && query.page > totalPages) {\n // Query for a page out of bounds, set page to the last existing page\n // It occurs when deleting the last element of the last page\n queryModifiers.setPage(totalPages);\n }\n }, [isFetching, query.page, query.perPage, data, queryModifiers, total]);\n var currentSort = useMemo(function () { return ({\n field: query.sort,\n order: query.order,\n }); }, [query.sort, query.order]);\n var getResourceLabel = useGetResourceLabel();\n var defaultTitle = translate('ra.page.list', {\n name: getResourceLabel(resource, 2),\n });\n var onSelectAll = useSelectAll({\n resource: resource,\n sort: { field: query.sort, order: query.order },\n filter: __assign(__assign({}, query.filter), filter),\n });\n return {\n sort: currentSort,\n data: data,\n meta: responseMeta,\n defaultTitle: defaultTitle,\n displayedFilters: query.displayedFilters,\n error: error,\n exporter: exporter,\n filter: filter,\n filterValues: query.filterValues,\n hideFilter: queryModifiers.hideFilter,\n isFetching: isFetching,\n isLoading: isLoading,\n isPending: isPending,\n onSelect: selectionModifiers.select,\n onSelectAll: onSelectAll,\n onToggleItem: selectionModifiers.toggle,\n onUnselectItems: selectionModifiers.clearSelection,\n page: query.page,\n perPage: query.perPage,\n refetch: refetch,\n resource: resource,\n selectedIds: selectedIds,\n setFilters: queryModifiers.setFilters,\n setPage: queryModifiers.setPage,\n setPerPage: queryModifiers.setPerPage,\n setSort: queryModifiers.setSort,\n showFilter: queryModifiers.showFilter,\n total: total,\n hasNextPage: pageInfo\n ? pageInfo.hasNextPage\n : total != null\n ? query.page * query.perPage < total\n : undefined,\n hasPreviousPage: pageInfo ? pageInfo.hasPreviousPage : query.page > 1,\n };\n};\nvar defaultSort = {\n field: 'id',\n order: SORT_ASC,\n};\nexport var injectedProps = [\n 'sort',\n 'data',\n 'defaultTitle',\n 'displayedFilters',\n 'error',\n 'exporter',\n 'filterValues',\n 'hasNextPage',\n 'hasPreviousPage',\n 'hideFilter',\n 'isFetching',\n 'isLoading',\n 'isPending',\n 'onSelect',\n 'onSelectAll',\n 'onToggleItem',\n 'onUnselectItems',\n 'page',\n 'perPage',\n 'refetch',\n 'refresh',\n 'resource',\n 'selectedIds',\n 'setFilters',\n 'setPage',\n 'setPerPage',\n 'setSort',\n 'showFilter',\n 'total',\n 'totalPages',\n];\n/**\n * Select the props injected by the useListController hook\n * to be passed to the List children need\n * This is an implementation of pick()\n */\nexport var getListControllerProps = function (props) {\n return injectedProps.reduce(function (acc, key) {\n var _a;\n return (__assign(__assign({}, acc), (_a = {}, _a[key] = props[key], _a)));\n }, {});\n};\n/**\n * Select the props not injected by the useListController hook\n * to be used inside the List children to sanitize props injected by List\n * This is an implementation of omit()\n */\nexport var sanitizeListRestProps = function (props) {\n return Object.keys(props)\n .filter(function (propName) { return !injectedProps.includes(propName); })\n .reduce(function (acc, key) {\n var _a;\n return (__assign(__assign({}, acc), (_a = {}, _a[key] = props[key], _a)));\n }, {});\n};\n//# sourceMappingURL=useListController.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport * as React from 'react';\nimport { useListController } from './useListController';\nimport { OptionalResourceContextProvider } from '../../core';\nimport { ListContextProvider } from './ListContextProvider';\nimport { useIsAuthPending } from '../../auth';\n/**\n * Call useListController and put the value in a ListContext\n *\n * Base class for components, without UI.\n *\n * Accepts any props accepted by useListController:\n * - filter: permanent filter applied to the list\n * - filters: Filter element, to display the filters\n * - filterDefaultValues: object;\n * - perPage: Number of results per page\n * - sort: Default sort\n * - exporter: exported function\n *\n * @example // Custom list layout\n *\n * const PostList = () => (\n * \n *
\n * List metrics...\n *
\n * \n * \n * record.title} />\n * \n * \n * List instructions...\n * \n * \n *
\n * Post related links...\n *
\n *
\n * );\n */\nexport var ListBase = function (_a) {\n var children = _a.children, _b = _a.loading, loading = _b === void 0 ? null : _b, props = __rest(_a, [\"children\", \"loading\"]);\n var controllerProps = useListController(props);\n var isAuthPending = useIsAuthPending({\n resource: controllerProps.resource,\n action: 'list',\n });\n if (isAuthPending && !props.disableAuthentication) {\n return loading;\n }\n return (\n // We pass props.resource here as we don't need to create a new ResourceContext if the props is not provided\n React.createElement(OptionalResourceContextProvider, { value: props.resource },\n React.createElement(ListContextProvider, { value: controllerProps }, children)));\n};\n//# sourceMappingURL=ListBase.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { useCallback } from 'react';\nimport { useStore } from '../../store';\n/**\n * State-like hook for controlling the expanded state of a list item\n *\n * @param {string} resource The resource name, e.g. 'posts'\n * @param {string|integer} id The record identifier, e.g. 123\n * @param {boolean} single Forces only one id to be expanded at a time\n * @returns {Object} Destructure as [expanded, toggleExpanded].\n *\n * @example\n *\n * const [expanded, toggleExpanded] = useExpanded('posts', 123);\n * const expandIcon = expanded ? ExpandLess : ExpandMore;\n * const onExpandClick = () => toggleExpanded();\n */\nexport var useExpanded = function (resource, id, single) {\n if (single === void 0) { single = false; }\n var _a = useStore(\"\".concat(resource, \".datagrid.expanded\"), []), expandedIds = _a[0], setExpandedIds = _a[1];\n var expanded = Array.isArray(expandedIds)\n ? // eslint-disable-next-line eqeqeq\n expandedIds.map(function (el) { return el == id; }).indexOf(true) !== -1\n : false;\n var toggleExpanded = useCallback(function () {\n setExpandedIds(function (ids) {\n if (!Array.isArray(ids)) {\n return [id];\n }\n var index = ids.findIndex(function (el) { return el == id; }); // eslint-disable-line eqeqeq\n return index > -1\n ? single\n ? []\n : __spreadArray(__spreadArray([], ids.slice(0, index), true), ids.slice(index + 1), true)\n : single\n ? [id]\n : __spreadArray(__spreadArray([], ids, true), [id], false);\n });\n }, [setExpandedIds, id, single]);\n return [expanded, toggleExpanded];\n};\n/**\n * State-like hook for controlling the expanded state of many list items\n * expanded state is true when at least one item from ids is expanded.\n *\n * @param {string} resource The resource name, e.g. 'posts'\n * @param {Identifier[]} ids A list of record identifiers\n * @returns {Object} Destructure as [expanded, toggleExpanded].\n *\n * @example\n *\n * const [expanded, toggleExpanded] = useExpandAll('posts', [123, 124, 125]);\n * const expandIcon = expanded ? ExpandLess : ExpandMore;\n * const onExpandClick = () => toggleExpanded();\n */\nexport var useExpandAll = function (resource, ids) {\n var _a = useStore(\"\".concat(resource, \".datagrid.expanded\"), []), expandedIds = _a[0], setExpandedIds = _a[1];\n var isExpanded = Array.isArray(expandedIds)\n ? // eslint-disable-next-line eqeqeq\n expandedIds.some(function (id) { return ids.some(function (id2) { return id2 == id; }); })\n : false;\n var toggleExpandedAll = useCallback(function () {\n var unaffectedExpandedIds = expandedIds.filter(\n // eslint-disable-next-line eqeqeq\n function (expanded_id) { return !ids.some(function (id) { return id == expanded_id; }); });\n setExpandedIds(isExpanded\n ? unaffectedExpandedIds\n : unaffectedExpandedIds.concat(ids));\n }, [expandedIds, setExpandedIds, isExpanded, ids]);\n return [isExpanded, toggleExpandedAll];\n};\n//# sourceMappingURL=useExpanded.js.map","import { useContext } from 'react';\nimport { InfinitePaginationContext, } from './InfinitePaginationContext';\n/**\n * Hook to read the infinite pagination callbacks from the InfinitePaginationContext.\n *\n * Must be used within a (e.g. as a descendent of \n * or ).\n *\n * @typedef {Object} InfinitePaginationContextValue\n * @prop {Function} fetchNextPage a callback to fetch the next page\n * @prop {Function} fetchPreviousPage a callback to fetch the previous page\n *\n * @returns {InfinitePaginationContextValue} infinite pagination callbacks\n *\n * @see useInfiniteListController for how the callbacks are built\n */\nexport var useInfinitePaginationContext = function () { return useContext(InfinitePaginationContext); };\n//# sourceMappingURL=useInfinitePaginationContext.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport get from 'lodash/get';\nimport isEqual from 'lodash/isEqual';\nimport { removeEmpty } from '../../util';\nimport { useResourceContext } from '../../core';\nimport usePaginationState from '../usePaginationState';\nimport useSortState from '../useSortState';\nimport { useRecordSelection } from './useRecordSelection';\nimport { flattenObject } from '../../dataProvider/fetch';\nvar refetch = function () {\n throw new Error('refetch is not available for a ListContext built from useList based on local data');\n};\n/**\n * Handle filtering, sorting and pagination on local data.\n *\n * Returns the data and callbacks expected by .\n *\n * @example\n * const data = [\n * { id: 1, name: 'Arnold' },\n * { id: 2, name: 'Sylvester' },\n * { id: 3, name: 'Jean-Claude' },\n * ]\n *\n * const MyComponent = () => {\n * const listContext = useList({ data });\n * return (\n * \n * \n * \n * \n * \n * \n * );\n * };\n *\n * @param {UseListOptions} props\n * @param {RaRecord[]} props.data An array of records\n * @param {Boolean} props.isFetching: Optional. A boolean indicating whether the data is being loaded\n * @param {Boolean} props.isLoading: Optional. A boolean indicating whether the data has been loaded at least once\n * @param {Error | String} props.error: Optional. The error if any occurred while loading the data\n * @param {Object} props.filter: Optional. An object containing the filters applied on the data\n * @param {Number} props.page: Optional. The initial page index\n * @param {Number} props.perPage: Optional. The initial page size\n * @param {SortPayload} props.sort: Optional. The initial sort (field and order)\n * @param {filterCallback} prop.filterCallback Optional. A function that allows you to make a custom filter\n */\nexport var useList = function (props) {\n var _a;\n var data = props.data, error = props.error, _b = props.filter, filter = _b === void 0 ? defaultFilter : _b, _c = props.isFetching, isFetching = _c === void 0 ? false : _c, _d = props.isLoading, isLoading = _d === void 0 ? false : _d, _e = props.isPending, isPending = _e === void 0 ? false : _e, _f = props.page, initialPage = _f === void 0 ? 1 : _f, _g = props.perPage, initialPerPage = _g === void 0 ? 1000 : _g, initialSort = props.sort, _h = props.filterCallback, filterCallback = _h === void 0 ? function (record) { return Boolean(record); } : _h;\n var resource = useResourceContext(props);\n var _j = useState(isFetching), fetchingState = _j[0], setFetchingState = _j[1];\n var _k = useState(isLoading), loadingState = _k[0], setLoadingState = _k[1];\n var _l = useState(isPending), pendingState = _l[0], setPendingState = _l[1];\n var _m = useState(function () { return ({\n data: data,\n total: data ? data.length : undefined,\n }); }), finalItems = _m[0], setFinalItems = _m[1];\n // pagination logic\n var _o = usePaginationState({\n page: initialPage,\n perPage: initialPerPage,\n }), page = _o.page, setPage = _o.setPage, perPage = _o.perPage, setPerPage = _o.setPerPage;\n // sort logic\n var _p = useSortState(initialSort), sort = _p.sort, setSortState = _p.setSort;\n var setSort = useCallback(function (sort) {\n setSortState(sort);\n setPage(1);\n }, [setPage, setSortState]);\n // selection logic\n var _q = useRecordSelection(resource\n ? {\n resource: resource,\n }\n : { disableSyncWithStore: true }), selectedIds = _q[0], selectionModifiers = _q[1];\n // filter logic\n var filterRef = useRef(filter);\n var _r = useState({}), displayedFilters = _r[0], setDisplayedFilters = _r[1];\n var _s = useState(filter), filterValues = _s[0], setFilterValues = _s[1];\n var hideFilter = useCallback(function (filterName) {\n setDisplayedFilters(function (previousState) {\n var _a = previousState, _b = filterName, _ = _a[_b], newState = __rest(_a, [typeof _b === \"symbol\" ? _b : _b + \"\"]);\n return newState;\n });\n setFilterValues(function (previousState) {\n var _a = previousState, _b = filterName, _ = _a[_b], newState = __rest(_a, [typeof _b === \"symbol\" ? _b : _b + \"\"]);\n return newState;\n });\n }, [setDisplayedFilters, setFilterValues]);\n var showFilter = useCallback(function (filterName, defaultValue) {\n setDisplayedFilters(function (previousState) {\n var _a;\n return (__assign(__assign({}, previousState), (_a = {}, _a[filterName] = true, _a)));\n });\n setFilterValues(function (previousState) {\n var _a;\n return removeEmpty(__assign(__assign({}, previousState), (_a = {}, _a[filterName] = defaultValue, _a)));\n });\n }, [setDisplayedFilters, setFilterValues]);\n var setFilters = useCallback(function (filters, displayedFilters) {\n if (displayedFilters === void 0) { displayedFilters = undefined; }\n setFilterValues(removeEmpty(filters));\n if (displayedFilters) {\n setDisplayedFilters(displayedFilters);\n }\n setPage(1);\n }, [setDisplayedFilters, setFilterValues, setPage]);\n // handle filter prop change\n useEffect(function () {\n if (!isEqual(filter, filterRef.current)) {\n filterRef.current = filter;\n setFilterValues(filter);\n }\n }, [filter]);\n // We do all the data processing (filtering, sorting, paginating) client-side\n useEffect(function () {\n if (isPending || !data)\n return;\n var tempData = data;\n // 1. filter\n if (filterValues) {\n var flattenFilterValues_1 = flattenObject(filterValues);\n tempData = data\n .filter(function (record) {\n return Object.entries(flattenFilterValues_1).every(function (_a) {\n var filterName = _a[0], filterValue = _a[1];\n var recordValue = get(record, filterName);\n var result = Array.isArray(recordValue)\n ? Array.isArray(filterValue)\n ? recordValue.some(function (item) {\n return filterValue.includes(item);\n })\n : recordValue.includes(filterValue)\n : Array.isArray(filterValue)\n ? filterValue.includes(recordValue)\n : filterName === 'q' // special full-text filter\n ? Object.keys(record).some(function (key) {\n return typeof record[key] ===\n 'string' &&\n record[key]\n .toLowerCase()\n .includes(filterValue.toLowerCase());\n })\n : filterValue == recordValue; // eslint-disable-line eqeqeq\n return result;\n });\n })\n .filter(filterCallback);\n }\n var filteredLength = tempData.length;\n // 2. sort\n if (sort.field) {\n tempData = tempData.sort(function (a, b) {\n if (get(a, sort.field) > get(b, sort.field)) {\n return sort.order === 'ASC' ? 1 : -1;\n }\n if (get(a, sort.field) < get(b, sort.field)) {\n return sort.order === 'ASC' ? -1 : 1;\n }\n return 0;\n });\n }\n // 3. paginate\n tempData = tempData.slice((page - 1) * perPage, page * perPage);\n setFinalItems({\n data: tempData,\n total: filteredLength,\n });\n }, // eslint-disable-next-line react-hooks/exhaustive-deps\n [\n // eslint-disable-next-line react-hooks/exhaustive-deps\n JSON.stringify(data),\n filterValues,\n isPending,\n page,\n perPage,\n setFinalItems,\n sort.field,\n sort.order,\n ]);\n useEffect(function () {\n if (isFetching !== fetchingState) {\n setFetchingState(isFetching);\n }\n }, [isFetching, fetchingState, setFetchingState]);\n useEffect(function () {\n if (isLoading !== loadingState) {\n setLoadingState(isLoading);\n }\n }, [isLoading, loadingState, setLoadingState]);\n useEffect(function () {\n if (isPending !== pendingState) {\n setPendingState(isPending);\n }\n }, [isPending, pendingState, setPendingState]);\n var onSelectAll = useCallback(function () {\n var allIds = (data === null || data === void 0 ? void 0 : data.map(function (_a) {\n var id = _a.id;\n return id;\n })) || [];\n selectionModifiers.select(allIds);\n }, [data, selectionModifiers]);\n return {\n sort: sort,\n data: pendingState ? undefined : (_a = finalItems === null || finalItems === void 0 ? void 0 : finalItems.data) !== null && _a !== void 0 ? _a : [],\n defaultTitle: '',\n error: error !== null && error !== void 0 ? error : null,\n displayedFilters: displayedFilters,\n filterValues: filterValues,\n hasNextPage: (finalItems === null || finalItems === void 0 ? void 0 : finalItems.total) == null\n ? false\n : page * perPage < finalItems.total,\n hasPreviousPage: page > 1,\n hideFilter: hideFilter,\n isFetching: fetchingState,\n isLoading: loadingState,\n isPending: pendingState,\n onSelect: selectionModifiers.select,\n onSelectAll: onSelectAll,\n onToggleItem: selectionModifiers.toggle,\n onUnselectItems: selectionModifiers.clearSelection,\n page: page,\n perPage: perPage,\n resource: '',\n refetch: refetch,\n selectedIds: selectedIds,\n setFilters: setFilters,\n setPage: setPage,\n setPerPage: setPerPage,\n setSort: setSort,\n showFilter: showFilter,\n total: finalItems === null || finalItems === void 0 ? void 0 : finalItems.total,\n };\n};\nvar defaultFilter = {};\n//# sourceMappingURL=useList.js.map","import { useContext } from 'react';\nimport { ListContext } from './ListContext';\n/**\n * Hook to read the list controller props from the ListContext.\n *\n * Used within a (e.g. as a descendent of ).\n *\n * @returns {ListControllerResult} list controller props\n *\n * @see useListController for how it is filled\n *\n * @example // custom list view\n *\n * import { useListContext } from 'react-admin';\n *\n * const MyList = () => {\n * const { data, isPending } = useListContext();\n * if (isPending) {\n * return <>Loading...;\n * }\n * return (\n *
    \n * {data.map(record => (\n *
  • {record.name}
  • \n * ))}\n *
\n * );\n * }\n *\n * @example // custom pagination\n *\n * import { useListContext } from 'react-admin';\n * import { Button, Toolbar } from '@mui/material';\n * import ChevronLeft from '@mui/icons-material/ChevronLeft';\n * import ChevronRight from '@mui/icons-material/ChevronRight';\n *\n * const PrevNextPagination = () => {\n * const { page, perPage, total, setPage } = useListContext();\n * const nbPages = Math.ceil(total / perPage) || 1;\n * return (\n * nbPages > 1 &&\n * \n * {page > 1 &&\n * \n * }\n * {page !== nbPages &&\n * \n * }\n * \n * );\n * }\n */\nexport var useListContext = function () {\n var context = useContext(ListContext);\n if (!context) {\n throw new Error('useListContext must be used inside a ListContextProvider');\n }\n return context;\n};\n//# sourceMappingURL=useListContext.js.map","var baseRest = require('./_baseRest'),\n eq = require('./eq'),\n isIterateeCall = require('./_isIterateeCall'),\n keysIn = require('./keysIn');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns own and inherited enumerable string keyed properties of source\n * objects to the destination object for all destination properties that\n * resolve to `undefined`. Source objects are applied from left to right.\n * Once a property is set, additional values of the same property are ignored.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaultsDeep\n * @example\n *\n * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\nvar defaults = baseRest(function(object, sources) {\n object = Object(object);\n\n var index = -1;\n var length = sources.length;\n var guard = length > 2 ? sources[2] : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n length = 1;\n }\n\n while (++index < length) {\n var source = sources[index];\n var props = keysIn(source);\n var propsIndex = -1;\n var propsLength = props.length;\n\n while (++propsIndex < propsLength) {\n var key = props[propsIndex];\n var value = object[key];\n\n if (value === undefined ||\n (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n object[key] = source[key];\n }\n }\n }\n\n return object;\n});\n\nmodule.exports = defaults;\n","import { useContext, useMemo } from 'react';\nimport defaults from 'lodash/defaults';\nimport { ListContext } from './ListContext';\n/**\n * Hook to read the list controller props from the ListContext.\n *\n * Mostly used within a (e.g. as a descendent of \n * or ).\n *\n * But you can also use it without a . In this case, it is up to you\n * to pass all the necessary props (see the list below).\n *\n * The given props will take precedence over context values.\n *\n * @typedef {Object} ListControllerProps\n * @prop {Object} data an array of the list records, e.g. [{ id: 123, title: 'hello world' }, { ... }]\n * @prop {integer} total the total number of results for the current filters, excluding pagination. Useful to build the pagination controls. e.g. 23\n * @prop {boolean} isFetching boolean that is true on mount, and false once the data was fetched\n * @prop {boolean} isLoading boolean that is false until the data is available\n * @prop {integer} page the current page. Starts at 1\n * @prop {Function} setPage a callback to change the page, e.g. setPage(3)\n * @prop {integer} perPage the number of results per page. Defaults to 25\n * @prop {Function} setPerPage a callback to change the number of results per page, e.g. setPerPage(25)\n * @prop {Object} sort a sort object { field, order }, e.g. { field: 'date', order: 'DESC' }\n * @prop {Function} setSort a callback to change the sort, e.g. setSort({ field : 'name', order: 'ASC' })\n * @prop {Object} filterValues a dictionary of filter values, e.g. { title: 'lorem', nationality: 'fr' }\n * @prop {Function} setFilters a callback to update the filters, e.g. setFilters(filters, displayedFilters)\n * @prop {Object} displayedFilters a dictionary of the displayed filters, e.g. { title: true, nationality: true }\n * @prop {Function} showFilter a callback to show one of the filters, e.g. showFilter('title', defaultValue)\n * @prop {Function} hideFilter a callback to hide one of the filters, e.g. hideFilter('title')\n * @prop {Array} selectedIds an array listing the ids of the selected rows, e.g. [123, 456]\n * @prop {Function} onSelect callback to change the list of selected rows, e.g. onSelect([456, 789])\n * @prop {Function} onSelectAll callback to select all the records, e.g. onSelectAll({ limit: 50, queryOptions: { meta: { foo: 'bar' } } })\n * @prop {Function} onToggleItem callback to toggle the selection of a given record based on its id, e.g. onToggleItem(456)\n * @prop {Function} onUnselectItems callback to clear the selection, e.g. onUnselectItems();\n * @prop {string} defaultTitle the translated title based on the resource, e.g. 'Posts'\n * @prop {string} resource the resource name, deduced from the location. e.g. 'posts'\n *\n * @param {ListControllerProps} props Props passed to the useListContext hook\n *\n * @returns {ListControllerResult} list controller props\n *\n * @see useListController for how it is filled\n */\nexport var useListContextWithProps = function (props) {\n var context = useContext(ListContext);\n // Props take precedence over the context\n return useMemo(function () {\n return defaults({}, props != null ? extractListContextProps(props) : {}, context);\n }, [context, props]);\n};\n/**\n * Extract only the list controller props\n *\n * @param {Object} props Props passed to the useListContext hook\n *\n * @returns {ListControllerResult} List controller props\n */\nvar extractListContextProps = function (_a) {\n var sort = _a.sort, data = _a.data, defaultTitle = _a.defaultTitle, displayedFilters = _a.displayedFilters, exporter = _a.exporter, filterValues = _a.filterValues, hasCreate = _a.hasCreate, hideFilter = _a.hideFilter, isFetching = _a.isFetching, isLoading = _a.isLoading, isPending = _a.isPending, onSelect = _a.onSelect, onSelectAll = _a.onSelectAll, onToggleItem = _a.onToggleItem, onUnselectItems = _a.onUnselectItems, page = _a.page, perPage = _a.perPage, refetch = _a.refetch, resource = _a.resource, selectedIds = _a.selectedIds, setFilters = _a.setFilters, setPage = _a.setPage, setPerPage = _a.setPerPage, setSort = _a.setSort, showFilter = _a.showFilter, total = _a.total;\n return ({\n sort: sort,\n data: data,\n defaultTitle: defaultTitle,\n displayedFilters: displayedFilters,\n exporter: exporter,\n filterValues: filterValues,\n hasCreate: hasCreate,\n hideFilter: hideFilter,\n isFetching: isFetching,\n isLoading: isLoading,\n isPending: isPending,\n onSelect: onSelect,\n onSelectAll: onSelectAll,\n onToggleItem: onToggleItem,\n onUnselectItems: onUnselectItems,\n page: page,\n perPage: perPage,\n refetch: refetch,\n resource: resource,\n selectedIds: selectedIds,\n setFilters: setFilters,\n setPage: setPage,\n setPerPage: setPerPage,\n setSort: setSort,\n showFilter: showFilter,\n total: total,\n });\n};\n//# sourceMappingURL=useListContextWithProps.js.map","import { useContext } from 'react';\nimport { ListPaginationContext, } from './ListPaginationContext';\n/**\n * Hook to read the list pagination controller props from the ListPaginationContext.\n *\n * Must be used within a (e.g. as a descendent of \n * or ).\n *\n * @returns {ListPaginationContextValue} list controller props\n *\n * @see useListController for how it is filled\n */\nexport var useListPaginationContext = function () {\n var context = useContext(ListPaginationContext);\n if (!context) {\n throw new Error('useListPaginationContext must be used inside a ListPaginationContextProvider');\n }\n return context;\n};\n//# sourceMappingURL=useListPaginationContext.js.map","import { useCallback } from 'react';\nimport { useRecordSelection } from './useRecordSelection';\n/**\n * Hook to Unselect the rows of a datagrid\n *\n * @example\n *\n * const unselect = useUnselect('posts');\n * unselect([123, 456]);\n */\nexport var useUnselect = function (resource) {\n var _a = useRecordSelection(resource ? { resource: resource } : { disableSyncWithStore: true }), unselect = _a[1].unselect;\n return useCallback(function (ids) {\n unselect(ids);\n }, [unselect]);\n};\n//# sourceMappingURL=useUnselect.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport get from 'lodash/get';\nimport { useGetManyAggregate } from '../../dataProvider';\nimport { useList } from '../list';\nimport { useNotify } from '../../notification';\nvar emptyArray = [];\nvar defaultFilter = {};\n/**\n * Hook that fetches records from another resource specified\n * by an array of *ids* in current record.\n *\n * @example\n *\n * const { data, error, isFetching, isPending } = useReferenceArrayFieldController({\n * record: { referenceIds: ['id1', 'id2']};\n * reference: 'reference';\n * resource: 'resource';\n * source: 'referenceIds';\n * });\n *\n * @param {Object} props\n * @param {Object} props.record The current resource record\n * @param {string} props.reference The linked resource name\n * @param {string} props.resource The current resource name\n * @param {string} props.source The key of the linked resource identifier\n *\n * @param {Props} props\n *\n * @returns {ListControllerResult} The reference props\n */\nexport var useReferenceArrayFieldController = function (props) {\n var _a = props.filter, filter = _a === void 0 ? defaultFilter : _a, _b = props.page, page = _b === void 0 ? 1 : _b, _c = props.perPage, perPage = _c === void 0 ? 1000 : _c, record = props.record, reference = props.reference, sort = props.sort, source = props.source, _d = props.queryOptions, queryOptions = _d === void 0 ? {} : _d;\n var notify = useNotify();\n var value = get(record, source);\n var meta = queryOptions.meta, otherQueryOptions = __rest(queryOptions, [\"meta\"]);\n var ids = Array.isArray(value) ? value : emptyArray;\n var _e = useGetManyAggregate(reference, { ids: ids, meta: meta }, __assign({ onError: function (error) {\n return notify(typeof error === 'string'\n ? error\n : (error === null || error === void 0 ? void 0 : error.message) ||\n 'ra.notification.http_error', {\n type: 'error',\n messageArgs: {\n _: typeof error === 'string'\n ? error\n : (error === null || error === void 0 ? void 0 : error.message)\n ? error.message\n : undefined,\n },\n });\n } }, otherQueryOptions)), data = _e.data, error = _e.error, isLoading = _e.isLoading, isFetching = _e.isFetching, isPending = _e.isPending, refetch = _e.refetch;\n var listProps = useList({\n data: data,\n error: error,\n filter: filter,\n isFetching: isFetching,\n isLoading: isLoading,\n isPending: isPending,\n page: page,\n perPage: perPage,\n sort: sort,\n });\n return __assign(__assign({}, listProps), { defaultTitle: undefined, refetch: refetch, resource: reference });\n};\n//# sourceMappingURL=useReferenceArrayFieldController.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useQueryClient } from '@tanstack/react-query';\nimport get from 'lodash/get';\nimport isEqual from 'lodash/isEqual';\nimport lodashDebounce from 'lodash/debounce';\nimport { removeEmpty, useEvent } from '../../util';\nimport { useDataProvider, useGetManyReference } from '../../dataProvider';\nimport { useNotify } from '../../notification';\nimport usePaginationState from '../usePaginationState';\nimport { useRecordSelection } from '../list/useRecordSelection';\nimport useSortState from '../useSortState';\nimport { useResourceContext } from '../../core';\n/**\n * Fetch reference records, and return them when available\n *\n * Uses dataProvider.getManyReference() internally.\n *\n * @example // fetch the comments related to the current post\n * const { isPending, data } = useReferenceManyFieldController({\n * reference: 'comments',\n * target: 'post_id',\n * record: { id: 123, title: 'hello, world' },\n * resource: 'posts',\n * });\n *\n * @param {Object} props\n * @param {string} props.reference The linked resource name. Required.\n * @param {string} props.target The target resource key. Required.\n * @param {Object} props.filter The filter applied on the recorded records list\n * @param {number} props.page the page number\n * @param {number} props.perPage the number of item per page\n * @param {Object} props.record The current resource record\n * @param {string} props.resource The current resource name\n * @param {Object} props.sort the sort to apply to the referenced records\n * @param {string} props.source The key of the linked resource identifier\n * @param {UseQuery Options} props.queryOptions `react-query` options`\n *\n * @returns {ListControllerResult} The reference many props\n */\nexport var useReferenceManyFieldController = function (props) {\n var _a;\n var _b = props.debounce, debounce = _b === void 0 ? 500 : _b, reference = props.reference, record = props.record, target = props.target, _c = props.filter, filter = _c === void 0 ? defaultFilter : _c, _d = props.source, source = _d === void 0 ? 'id' : _d, initialPage = props.page, initialPerPage = props.perPage, _e = props.sort, initialSort = _e === void 0 ? { field: 'id', order: 'DESC' } : _e, _f = props.queryOptions, queryOptions = _f === void 0 ? {} : _f;\n var notify = useNotify();\n var resource = useResourceContext(props);\n var dataProvider = useDataProvider();\n var queryClient = useQueryClient();\n var storeKey = (_a = props.storeKey) !== null && _a !== void 0 ? _a : \"\".concat(resource, \".\").concat(record === null || record === void 0 ? void 0 : record.id, \".\").concat(reference);\n var meta = queryOptions.meta, otherQueryOptions = __rest(queryOptions, [\"meta\"]);\n // pagination logic\n var _g = usePaginationState({\n page: initialPage,\n perPage: initialPerPage,\n }), page = _g.page, setPage = _g.setPage, perPage = _g.perPage, setPerPage = _g.setPerPage;\n // sort logic\n var _h = useSortState(initialSort), sort = _h.sort, setSortState = _h.setSort;\n var setSort = useCallback(function (sort) {\n setSortState(sort);\n setPage(1);\n }, [setPage, setSortState]);\n // selection logic\n var _j = useRecordSelection({\n resource: storeKey,\n }), selectedIds = _j[0], selectionModifiers = _j[1];\n // filter logic\n var filterRef = useRef(filter);\n var _k = useState({}), displayedFilters = _k[0], setDisplayedFilters = _k[1];\n var _l = useState(filter), filterValues = _l[0], setFilterValues = _l[1];\n var hideFilter = useCallback(function (filterName) {\n setDisplayedFilters(function (previousState) {\n var _a = previousState, _b = filterName, _ = _a[_b], newState = __rest(_a, [typeof _b === \"symbol\" ? _b : _b + \"\"]);\n return newState;\n });\n setFilterValues(function (previousState) {\n var _a = previousState, _b = filterName, _ = _a[_b], newState = __rest(_a, [typeof _b === \"symbol\" ? _b : _b + \"\"]);\n return newState;\n });\n }, [setDisplayedFilters, setFilterValues]);\n var showFilter = useCallback(function (filterName, defaultValue) {\n setDisplayedFilters(function (previousState) {\n var _a;\n return (__assign(__assign({}, previousState), (_a = {}, _a[filterName] = true, _a)));\n });\n setFilterValues(function (previousState) {\n var _a;\n return (__assign(__assign({}, previousState), (_a = {}, _a[filterName] = defaultValue, _a)));\n });\n }, [setDisplayedFilters, setFilterValues]);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n var debouncedSetFilters = useCallback(lodashDebounce(function (filters, displayedFilters) {\n setFilterValues(removeEmpty(filters));\n setDisplayedFilters(displayedFilters);\n setPage(1);\n }, debounce), [setDisplayedFilters, setFilterValues, setPage]);\n var setFilters = useCallback(function (filters, displayedFilters, debounce) {\n if (debounce === void 0) { debounce = false; }\n if (debounce) {\n debouncedSetFilters(filters, displayedFilters);\n }\n else {\n setFilterValues(removeEmpty(filters));\n setDisplayedFilters(displayedFilters);\n setPage(1);\n }\n }, [setDisplayedFilters, setFilterValues, setPage, debouncedSetFilters]);\n // handle filter prop change\n useEffect(function () {\n if (!isEqual(filter, filterRef.current)) {\n filterRef.current = filter;\n setFilterValues(filter);\n }\n }, [filter]);\n var _m = useGetManyReference(reference, {\n target: target,\n id: get(record, source),\n pagination: { page: page, perPage: perPage },\n sort: sort,\n filter: filterValues,\n meta: meta,\n }, __assign({ enabled: get(record, source) != null, placeholderData: function (previousData) { return previousData; }, onError: function (error) {\n return notify(typeof error === 'string'\n ? error\n : (error === null || error === void 0 ? void 0 : error.message) ||\n 'ra.notification.http_error', {\n type: 'error',\n messageArgs: {\n _: typeof error === 'string'\n ? error\n : (error === null || error === void 0 ? void 0 : error.message)\n ? error.message\n : undefined,\n },\n });\n } }, otherQueryOptions)), data = _m.data, total = _m.total, responseMeta = _m.meta, pageInfo = _m.pageInfo, error = _m.error, isFetching = _m.isFetching, isLoading = _m.isLoading, isPending = _m.isPending, refetch = _m.refetch;\n var onSelectAll = useEvent(function (_a) {\n var _b = _a === void 0 ? {} : _a, _c = _b.limit, limit = _c === void 0 ? 250 : _c, _d = _b.queryOptions, queryOptions = _d === void 0 ? {} : _d;\n return __awaiter(void 0, void 0, void 0, function () {\n var meta, onSuccess, onError, results, allIds, error_1;\n var _e;\n return __generator(this, function (_f) {\n switch (_f.label) {\n case 0:\n meta = queryOptions.meta, onSuccess = queryOptions.onSuccess, onError = queryOptions.onError;\n _f.label = 1;\n case 1:\n _f.trys.push([1, 3, , 4]);\n return [4 /*yield*/, queryClient.fetchQuery({\n queryKey: [\n resource,\n 'getManyReference',\n {\n target: target,\n id: get(record, source),\n pagination: { page: 1, perPage: limit },\n sort: sort,\n filter: filter,\n meta: meta,\n },\n ],\n queryFn: function () {\n return dataProvider.getManyReference(reference, {\n target: target,\n id: get(record, source),\n pagination: { page: 1, perPage: limit },\n sort: sort,\n filter: filter,\n meta: meta,\n });\n },\n })];\n case 2:\n results = _f.sent();\n allIds = ((_e = results.data) === null || _e === void 0 ? void 0 : _e.map(function (_a) {\n var id = _a.id;\n return id;\n })) || [];\n selectionModifiers.select(allIds);\n if (allIds.length === limit) {\n notify('ra.message.select_all_limit_reached', {\n messageArgs: { max: limit },\n type: 'warning',\n });\n }\n if (onSuccess) {\n onSuccess(results);\n }\n return [2 /*return*/, results.data];\n case 3:\n error_1 = _f.sent();\n if (onError) {\n onError(error_1);\n }\n notify('ra.notification.http_error', { type: 'warning' });\n return [3 /*break*/, 4];\n case 4: return [2 /*return*/];\n }\n });\n });\n });\n return {\n sort: sort,\n data: data,\n meta: responseMeta,\n defaultTitle: undefined,\n displayedFilters: displayedFilters,\n error: error,\n filterValues: filterValues,\n hideFilter: hideFilter,\n isFetching: isFetching,\n isLoading: isLoading,\n isPending: isPending,\n onSelect: selectionModifiers.select,\n onSelectAll: onSelectAll,\n onToggleItem: selectionModifiers.toggle,\n onUnselectItems: selectionModifiers.clearSelection,\n page: page,\n perPage: perPage,\n refetch: refetch,\n resource: reference,\n selectedIds: selectedIds,\n setFilters: setFilters,\n setPage: setPage,\n setPerPage: setPerPage,\n hasNextPage: pageInfo\n ? pageInfo.hasNextPage\n : total != null\n ? page * perPage < total\n : undefined,\n hasPreviousPage: pageInfo ? pageInfo.hasPreviousPage : page > 1,\n setSort: setSort,\n showFilter: showFilter,\n total: total,\n };\n};\nvar defaultFilter = {};\n//# sourceMappingURL=useReferenceManyFieldController.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport { useCallback, useMemo, useState, useRef, useEffect } from 'react';\nimport lodashDebounce from 'lodash/debounce';\nimport removeEmpty from '../../util/removeEmpty';\nimport { queryReducer, HIDE_FILTER, SET_FILTER, SET_PAGE, SET_PER_PAGE, SET_SORT, SHOW_FILTER, SORT_ASC, } from '../list';\n/**\n * Get the reference inputs parameters (page, sort, filters) and modifiers.\n *\n * @returns {Array} A tuple [parameters, modifiers].\n * Destructure as [\n * { page, perPage, sort, order, filter, filterValues, displayedFilters, requestSignature },\n * { setFilters, hideFilter, showFilter, setPage, setPerPage, setSort }\n * ]\n *\n * @example\n *\n * const [referenceParams, referenceParamsActions] = useReferenceParams({\n * resource: 'posts',\n * filterDefaultValues: {\n * published: true\n * },\n * sort: {\n * field: 'published_at',\n * order: 'DESC'\n * },\n * perPage: 25\n * });\n *\n * const {\n * page,\n * perPage,\n * sort,\n * order,\n * filter,\n * filterValues,\n * displayedFilters,\n * requestSignature\n * } = referenceParams;\n *\n * const {\n * setFilters,\n * hideFilter,\n * showFilter,\n * setPage,\n * setPerPage,\n * setSort,\n * } = referenceParamsActions;\n */\nexport var useReferenceParams = function (_a) {\n var resource = _a.resource, filter = _a.filter, _b = _a.sort, sort = _b === void 0 ? defaultSort : _b, _c = _a.page, page = _c === void 0 ? 1 : _c, _d = _a.perPage, perPage = _d === void 0 ? 10 : _d, _e = _a.debounce, debounce = _e === void 0 ? 500 : _e;\n var _f = useState(defaultParams), params = _f[0], setParams = _f[1];\n var tempParams = useRef();\n var requestSignature = [\n resource,\n JSON.stringify(params),\n JSON.stringify(filter),\n JSON.stringify(sort),\n page,\n perPage,\n ];\n var query = useMemo(function () {\n return getQuery({\n params: params,\n filterDefaultValues: filter,\n sort: sort,\n page: page,\n perPage: perPage,\n });\n }, requestSignature // eslint-disable-line react-hooks/exhaustive-deps\n );\n var changeParams = useCallback(function (action) {\n if (!tempParams.current) {\n // no other changeParams action dispatched this tick\n var newTempParams_1 = queryReducer(query, action);\n tempParams.current = newTempParams_1;\n // schedule side effects for next tick\n setTimeout(function () {\n setParams(newTempParams_1);\n tempParams.current = undefined;\n }, 0);\n }\n else {\n // side effects already scheduled, just change the params\n tempParams.current = queryReducer(tempParams.current, action);\n }\n }, requestSignature); // eslint-disable-line react-hooks/exhaustive-deps\n var setSort = useCallback(function (sort) {\n return changeParams({\n type: SET_SORT,\n payload: sort,\n });\n }, requestSignature // eslint-disable-line react-hooks/exhaustive-deps\n );\n var setPage = useCallback(function (newPage) { return changeParams({ type: SET_PAGE, payload: newPage }); }, requestSignature // eslint-disable-line react-hooks/exhaustive-deps\n );\n var setPerPage = useCallback(function (newPerPage) {\n return changeParams({ type: SET_PER_PAGE, payload: newPerPage });\n }, requestSignature // eslint-disable-line react-hooks/exhaustive-deps\n );\n var filterValues = query.filter || emptyObject;\n var displayedFilterValues = query.displayedFilters || emptyObject;\n var debouncedSetFilters = useRef(lodashDebounce(function (filter, displayedFilters) {\n if (displayedFilters === void 0) { displayedFilters = undefined; }\n changeParams({\n type: SET_FILTER,\n payload: {\n filter: removeEmpty(filter),\n displayedFilters: displayedFilters,\n },\n });\n }, debounce));\n useEffect(function () {\n return function () {\n // eslint-disable-next-line react-hooks/exhaustive-deps\n debouncedSetFilters.current.cancel();\n };\n }, []);\n var setFilters = useCallback(function (filter, displayedFilters, debounce) {\n if (displayedFilters === void 0) { displayedFilters = undefined; }\n if (debounce === void 0) { debounce = false; }\n debounce\n ? debouncedSetFilters.current(filter, displayedFilters)\n : changeParams({\n type: SET_FILTER,\n payload: {\n filter: removeEmpty(filter),\n displayedFilters: displayedFilters,\n },\n });\n }, requestSignature // eslint-disable-line react-hooks/exhaustive-deps\n );\n var hideFilter = useCallback(function (filterName) {\n changeParams({\n type: HIDE_FILTER,\n payload: filterName,\n });\n }, requestSignature); // eslint-disable-line react-hooks/exhaustive-deps\n var showFilter = useCallback(function (filterName, defaultValue) {\n changeParams({\n type: SHOW_FILTER,\n payload: {\n filterName: filterName,\n defaultValue: defaultValue,\n },\n });\n }, requestSignature); // eslint-disable-line react-hooks/exhaustive-deps\n return [\n __assign(__assign({ filterValues: filterValues, requestSignature: requestSignature }, query), { displayedFilters: displayedFilterValues }),\n {\n changeParams: changeParams,\n setPage: setPage,\n setPerPage: setPerPage,\n setSort: setSort,\n setFilters: setFilters,\n hideFilter: hideFilter,\n showFilter: showFilter,\n },\n ];\n};\nexport var validQueryParams = [\n 'page',\n 'perPage',\n 'sort',\n 'order',\n 'filter',\n 'displayedFilters',\n];\n/**\n * Merge list params from 2 different sources:\n * - the params stored in the local state\n * - the props passed to the List component (including the filter defaultValues)\n */\nexport var getQuery = function (_a) {\n var params = _a.params, filterDefaultValues = _a.filterDefaultValues, sort = _a.sort, page = _a.page, perPage = _a.perPage;\n var query = hasCustomParams(params)\n ? __assign({}, params) : { filter: filterDefaultValues || {} };\n if (!query.sort) {\n query.sort = sort.field;\n query.order = sort.order;\n }\n if (query.page == null) {\n query.page = page;\n }\n if (query.perPage == null) {\n query.perPage = perPage;\n }\n if (query.page == null) {\n query.page = 1;\n }\n return __assign(__assign({}, query), { page: getNumberOrDefault(query.page, 1), perPage: getNumberOrDefault(query.perPage, 10) });\n};\n/**\n * Check if user has already set custom sort, page, or filters for this list\n *\n * User params come from the Redux store as the params props. By default,\n * this object is:\n *\n * { filter: {}, order: null, page: 1, perPage: null, sort: null }\n *\n * To check if the user has custom params, we must compare the params\n * to these initial values.\n *\n * @param {Object} params\n */\nexport var hasCustomParams = function (params) {\n return (params &&\n params.filter &&\n (Object.keys(params.filter).length > 0 ||\n params.order != null ||\n params.page !== 1 ||\n params.perPage != null ||\n params.sort != null));\n};\nexport var getNumberOrDefault = function (possibleNumber, defaultValue) {\n if (typeof possibleNumber === 'undefined') {\n return defaultValue;\n }\n var parsedNumber = typeof possibleNumber === 'string'\n ? parseInt(possibleNumber, 10)\n : possibleNumber;\n return isNaN(parsedNumber) ? defaultValue : parsedNumber;\n};\nvar emptyObject = {};\nvar defaultSort = {\n field: 'id',\n order: SORT_ASC,\n};\nvar defaultParams = {};\n//# sourceMappingURL=useReferenceParams.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { useCallback, useMemo } from 'react';\nimport { useFormContext, useWatch } from 'react-hook-form';\nimport { useGetList, useGetManyAggregate } from '../../dataProvider';\nimport { useReferenceParams } from './useReferenceParams';\nimport { useWrappedSource } from '../../core';\n/**\n * Prepare data for the ReferenceArrayInput components\n *\n * @example\n *\n * const { allChoices, availableChoices, selectedChoices, error, isFetching, isLoading, isPending } = useReferenceArrayInputController({\n * record: { referenceIds: ['id1', 'id2']};\n * reference: 'reference';\n * resource: 'resource';\n * source: 'referenceIds';\n * });\n *\n * @param {Object} props\n * @param {Object} props.record The current resource record\n * @param {string} props.reference The linked resource name\n * @param {string} props.resource The current resource name\n * @param {string} props.source The key of the linked resource identifier\n *\n * @param {Props} props\n *\n * @return {Object} controllerProps Fetched data and callbacks for the ReferenceArrayInput components\n */\nexport var useReferenceArrayInputController = function (props) {\n var _a;\n var debounce = props.debounce, enableGetChoices = props.enableGetChoices, filter = props.filter, _b = props.page, initialPage = _b === void 0 ? 1 : _b, _c = props.perPage, initialPerPage = _c === void 0 ? 25 : _c, _d = props.sort, initialSort = _d === void 0 ? { field: 'id', order: 'DESC' } : _d, _e = props.queryOptions, queryOptions = _e === void 0 ? {} : _e, reference = props.reference, source = props.source;\n var getValues = useFormContext().getValues;\n var finalSource = useWrappedSource(source);\n // When we change the defaultValue of the child input using react-hook-form resetField function,\n // useWatch does not seem to get the new value. We fallback to getValues to get it.\n var value = (_a = useWatch({ name: finalSource })) !== null && _a !== void 0 ? _a : getValues(finalSource);\n var meta = queryOptions.meta, otherQueryOptions = __rest(queryOptions, [\"meta\"]);\n /**\n * Get the records related to the current value (with getMany)\n */\n var _f = useGetManyAggregate(reference, {\n ids: value || EmptyArray,\n meta: meta,\n }, {\n enabled: value != null && value.length > 0,\n }), referenceRecords = _f.data, errorGetMany = _f.error, isLoadingGetMany = _f.isLoading, isFetchingGetMany = _f.isFetching, isPendingGetMany = _f.isPending, refetchGetMany = _f.refetch;\n var _g = useReferenceParams({\n resource: reference,\n page: initialPage,\n perPage: initialPerPage,\n sort: initialSort,\n debounce: debounce,\n filter: filter,\n }), params = _g[0], paramsModifiers = _g[1];\n // filter out not found references - happens when the dataProvider doesn't guarantee referential integrity\n var finalReferenceRecords = referenceRecords\n ? referenceRecords.filter(Boolean)\n : [];\n var isGetMatchingEnabled = enableGetChoices\n ? enableGetChoices(params.filterValues)\n : true;\n var _h = useGetList(reference, {\n pagination: {\n page: params.page,\n perPage: params.perPage,\n },\n sort: { field: params.sort, order: params.order },\n filter: __assign(__assign({}, params.filter), filter),\n meta: meta,\n }, __assign({ retry: false, enabled: isGetMatchingEnabled, placeholderData: function (previousData) { return previousData; } }, otherQueryOptions)), matchingReferences = _h.data, total = _h.total, pageInfo = _h.pageInfo, errorGetList = _h.error, isLoadingGetList = _h.isLoading, isFetchingGetList = _h.isFetching, isPendingGetList = _h.isPending, refetchGetMatching = _h.refetch;\n // We merge the currently selected records with the matching ones, otherwise\n // the component displaying the currently selected records may fail\n var finalMatchingReferences = matchingReferences && matchingReferences.length > 0\n ? mergeReferences(matchingReferences, finalReferenceRecords)\n : finalReferenceRecords.length > 0\n ? finalReferenceRecords\n : matchingReferences;\n var refetch = useCallback(function () {\n refetchGetMany();\n refetchGetMatching();\n }, [refetchGetMany, refetchGetMatching]);\n var currentSort = useMemo(function () { return ({\n field: params.sort,\n order: params.order,\n }); }, [params.sort, params.order]);\n return {\n sort: currentSort,\n allChoices: finalMatchingReferences,\n availableChoices: matchingReferences,\n selectedChoices: finalReferenceRecords,\n displayedFilters: params.displayedFilters,\n error: errorGetMany || errorGetList,\n filter: filter,\n filterValues: params.filterValues,\n hideFilter: paramsModifiers.hideFilter,\n isFetching: isFetchingGetMany || isFetchingGetList,\n isLoading: isLoadingGetMany || isLoadingGetList,\n isPending: isPendingGetMany || isPendingGetList,\n page: params.page,\n perPage: params.perPage,\n refetch: refetch,\n resource: reference,\n setFilters: paramsModifiers.setFilters,\n setPage: paramsModifiers.setPage,\n setPerPage: paramsModifiers.setPerPage,\n setSort: paramsModifiers.setSort,\n showFilter: paramsModifiers.showFilter,\n // we return source and not finalSource because child inputs (e.g. AutocompleteArrayInput) already call useInput and compute the final source\n source: source,\n total: total,\n hasNextPage: pageInfo\n ? pageInfo.hasNextPage\n : total != null\n ? params.page * params.perPage < total\n : undefined,\n hasPreviousPage: pageInfo ? pageInfo.hasPreviousPage : params.page > 1,\n isFromReference: true,\n };\n};\nvar EmptyArray = [];\n// concatenate and deduplicate two lists of records\nvar mergeReferences = function (ref1, ref2) {\n var res = __spreadArray([], ref1, true);\n var ids = ref1.map(function (ref) { return ref.id; });\n ref2.forEach(function (ref) {\n if (!ids.includes(ref.id)) {\n ids.push(ref.id);\n res.push(ref);\n }\n });\n return res;\n};\n//# sourceMappingURL=useReferenceArrayInputController.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { useWatch } from 'react-hook-form';\nimport { useGetList } from '../../dataProvider';\nimport { useReference } from '../useReference';\nimport { useReferenceParams } from './useReferenceParams';\nimport { useWrappedSource } from '../../core';\n/**\n * A hook for choosing a reference record. Useful for foreign keys.\n *\n * This hook fetches the possible values in the reference resource\n * (using `dataProvider.getList()`), it returns the possible choices\n * as the `choices` attribute.\n *\n * @example\n * const {\n * choices, // the available reference resource\n * } = useReferenceInputController({\n * input, // the input props\n * resource: 'comments',\n * reference: 'posts',\n * source: 'post_id',\n * });\n *\n * The hook also allow to filter results. It returns a `setFilters`\n * function. It uses the value to create a filter for the query.\n * You can also add a permanentFilter to further filter the result:\n *\n * @example\n * const {\n * choices, // the available reference resource\n * setFilter,\n * } = useReferenceInputController({\n * input, // the input props\n * resource: 'comments',\n * reference: 'posts',\n * source: 'post_id',\n * permanentFilter: {\n * author: 'john'\n * },\n * });\n */\nexport var useReferenceInputController = function (props) {\n var debounce = props.debounce, enableGetChoices = props.enableGetChoices, filter = props.filter, _a = props.page, initialPage = _a === void 0 ? 1 : _a, _b = props.perPage, initialPerPage = _b === void 0 ? 25 : _b, initialSort = props.sort, _c = props.queryOptions, queryOptions = _c === void 0 ? {} : _c, reference = props.reference, source = props.source;\n var meta = queryOptions.meta, otherQueryOptions = __rest(queryOptions, [\"meta\"]);\n var _d = useReferenceParams({\n resource: reference,\n page: initialPage,\n perPage: initialPerPage,\n sort: initialSort,\n debounce: debounce,\n filter: filter,\n }), params = _d[0], paramsModifiers = _d[1];\n // selection logic\n var finalSource = useWrappedSource(source);\n var currentValue = useWatch({ name: finalSource });\n var isGetMatchingEnabled = enableGetChoices\n ? enableGetChoices(params.filterValues)\n : true;\n // fetch possible values\n var _e = useGetList(reference, {\n pagination: {\n page: params.page,\n perPage: params.perPage,\n },\n sort: { field: params.sort, order: params.order },\n filter: __assign(__assign({}, params.filter), filter),\n meta: meta,\n }, __assign({ enabled: isGetMatchingEnabled, placeholderData: function (previousData) { return previousData; } }, otherQueryOptions)), _f = _e.data, possibleValuesData = _f === void 0 ? [] : _f, total = _e.total, pageInfo = _e.pageInfo, isFetchingPossibleValues = _e.isFetching, isLoadingPossibleValues = _e.isLoading, isPendingPossibleValues = _e.isPending, errorPossibleValues = _e.error, refetchGetList = _e.refetch;\n // fetch current value\n var _g = useReference({\n id: currentValue,\n reference: reference,\n // @ts-ignore the types of the queryOptions for the getMAny and getList are not compatible\n options: __assign({ enabled: currentValue != null && currentValue !== '', meta: meta }, otherQueryOptions),\n }), currentReferenceRecord = _g.referenceRecord, refetchReference = _g.refetch, errorReference = _g.error, isLoadingReference = _g.isLoading, isFetchingReference = _g.isFetching, isPendingReference = _g.isPending;\n var isPending = \n // The reference query isn't enabled when there is no value yet but as it has no data, react-query will flag it as pending\n (currentValue != null && currentValue !== '' && isPendingReference) ||\n isPendingPossibleValues;\n // We need to delay the update of the referenceRecord and the finalData\n // to the next React state update, because otherwise it can raise a warning\n // with AutocompleteInput saying the current value is not in the list of choices\n var _h = useState(undefined), referenceRecord = _h[0], setReferenceRecord = _h[1];\n useEffect(function () {\n setReferenceRecord(currentReferenceRecord);\n }, [currentReferenceRecord]);\n // add current value to possible sources\n var finalData, finalTotal;\n if (!referenceRecord ||\n possibleValuesData.find(function (record) { return record.id === referenceRecord.id; })) {\n finalData = possibleValuesData;\n finalTotal = total;\n }\n else {\n finalData = __spreadArray([referenceRecord], possibleValuesData, true);\n finalTotal = total == null ? undefined : total + 1;\n }\n var refetch = useCallback(function () {\n refetchGetList();\n refetchReference();\n }, [refetchGetList, refetchReference]);\n var currentSort = useMemo(function () { return ({\n field: params.sort,\n order: params.order,\n }); }, [params.sort, params.order]);\n return {\n sort: currentSort,\n allChoices: finalData,\n availableChoices: possibleValuesData,\n selectedChoices: referenceRecord ? [referenceRecord] : [],\n displayedFilters: params.displayedFilters,\n error: errorReference || errorPossibleValues,\n filter: params.filter,\n filterValues: params.filterValues,\n hideFilter: paramsModifiers.hideFilter,\n isFetching: isFetchingReference || isFetchingPossibleValues,\n isLoading: isLoadingReference || isLoadingPossibleValues,\n isPending: isPending,\n page: params.page,\n perPage: params.perPage,\n refetch: refetch,\n resource: reference,\n setFilters: paramsModifiers.setFilters,\n setPage: paramsModifiers.setPage,\n setPerPage: paramsModifiers.setPerPage,\n setSort: paramsModifiers.setSort,\n showFilter: paramsModifiers.showFilter,\n // we return source and not finalSource because child inputs (e.g. AutocompleteInput) already call useInput and compute the final source\n source: source,\n total: finalTotal,\n hasNextPage: pageInfo\n ? pageInfo.hasNextPage\n : total != null\n ? params.page * params.perPage < total\n : undefined,\n hasPreviousPage: pageInfo ? pageInfo.hasPreviousPage : params.page > 1,\n isFromReference: true,\n };\n};\n//# sourceMappingURL=useReferenceInputController.js.map","import { createContext } from 'react';\n/**\n * Context to store choices and functions to retrieve them.\n *\n * Use the useChoicesContext() hook to read the context.\n */\nexport var ChoicesContext = createContext(undefined);\n//# sourceMappingURL=ChoicesContext.js.map","import * as React from 'react';\nimport { ChoicesContext } from './ChoicesContext';\nexport var ChoicesContextProvider = function (_a) {\n var children = _a.children, value = _a.value;\n return (React.createElement(ChoicesContext.Provider, { value: value }, children));\n};\n//# sourceMappingURL=ChoicesContextProvider.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useContext, useMemo } from 'react';\nimport { useList } from '../../controller';\nimport { ChoicesContext } from './ChoicesContext';\nexport var useChoicesContext = function (options) {\n var _a, _b, _c;\n if (options === void 0) { options = {}; }\n var context = useContext(ChoicesContext);\n var choices = options.choices && isArrayOfStrings(options.choices)\n ? convertOptionsToChoices(options.choices)\n : options.choices;\n // @ts-ignore cannot satisfy the type of useList because of ability to pass partial options\n var _d = useList({\n data: choices,\n isLoading: (_a = options.isLoading) !== null && _a !== void 0 ? _a : false,\n isPending: (_b = options.isPending) !== null && _b !== void 0 ? _b : false,\n isFetching: (_c = options.isFetching) !== null && _c !== void 0 ? _c : false,\n error: options.error,\n // When not in a ChoicesContext, paginating does not make sense (e.g. AutocompleteInput).\n perPage: Infinity,\n }), data = _d.data, list = __rest(_d, [\"data\"]);\n var result = useMemo(function () {\n var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;\n // Props take precedence over context.\n if (options.choices || !context) {\n return {\n allChoices: data,\n availableChoices: (_a = options.availableChoices) !== null && _a !== void 0 ? _a : data,\n selectedChoices: (_b = options.selectedChoices) !== null && _b !== void 0 ? _b : data,\n displayedFilters: (_c = options.selectedChoices) !== null && _c !== void 0 ? _c : list.displayedFilters,\n error: options.error,\n filter: (_d = options.filter) !== null && _d !== void 0 ? _d : list.filter,\n filterValues: (_e = options.filterValues) !== null && _e !== void 0 ? _e : list.filterValues,\n hasNextPage: (_f = options.hasNextPage) !== null && _f !== void 0 ? _f : list.hasNextPage,\n hasPreviousPage: (_g = options.hasPreviousPage) !== null && _g !== void 0 ? _g : list.hasPreviousPage,\n hideFilter: (_h = options.hideFilter) !== null && _h !== void 0 ? _h : list.hideFilter,\n isLoading: (_j = list.isLoading) !== null && _j !== void 0 ? _j : false,\n isPending: (_k = list.isPending) !== null && _k !== void 0 ? _k : false,\n isFetching: (_l = list.isFetching) !== null && _l !== void 0 ? _l : false,\n page: (_m = options.page) !== null && _m !== void 0 ? _m : list.page,\n perPage: (_o = options.perPage) !== null && _o !== void 0 ? _o : list.perPage,\n refetch: (_p = options.refetch) !== null && _p !== void 0 ? _p : list.refetch,\n resource: (_q = options.resource) !== null && _q !== void 0 ? _q : list.resource,\n setFilters: (_r = options.setFilters) !== null && _r !== void 0 ? _r : list.setFilters,\n setPage: (_s = options.setPage) !== null && _s !== void 0 ? _s : list.setPage,\n setPerPage: (_t = options.setPerPage) !== null && _t !== void 0 ? _t : list.setPerPage,\n setSort: (_u = options.setSort) !== null && _u !== void 0 ? _u : list.setSort,\n showFilter: (_v = options.showFilter) !== null && _v !== void 0 ? _v : list.showFilter,\n sort: (_w = options.sort) !== null && _w !== void 0 ? _w : list.sort,\n source: options.source,\n total: (_x = options.total) !== null && _x !== void 0 ? _x : list.total,\n isFromReference: false,\n };\n }\n return context;\n }, [context, data, list, options]);\n return result;\n};\nvar isArrayOfStrings = function (choices) {\n return Array.isArray(choices) &&\n choices.every(function (choice) { return typeof choice === 'string'; });\n};\nvar convertOptionsToChoices = function (options) {\n return options.map(function (choice) { return ({\n id: choice,\n name: choice,\n }); });\n};\n//# sourceMappingURL=useChoicesContext.js.map","import * as React from 'react';\nimport { isValidElement, useCallback } from 'react';\nimport get from 'lodash/get';\nimport { useTranslate } from '../../i18n';\nimport { RecordContextProvider } from '../../controller';\n/*\n * Returns helper functions for choices handling.\n *\n * @param optionText Either a string defining the property to use to get the choice text, a function or a React element\n * @param optionValue The property to use to get the choice value\n * @param translateChoice A boolean indicating whether to option text should be translated\n *\n * @returns An object with helper functions:\n * - getChoiceText: Returns the choice text or a React element\n * - getChoiceValue: Returns the choice value\n */\nexport var useChoices = function (_a) {\n var _b = _a.optionText, optionText = _b === void 0 ? 'name' : _b, _c = _a.optionValue, optionValue = _c === void 0 ? 'id' : _c, _d = _a.disableValue, disableValue = _d === void 0 ? 'disabled' : _d, _e = _a.translateChoice, translateChoice = _e === void 0 ? true : _e;\n var translate = useTranslate();\n var getChoiceText = useCallback(function (choice) {\n if (isValidElement(optionText)) {\n return (React.createElement(RecordContextProvider, { value: choice }, optionText));\n }\n var choiceName = typeof optionText === 'function'\n ? optionText(choice)\n : get(choice, optionText);\n return isValidElement(choiceName)\n ? choiceName\n : translateChoice\n ? translate(String(choiceName), { _: choiceName })\n : String(choiceName);\n }, [optionText, translate, translateChoice]);\n var getChoiceValue = useCallback(function (choice) { return get(choice, optionValue); }, [optionValue]);\n var getDisableValue = useCallback(function (choice) { return get(choice, disableValue); }, [disableValue]);\n return {\n getChoiceText: getChoiceText,\n getChoiceValue: getChoiceValue,\n getDisableValue: getDisableValue,\n };\n};\n//# sourceMappingURL=useChoices.js.map","import { createContext } from 'react';\nexport var FormGroupsContext = createContext(undefined);\n//# sourceMappingURL=FormGroupsContext.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport * as React from 'react';\nimport { useMemo, useRef } from 'react';\nimport { FormGroupsContext, } from './FormGroupsContext';\n/**\n * This component provides functions through context to manage form groups,\n * allowing to link or unlink an input to a group.\n * @see FormGroupContextProvider\n * @see useFormGroup\n * @see useFormGroups\n */\nexport var FormGroupsProvider = function (_a) {\n var children = _a.children;\n var formGroups = useRef({});\n var subscribers = useRef({});\n var formContextValue = useMemo(function () { return ({\n /**\n * Register a subscriber function for the specified group. The subscriber\n * will be called whenever the group content changes (fields added or removed).\n */\n subscribe: function (group, subscriber) {\n if (!subscribers.current[group]) {\n subscribers.current[group] = [];\n }\n subscribers.current[group].push(subscriber);\n return function () {\n subscribers.current[group] = subscribers.current[group].filter(function (s) { return s !== subscriber; });\n };\n },\n getGroupFields: function (name) { return formGroups.current[name] || []; },\n registerGroup: function (name) {\n formGroups.current[name] = formGroups.current[name] || [];\n },\n unregisterGroup: function (name) {\n delete formGroups[name];\n },\n registerField: function (source, group) {\n if (group != null) {\n if (!(formGroups.current[group] || []).includes(source)) {\n formGroups.current[group] = __spreadArray(__spreadArray([], (formGroups.current[group] || []), true), [\n source,\n ], false);\n // Notify subscribers that the group fields have changed\n if (subscribers.current[group]) {\n subscribers.current[group].forEach(function (subscriber) {\n return subscriber();\n });\n }\n }\n }\n },\n unregisterField: function (source, group) {\n if (group != null) {\n if (!formGroups.current[group]) {\n console.warn(\"Invalid form group \".concat(group));\n }\n else {\n var fields = new Set(formGroups.current[group]);\n fields.delete(source);\n formGroups.current[group] = Array.from(fields);\n // Notify subscribers that the group fields have changed\n if (subscribers.current[group]) {\n subscribers.current[group].forEach(function (subscriber) {\n return subscriber();\n });\n }\n }\n }\n },\n }); }, []);\n return (React.createElement(FormGroupsContext.Provider, { value: formContextValue }, children));\n};\n//# sourceMappingURL=FormGroupsProvider.js.map","import { useEffect, useState } from 'react';\nimport { useFormState } from 'react-hook-form';\nimport { useBlocker } from 'react-router-dom';\nimport { useTranslate } from '../i18n';\n/**\n * Display a confirmation dialog if the form has unsaved changes.\n * - If the user confirms, the navigation continues and the changes are lost.\n * - If the user cancels, the navigation is cancelled and the changes are kept.\n */\nexport var useWarnWhenUnsavedChanges = function (enable, formRootPathname, control) {\n var translate = useTranslate();\n var _a = useFormState(control ? { control: control } : undefined), isSubmitSuccessful = _a.isSubmitSuccessful, dirtyFields = _a.dirtyFields;\n var isDirty = Object.keys(dirtyFields).length > 0;\n var _b = useState(false), shouldNotify = _b[0], setShouldNotify = _b[1];\n var shouldNotBlock = !enable || !isDirty || isSubmitSuccessful;\n var blocker = useBlocker(function (_a) {\n var currentLocation = _a.currentLocation, nextLocation = _a.nextLocation;\n if (shouldNotBlock)\n return false;\n // Also check if the new location is inside the form\n var initialLocation = formRootPathname || currentLocation.pathname;\n var newLocationIsInsideCurrentLocation = nextLocation.pathname.startsWith(initialLocation);\n var newLocationIsShowView = nextLocation.pathname.startsWith(\"\".concat(initialLocation, \"/show\"));\n var newLocationIsInsideForm = newLocationIsInsideCurrentLocation && !newLocationIsShowView;\n if (newLocationIsInsideForm)\n return false;\n return true;\n });\n useEffect(function () {\n if (blocker.state === 'blocked') {\n // Corner case: the blocker might be triggered by a redirect in the onSuccess side effect,\n // happening during the same tick the form is reset after a successful save.\n // In that case, the blocker will block but shouldNotBlock will be true one tick after.\n // If we are in that case, we can proceed immediately.\n if (shouldNotBlock) {\n blocker.proceed();\n return;\n }\n setShouldNotify(true);\n }\n // This effect should only run when the blocker state changes, not when shouldNotBlock changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [blocker.state]);\n useEffect(function () {\n if (shouldNotify) {\n var shouldProceed = window.confirm(translate('ra.message.unsaved_changes'));\n if (shouldProceed) {\n blocker.proceed && blocker.proceed();\n }\n else {\n blocker.reset && blocker.reset();\n }\n }\n setShouldNotify(false);\n // Can't use blocker in the dependency array because it is not stable across rerenders\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [shouldNotify, translate]);\n // This effect handles document navigation, e.g. closing the tab\n useEffect(function () {\n var beforeunload = function (e) {\n // Invoking event.preventDefault() will trigger a warning dialog when the user closes or navigates the tab\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event#examples\n e.preventDefault();\n // Included for legacy support, e.g. Chrome/Edge < 119\n e.returnValue = true;\n };\n if (shouldNotBlock) {\n return;\n }\n window.addEventListener('beforeunload', beforeunload);\n return function () {\n window.removeEventListener('beforeunload', beforeunload);\n };\n }, [shouldNotBlock]);\n};\n//# sourceMappingURL=useWarnWhenUnsavedChanges.js.map","import { useWarnWhenUnsavedChanges } from './useWarnWhenUnsavedChanges';\nexport var WarnWhenUnsavedChanges = function (_a) {\n var _b = _a.enable, enable = _b === void 0 ? true : _b, formRootPathName = _a.formRootPathName, formControl = _a.formControl;\n useWarnWhenUnsavedChanges(enable, formRootPathName, formControl);\n return null;\n};\n//# sourceMappingURL=WarnWhenUnsavedChanges.js.map","import merge from 'lodash/merge';\nexport default function getFormInitialValues(defaultValues, record) {\n var finalInitialValues = merge({}, getValues(defaultValues, record), record);\n return finalInitialValues;\n}\nfunction getValues(values, record) {\n if (typeof values === 'object') {\n return values;\n }\n if (typeof values === 'function') {\n return values(record);\n }\n return {};\n}\n//# sourceMappingURL=getFormInitialValues.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\n/**\n * Convert a simple validation function that returns an object matching the form shape with errors\n * to a validation resolver compatible with react-hook-form.\n *\n * @example\n * const validate = (values: any) => {\n * if (values.username == null || values.username.trim() === '') {\n * return { username: 'Required' };\n * }\n * }\n *\n * const validationResolver = getSimpleValidationResolver(validate);\n *\n * const UserForm = () => (\n * \n * \n * \n * );\n */\nexport var getSimpleValidationResolver = function (validate) { return function (data) { return __awaiter(void 0, void 0, void 0, function () {\n var errors, transformedErrors;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0: return [4 /*yield*/, validate(data)];\n case 1:\n errors = _a.sent();\n // If there are no errors, early return the form values\n if (!errors || isEmptyObject(errors)) {\n return [2 /*return*/, { values: data, errors: {} }];\n }\n transformedErrors = transformErrorFields(errors);\n // Sometimes we still need to transform the error object to realize there are actually\n // no errors in it.\n // e.g. with an ArrayInput we can get something like: `{backlinks: [{}, {}]}`\n // If, after transformation, there are no errors, we return the form values\n if (!transformedErrors || isEmptyObject(transformedErrors)) {\n return [2 /*return*/, { values: data, errors: {} }];\n }\n // Else return the errors and no values\n return [2 /*return*/, {\n values: {},\n errors: transformedErrors,\n }];\n }\n });\n}); }; };\nvar transformErrorFields = function (error) {\n return Object.keys(error).reduce(function (acc, field) {\n var _a, _b, _c;\n // Handle arrays\n if (Array.isArray(error[field])) {\n var arrayHasErrors_1 = false;\n var transformedArrayErrors = error[field].map(function (item) {\n if (!isEmptyObject(item)) {\n arrayHasErrors_1 = true;\n }\n return transformErrorFields(item);\n });\n if (!arrayHasErrors_1) {\n return acc;\n }\n return __assign(__assign({}, acc), (_a = {}, _a[field] = transformedArrayErrors, _a));\n }\n // Handle objects\n if (isEmptyObject(error[field])) {\n return acc;\n }\n if (typeof error[field] === 'object' &&\n !isRaTranslationObj(error[field])) {\n return __assign(__assign({}, acc), (_b = {}, _b[field] = transformErrorFields(error[field]), _b));\n }\n // Handle leaf (either primary type or RaTranslationObj)\n return __assign(__assign({}, acc), (_c = {}, _c[field] = addTypeAndMessage(error[field]), _c));\n }, {});\n};\nvar addTypeAndMessage = function (error) { return ({\n type: 'manual',\n message: isRaTranslationObj(error) ? error : { message: error },\n}); };\nvar isRaTranslationObj = function (obj) {\n return Object.keys(obj).includes('message') && Object.keys(obj).includes('args');\n};\nvar isEmptyObject = function (obj) {\n return obj == null || Object.getOwnPropertyNames(obj).length === 0;\n};\n//# sourceMappingURL=getSimpleValidationResolver.js.map","/**\n * This internal function is used to convert an object matching the form shape with errors to a\n * format compatible with react-hook-form. It's used to handle submission errors. Only useful when\n * you are implementing a custom form without leveraging our Form component.\n *\n * @example\n * const MyForm = () => {\n * const { register, handleSubmit, setError } = useForm();\n * const onSubmit = data => {\n * return saveAsync(data).catch(error => setSubmissionErrors(error.body.details));\n * };\n *\n * return (\n *
\n * ...\n *
\n * );\n * };\n */\nexport var setSubmissionErrors = function (errors, setError) {\n var setErrorFromObject = function (errors, rootPath) {\n Object.entries(errors).forEach(function (_a) {\n var name = _a[0], error = _a[1];\n if (typeof error === 'object') {\n setErrorFromObject(error, \"\".concat(rootPath).concat(name, \".\"));\n return;\n }\n setError(\"\".concat(rootPath).concat(name), {\n type: 'server',\n message: error.toString(),\n });\n });\n };\n setErrorFromObject(errors, '');\n};\n//# sourceMappingURL=setSubmissionErrors.js.map","import { useEffect, useRef } from 'react';\nimport { useFormState } from 'react-hook-form';\nimport { useNotify } from '../../notification';\n/**\n * This hook display an error message on submit in Form and SaveButton.\n *\n * We can't do the form validity check in the form submit handler\n * as the form state may not have been updated yet when onSubmit validation mode is enabled\n * or when the form hasn't been touched at all.\n */\nexport var useNotifyIsFormInvalid = function (control, enabled) {\n if (enabled === void 0) { enabled = true; }\n var _a = useFormState(control ? { control: control } : undefined), submitCount = _a.submitCount, errors = _a.errors;\n var submitCountRef = useRef(submitCount);\n var notify = useNotify();\n useEffect(function () {\n var _a, _b;\n // Checking the submit count allows us to only display the notification after users\n // tried to submit\n if (submitCount > submitCountRef.current && enabled) {\n submitCountRef.current = submitCount;\n if (Object.keys(errors).length > 0) {\n var serverError = typeof ((_b = (_a = errors.root) === null || _a === void 0 ? void 0 : _a.serverError) === null || _b === void 0 ? void 0 : _b.message) === 'string'\n ? errors.root.serverError.message\n : undefined;\n notify(serverError || 'ra.message.invalid_form', {\n type: 'error',\n });\n }\n }\n }, [errors, submitCount, notify, enabled]);\n};\n//# sourceMappingURL=useNotifyIsFormInvalid.js.map","/**\n * Remove empty strings from form state\n *\n * @example\n * sanitizeEmptyValues({ foo: '', bar: 'baz' }) // { bar: 'baz' }\n */\nexport var sanitizeEmptyValues = function (values, record) {\n if (record === void 0) { record = {}; }\n var sanitizedValues = {};\n Object.keys(values).forEach(function (key) {\n if (values[key] == null || values[key] === '') {\n if (record.hasOwnProperty(key)) {\n // user has emptied a field, make the value null\n sanitizedValues[key] = null;\n }\n else {\n // user has emptied a field, but the initial value was undefined\n // so we don't include it in the sanitized values\n }\n }\n else {\n // this is a non-empty value, so we include it in the sanitized values\n sanitizedValues[key] = values[key];\n }\n });\n return sanitizedValues;\n};\n//# sourceMappingURL=sanitizeEmptyValues.js.map","import { useEffect, useRef, useState } from 'react';\nimport { parse } from 'query-string';\nimport { useLocation } from 'react-router-dom';\nimport isEqual from 'lodash/isEqual';\n/**\n * A hook that returns the record to use to override the values in a form\n * @param options The hook options\n * @param options.searchSource The key in the location search to use as a source for the record. Its content should be a stringified JSON object.\n * @param options.stateSource The key in the location state to use as a source for the record\n * @returns The record to use to override the values in a form\n */\nexport var useRecordFromLocation = function (props) {\n if (props === void 0) { props = {}; }\n var searchSource = props.searchSource, stateSource = props.stateSource;\n var location = useLocation();\n var _a = useState(function () {\n return getRecordFromLocation(location, {\n stateSource: stateSource,\n searchSource: searchSource,\n });\n }), recordFromLocation = _a[0], setRecordFromLocation = _a[1];\n // To avoid having the form resets when the location changes but the final record is the same\n // This is needed for forms such as TabbedForm or WizardForm that may change the location for their sections\n var previousRecordRef = useRef(recordFromLocation);\n useEffect(function () {\n var newRecordFromLocation = getRecordFromLocation(location, {\n stateSource: stateSource,\n searchSource: searchSource,\n });\n if (!isEqual(newRecordFromLocation, previousRecordRef.current)) {\n previousRecordRef.current = newRecordFromLocation;\n setRecordFromLocation(newRecordFromLocation);\n }\n }, [location, stateSource, searchSource]);\n return recordFromLocation;\n};\n/**\n * Get the initial record from the location, whether it comes from the location\n * state or is serialized in the url search part.\n */\nexport var getRecordFromLocation = function (_a, _b) {\n var state = _a.state, search = _a.search;\n var _c = _b === void 0 ? {} : _b, _d = _c.searchSource, searchSource = _d === void 0 ? 'source' : _d, _e = _c.stateSource, stateSource = _e === void 0 ? 'record' : _e;\n if (state && state[stateSource]) {\n return state[stateSource];\n }\n if (search) {\n try {\n var searchParams = parse(search);\n var source = searchParams[searchSource];\n if (source) {\n if (Array.isArray(source)) {\n console.error(\"Failed to parse location \".concat(searchSource, \" parameter '\").concat(search, \"'. To pre-fill some fields in the Create form, pass a stringified \").concat(searchSource, \" parameter (e.g. '?\").concat(searchSource, \"={\\\"title\\\":\\\"foo\\\"}')\"));\n return null;\n }\n return JSON.parse(source);\n }\n }\n catch (e) {\n console.error(\"Failed to parse location \".concat(searchSource, \" parameter '\").concat(search, \"'. To pre-fill some fields in the Create form, pass a stringified \").concat(searchSource, \" parameter (e.g. '?\").concat(searchSource, \"={\\\"title\\\":\\\"foo\\\"}')\"));\n }\n }\n return null;\n};\n//# sourceMappingURL=useRecordFromLocation.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useCallback, useEffect, useMemo, useRef, } from 'react';\nimport { useForm, } from 'react-hook-form';\nimport merge from 'lodash/merge';\nimport { useRecordContext, useSaveContext } from '../controller';\nimport getFormInitialValues from './getFormInitialValues';\nimport { getSimpleValidationResolver, } from './validation/getSimpleValidationResolver';\nimport { setSubmissionErrors } from './validation/setSubmissionErrors';\nimport { useNotifyIsFormInvalid } from './validation/useNotifyIsFormInvalid';\nimport { sanitizeEmptyValues as sanitizeValues } from './sanitizeEmptyValues';\nimport { useRecordFromLocation } from './useRecordFromLocation';\n/**\n * Wrapper around react-hook-form's useForm\n *\n * This hook adds the following features to react-hook-form's useForm:\n *\n * - form initialization based on RecordContext\n * - validation based on a validate function\n * - sanitization of empty values\n * - notification on invalid form\n * - stop form submission event propagation\n */\nexport var useAugmentedForm = function (props) {\n var _a = props.criteriaMode, criteriaMode = _a === void 0 ? 'firstError' : _a, defaultValues = props.defaultValues, formRootPathname = props.formRootPathname, resolver = props.resolver, _b = props.reValidateMode, reValidateMode = _b === void 0 ? 'onChange' : _b, onSubmit = props.onSubmit, sanitizeEmptyValues = props.sanitizeEmptyValues, validate = props.validate, disableInvalidFormNotification = props.disableInvalidFormNotification, rest = __rest(props, [\"criteriaMode\", \"defaultValues\", \"formRootPathname\", \"resolver\", \"reValidateMode\", \"onSubmit\", \"sanitizeEmptyValues\", \"validate\", \"disableInvalidFormNotification\"]);\n var saveContext = useSaveContext();\n var record = useRecordContext(props);\n var defaultValuesIncludingRecord = useMemo(function () { return getFormInitialValues(defaultValues, record); }, \n // eslint-disable-next-line\n [\n // eslint-disable-next-line\n JSON.stringify({\n defaultValues: typeof defaultValues === 'function'\n ? 'function'\n : defaultValues,\n record: record,\n }),\n ]);\n var finalResolver = resolver\n ? resolver\n : validate\n ? getSimpleValidationResolver(validate)\n : undefined;\n var form = useForm(__assign({ criteriaMode: criteriaMode, values: defaultValuesIncludingRecord, reValidateMode: reValidateMode, resolver: finalResolver }, rest));\n var formRef = useRef(form);\n // notify on invalid form\n useNotifyIsFormInvalid(form.control, !disableInvalidFormNotification);\n var recordFromLocation = useRecordFromLocation();\n var recordFromLocationApplied = useRef(false);\n var reset = form.reset;\n useEffect(function () {\n if (recordFromLocation && !recordFromLocationApplied.current) {\n reset(merge({}, defaultValuesIncludingRecord, recordFromLocation), {\n keepDefaultValues: true,\n });\n recordFromLocationApplied.current = true;\n }\n }, [defaultValuesIncludingRecord, recordFromLocation, reset]);\n // submit callbacks\n var handleSubmit = useCallback(function (values, event) { return __awaiter(void 0, void 0, void 0, function () {\n var errors, finalValues;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n finalValues = sanitizeEmptyValues\n ? sanitizeValues(values, record)\n : values;\n if (!onSubmit) return [3 /*break*/, 2];\n return [4 /*yield*/, onSubmit(finalValues, event)];\n case 1:\n errors = _a.sent();\n _a.label = 2;\n case 2:\n if (!(onSubmit == null && (saveContext === null || saveContext === void 0 ? void 0 : saveContext.save))) return [3 /*break*/, 4];\n return [4 /*yield*/, saveContext.save(finalValues, event)];\n case 3:\n errors = _a.sent();\n _a.label = 4;\n case 4:\n if (errors != null) {\n setSubmissionErrors(errors, formRef.current.setError);\n }\n return [2 /*return*/];\n }\n });\n }); }, [onSubmit, saveContext, sanitizeEmptyValues, record]);\n var formHandleSubmit = useCallback(function (event) {\n if (!event.defaultPrevented) {\n // Prevent outer forms to receive the event\n event.stopPropagation();\n form.handleSubmit(handleSubmit)(event);\n }\n return;\n }, [form, handleSubmit]);\n return {\n form: form,\n handleSubmit: handleSubmit,\n formHandleSubmit: formHandleSubmit,\n };\n};\n//# sourceMappingURL=useAugmentedForm.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport * as React from 'react';\nimport { useContext } from 'react';\nimport { FormProvider, } from 'react-hook-form';\nimport { UNSAFE_DataRouterContext, UNSAFE_DataRouterStateContext, } from 'react-router';\nimport { FormGroupsProvider } from './groups/FormGroupsProvider';\nimport { useRecordContext, OptionalRecordContextProvider, } from '../controller';\nimport { SourceContextProvider, useResourceContext, } from '../core';\nimport { WarnWhenUnsavedChanges } from './WarnWhenUnsavedChanges';\nimport { useAugmentedForm } from './useAugmentedForm';\n/**\n * Creates a form element, initialized with the current record, calling the saveContext on submit\n *\n * Wrapper around react-hook-form's useForm, FormContextProvider, and
.\n * Also sets up a FormGroupContext, and handles submission validation.\n *\n * @example\n *\n * const MyForm = ({ record, defaultValues, validate }) => (\n * \n * \n * \n * \n * \n *
\n * );\n *\n * @typedef {Object} Props the props you can use\n * @prop {Object} defaultValues\n * @prop {Function} validate\n * @prop {Function} save\n *\n * @see useForm\n * @see FormGroupContext\n *\n * @link https://react-hook-form.com/docs/useformcontext\n */\nexport function Form(props) {\n var children = props.children, id = props.id, className = props.className, _a = props.noValidate, noValidate = _a === void 0 ? false : _a, formRootPathname = props.formRootPathname, warnWhenUnsavedChanges = props.warnWhenUnsavedChanges, _b = props.WarnWhenUnsavedChangesComponent, WarnWhenUnsavedChangesComponent = _b === void 0 ? WarnWhenUnsavedChanges : _b;\n var record = useRecordContext(props);\n var resource = useResourceContext(props);\n var _c = useAugmentedForm(props), form = _c.form, formHandleSubmit = _c.formHandleSubmit;\n var sourceContext = React.useMemo(function () { return ({\n getSource: function (source) { return source; },\n getLabel: function (source) {\n return \"resources.\".concat(resource, \".fields.\").concat(source);\n },\n }); }, [resource]);\n var dataRouterContext = useContext(UNSAFE_DataRouterContext);\n var dataRouterStateContext = useContext(UNSAFE_DataRouterStateContext);\n if (warnWhenUnsavedChanges &&\n (!dataRouterContext || !dataRouterStateContext) &&\n process.env.NODE_ENV === 'development') {\n console.error('Cannot use the warnWhenUnsavedChanges feature outside of a DataRouter. ' +\n 'The warnWhenUnsavedChanges feature is disabled. ' +\n 'Remove the warnWhenUnsavedChanges prop or convert your custom router to a Data Router.');\n }\n return (React.createElement(OptionalRecordContextProvider, { value: record },\n React.createElement(SourceContextProvider, { value: sourceContext },\n React.createElement(FormProvider, __assign({}, form),\n React.createElement(FormGroupsProvider, null,\n React.createElement(\"form\", { onSubmit: formHandleSubmit, noValidate: noValidate, id: id, className: className }, children),\n warnWhenUnsavedChanges &&\n dataRouterContext &&\n dataRouterStateContext && (React.createElement(WarnWhenUnsavedChangesComponent, { enable: true, formRootPathName: formRootPathname, formControl: form.control })))))));\n}\n//# sourceMappingURL=Form.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport { useFormContext, useWatch } from 'react-hook-form';\n// hook taken from https://react-hook-form.com/docs/usewatch/#rules\nexport var useFormValues = function () {\n var getValues = useFormContext().getValues;\n return __assign(__assign({}, useWatch()), getValues());\n};\n//# sourceMappingURL=useFormValues.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport * as React from 'react';\nimport { useFormContext } from 'react-hook-form';\nimport get from 'lodash/get';\nimport { useFormValues } from './useFormValues';\nimport { useWrappedSource } from '../core';\n/**\n * Get the current (edited) value of the record from the form and pass it\n * to a child function\n *\n * @example\n *\n * const PostEdit = () => (\n * \n * >\n * \n * \n * {({ formData }) => formData.hasEmail &&\n * \n * }\n * \n * \n * \n * );\n *\n * @example\n *\n * const OrderEdit = () => (\n * \n * \n * \n * >\n * {({ formData }) =>\n * \n * }\n * \n * \n * \n * );\n */\nexport var FormDataConsumer = function (props) {\n var form = useFormContext();\n var \n // Don't know exactly why, but this is needed for the form values to be updated\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n isDirty = form.formState.isDirty;\n var formData = useFormValues();\n return (React.createElement(FormDataConsumerView, __assign({ formData: formData }, props)));\n};\nexport var FormDataConsumerView = function (props) {\n var children = props.children, formData = props.formData, source = props.source;\n var result;\n var finalSource = useWrappedSource(source || '');\n // Passes an empty string here as we don't have the children sources and we just want to know if we are in an iterator\n var matches = ArraySourceRegex.exec(finalSource);\n // If we have an index, we are in an iterator like component (such as the SimpleFormIterator)\n if (matches) {\n var scopedFormData = get(formData, matches[0]);\n result = children({ formData: formData, scopedFormData: scopedFormData });\n }\n else {\n result = children({ formData: formData });\n }\n return result === undefined ? null : result;\n};\nvar ArraySourceRegex = new RegExp(/.+\\.\\d+$/);\n//# sourceMappingURL=FormDataConsumer.js.map","import { createContext } from 'react';\n/**\n * Context allowing inputs to register to a specific group.\n * This enables other components in the group to access group properties such as its\n * validation (valid/invalid) or whether its inputs have been updated (dirty/pristine).\n *\n * This should only be used through a FormGroupContextProvider.\n */\nexport var FormGroupContext = createContext(null);\n//# sourceMappingURL=FormGroupContext.js.map","import { useContext } from 'react';\nimport { FormGroupsContext } from './FormGroupsContext';\n/**\n * Retrieve the form groups management context. Used by inputs to register themselves into a form group.\n */\nexport var useFormGroups = function () {\n var context = useContext(FormGroupsContext);\n return context;\n};\n//# sourceMappingURL=useFormGroups.js.map","import { useContext } from 'react';\nimport { FormGroupContext } from './FormGroupContext';\n/**\n * Retrieve the name of the form group the consumer belongs to. May be undefined if the consumer is not inside a form group.\n */\nexport var useFormGroupContext = function () {\n var context = useContext(FormGroupContext);\n return context;\n};\n//# sourceMappingURL=useFormGroupContext.js.map","import { useEffect } from 'react';\nimport { useFormContext, } from 'react-hook-form';\nimport get from 'lodash/get';\nimport { useRecordContext } from '../controller';\nimport { useWrappedSource } from '../core';\n/*\n * This hook updates the input with the default value if default value is present\n * and field input is not already populated or dirty\n */\nexport var useApplyInputDefaultValues = function (_a) {\n var inputProps = _a.inputProps, isArrayInput = _a.isArrayInput, fieldArrayInputControl = _a.fieldArrayInputControl;\n var defaultValue = inputProps.defaultValue, source = inputProps.source;\n var finalSource = useWrappedSource(source);\n var record = useRecordContext(inputProps);\n var _b = useFormContext(), getValues = _b.getValues, resetField = _b.resetField, formState = _b.formState, reset = _b.reset;\n var recordValue = get(record, finalSource);\n var formValue = get(getValues(), finalSource);\n var dirtyFields = formState.dirtyFields;\n var isDirty = Object.keys(dirtyFields).includes(finalSource);\n useEffect(function () {\n if (defaultValue == null ||\n formValue != null ||\n recordValue != null ||\n isDirty) {\n return;\n }\n // Side note: For Array Input but checked for all to avoid possible regression\n // Since we use get(record, source), if source is like foo.23.bar,\n // this effect will run. However we only want to set the default value\n // for the subfield bar if the record actually has a value for foo.23\n var pathContainsIndex = finalSource\n .split('.')\n .some(function (pathPart) { return numericRegex.test(pathPart); });\n if (pathContainsIndex) {\n var parentPath = finalSource.split('.').slice(0, -1).join('.');\n var parentValue = get(getValues(), parentPath);\n if (parentValue == null) {\n // the parent is undefined, so we don't want to set the default value\n return;\n }\n }\n if (isArrayInput) {\n if (!fieldArrayInputControl) {\n throw new Error('useApplyInputDefaultValues: No fieldArrayInputControl passed in props for array input usage');\n }\n // We need to update inputs nested in array using react hook forms\n // own array controller rather then the generic reset to prevent control losing\n // context of the nested inputs\n fieldArrayInputControl.replace(defaultValue);\n // resets the form so that control no longer sees the form as dirty after\n // defaults applied\n reset({}, { keepValues: true });\n return;\n }\n resetField(finalSource, { defaultValue: defaultValue });\n });\n};\nvar numericRegex = /^\\d+$/;\n//# sourceMappingURL=useApplyInputDefaultValues.js.map","import lodashMemoize from 'lodash/memoize';\n/* eslint-disable no-underscore-dangle */\n/* @link http://stackoverflow.com/questions/46155/validate-email-address-in-javascript */\nvar EMAIL_REGEX = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/; // eslint-disable-line no-useless-escape\nexport var isEmpty = function (value) {\n return typeof value === 'undefined' ||\n value === null ||\n value === '' ||\n (Array.isArray(value) && value.length === 0);\n};\n// type predicate, see https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates\nfunction isValidationErrorMessageWithArgs(error) {\n return error ? error.hasOwnProperty('message') : false;\n}\nvar getMessage = function (message, messageArgs, value, values) {\n return typeof message === 'function'\n ? message({\n args: messageArgs,\n value: value,\n values: values,\n })\n : messageArgs\n ? {\n message: message,\n args: messageArgs,\n }\n : message;\n};\n// If we define validation functions directly in JSX, it will\n// result in a new function at every render, and then trigger infinite re-render.\n// Hence, we memoize every built-in validator to prevent a \"Maximum call stack\" error.\nvar memoize = function (fn) {\n return lodashMemoize(fn, function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return JSON.stringify(args);\n });\n};\nvar isFunction = function (value) { return typeof value === 'function'; };\nexport var combine2Validators = function (validator1, validator2) {\n return function (value, values, meta) {\n var result1 = validator1(value, values, meta);\n if (!result1) {\n return validator2(value, values, meta);\n }\n if (typeof result1 === 'string' ||\n isValidationErrorMessageWithArgs(result1)) {\n return result1;\n }\n return result1.then(function (resolvedResult1) {\n if (!resolvedResult1) {\n return validator2(value, values, meta);\n }\n return resolvedResult1;\n });\n };\n};\n// Compose multiple validators into a single one for use with react-hook-form\nexport var composeValidators = function () {\n var validators = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n validators[_i] = arguments[_i];\n }\n var allValidators = (Array.isArray(validators[0]) ? validators[0] : validators).filter(isFunction);\n return allValidators.reduce(combine2Validators, function () { return null; });\n};\n// Compose multiple validators into a single one for use with react-hook-form\nexport var composeSyncValidators = function () {\n var validators = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n validators[_i] = arguments[_i];\n }\n return function (value, values, meta) {\n var allValidators = (Array.isArray(validators[0]) ? validators[0] : validators).filter(isFunction);\n for (var _i = 0, allValidators_1 = allValidators; _i < allValidators_1.length; _i++) {\n var validator = allValidators_1[_i];\n var error = validator(value, values, meta);\n if (error) {\n return error;\n }\n }\n };\n};\n/**\n * Required validator\n *\n * Returns an error if the value is null, undefined, or empty\n *\n * @param {string|Function} message\n *\n * @example\n *\n * const titleValidators = [required('The title is required')];\n * \n */\nexport var required = memoize(function (message) {\n if (message === void 0) { message = 'ra.validation.required'; }\n return Object.assign(function (value, values) {\n return isEmpty(value)\n ? getMessage(message, undefined, value, values)\n : undefined;\n }, { isRequired: true });\n});\n/**\n * Minimum length validator\n *\n * Returns an error if the value has a length less than the parameter\n *\n * @param {integer} min\n * @param {string|Function} message\n *\n * @example\n *\n * const passwordValidators = [minLength(10, 'Should be at least 10 characters')];\n * \n */\nexport var minLength = memoize(function (min, message) {\n if (message === void 0) { message = 'ra.validation.minLength'; }\n return function (value, values) {\n return !isEmpty(value) && value.length < min\n ? getMessage(message, { min: min }, value, values)\n : undefined;\n };\n});\n/**\n * Maximum length validator\n *\n * Returns an error if the value has a length higher than the parameter\n *\n * @param {integer} max\n * @param {string|Function} message\n *\n * @example\n *\n * const nameValidators = [maxLength(10, 'Should be at most 10 characters')];\n * \n */\nexport var maxLength = memoize(function (max, message) {\n if (message === void 0) { message = 'ra.validation.maxLength'; }\n return function (value, values) {\n return !isEmpty(value) && value.length > max\n ? getMessage(message, { max: max }, value, values)\n : undefined;\n };\n});\n/**\n * Minimum validator\n *\n * Returns an error if the value is less than the parameter\n *\n * @param {integer} min\n * @param {string|Function} message\n *\n * @example\n *\n * const fooValidators = [minValue(5, 'Should be more than 5')];\n * \n */\nexport var minValue = memoize(function (min, message) {\n if (message === void 0) { message = 'ra.validation.minValue'; }\n return function (value, values) {\n return !isEmpty(value) && value < min\n ? getMessage(message, { min: min }, value, values)\n : undefined;\n };\n});\n/**\n * Maximum validator\n *\n * Returns an error if the value is higher than the parameter\n *\n * @param {integer} max\n * @param {string|Function} message\n *\n * @example\n *\n * const fooValidators = [maxValue(10, 'Should be less than 10')];\n * \n */\nexport var maxValue = memoize(function (max, message) {\n if (message === void 0) { message = 'ra.validation.maxValue'; }\n return function (value, values) {\n return !isEmpty(value) && value > max\n ? getMessage(message, { max: max }, value, values)\n : undefined;\n };\n});\n/**\n * Number validator\n *\n * Returns an error if the value is not a number\n *\n * @param {string|Function} message\n *\n * @example\n *\n * const ageValidators = [number('Must be a number')];\n * \n */\nexport var number = memoize(function (message) {\n if (message === void 0) { message = 'ra.validation.number'; }\n return function (value, values) {\n return !isEmpty(value) && isNaN(Number(value))\n ? getMessage(message, undefined, value, values)\n : undefined;\n };\n});\n/**\n * Regular expression validator\n *\n * Returns an error if the value does not match the pattern given as parameter\n *\n * @param {RegExp} pattern\n * @param {string|Function} message\n *\n * @example\n *\n * const zipValidators = [regex(/^\\d{5}(?:[-\\s]\\d{4})?$/, 'Must be a zip code')];\n * \n */\nexport var regex = lodashMemoize(function (pattern, message) {\n if (message === void 0) { message = 'ra.validation.regex'; }\n return function (value, values) {\n return !isEmpty(value) && typeof value === 'string' && !pattern.test(value)\n ? getMessage(message, { pattern: pattern }, value, values)\n : undefined;\n };\n}, function (pattern, message) {\n return pattern.toString() + message;\n});\n/**\n * Email validator\n *\n * Returns an error if the value is not a valid email\n *\n * @param {string|Function} message\n *\n * @example\n *\n * const emailValidators = [email('Must be an email')];\n * \n */\nexport var email = memoize(function (message) {\n if (message === void 0) { message = 'ra.validation.email'; }\n return regex(EMAIL_REGEX, message);\n});\nvar oneOfTypeMessage = function (_a) {\n var args = _a.args;\n return ({\n message: 'ra.validation.oneOf',\n args: args,\n });\n};\n/**\n * Choices validator\n *\n * Returns an error if the value is not among the list passed as parameter\n *\n * @param {array} list\n * @param {string|Function} message\n *\n * @example\n *\n * const genderValidators = [choices(['male', 'female'], 'Must be either Male or Female')];\n * \n */\nexport var choices = memoize(function (list, message) {\n if (message === void 0) { message = oneOfTypeMessage; }\n return function (value, values) {\n return !isEmpty(value) && list.indexOf(value) === -1\n ? getMessage(message, { list: list }, value, values)\n : undefined;\n };\n});\n/**\n * Given a validator, returns a boolean indicating whether the field is required or not.\n */\nexport var isRequired = function (validate) {\n if (validate && validate.isRequired) {\n return true;\n }\n if (Array.isArray(validate)) {\n return !!validate.find(function (it) { return it.isRequired; });\n }\n return false;\n};\n//# sourceMappingURL=validate.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nimport { useCallback, useRef } from 'react';\nimport merge from 'lodash/merge';\nimport set from 'lodash/set';\nimport { useResourceContext } from '../../core';\nimport { useDataProvider } from '../../dataProvider';\nimport { useTranslate, useTranslateLabel } from '../../i18n';\nimport { asyncDebounce } from '../../util';\nimport { useRecordContext } from '../../controller';\nimport { isEmpty } from './validate';\n/**\n * A hook that returns a validation function checking for a record field uniqueness\n * by calling the dataProvider getList function with a filter.\n *\n * @example // Passing options at declaration time\n * const UserCreateForm = () => {\n * const unique = useUnique({ message: 'Username is already used'});\n * return (\n * \n * \n * \n * );\n * }\n *\n * @example // Passing options at call time\n * const UserCreateForm = () => {\n * const unique = useUnique();\n * return (\n * \n * \n * \n * );\n * }\n *\n * @example // With additional filters\n * const UserCreateForm = () => {\n * const unique = useUnique();\n * return (\n * \n * \n * \n * {({ formData }) => (\n * \n * )}\n * \n * \n * );\n * }\n */\nexport var useUnique = function (options) {\n var _a;\n var dataProvider = useDataProvider();\n var translateLabel = useTranslateLabel();\n var resource = useResourceContext(options);\n if (!resource) {\n throw new Error('useUnique: missing resource prop or context');\n }\n var translate = useTranslate();\n var record = useRecordContext();\n var debouncedGetList = useRef(\n // The initial value is here to set the correct type on useRef\n asyncDebounce(dataProvider.getList, (_a = options === null || options === void 0 ? void 0 : options.debounce) !== null && _a !== void 0 ? _a : DEFAULT_DEBOUNCE));\n var validateUnique = useCallback(function (callTimeOptions) {\n var _a = merge({\n debounce: DEFAULT_DEBOUNCE,\n filter: {},\n message: 'ra.validation.unique',\n }, options, callTimeOptions), message = _a.message, filter = _a.filter, interval = _a.debounce;\n debouncedGetList.current = asyncDebounce(dataProvider.getList, interval);\n return function (value, allValues, props) { return __awaiter(void 0, void 0, void 0, function () {\n var finalFilter, _a, data, total, error_1;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n if (isEmpty(value)) {\n return [2 /*return*/, undefined];\n }\n _b.label = 1;\n case 1:\n _b.trys.push([1, 3, , 4]);\n finalFilter = set(merge({}, filter), props.source, value);\n return [4 /*yield*/, debouncedGetList.current(resource, {\n filter: finalFilter,\n pagination: { page: 1, perPage: 1 },\n sort: { field: 'id', order: 'ASC' },\n })];\n case 2:\n _a = _b.sent(), data = _a.data, total = _a.total;\n if (typeof total !== 'undefined' &&\n total > 0 &&\n !data.some(function (r) { return r.id === (record === null || record === void 0 ? void 0 : record.id); })) {\n return [2 /*return*/, {\n message: message,\n args: {\n source: props.source,\n value: value,\n field: translateLabel({\n label: props.label,\n source: props.source,\n resource: resource,\n }),\n },\n }];\n }\n return [3 /*break*/, 4];\n case 3:\n error_1 = _b.sent();\n return [2 /*return*/, translate('ra.notification.http_error')];\n case 4: return [2 /*return*/, undefined];\n }\n });\n }); };\n }, [dataProvider, options, record, resource, translate, translateLabel]);\n return validateUnique;\n};\nvar DEFAULT_DEBOUNCE = 1000;\n//# sourceMappingURL=useUnique.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport * as React from 'react';\nimport { useTranslate } from '../../i18n';\nvar ValidationErrorSpecialFormatPrefix = '@@react-admin@@';\nexport var ValidationError = function (props) {\n var error = props.error;\n var errorMessage = error;\n var translate = useTranslate();\n // react-hook-form expects errors to be plain strings but our validators can return objects\n // that have message and args.\n // To avoid double translation for users that validate with a schema instead of our validators\n // we use a special format for our validators errors.\n // The useInput hook handle the special formatting\n if (typeof error === 'string' &&\n error.startsWith(ValidationErrorSpecialFormatPrefix)) {\n errorMessage = JSON.parse(error.substring(ValidationErrorSpecialFormatPrefix.length));\n }\n if (errorMessage.message) {\n var _a = errorMessage, message = _a.message, args = _a.args;\n return React.createElement(React.Fragment, null, translate(message, __assign({ _: message }, args)));\n }\n return React.createElement(React.Fragment, null, translate(errorMessage, { _: errorMessage }));\n};\n//# sourceMappingURL=ValidationError.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useEffect, useId } from 'react';\nimport { useController, } from 'react-hook-form';\nimport get from 'lodash/get';\nimport { useRecordContext } from '../controller';\nimport { composeValidators, isRequired } from './validation';\nimport { useFormGroupContext, useFormGroups } from './groups';\nimport { useApplyInputDefaultValues } from './useApplyInputDefaultValues';\nimport { useEvent } from '../util';\nimport { useWrappedSource } from '../core';\n// replace null or undefined values by empty string to avoid controlled/uncontrolled input warning\nvar defaultFormat = function (value) { return (value == null ? '' : value); };\n// parse empty string into null as it's more suitable for a majority of backends\nvar defaultParse = function (value) { return (value === '' ? null : value); };\nexport var useInput = function (props) {\n var defaultValue = props.defaultValue, _a = props.format, format = _a === void 0 ? defaultFormat : _a, id = props.id, isRequiredOption = props.isRequired, name = props.name, initialOnBlur = props.onBlur, initialOnChange = props.onChange, _b = props.parse, parseProp = _b === void 0 ? defaultParse : _b, source = props.source, validate = props.validate, options = __rest(props, [\"defaultValue\", \"format\", \"id\", \"isRequired\", \"name\", \"onBlur\", \"onChange\", \"parse\", \"source\", \"validate\"]);\n var finalSource = useWrappedSource(source);\n var finalName = name || finalSource;\n var formGroupName = useFormGroupContext();\n var formGroups = useFormGroups();\n var record = useRecordContext();\n // @ts-ignore\n var parse = useEvent(parseProp);\n var defaultId = useId();\n if (!finalName && process.env.NODE_ENV === 'development') {\n console.warn('Input components require either a source or a name prop.');\n }\n useEffect(function () {\n if (!formGroups || formGroupName == null) {\n return;\n }\n formGroups.registerField(finalSource, formGroupName);\n return function () {\n formGroups.unregisterField(finalSource, formGroupName);\n };\n }, [formGroups, formGroupName, finalSource]);\n var sanitizedValidate = Array.isArray(validate)\n ? composeValidators(validate)\n : validate;\n // Fetch the defaultValue from the record if available or apply the provided defaultValue.\n // This ensures dynamically added inputs have their value set correctly (ArrayInput for example).\n // We don't do this for the form level defaultValues so that it works as it should in react-hook-form\n // (i.e. field level defaultValue override form level defaultValues for this field).\n var _c = useController(__assign({ name: finalName, defaultValue: get(record, finalSource, defaultValue), rules: {\n validate: function (value, values) { return __awaiter(void 0, void 0, void 0, function () {\n var error;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!sanitizedValidate)\n return [2 /*return*/, true];\n return [4 /*yield*/, sanitizedValidate(value, values, __assign(__assign({}, props), { finalSource: finalSource }))];\n case 1:\n error = _a.sent();\n if (!error)\n return [2 /*return*/, true];\n // react-hook-form expects errors to be plain strings but our validators can return objects\n // that have message and args.\n // To avoid double translation for users that validate with a schema instead of our validators\n // we use a special format for our validators errors.\n // The ValidationError component will check for this format and extract the message and args\n // to translate.\n return [2 /*return*/, \"@@react-admin@@\".concat(JSON.stringify(error))];\n }\n });\n }); },\n } }, options)), controllerField = _c.field, fieldState = _c.fieldState, formState = _c.formState;\n // Because our forms may receive an asynchronously loaded record for instance,\n // they may reset their default values which would override the input default value.\n // This hook ensures that the input default value is applied when a new record is loaded but has\n // no value for the input.\n useApplyInputDefaultValues({ inputProps: props });\n var onBlur = useEvent(function () {\n var event = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n event[_i] = arguments[_i];\n }\n controllerField.onBlur();\n if (initialOnBlur) {\n initialOnBlur.apply(void 0, event);\n }\n });\n var onChange = useEvent(function () {\n var _a, _b, _c, _d, _e;\n var event = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n event[_i] = arguments[_i];\n }\n var eventOrValue = (props.type === 'checkbox' && ((_b = (_a = event[0]) === null || _a === void 0 ? void 0 : _a.target) === null || _b === void 0 ? void 0 : _b.value) === 'on'\n ? event[0].target.checked\n : (_e = (_d = (_c = event[0]) === null || _c === void 0 ? void 0 : _c.target) === null || _d === void 0 ? void 0 : _d.value) !== null && _e !== void 0 ? _e : event[0]);\n controllerField.onChange(parse ? parse(eventOrValue) : eventOrValue);\n if (initialOnChange) {\n initialOnChange.apply(void 0, event);\n }\n });\n var field = __assign(__assign({}, controllerField), { value: format ? format(controllerField.value) : controllerField.value, onBlur: onBlur, onChange: onChange });\n return {\n id: id || defaultId,\n field: field,\n fieldState: fieldState,\n formState: formState,\n isRequired: isRequiredOption || isRequired(validate),\n };\n};\n//# sourceMappingURL=useInput.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { useCallback, isValidElement } from 'react';\nimport set from 'lodash/set';\nimport { useChoices, } from './choices/useChoices';\nimport { useTranslate } from '../i18n';\n/*\n * Returns helper functions for suggestions handling.\n *\n * @param allowDuplicates A boolean indicating whether a suggestion can be added several times\n * @param choices An array of available choices\n * @param limitChoicesToValue A boolean indicating whether the initial suggestions should be limited to the currently selected one(s)\n * @param matchSuggestion Optional unless `optionText` is a React element. Function which check whether a choice matches a filter. Must return a boolean.\n * @param optionText Either a string defining the property to use to get the choice text, a function or a React element\n * @param optionValue The property to use to get the choice value\n * @param selectedItem The currently selected item. Maybe an array of selected items\n * @param suggestionLimit The maximum number of suggestions returned\n * @param translateChoice A boolean indicating whether to option text should be translated\n *\n * @returns An object with helper functions:\n * - getChoiceText: Returns the choice text or a React element\n * - getChoiceValue: Returns the choice value\n * - getSuggestions: A function taking a filter value (string) and returning the matching suggestions\n */\nexport var useSuggestions = function (_a) {\n var allowCreate = _a.allowCreate, choices = _a.choices, _b = _a.createText, createText = _b === void 0 ? 'ra.action.create' : _b, _c = _a.createValue, createValue = _c === void 0 ? '@@create' : _c, limitChoicesToValue = _a.limitChoicesToValue, matchSuggestion = _a.matchSuggestion, optionText = _a.optionText, optionValue = _a.optionValue, selectedItem = _a.selectedItem, _d = _a.suggestionLimit, suggestionLimit = _d === void 0 ? 0 : _d, translateChoice = _a.translateChoice;\n var translate = useTranslate();\n var _e = useChoices({\n optionText: optionText,\n optionValue: optionValue,\n translateChoice: translateChoice,\n }), getChoiceText = _e.getChoiceText, getChoiceValue = _e.getChoiceValue;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n var getSuggestions = useCallback(getSuggestionsFactory({\n allowCreate: allowCreate,\n choices: choices,\n createText: createText,\n createValue: createValue,\n getChoiceText: getChoiceText,\n getChoiceValue: getChoiceValue,\n limitChoicesToValue: limitChoicesToValue,\n matchSuggestion: matchSuggestion,\n optionText: optionText,\n optionValue: optionValue,\n selectedItem: selectedItem,\n suggestionLimit: suggestionLimit,\n }), [\n allowCreate,\n choices,\n createText,\n createValue,\n getChoiceText,\n getChoiceValue,\n limitChoicesToValue,\n matchSuggestion,\n optionText,\n optionValue,\n selectedItem,\n suggestionLimit,\n translate,\n ]);\n return {\n getChoiceText: getChoiceText,\n getChoiceValue: getChoiceValue,\n getSuggestions: getSuggestions,\n };\n};\nvar escapeRegExp = function (value) {\n return value ? value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&') : '';\n}; // $& means the whole matched string\n/**\n * Default matcher implementation which check whether the suggestion text matches the filter.\n */\nvar defaultMatchSuggestion = function (getChoiceText) {\n return function (filter, suggestion, exact) {\n if (exact === void 0) { exact = false; }\n var suggestionText = getChoiceText(suggestion);\n var isReactElement = isValidElement(suggestionText);\n var regex = escapeRegExp(filter);\n return isReactElement\n ? false\n : suggestionText &&\n !!suggestionText.match(\n // We must escape any RegExp reserved characters to avoid errors\n // For example, the filter might contain * which must be escaped as \\*\n new RegExp(exact ? \"^\".concat(regex, \"$\") : regex, 'i'));\n };\n};\n/**\n * Get the suggestions to display after applying a fuzzy search on the available choices\n *\n * @example\n *\n * getSuggestions({\n * choices: [{ id: 1, name: 'admin' }, { id: 2, name: 'publisher' }],\n * optionText: 'name',\n * optionValue: 'id',\n * getSuggestionText: choice => choice[optionText],\n * })('pub')\n *\n * // Will return [{ id: 2, name: 'publisher' }]\n * getSuggestions({\n * choices: [{ id: 1, name: 'admin' }, { id: 2, name: 'publisher' }],\n * optionText: 'name',\n * optionValue: 'id',\n * getSuggestionText: choice => choice[optionText],\n * })('pub')\n *\n * // Will return [{ id: 2, name: 'publisher' }]\n */\nexport var getSuggestionsFactory = function (_a) {\n var _b = _a.allowCreate, allowCreate = _b === void 0 ? false : _b, _c = _a.choices, choices = _c === void 0 ? [] : _c, _d = _a.createText, createText = _d === void 0 ? 'ra.action.create' : _d, _e = _a.createValue, createValue = _e === void 0 ? '@@create' : _e, _f = _a.optionText, optionText = _f === void 0 ? 'name' : _f, _g = _a.optionValue, optionValue = _g === void 0 ? 'id' : _g, getChoiceText = _a.getChoiceText, getChoiceValue = _a.getChoiceValue, _h = _a.limitChoicesToValue, limitChoicesToValue = _h === void 0 ? false : _h, _j = _a.matchSuggestion, matchSuggestion = _j === void 0 ? defaultMatchSuggestion(getChoiceText) : _j, selectedItem = _a.selectedItem, _k = _a.suggestionLimit, suggestionLimit = _k === void 0 ? 0 : _k;\n return function (filter) {\n var suggestions = [];\n // if an item is selected and matches the filter\n if (selectedItem &&\n !Array.isArray(selectedItem) &&\n matchSuggestion(filter, selectedItem)) {\n if (limitChoicesToValue) {\n // display only the selected item\n suggestions = choices.filter(function (choice) {\n return getChoiceValue(choice) === getChoiceValue(selectedItem);\n });\n }\n else {\n suggestions = __spreadArray([], choices, true);\n }\n }\n else {\n suggestions = choices.filter(function (choice) {\n return matchSuggestion(filter, choice) ||\n (selectedItem != null &&\n (!Array.isArray(selectedItem)\n ? getChoiceValue(choice) ===\n getChoiceValue(selectedItem)\n : selectedItem.some(function (selected) {\n return getChoiceValue(choice) ===\n getChoiceValue(selected);\n })));\n });\n }\n suggestions = limitSuggestions(suggestions, suggestionLimit);\n var hasExactMatch = suggestions.some(function (suggestion) {\n return matchSuggestion(filter, suggestion, true);\n });\n if (allowCreate) {\n var filterIsSelectedItem = \n // If the selectedItem is an array (for example AutocompleteArrayInput)\n // we shouldn't try to match\n !!selectedItem && !Array.isArray(selectedItem)\n ? matchSuggestion(filter, selectedItem, true)\n : false;\n if (!hasExactMatch && !filterIsSelectedItem) {\n suggestions.push(getSuggestion({\n optionText: optionText,\n optionValue: optionValue,\n text: createText,\n value: createValue,\n }));\n }\n }\n // Only keep unique items. Necessary because we might have fetched\n // the currently selected choice in addition of the possible choices\n // that may also contain it\n var result = suggestions.filter(function (suggestion, index) { return suggestions.indexOf(suggestion) === index; });\n return result;\n };\n};\n/**\n * @example\n *\n * limitSuggestions(\n * [{ id: 1, name: 'foo'}, { id: 2, name: 'bar' }],\n * 1\n * );\n *\n * // Will return [{ id: 1, name: 'foo' }]\n *\n * @param suggestions List of suggestions\n * @param limit\n */\nvar limitSuggestions = function (suggestions, limit) {\n if (limit === void 0) { limit = 0; }\n return Number.isInteger(limit) && limit > 0\n ? suggestions.slice(0, limit)\n : suggestions;\n};\n/**\n * addSuggestion(\n * [{ id: 1, name: 'foo'}, { id: 2, name: 'bar' }],\n * );\n *\n * // Will return [{ id: null, name: '' }, { id: 1, name: 'foo' }, { id: 2, name: 'bar' }]\n *\n * @param suggestions List of suggestions\n * @param options\n * @param options.optionText\n */\nvar getSuggestion = function (_a) {\n var _b = _a.optionText, optionText = _b === void 0 ? 'name' : _b, _c = _a.optionValue, optionValue = _c === void 0 ? 'id' : _c, _d = _a.text, text = _d === void 0 ? '' : _d, _e = _a.value, value = _e === void 0 ? null : _e;\n var suggestion = {};\n set(suggestion, optionValue, value);\n if (typeof optionText === 'string') {\n set(suggestion, optionText, text);\n }\n return suggestion;\n};\n//# sourceMappingURL=useSuggestions.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport * as React from 'react';\nimport isEqual from 'lodash/isEqual';\nimport cloneDeep from 'lodash/cloneDeep';\nimport get from 'lodash/get';\nimport set from 'lodash/set';\nimport { useEffect } from 'react';\nimport { FormProvider, useForm } from 'react-hook-form';\nimport { SourceContextProvider, useResourceContext, } from '../core';\nimport { FormGroupsProvider, getSimpleValidationResolver, } from '.';\nimport { useDebouncedEvent } from '../util';\nimport { useListContext } from '../controller/list/useListContext';\n/**\n * This component offers a convenient way to create a form that automatically\n * updates the filters when the user changes its child input values.\n *\n * It fits nicely alongside a `` component, but you can also use it\n * at other places to create your own filter UI.\n *\n * @example\n * import MailIcon from '@mui/icons-material/MailOutline';\n * import TitleIcon from '@mui/icons-material/Title';\n * import { Card, CardContent } from '@mui/material';\n * import * as React from 'react';\n * import {\n * FilterLiveForm,\n * FilterList,\n * FilterListItem,\n * FilterListSection,\n * TextInput,\n * } from 'react-admin';\n *\n * export const BookListAside = () => (\n * \n * \n * }>\n * \n * \n * \n * }>\n * \n * \n * \n * \n * \n * \n * );\n */\nexport var FilterLiveForm = function (props) {\n var _a = useListContext(), filterValues = _a.filterValues, setFilters = _a.setFilters;\n var resource = useResourceContext(props);\n var _b = props.debounce, debounce = _b === void 0 ? 500 : _b, resolver = props.resolver, validate = props.validate, children = props.children, _c = props.formComponent, Component = _c === void 0 ? HTMLForm : _c, rest = __rest(props, [\"debounce\", \"resolver\", \"validate\", \"children\", \"formComponent\"]);\n var finalResolver = resolver\n ? resolver\n : validate\n ? getSimpleValidationResolver(validate)\n : undefined;\n var formContext = useForm(__assign({ mode: 'onChange', defaultValues: filterValues, resolver: finalResolver }, rest));\n var handleSubmit = formContext.handleSubmit, getValues = formContext.getValues, reset = formContext.reset, watch = formContext.watch, formState = formContext.formState;\n var isValid = formState.isValid;\n // Ref tracking if there are internal changes pending, i.e. changes that\n // should not trigger a reset\n var formChangesPending = React.useRef(false);\n // Reapply filterValues when they change externally\n useEffect(function () {\n var newValues = getFilterFormValues(getValues(), filterValues);\n var previousValues = getValues();\n if (formChangesPending.current) {\n // The effect was triggered by a form change (i.e. internal change),\n // so we don't need to reset the form\n formChangesPending.current = false;\n return;\n }\n if (!isEqual(newValues, previousValues)) {\n reset(newValues);\n }\n // The reference to the filterValues object is not updated when it changes,\n // so we must stringify it to compare it by value.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [JSON.stringify(filterValues), getValues, reset]);\n var onSubmit = function (values) {\n // Do not call setFilters if the form is invalid\n if (!isValid) {\n return;\n }\n formChangesPending.current = true;\n setFilters(__assign(__assign({}, filterValues), values));\n };\n var debouncedOnSubmit = useDebouncedEvent(onSubmit, debounce || 0);\n // Submit the form on values change\n useEffect(function () {\n var unsubscribe = watch(function (values, _a) {\n var name = _a.name;\n // Check that the name is present to avoid setting filters when\n // watch was triggered by a reset\n if (name) {\n if (get(values, name) === '') {\n var newValues = cloneDeep(values);\n set(newValues, name, '');\n debouncedOnSubmit(newValues);\n }\n else {\n debouncedOnSubmit(values);\n }\n }\n }).unsubscribe;\n return function () { return unsubscribe(); };\n }, [watch, debouncedOnSubmit]);\n var sourceContext = React.useMemo(function () { return ({\n getSource: function (source) { return source; },\n getLabel: function (source) {\n return \"resources.\".concat(resource, \".fields.\").concat(source);\n },\n }); }, [resource]);\n return (React.createElement(FormProvider, __assign({}, formContext),\n React.createElement(FormGroupsProvider, null,\n React.createElement(SourceContextProvider, { value: sourceContext },\n React.createElement(Component, { onSubmit: handleSubmit(onSubmit) }, children)))));\n};\nvar HTMLForm = function (props) { return (React.createElement(\"form\", __assign({}, props))); };\n/**\n * Because we are using controlled inputs with react-hook-form, we must provide a default value\n * for each input when resetting the form. (see https://react-hook-form.com/docs/useform/reset).\n * To ensure we don't provide undefined which will result to the current input value being reapplied\n * and due to the dynamic nature of the filter form, we rebuild the filter form values from its current\n * values and make sure to pass at least an empty string for each input.\n */\nexport var getFilterFormValues = function (formValues, filterValues) {\n var _a;\n return Object.keys(formValues).reduce(function (acc, key) {\n acc[key] = getInputValue(formValues, key, filterValues);\n return acc;\n }, (_a = cloneDeep(filterValues)) !== null && _a !== void 0 ? _a : {});\n};\nvar getInputValue = function (formValues, key, filterValues) {\n if (formValues[key] === undefined || formValues[key] === null) {\n return get(filterValues, key, '');\n }\n if (Array.isArray(formValues[key])) {\n return get(filterValues, key, '');\n }\n if (formValues[key] instanceof Date) {\n return get(filterValues, key, '');\n }\n if (typeof formValues[key] === 'object') {\n var inputValues = Object.keys(formValues[key]).reduce(function (acc, innerKey) {\n var _a;\n var nestedInputValue = getInputValue(formValues[key], innerKey, (_a = (filterValues || {})[key]) !== null && _a !== void 0 ? _a : {});\n acc[innerKey] = nestedInputValue;\n return acc;\n }, {});\n if (!Object.keys(inputValues).length)\n return '';\n return inputValues;\n }\n return get(filterValues, key, '');\n};\n//# sourceMappingURL=FilterLiveForm.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport React from 'react';\nimport { ResourceContextProvider } from '../../core';\nimport { ChoicesContextProvider } from '../../form';\nimport { useReferenceInputController, } from './useReferenceInputController';\n/**\n * An Input component for choosing a reference record. Useful for foreign keys.\n *\n * This component fetches the possible values in the reference resource\n * (using `dataProvider.getList()`), and renders the child you passed\n * to which it passes the possible choices via a `ChoicesContext`.\n *\n * You must pass a child selection component to customize the way the reference\n * selector is displayed (e.g. using `` or ``\n * instead of `` ).\n *\n * Note that the child component should handle the error and loading cases as this base component does not.\n *\n * @example // using a SelectInput as selector\n * export const CommentEdit = () => (\n * \n * \n * \n * \n * \n * \n * \n * );\n *\n * By default, restricts the possible values to 25. You can extend this limit\n * by setting the `perPage` prop.\n *\n * @example\n * \n *\n * By default, orders the possible values by id desc. You can change this order\n * by setting the `sort` prop (an object with `field` and `order` properties).\n *\n * @example\n * \n * \n * \n *\n * Also, you can filter the query used to populate the possible values. Use the\n * `filter` prop for that.\n *\n * @example\n * \n * \n * \n *\n * The enclosed component may filter results. ReferenceInputBase create a ChoicesContext which provides\n * a `setFilters` function. You can call this function to filter the results.\n */\nexport var ReferenceInputBase = function (props) {\n var children = props.children, reference = props.reference, _a = props.sort, sort = _a === void 0 ? { field: 'id', order: 'DESC' } : _a, _b = props.filter, filter = _b === void 0 ? {} : _b;\n var controllerProps = useReferenceInputController(__assign(__assign({}, props), { sort: sort, filter: filter }));\n return (React.createElement(ResourceContextProvider, { value: reference },\n React.createElement(ChoicesContextProvider, { value: controllerProps }, children)));\n};\n//# sourceMappingURL=ReferenceInputBase.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useParams } from 'react-router-dom';\nimport { useAuthenticated, useRequireAccess } from '../../auth';\nimport { useGetOne, useRefresh, } from '../../dataProvider';\nimport { useTranslate } from '../../i18n';\nimport { useRedirect } from '../../routing';\nimport { useNotify } from '../../notification';\nimport { useResourceContext, useGetResourceLabel, useGetRecordRepresentation, } from '../../core';\n/**\n * Prepare data for the Show view.\n *\n * useShowController does a few things:\n * - it grabs the id from the URL and the resource name from the ResourceContext,\n * - it fetches the record via useGetOne,\n * - it prepares the page title.\n *\n * @param {Object} props The props passed to the Show component.\n *\n * @return {Object} controllerProps Fetched data and callbacks for the Show view\n *\n * @example\n *\n * import { useShowController } from 'react-admin';\n * import ShowView from './ShowView';\n *\n * const MyShow = () => {\n * const controllerProps = useShowController();\n * return ;\n * };\n *\n * @example // useShowController can also take its parameters from props\n *\n * import { useShowController } from 'react-admin';\n * import ShowView from './ShowView';\n *\n * const MyShow = () => {\n * const controllerProps = useShowController({ resource: 'posts', id: 1234 });\n * return ;\n * };\n */\nexport var useShowController = function (props) {\n if (props === void 0) { props = {}; }\n var _a = props.disableAuthentication, disableAuthentication = _a === void 0 ? false : _a, propsId = props.id, _b = props.queryOptions, queryOptions = _b === void 0 ? {} : _b;\n var resource = useResourceContext(props);\n if (!resource) {\n throw new Error(\"useShowController requires a non-empty resource prop or context\");\n }\n var isPendingAuthenticated = useAuthenticated({\n enabled: !disableAuthentication,\n }).isPending;\n var isPendingCanAccess = useRequireAccess({\n action: 'show',\n resource: resource,\n // If disableAuthentication is true then isPendingAuthenticated will always be true so this hook is disabled\n enabled: !isPendingAuthenticated,\n }).isPending;\n var getRecordRepresentation = useGetRecordRepresentation(resource);\n var translate = useTranslate();\n var notify = useNotify();\n var redirect = useRedirect();\n var refresh = useRefresh();\n var routeId = useParams().id;\n if (!routeId && !propsId) {\n throw new Error('useShowController requires an id prop or a route with an /:id? parameter.');\n }\n var id = propsId != null ? propsId : routeId;\n var meta = queryOptions.meta, otherQueryOptions = __rest(queryOptions, [\"meta\"]);\n var _c = useGetOne(resource, { id: id, meta: meta }, __assign({ enabled: (!isPendingAuthenticated && !isPendingCanAccess) ||\n disableAuthentication, onError: function () {\n notify('ra.notification.item_doesnt_exist', {\n type: 'error',\n });\n redirect('list', resource);\n refresh();\n }, retry: false }, otherQueryOptions)), record = _c.data, error = _c.error, isLoading = _c.isLoading, isFetching = _c.isFetching, isPending = _c.isPending, refetch = _c.refetch;\n // eslint-disable-next-line eqeqeq\n if (record && record.id && record.id != id) {\n throw new Error(\"useShowController: Fetched record's id attribute (\".concat(record.id, \") must match the requested 'id' (\").concat(id, \")\"));\n }\n var getResourceLabel = useGetResourceLabel();\n var recordRepresentation = getRecordRepresentation(record);\n var defaultTitle = translate('ra.page.show', {\n name: getResourceLabel(resource, 1),\n id: id,\n record: record,\n recordRepresentation: typeof recordRepresentation === 'string'\n ? recordRepresentation\n : '',\n });\n return {\n defaultTitle: defaultTitle,\n error: error,\n isLoading: isLoading,\n isFetching: isFetching,\n isPending: isPending,\n record: record,\n refetch: refetch,\n resource: resource,\n };\n};\n//# sourceMappingURL=useShowController.js.map","import { createContext } from 'react';\n/**\n * Context to store the result of the useShowController() hook.\n *\n * Use the useShowContext() hook to read the context. That's what the Show components do in react-admin.\n *\n * @example\n *\n * import { useShowController, ShowContextProvider } from 'ra-core';\n *\n * const Show = props => {\n * const controllerProps = useShowController(props);\n * return (\n * \n * ...\n * \n * );\n * };\n */\nexport var ShowContext = createContext(null);\nShowContext.displayName = 'ShowContext';\n//# sourceMappingURL=ShowContext.js.map","import * as React from 'react';\nimport { RecordContextProvider } from '../record/RecordContext';\nimport { ShowContext } from './ShowContext';\n/**\n * Create a Show Context.\n *\n * @example\n *\n * const MyShow = (props) => {\n * const controllerProps = useShowController(props);\n * return (\n * \n * \n * \n * );\n * };\n *\n * const MyShowView = () => {\n * const record = useRecordContext();\n * }\n *\n * @see ShowContext\n * @see RecordContext\n */\nexport var ShowContextProvider = function (_a) {\n var children = _a.children, value = _a.value;\n return (React.createElement(ShowContext.Provider, { value: value },\n React.createElement(RecordContextProvider, { value: value && value.record }, children)));\n};\n//# sourceMappingURL=ShowContextProvider.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport * as React from 'react';\nimport { useShowController } from './useShowController';\nimport { ShowContextProvider } from './ShowContextProvider';\nimport { OptionalResourceContextProvider } from '../../core';\nimport { useIsAuthPending } from '../../auth';\n/**\n * Call useShowController and put the value in a ShowContext\n *\n * Base class for components, without UI.\n *\n * Accepts any props accepted by useShowController:\n * - id: The record identifier\n * - resource: The resource\n *\n * @example // Custom show layout\n *\n * const PostShow = () => (\n * \n * \n * \n * \n * ...\n * \n * \n * \n * Show instructions...\n * \n * \n *
\n * Post related links...\n *
\n *
\n * );\n */\nexport var ShowBase = function (_a) {\n var children = _a.children, _b = _a.loading, loading = _b === void 0 ? null : _b, props = __rest(_a, [\"children\", \"loading\"]);\n var controllerProps = useShowController(props);\n var isAuthPending = useIsAuthPending({\n resource: controllerProps.resource,\n action: 'show',\n });\n if (isAuthPending && !props.disableAuthentication) {\n return loading;\n }\n return (\n // We pass props.resource here as we don't need to create a new ResourceContext if the props is not provided\n React.createElement(OptionalResourceContextProvider, { value: props.resource },\n React.createElement(ShowContextProvider, { value: controllerProps }, children)));\n};\n//# sourceMappingURL=ShowBase.js.map","import { useContext } from 'react';\nimport { ShowContext } from './ShowContext';\n/**\n * Hook to read the show controller props from the ShowContext.\n *\n * Used within a (e.g. as a descendent of ).\n *\n * @returns {ShowControllerResult} create controller props\n *\n * @see useShowController for how it is filled\n */\nexport var useShowContext = function () {\n var context = useContext(ShowContext);\n // Props take precedence over the context\n if (!context) {\n throw new Error('useShowContext must be used inside a ShowContextProvider');\n }\n return context;\n};\n//# sourceMappingURL=useShowContext.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useMemo, useRef } from 'react';\nimport { useMutation, useQueryClient, } from '@tanstack/react-query';\nimport { useDataProvider } from './useDataProvider';\nimport { useEvent } from '../util';\n/**\n * Get a callback to call the dataProvider.create() method, the result and the loading state.\n *\n * @param {string} resource\n * @param {Params} params The create parameters { data }\n * @param {Object} options Options object to pass to the queryClient.\n * May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } }\n *\n * @typedef Params\n * @prop params.data The record to create, e.g. { title: 'hello, world' }\n *\n * @returns The current mutation state. Destructure as [create, { data, error, isPending }].\n *\n * The return value updates according to the request state:\n *\n * - initial: [create, { isPending: false, isIdle: true }]\n * - start: [create, { isPending: true }]\n * - success: [create, { data: [data from response], isPending: false, isSuccess: true }]\n * - error: [create, { error: [error from response], isPending: false, isError: true }]\n *\n * The create() function must be called with a resource and a parameter object: create(resource, { data, meta }, options)\n *\n * This hook uses react-query useMutation under the hood.\n * This means the state object contains mutate, isIdle, reset and other react-query methods.\n *\n * @see https://tanstack.com/query/v5/docs/react/reference/useMutation\n *\n * @example // set params when calling the create callback\n *\n * import { useCreate, useRecordContext } from 'react-admin';\n *\n * const LikeButton = () => {\n * const record = useRecordContext();\n * const like = { postId: record.id };\n * const [create, { isPending, error }] = useCreate();\n * const handleClick = () => {\n * create('likes', { data: like })\n * }\n * if (error) { return

ERROR

; }\n * return ;\n * };\n *\n * @example // set params when calling the hook\n *\n * import { useCreate, useRecordContext } from 'react-admin';\n *\n * const LikeButton = () => {\n * const record = useRecordContext();\n * const like = { postId: record.id };\n * const [create, { isPending, error }] = useCreate('likes', { data: like });\n * if (error) { return

ERROR

; }\n * return ;\n * };\n *\n * @example // TypeScript\n * const [create, { data }] = useCreate('products', { data: product });\n * \\-- data is Product\n */\nexport var useCreate = function (resource, params, options) {\n if (params === void 0) { params = {}; }\n if (options === void 0) { options = {}; }\n var dataProvider = useDataProvider();\n var queryClient = useQueryClient();\n var paramsRef = useRef(params);\n var hasCallTimeOnError = useRef(false);\n var hasCallTimeOnSuccess = useRef(false);\n var hasCallTimeOnSettled = useRef(false);\n var getMutateWithMiddlewares = options.getMutateWithMiddlewares, mutationOptions = __rest(options, [\"getMutateWithMiddlewares\"]);\n var mutation = useMutation(__assign(__assign({ mutationFn: function (_a) {\n var _b = _a === void 0 ? {} : _a, _c = _b.resource, callTimeResource = _c === void 0 ? resource : _c, _d = _b.data, callTimeData = _d === void 0 ? paramsRef.current.data : _d, _e = _b.meta, callTimeMeta = _e === void 0 ? paramsRef.current.meta : _e;\n if (!callTimeResource) {\n throw new Error('useCreate mutation requires a non-empty resource');\n }\n if (!callTimeData) {\n throw new Error('useCreate mutation requires a non-empty data object');\n }\n if (getMutateWithMiddlewares) {\n var createWithMiddlewares = getMutateWithMiddlewares(dataProvider.create.bind(dataProvider));\n return createWithMiddlewares(callTimeResource, {\n data: callTimeData,\n meta: callTimeMeta,\n }).then(function (_a) {\n var data = _a.data;\n return data;\n });\n }\n return dataProvider\n .create(callTimeResource, {\n data: callTimeData,\n meta: callTimeMeta,\n })\n .then(function (_a) {\n var data = _a.data;\n return data;\n });\n } }, mutationOptions), { onError: function (error, variables, context) {\n if (options.onError && !hasCallTimeOnError.current) {\n return options.onError(error, variables, context);\n }\n }, onSuccess: function (data, variables, context) {\n if (variables === void 0) { variables = {}; }\n var _a = variables.resource, callTimeResource = _a === void 0 ? resource : _a;\n queryClient.setQueryData([callTimeResource, 'getOne', { id: String(data.id) }], data);\n queryClient.invalidateQueries({\n queryKey: [callTimeResource, 'getList'],\n });\n queryClient.invalidateQueries({\n queryKey: [callTimeResource, 'getInfiniteList'],\n });\n queryClient.invalidateQueries({\n queryKey: [callTimeResource, 'getMany'],\n });\n queryClient.invalidateQueries({\n queryKey: [callTimeResource, 'getManyReference'],\n });\n if (options.onSuccess && !hasCallTimeOnSuccess.current) {\n options.onSuccess(data, variables, context);\n }\n }, onSettled: function (data, error, variables, context) {\n if (options.onSettled && !hasCallTimeOnSettled.current) {\n return options.onSettled(data, error, variables, context);\n }\n } }));\n var create = function (callTimeResource, callTimeParams, callTimeOptions) {\n if (callTimeResource === void 0) { callTimeResource = resource; }\n if (callTimeParams === void 0) { callTimeParams = {}; }\n if (callTimeOptions === void 0) { callTimeOptions = {}; }\n var _a = callTimeOptions.returnPromise, returnPromise = _a === void 0 ? options.returnPromise : _a, otherCallTimeOptions = __rest(callTimeOptions, [\"returnPromise\"]);\n hasCallTimeOnError.current = !!otherCallTimeOptions.onError;\n hasCallTimeOnSuccess.current = !!otherCallTimeOptions.onSuccess;\n hasCallTimeOnSettled.current = !!otherCallTimeOptions.onSettled;\n if (returnPromise) {\n return mutation.mutateAsync(__assign({ resource: callTimeResource }, callTimeParams), otherCallTimeOptions);\n }\n return mutation.mutate(__assign({ resource: callTimeResource }, callTimeParams), otherCallTimeOptions);\n };\n var mutationResult = useMemo(function () { return (__assign({ isLoading: mutation.isPending }, mutation)); }, [mutation]);\n return [useEvent(create), mutationResult];\n};\n//# sourceMappingURL=useCreate.js.map","import { createContext } from 'react';\nexport var AddUndoableMutationContext = createContext(function () { });\n//# sourceMappingURL=AddUndoableMutationContext.js.map","import { useContext } from 'react';\nimport { AddUndoableMutationContext } from './AddUndoableMutationContext';\nexport var useAddUndoableMutation = function () {\n return useContext(AddUndoableMutationContext);\n};\n//# sourceMappingURL=useAddUndoableMutation.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { useMemo, useRef } from 'react';\nimport { useMutation, useQueryClient, } from '@tanstack/react-query';\nimport { useDataProvider } from './useDataProvider';\nimport { useAddUndoableMutation } from './undo/useAddUndoableMutation';\nimport { useEvent } from '../util';\n/**\n * Get a callback to call the dataProvider.update() method, the result and the loading state.\n *\n * @param {string} resource\n * @param {Params} params The update parameters { id, data, previousData, meta }\n * @param {Object} options Options object to pass to the queryClient.\n * May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } }\n * May include a mutation mode (optimistic/pessimistic/undoable), e.g. { mutationMode: 'undoable' }\n *\n * @typedef Params\n * @prop params.id The resource identifier, e.g. 123\n * @prop params.data The updates to merge into the record, e.g. { views: 10 }\n * @prop params.previousData The record before the update is applied\n * @prop params.meta Optional meta data\n *\n * @returns The current mutation state. Destructure as [update, { data, error, isPending }].\n *\n * The return value updates according to the request state:\n *\n * - initial: [update, { isPending: false, isIdle: true }]\n * - start: [update, { isPending: true }]\n * - success: [update, { data: [data from response], isPending: false, isSuccess: true }]\n * - error: [update, { error: [error from response], isPending: false, isError: true }]\n *\n * The update() function must be called with a resource and a parameter object: update(resource, { id, data, previousData }, options)\n *\n * This hook uses react-query useMutation under the hood.\n * This means the state object contains mutate, isIdle, reset and other react-query methods.\n *\n * @see https://react-query-v3.tanstack.com/reference/useMutation\n *\n * @example // set params when calling the update callback\n *\n * import { useUpdate, useRecordContext } from 'react-admin';\n *\n * const IncreaseLikeButton = () => {\n * const record = useRecordContext();\n * const diff = { likes: record.likes + 1 };\n * const [update, { isPending, error }] = useUpdate();\n * const handleClick = () => {\n * update('likes', { id: record.id, data: diff, previousData: record })\n * }\n * if (error) { return

ERROR

; }\n * return ;\n * };\n *\n * @example // TypeScript\n * const [update, { data }] = useUpdate('products', { id, data: diff, previousData: product });\n * \\-- data is Product\n */\nexport var useUpdate = function (resource, params, options) {\n if (params === void 0) { params = {}; }\n if (options === void 0) { options = {}; }\n var dataProvider = useDataProvider();\n var queryClient = useQueryClient();\n var addUndoableMutation = useAddUndoableMutation();\n var id = params.id, data = params.data, meta = params.meta;\n var _a = options.mutationMode, mutationMode = _a === void 0 ? 'pessimistic' : _a, getMutateWithMiddlewares = options.getMutateWithMiddlewares, mutationOptions = __rest(options, [\"mutationMode\", \"getMutateWithMiddlewares\"]);\n var mode = useRef(mutationMode);\n var paramsRef = useRef(params);\n var snapshot = useRef([]);\n // Ref that stores the mutation with middlewares to avoid losing them if the calling component is unmounted\n var mutateWithMiddlewares = useRef(dataProvider.update);\n // We need to store the call-time onError and onSettled in refs to be able to call them in the useMutation hook even\n // when the calling component is unmounted\n var callTimeOnError = useRef();\n var callTimeOnSettled = useRef();\n // We don't need to keep a ref on the onSuccess callback as we call it ourselves for optimistic and\n // undoable mutations. There is a limitation though: if one of the side effects applied by the onSuccess callback\n // unmounts the component that called the useUpdate hook (redirect for instance), it must be the last one applied,\n // otherwise the other side effects may not applied.\n var hasCallTimeOnSuccess = useRef(false);\n var updateCache = function (_a) {\n var resource = _a.resource, id = _a.id, data = _a.data, meta = _a.meta;\n // hack: only way to tell react-query not to fetch this query for the next 5 seconds\n // because setQueryData doesn't accept a stale time option\n var now = Date.now();\n var updatedAt = mode.current === 'undoable' ? now + 5 * 1000 : now;\n // Stringify and parse the data to remove undefined values.\n // If we don't do this, an update with { id: undefined } as payload\n // would remove the id from the record, which no real data provider does.\n var clonedData = JSON.parse(JSON.stringify(data));\n var updateColl = function (old) {\n if (!old)\n return old;\n var index = old.findIndex(\n // eslint-disable-next-line eqeqeq\n function (record) { return record.id == id; });\n if (index === -1) {\n return old;\n }\n return __spreadArray(__spreadArray(__spreadArray([], old.slice(0, index), true), [\n __assign(__assign({}, old[index]), clonedData)\n ], false), old.slice(index + 1), true);\n };\n queryClient.setQueryData([resource, 'getOne', { id: String(id), meta: meta }], function (record) { return (__assign(__assign({}, record), clonedData)); }, { updatedAt: updatedAt });\n queryClient.setQueriesData({ queryKey: [resource, 'getList'] }, function (res) {\n return res && res.data ? __assign(__assign({}, res), { data: updateColl(res.data) }) : res;\n }, { updatedAt: updatedAt });\n queryClient.setQueriesData({ queryKey: [resource, 'getInfiniteList'] }, function (res) {\n return res && res.pages\n ? __assign(__assign({}, res), { pages: res.pages.map(function (page) { return (__assign(__assign({}, page), { data: updateColl(page.data) })); }) }) : res;\n }, { updatedAt: updatedAt });\n queryClient.setQueriesData({ queryKey: [resource, 'getMany'] }, function (coll) {\n return coll && coll.length > 0 ? updateColl(coll) : coll;\n }, { updatedAt: updatedAt });\n queryClient.setQueriesData({ queryKey: [resource, 'getManyReference'] }, function (res) {\n return res && res.data\n ? { data: updateColl(res.data), total: res.total }\n : res;\n }, { updatedAt: updatedAt });\n };\n var mutation = useMutation(__assign(__assign({ mutationFn: function (_a) {\n var _b = _a === void 0 ? {} : _a, _c = _b.resource, callTimeResource = _c === void 0 ? resource : _c, _d = _b.id, callTimeId = _d === void 0 ? paramsRef.current.id : _d, _e = _b.data, callTimeData = _e === void 0 ? paramsRef.current.data : _e, _f = _b.meta, callTimeMeta = _f === void 0 ? paramsRef.current.meta : _f, _g = _b.previousData, callTimePreviousData = _g === void 0 ? paramsRef.current.previousData : _g;\n if (!callTimeResource) {\n throw new Error('useUpdate mutation requires a non-empty resource');\n }\n if (callTimeId == null) {\n throw new Error('useUpdate mutation requires a non-empty id');\n }\n if (!callTimeData) {\n throw new Error('useUpdate mutation requires a non-empty data object');\n }\n return mutateWithMiddlewares\n .current(callTimeResource, {\n id: callTimeId,\n data: callTimeData,\n previousData: callTimePreviousData,\n meta: callTimeMeta,\n })\n .then(function (_a) {\n var data = _a.data;\n return data;\n });\n } }, mutationOptions), { onMutate: function (variables) { return __awaiter(void 0, void 0, void 0, function () {\n var userContext;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!mutationOptions.onMutate) return [3 /*break*/, 2];\n return [4 /*yield*/, mutationOptions.onMutate(variables)];\n case 1:\n userContext = (_a.sent()) || {};\n return [2 /*return*/, __assign({ snapshot: snapshot.current }, userContext)];\n case 2: \n // Return a context object with the snapshot value\n return [2 /*return*/, { snapshot: snapshot.current }];\n }\n });\n }); }, onError: function (error, variables, context) {\n if (variables === void 0) { variables = {}; }\n if (mode.current === 'optimistic' || mode.current === 'undoable') {\n // If the mutation fails, use the context returned from onMutate to rollback\n context.snapshot.forEach(function (_a) {\n var key = _a[0], value = _a[1];\n queryClient.setQueryData(key, value);\n });\n }\n if (callTimeOnError.current) {\n return callTimeOnError.current(error, variables, context);\n }\n if (mutationOptions.onError) {\n return mutationOptions.onError(error, variables, context);\n }\n // call-time error callback is executed by react-query\n }, onSuccess: function (data, variables, context) {\n if (variables === void 0) { variables = {}; }\n if (mode.current === 'pessimistic') {\n // update the getOne and getList query cache with the new result\n var _a = variables.resource, callTimeResource = _a === void 0 ? resource : _a, _b = variables.id, callTimeId = _b === void 0 ? id : _b, _c = variables.meta, callTimeMeta = _c === void 0 ? meta : _c;\n updateCache({\n resource: callTimeResource,\n id: callTimeId,\n data: data,\n meta: callTimeMeta,\n });\n if (mutationOptions.onSuccess &&\n !hasCallTimeOnSuccess.current) {\n mutationOptions.onSuccess(data, variables, context);\n }\n }\n }, onSettled: function (data, error, variables, context) {\n if (variables === void 0) { variables = {}; }\n if (mode.current === 'optimistic' || mode.current === 'undoable') {\n // Always refetch after error or success:\n context.snapshot.forEach(function (_a) {\n var queryKey = _a[0];\n queryClient.invalidateQueries({ queryKey: queryKey });\n });\n }\n if (callTimeOnSettled.current) {\n return callTimeOnSettled.current(data, error, variables, context);\n }\n if (mutationOptions.onSettled) {\n return mutationOptions.onSettled(data, error, variables, context);\n }\n } }));\n var update = function (callTimeResource, callTimeParams, callTimeOptions) {\n if (callTimeResource === void 0) { callTimeResource = resource; }\n if (callTimeParams === void 0) { callTimeParams = {}; }\n if (callTimeOptions === void 0) { callTimeOptions = {}; }\n return __awaiter(void 0, void 0, void 0, function () {\n var mutationMode, _a, returnPromise, onError, onSettled, onSuccess, otherCallTimeOptions, _b, callTimeId, _c, callTimeData, _d, callTimeMeta, previousRecord, queryKeys;\n return __generator(this, function (_e) {\n switch (_e.label) {\n case 0:\n mutationMode = callTimeOptions.mutationMode, _a = callTimeOptions.returnPromise, returnPromise = _a === void 0 ? mutationOptions.returnPromise : _a, onError = callTimeOptions.onError, onSettled = callTimeOptions.onSettled, onSuccess = callTimeOptions.onSuccess, otherCallTimeOptions = __rest(callTimeOptions, [\"mutationMode\", \"returnPromise\", \"onError\", \"onSettled\", \"onSuccess\"]);\n // Store the mutation with middlewares to avoid losing them if the calling component is unmounted\n if (getMutateWithMiddlewares) {\n mutateWithMiddlewares.current = getMutateWithMiddlewares(dataProvider.update.bind(dataProvider));\n }\n else {\n mutateWithMiddlewares.current = dataProvider.update;\n }\n // We need to keep the onSuccess callback here and not in the useMutation for undoable mutations\n hasCallTimeOnSuccess.current = !!onSuccess;\n // We need to store the onError and onSettled callbacks here to be able to call them in the useMutation hook\n // so that they are called even when the calling component is unmounted\n callTimeOnError.current = onError;\n callTimeOnSettled.current = onSettled;\n // store the hook time params *at the moment of the call*\n // because they may change afterwards, which would break the undoable mode\n // as the previousData would be overwritten by the optimistic update\n paramsRef.current = params;\n if (mutationMode) {\n mode.current = mutationMode;\n }\n if (returnPromise && mode.current !== 'pessimistic') {\n console.warn('The returnPromise parameter can only be used if the mutationMode is set to pessimistic');\n }\n if (mode.current === 'pessimistic') {\n if (returnPromise) {\n return [2 /*return*/, mutation.mutateAsync(__assign({ resource: callTimeResource }, callTimeParams), __assign({ onSuccess: onSuccess }, otherCallTimeOptions))];\n }\n return [2 /*return*/, mutation.mutate(__assign({ resource: callTimeResource }, callTimeParams), __assign({ onSuccess: onSuccess }, otherCallTimeOptions))];\n }\n _b = callTimeParams.id, callTimeId = _b === void 0 ? id : _b, _c = callTimeParams.data, callTimeData = _c === void 0 ? data : _c, _d = callTimeParams.meta, callTimeMeta = _d === void 0 ? meta : _d;\n previousRecord = queryClient.getQueryData([\n callTimeResource,\n 'getOne',\n { id: String(callTimeId), meta: callTimeMeta },\n ]);\n queryKeys = [\n [\n callTimeResource,\n 'getOne',\n { id: String(callTimeId), meta: callTimeMeta },\n ],\n [callTimeResource, 'getList'],\n [callTimeResource, 'getInfiniteList'],\n [callTimeResource, 'getMany'],\n [callTimeResource, 'getManyReference'],\n ];\n /**\n * Snapshot the previous values via queryClient.getQueriesData()\n *\n * The snapshotData ref will contain an array of tuples [query key, associated data]\n *\n * @example\n * [\n * [['posts', 'getOne', { id: '1' }], { id: 1, title: 'Hello' }],\n * [['posts', 'getList'], { data: [{ id: 1, title: 'Hello' }], total: 1 }],\n * [['posts', 'getMany'], [{ id: 1, title: 'Hello' }]],\n * ]\n *\n * @see https://react-query-v3.tanstack.com/reference/QueryClient#queryclientgetqueriesdata\n */\n snapshot.current = queryKeys.reduce(function (prev, queryKey) {\n return prev.concat(queryClient.getQueriesData({ queryKey: queryKey }));\n }, []);\n // Cancel any outgoing re-fetches (so they don't overwrite our optimistic update)\n return [4 /*yield*/, Promise.all(snapshot.current.map(function (_a) {\n var queryKey = _a[0];\n return queryClient.cancelQueries({ queryKey: queryKey });\n }))];\n case 1:\n // Cancel any outgoing re-fetches (so they don't overwrite our optimistic update)\n _e.sent();\n // Optimistically update to the new value\n updateCache({\n resource: callTimeResource,\n id: callTimeId,\n data: callTimeData,\n meta: callTimeMeta,\n });\n // run the success callbacks during the next tick\n setTimeout(function () {\n if (onSuccess) {\n onSuccess(__assign(__assign({}, previousRecord), callTimeData), __assign({ resource: callTimeResource }, callTimeParams), { snapshot: snapshot.current });\n }\n else if (mutationOptions.onSuccess &&\n !hasCallTimeOnSuccess.current) {\n mutationOptions.onSuccess(__assign(__assign({}, previousRecord), callTimeData), __assign({ resource: callTimeResource }, callTimeParams), { snapshot: snapshot.current });\n }\n }, 0);\n if (mode.current === 'optimistic') {\n // call the mutate method without success side effects\n return [2 /*return*/, mutation.mutate(__assign({ resource: callTimeResource }, callTimeParams))];\n }\n else {\n // Undoable mutation: add the mutation to the undoable queue.\n // The Notification component will dequeue it when the user confirms or cancels the message.\n addUndoableMutation(function (_a) {\n var isUndo = _a.isUndo;\n if (isUndo) {\n // rollback\n snapshot.current.forEach(function (_a) {\n var key = _a[0], value = _a[1];\n queryClient.setQueryData(key, value);\n });\n }\n else {\n // call the mutate method without success side effects\n mutation.mutate(__assign({ resource: callTimeResource }, callTimeParams));\n }\n });\n }\n return [2 /*return*/];\n }\n });\n });\n };\n var mutationResult = useMemo(function () { return (__assign({ isLoading: mutation.isPending }, mutation)); }, [mutation]);\n return [useEvent(update), mutationResult];\n};\n//# sourceMappingURL=useUpdate.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { useMemo, useRef } from 'react';\nimport { useMutation, useQueryClient, } from '@tanstack/react-query';\nimport { useDataProvider } from './useDataProvider';\nimport { useAddUndoableMutation } from './undo/useAddUndoableMutation';\nimport { useEvent } from '../util';\n/**\n * Get a callback to call the dataProvider.delete() method, the result and the loading state.\n *\n * @param {string} resource\n * @param {Params} params The delete parameters { id, previousData }\n * @param {Object} options Options object to pass to the queryClient.\n * May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } }\n * May include a mutation mode (optimistic/pessimistic/undoable), e.g. { mutationMode: 'undoable' }\n *\n * @typedef Params\n * @prop params.id The resource identifier, e.g. 123\n * @prop params.previousData The record before the update is applied\n *\n * @returns The current mutation state. Destructure as [deleteOne, { data, error, isPending }].\n *\n * The return value updates according to the request state:\n *\n * - initial: [deleteOne, { isPending: false, isIdle: true }]\n * - start: [deleteOne, { isPending: true }]\n * - success: [deleteOne, { data: [data from response], isPending: false, isSuccess: true }]\n * - error: [deleteOne, { error: [error from response], isPending: false, isError: true }]\n *\n * The deleteOne() function must be called with a resource and a parameter object: deleteOne(resource, { id, previousData, meta }, options)\n *\n * This hook uses react-query useMutation under the hood.\n * This means the state object contains mutate, isIdle, reset and other react-query methods.\n *\n * @see https://tanstack.com/query/v5/docs/react/reference/useMutation\n *\n * @example // set params when calling the deleteOne callback\n *\n * import { useDelete, useRecordContext } from 'react-admin';\n *\n * const DeleteButton = () => {\n * const record = useRecordContext();\n * const [deleteOne, { isPending, error }] = useDelete();\n * const handleClick = () => {\n * deleteOne('likes', { id: record.id, previousData: record })\n * }\n * if (error) { return

ERROR

; }\n * return ;\n * };\n *\n * @example // TypeScript\n * const [delete, { data }] = useDelete('products', { id, previousData: product });\n * \\-- data is Product\n */\nexport var useDelete = function (resource, params, options) {\n if (params === void 0) { params = {}; }\n if (options === void 0) { options = {}; }\n var dataProvider = useDataProvider();\n var queryClient = useQueryClient();\n var addUndoableMutation = useAddUndoableMutation();\n var id = params.id, previousData = params.previousData;\n var _a = options.mutationMode, mutationMode = _a === void 0 ? 'pessimistic' : _a, mutationOptions = __rest(options, [\"mutationMode\"]);\n var mode = useRef(mutationMode);\n var paramsRef = useRef(params);\n var snapshot = useRef([]);\n var hasCallTimeOnError = useRef(false);\n var hasCallTimeOnSuccess = useRef(false);\n var hasCallTimeOnSettled = useRef(false);\n var updateCache = function (_a) {\n var resource = _a.resource, id = _a.id;\n // hack: only way to tell react-query not to fetch this query for the next 5 seconds\n // because setQueryData doesn't accept a stale time option\n var now = Date.now();\n var updatedAt = mode.current === 'undoable' ? now + 5 * 1000 : now;\n var updateColl = function (old) {\n if (!old)\n return old;\n var index = old.findIndex(\n // eslint-disable-next-line eqeqeq\n function (record) { return record.id == id; });\n if (index === -1) {\n return old;\n }\n return __spreadArray(__spreadArray([], old.slice(0, index), true), old.slice(index + 1), true);\n };\n queryClient.setQueriesData({ queryKey: [resource, 'getList'] }, function (res) {\n if (!res || !res.data)\n return res;\n var newCollection = updateColl(res.data);\n var recordWasFound = newCollection.length < res.data.length;\n return recordWasFound\n ? {\n data: newCollection,\n total: res.total ? res.total - 1 : undefined,\n pageInfo: res.pageInfo,\n }\n : res;\n }, { updatedAt: updatedAt });\n queryClient.setQueriesData({ queryKey: [resource, 'getInfiniteList'] }, function (res) {\n if (!res || !res.pages)\n return res;\n return __assign(__assign({}, res), { pages: res.pages.map(function (page) {\n var newCollection = updateColl(page.data);\n var recordWasFound = newCollection.length < page.data.length;\n return recordWasFound\n ? __assign(__assign({}, page), { data: newCollection, total: page.total\n ? page.total - 1\n : undefined, pageInfo: page.pageInfo }) : page;\n }) });\n }, { updatedAt: updatedAt });\n queryClient.setQueriesData({ queryKey: [resource, 'getMany'] }, function (coll) {\n return coll && coll.length > 0 ? updateColl(coll) : coll;\n }, { updatedAt: updatedAt });\n queryClient.setQueriesData({ queryKey: [resource, 'getManyReference'] }, function (res) {\n if (!res || !res.data)\n return res;\n var newCollection = updateColl(res.data);\n var recordWasFound = newCollection.length < res.data.length;\n return recordWasFound\n ? {\n data: newCollection,\n total: res.total - 1,\n }\n : res;\n }, { updatedAt: updatedAt });\n };\n var mutation = useMutation(__assign(__assign({ mutationFn: function (_a) {\n var _b = _a === void 0 ? {} : _a, _c = _b.resource, callTimeResource = _c === void 0 ? resource : _c, _d = _b.id, callTimeId = _d === void 0 ? paramsRef.current.id : _d, _e = _b.previousData, callTimePreviousData = _e === void 0 ? paramsRef.current.previousData : _e, _f = _b.meta, callTimeMeta = _f === void 0 ? paramsRef.current.meta : _f;\n if (!callTimeResource) {\n throw new Error('useDelete mutation requires a non-empty resource');\n }\n if (callTimeId == null) {\n throw new Error('useDelete mutation requires a non-empty id');\n }\n return dataProvider\n .delete(callTimeResource, {\n id: callTimeId,\n previousData: callTimePreviousData,\n meta: callTimeMeta,\n })\n .then(function (_a) {\n var data = _a.data;\n return data;\n });\n } }, mutationOptions), { onMutate: function (variables) { return __awaiter(void 0, void 0, void 0, function () {\n var userContext;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!mutationOptions.onMutate) return [3 /*break*/, 2];\n return [4 /*yield*/, mutationOptions.onMutate(variables)];\n case 1:\n userContext = (_a.sent()) || {};\n return [2 /*return*/, __assign({ snapshot: snapshot.current }, userContext)];\n case 2: \n // Return a context object with the snapshot value\n return [2 /*return*/, { snapshot: snapshot.current }];\n }\n });\n }); }, onError: function (error, variables, context) {\n if (variables === void 0) { variables = {}; }\n if (mode.current === 'optimistic' || mode.current === 'undoable') {\n // If the mutation fails, use the context returned from onMutate to rollback\n context.snapshot.forEach(function (_a) {\n var key = _a[0], value = _a[1];\n queryClient.setQueryData(key, value);\n });\n }\n if (mutationOptions.onError && !hasCallTimeOnError.current) {\n return mutationOptions.onError(error, variables, context);\n }\n // call-time error callback is executed by react-query\n }, onSuccess: function (data, variables, context) {\n if (variables === void 0) { variables = {}; }\n if (mode.current === 'pessimistic') {\n // update the getOne and getList query cache with the new result\n var _a = variables.resource, callTimeResource = _a === void 0 ? resource : _a, _b = variables.id, callTimeId = _b === void 0 ? id : _b;\n updateCache({\n resource: callTimeResource,\n id: callTimeId,\n });\n if (mutationOptions.onSuccess &&\n !hasCallTimeOnSuccess.current) {\n mutationOptions.onSuccess(data, variables, context);\n }\n // call-time success callback is executed by react-query\n }\n }, onSettled: function (data, error, variables, context) {\n if (variables === void 0) { variables = {}; }\n // Always refetch after error or success:\n context.snapshot.forEach(function (_a) {\n var queryKey = _a[0];\n queryClient.invalidateQueries({ queryKey: queryKey });\n });\n if (mutationOptions.onSettled && !hasCallTimeOnSettled.current) {\n return mutationOptions.onSettled(data, error, variables, context);\n }\n } }));\n var mutate = function (callTimeResource, callTimeParams, callTimeOptions) {\n if (callTimeResource === void 0) { callTimeResource = resource; }\n if (callTimeParams === void 0) { callTimeParams = {}; }\n if (callTimeOptions === void 0) { callTimeOptions = {}; }\n return __awaiter(void 0, void 0, void 0, function () {\n var mutationMode, otherCallTimeOptions, _a, callTimeId, _b, callTimePreviousData, queryKeys;\n return __generator(this, function (_c) {\n switch (_c.label) {\n case 0:\n mutationMode = callTimeOptions.mutationMode, otherCallTimeOptions = __rest(callTimeOptions, [\"mutationMode\"]);\n hasCallTimeOnError.current = !!callTimeOptions.onError;\n hasCallTimeOnSuccess.current = !!callTimeOptions.onSuccess;\n hasCallTimeOnSettled.current = !!callTimeOptions.onSettled;\n // store the hook time params *at the moment of the call*\n // because they may change afterwards, which would break the undoable mode\n // as the previousData would be overwritten by the optimistic update\n paramsRef.current = params;\n if (mutationMode) {\n mode.current = mutationMode;\n }\n _a = callTimeParams.id, callTimeId = _a === void 0 ? id : _a, _b = callTimeParams.previousData, callTimePreviousData = _b === void 0 ? previousData : _b;\n queryKeys = [\n [callTimeResource, 'getList'],\n [callTimeResource, 'getInfiniteList'],\n [callTimeResource, 'getMany'],\n [callTimeResource, 'getManyReference'],\n ];\n /**\n * Snapshot the previous values via queryClient.getQueriesData()\n *\n * The snapshotData ref will contain an array of tuples [query key, associated data]\n *\n * @example\n * [\n * [['posts', 'getList'], { data: [{ id: 1, title: 'Hello' }], total: 1 }],\n * [['posts', 'getMany'], [{ id: 1, title: 'Hello' }]],\n * ]\n *\n * @see https://tanstack.com/query/v5/docs/react/reference/QueryClient#queryclientgetqueriesdata\n */\n snapshot.current = queryKeys.reduce(function (prev, queryKey) {\n return prev.concat(queryClient.getQueriesData({ queryKey: queryKey }));\n }, []);\n if (mode.current === 'pessimistic') {\n return [2 /*return*/, mutation.mutate(__assign({ resource: callTimeResource }, callTimeParams), otherCallTimeOptions)];\n }\n // Cancel any outgoing re-fetches (so they don't overwrite our optimistic update)\n return [4 /*yield*/, Promise.all(snapshot.current.map(function (_a) {\n var queryKey = _a[0];\n return queryClient.cancelQueries({ queryKey: queryKey });\n }))];\n case 1:\n // Cancel any outgoing re-fetches (so they don't overwrite our optimistic update)\n _c.sent();\n // Optimistically update to the new value\n updateCache({\n resource: callTimeResource,\n id: callTimeId,\n });\n // run the success callbacks during the next tick\n setTimeout(function () {\n if (callTimeOptions.onSuccess) {\n callTimeOptions.onSuccess(callTimePreviousData, __assign({ resource: callTimeResource }, callTimeParams), { snapshot: snapshot.current });\n }\n else if (mutationOptions.onSuccess) {\n mutationOptions.onSuccess(callTimePreviousData, __assign({ resource: callTimeResource }, callTimeParams), { snapshot: snapshot.current });\n }\n }, 0);\n if (mode.current === 'optimistic') {\n // call the mutate method without success side effects\n return [2 /*return*/, mutation.mutate(__assign({ resource: callTimeResource }, callTimeParams), {\n onSettled: callTimeOptions.onSettled,\n onError: callTimeOptions.onError,\n })];\n }\n else {\n // Undoable mutation: add the mutation to the undoable queue.\n // The Notification component will dequeue it when the user confirms or cancels the message.\n addUndoableMutation(function (_a) {\n var isUndo = _a.isUndo;\n if (isUndo) {\n // rollback\n snapshot.current.forEach(function (_a) {\n var key = _a[0], value = _a[1];\n queryClient.setQueryData(key, value);\n });\n }\n else {\n // call the mutate method without success side effects\n mutation.mutate(__assign({ resource: callTimeResource }, callTimeParams), {\n onSettled: callTimeOptions.onSettled,\n onError: callTimeOptions.onError,\n });\n }\n });\n }\n return [2 /*return*/];\n }\n });\n });\n };\n var mutationResult = useMemo(function () { return (__assign({ isLoading: mutation.isPending }, mutation)); }, [mutation]);\n return [useEvent(mutate), mutationResult];\n};\n//# sourceMappingURL=useDelete.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nvar __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { useMemo, useRef } from 'react';\nimport { useMutation, useQueryClient, } from '@tanstack/react-query';\nimport { useDataProvider } from './useDataProvider';\nimport { useAddUndoableMutation } from './undo/useAddUndoableMutation';\nimport { useEvent } from '../util';\n/**\n * Get a callback to call the dataProvider.delete() method, the result and the loading state.\n *\n * @param {string} resource\n * @param {Params} params The delete parameters { ids }\n * @param {Object} options Options object to pass to the queryClient.\n * May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { refresh(); } }\n * May include a mutation mode (optimistic/pessimistic/undoable), e.g. { mutationMode: 'undoable' }\n *\n * @typedef Params\n * @prop params.ids The resource identifiers, e.g. [123, 456]\n *\n * @returns The current mutation state. Destructure as [deleteMany, { data, error, isPending }].\n *\n * The return value updates according to the request state:\n *\n * - initial: [deleteMany, { isPending: false, isIdle: true }]\n * - start: [deleteMany, { isPending: true }]\n * - success: [deleteMany, { data: [data from response], isPending: false, isSuccess: true }]\n * - error: [deleteMany, { error: [error from response], isPending: false, isError: true }]\n *\n * The deleteMany() function must be called with a resource and a parameter object: deleteMany(resource, { ids, meta }, options)\n *\n * This hook uses react-query useMutation under the hood.\n * This means the state object contains mutate, isIdle, reset and other react-query methods.\n *\n * @see https://tanstack.com/query/v5/docs/react/reference/useMutation\n *\n * @example // set params when calling the deleteMany callback\n *\n * import { useDeleteMany } from 'react-admin';\n *\n * const BulkDeletePostsButton = ({ selectedIds }) => {\n * const [deleteMany, { isPending, error }] = useDeleteMany();\n * const handleClick = () => {\n * deleteMany('posts', { ids: selectedIds })\n * }\n * if (error) { return

ERROR

; }\n * return ;\n * };\n *\n * @example // set params when calling the hook\n *\n * import { useDeleteMany } from 'react-admin';\n *\n * const BulkDeletePostsButton = ({ selectedIds }) => {\n * const [deleteMany, { isPending, error }] = useDeleteMany('posts', { ids: selectedIds });\n * const handleClick = () => {\n * deleteMany()\n * }\n * if (error) { return

ERROR

; }\n * return ;\n * };\n *\n * @example // TypeScript\n * const [deleteMany, { data }] = useDeleteMany('products', { ids });\n * \\-- data is Product\n */\nexport var useDeleteMany = function (resource, params, options) {\n if (params === void 0) { params = {}; }\n if (options === void 0) { options = {}; }\n var dataProvider = useDataProvider();\n var queryClient = useQueryClient();\n var addUndoableMutation = useAddUndoableMutation();\n var ids = params.ids;\n var _a = options.mutationMode, mutationMode = _a === void 0 ? 'pessimistic' : _a, mutationOptions = __rest(options, [\"mutationMode\"]);\n var mode = useRef(mutationMode);\n var paramsRef = useRef({});\n var snapshot = useRef([]);\n var hasCallTimeOnError = useRef(false);\n var hasCallTimeOnSuccess = useRef(false);\n var hasCallTimeOnSettled = useRef(false);\n var updateCache = function (_a) {\n var resource = _a.resource, ids = _a.ids;\n // hack: only way to tell react-query not to fetch this query for the next 5 seconds\n // because setQueryData doesn't accept a stale time option\n var now = Date.now();\n var updatedAt = mode.current === 'undoable' ? now + 5 * 1000 : now;\n var updateColl = function (old) {\n if (!old)\n return old;\n var newCollection = __spreadArray([], old, true);\n ids.forEach(function (id) {\n var index = newCollection.findIndex(\n // eslint-disable-next-line eqeqeq\n function (record) { return record.id == id; });\n if (index === -1) {\n return;\n }\n newCollection = __spreadArray(__spreadArray([], newCollection.slice(0, index), true), newCollection.slice(index + 1), true);\n });\n return newCollection;\n };\n queryClient.setQueriesData({ queryKey: [resource, 'getList'] }, function (res) {\n if (!res || !res.data)\n return res;\n var newCollection = updateColl(res.data);\n var recordWasFound = newCollection.length < res.data.length;\n return recordWasFound\n ? {\n data: newCollection,\n total: res.total\n ? res.total -\n (res.data.length - newCollection.length)\n : undefined,\n pageInfo: res.pageInfo,\n }\n : res;\n }, { updatedAt: updatedAt });\n queryClient.setQueriesData({ queryKey: [resource, 'getInfiniteList'] }, function (res) {\n if (!res || !res.pages)\n return res;\n return __assign(__assign({}, res), { pages: res.pages.map(function (page) {\n var newCollection = updateColl(page.data);\n var recordWasFound = newCollection.length < page.data.length;\n return recordWasFound\n ? __assign(__assign({}, page), { data: newCollection, total: page.total\n ? page.total -\n (page.data.length -\n newCollection.length)\n : undefined, pageInfo: page.pageInfo }) : page;\n }) });\n }, { updatedAt: updatedAt });\n queryClient.setQueriesData({ queryKey: [resource, 'getMany'] }, function (coll) {\n return coll && coll.length > 0 ? updateColl(coll) : coll;\n }, { updatedAt: updatedAt });\n queryClient.setQueriesData({ queryKey: [resource, 'getManyReference'] }, function (res) {\n if (!res || !res.data)\n return res;\n var newCollection = updateColl(res.data);\n var recordWasFound = newCollection.length < res.data.length;\n if (!recordWasFound) {\n return res;\n }\n if (res.total) {\n return {\n data: newCollection,\n total: res.total -\n (res.data.length - newCollection.length),\n };\n }\n if (res.pageInfo) {\n return {\n data: newCollection,\n pageInfo: res.pageInfo,\n };\n }\n throw new Error('Found getList result in cache without total or pageInfo');\n }, { updatedAt: updatedAt });\n };\n var mutation = useMutation(__assign(__assign({ mutationFn: function (_a) {\n var _b = _a === void 0 ? {} : _a, _c = _b.resource, callTimeResource = _c === void 0 ? resource : _c, _d = _b.ids, callTimeIds = _d === void 0 ? paramsRef.current.ids : _d, _e = _b.meta, callTimeMeta = _e === void 0 ? paramsRef.current.meta : _e;\n if (!callTimeResource) {\n throw new Error('useDeleteMany mutation requires a non-empty resource');\n }\n if (!callTimeIds) {\n throw new Error('useDeleteMany mutation requires an array of ids');\n }\n if (callTimeIds.length === 0) {\n return Promise.resolve([]);\n }\n return dataProvider\n .deleteMany(callTimeResource, {\n ids: callTimeIds,\n meta: callTimeMeta,\n })\n .then(function (_a) {\n var data = _a.data;\n return data || [];\n });\n } }, mutationOptions), { onMutate: function (variables) { return __awaiter(void 0, void 0, void 0, function () {\n var userContext;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!mutationOptions.onMutate) return [3 /*break*/, 2];\n return [4 /*yield*/, mutationOptions.onMutate(variables)];\n case 1:\n userContext = (_a.sent()) || {};\n return [2 /*return*/, __assign({ snapshot: snapshot.current }, userContext)];\n case 2: \n // Return a context object with the snapshot value\n return [2 /*return*/, { snapshot: snapshot.current }];\n }\n });\n }); }, onError: function (error, variables, context) {\n if (variables === void 0) { variables = {}; }\n if (mode.current === 'optimistic' || mode.current === 'undoable') {\n // If the mutation fails, use the context returned from onMutate to rollback\n context.snapshot.forEach(function (_a) {\n var key = _a[0], value = _a[1];\n queryClient.setQueryData(key, value);\n });\n }\n if (mutationOptions.onError && !hasCallTimeOnError.current) {\n return mutationOptions.onError(error, variables, context);\n }\n // call-time error callback is executed by react-query\n }, onSuccess: function (data, variables, context) {\n if (variables === void 0) { variables = {}; }\n if (mode.current === 'pessimistic') {\n // update the getOne and getList query cache with the new result\n var _a = variables.resource, callTimeResource = _a === void 0 ? resource : _a, _b = variables.ids, callTimeIds = _b === void 0 ? ids : _b;\n updateCache({\n resource: callTimeResource,\n ids: callTimeIds,\n });\n if (mutationOptions.onSuccess &&\n !hasCallTimeOnSuccess.current) {\n mutationOptions.onSuccess(data, variables, context);\n }\n // call-time success callback is executed by react-query\n }\n }, onSettled: function (data, error, variables, context) {\n if (variables === void 0) { variables = {}; }\n if (mode.current === 'optimistic' || mode.current === 'undoable') {\n // Always refetch after error or success:\n context.snapshot.forEach(function (_a) {\n var queryKey = _a[0];\n queryClient.invalidateQueries({ queryKey: queryKey });\n });\n }\n if (mutationOptions.onSettled && !hasCallTimeOnSettled.current) {\n return mutationOptions.onSettled(data, error, variables, context);\n }\n } }));\n var mutate = function (callTimeResource, callTimeParams, callTimeOptions) {\n if (callTimeResource === void 0) { callTimeResource = resource; }\n if (callTimeParams === void 0) { callTimeParams = {}; }\n if (callTimeOptions === void 0) { callTimeOptions = {}; }\n return __awaiter(void 0, void 0, void 0, function () {\n var mutationMode, otherCallTimeOptions, _a, callTimeIds, queryKeys;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n mutationMode = callTimeOptions.mutationMode, otherCallTimeOptions = __rest(callTimeOptions, [\"mutationMode\"]);\n hasCallTimeOnError.current = !!callTimeOptions.onError;\n hasCallTimeOnSuccess.current = !!callTimeOptions.onSuccess;\n hasCallTimeOnSettled.current = !!callTimeOptions.onSettled;\n // store the hook time params *at the moment of the call*\n // because they may change afterwards, which would break the undoable mode\n // as the previousData would be overwritten by the optimistic update\n paramsRef.current = params;\n if (mutationMode) {\n mode.current = mutationMode;\n }\n if (mode.current === 'pessimistic') {\n return [2 /*return*/, mutation.mutate(__assign({ resource: callTimeResource }, callTimeParams), {\n onSuccess: otherCallTimeOptions.onSuccess,\n onSettled: otherCallTimeOptions.onSettled,\n onError: otherCallTimeOptions.onError,\n })];\n }\n _a = callTimeParams.ids, callTimeIds = _a === void 0 ? ids : _a;\n if (!callTimeIds) {\n throw new Error('useDeleteMany mutation requires an array of ids');\n }\n queryKeys = [\n [callTimeResource, 'getList'],\n [callTimeResource, 'getInfiniteList'],\n [callTimeResource, 'getMany'],\n [callTimeResource, 'getManyReference'],\n ];\n /**\n * Snapshot the previous values via queryClient.getQueriesData()\n *\n * The snapshotData ref will contain an array of tuples [query key, associated data]\n *\n * @example\n * [\n * [['posts', 'getList'], { data: [{ id: 1, title: 'Hello' }], total: 1 }],\n * [['posts', 'getMany'], [{ id: 1, title: 'Hello' }]],\n * ]\n *\n * @see https://tanstack.com/query/v5/docs/react/reference/QueryClient#queryclientgetqueriesdata\n */\n snapshot.current = queryKeys.reduce(function (prev, queryKey) {\n return prev.concat(queryClient.getQueriesData({ queryKey: queryKey }));\n }, []);\n // Cancel any outgoing re-fetches (so they don't overwrite our optimistic update)\n return [4 /*yield*/, Promise.all(snapshot.current.map(function (_a) {\n var queryKey = _a[0];\n return queryClient.cancelQueries({ queryKey: queryKey });\n }))];\n case 1:\n // Cancel any outgoing re-fetches (so they don't overwrite our optimistic update)\n _b.sent();\n // Optimistically update to the new value\n updateCache({\n resource: callTimeResource,\n ids: callTimeIds,\n });\n // run the success callbacks during the next tick\n setTimeout(function () {\n if (otherCallTimeOptions.onSuccess) {\n otherCallTimeOptions.onSuccess(callTimeIds, __assign({ resource: callTimeResource }, callTimeParams), { snapshot: snapshot.current });\n }\n else if (mutationOptions.onSuccess) {\n mutationOptions.onSuccess(callTimeIds, __assign({ resource: callTimeResource }, callTimeParams), { snapshot: snapshot.current });\n }\n }, 0);\n if (mode.current === 'optimistic') {\n // call the mutate method without success side effects\n return [2 /*return*/, mutation.mutate(__assign({ resource: callTimeResource }, callTimeParams), {\n onSettled: otherCallTimeOptions.onSettled,\n onError: otherCallTimeOptions.onError,\n })];\n }\n else {\n // Undoable mutation: add the mutation to the undoable queue.\n // The Notification component will dequeue it when the user confirms or cancels the message.\n addUndoableMutation(function (_a) {\n var isUndo = _a.isUndo;\n if (isUndo) {\n // rollback\n snapshot.current.forEach(function (_a) {\n var key = _a[0], value = _a[1];\n queryClient.setQueryData(key, value);\n });\n }\n else {\n // call the mutate method without success side effects\n mutation.mutate(__assign({ resource: callTimeResource }, callTimeParams), {\n onSettled: otherCallTimeOptions.onSettled,\n onError: otherCallTimeOptions.onError,\n });\n }\n });\n }\n return [2 /*return*/];\n }\n });\n });\n };\n var mutationResult = useMemo(function () { return (__assign({ isLoading: mutation.isPending }, mutation)); }, [mutation]);\n return [useEvent(mutate), mutationResult];\n};\n//# sourceMappingURL=useDeleteMany.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useInfiniteQuery, useQueryClient, } from '@tanstack/react-query';\nimport { useDataProvider } from './useDataProvider';\nimport { useEffect, useRef } from 'react';\nimport { useEvent } from '../util';\nvar MAX_DATA_LENGTH_TO_CACHE = 100;\n/**\n * Call the dataProvider.getList() method and return the resolved result\n * as well as the loading state. The return from useInfiniteGetList is equivalent to the return from react-hook form useInfiniteQuery.\n *\n * @see https://tanstack.com/query/v5/docs/react/reference/useInfiniteQuery\n *\n * This hook will return the cached result when called a second time\n * with the same parameters, until the response arrives.\n *\n * @param {string} resource The resource name, e.g. 'posts'\n * @param {Params} params The getList parameters { pagination, sort, filter, meta }\n * @param {Object} options Options object to pass to the queryClient.\n * May include side effects to be executed upon success or failure, e.g. { onSuccess: () => { fetchNextPage(); } }\n *\n * @typedef Params\n * @prop params.pagination The request pagination { page, perPage }, e.g. { page: 1, perPage: 10 }\n * @prop params.sort The request sort { field, order }, e.g. { field: 'id', order: 'DESC' }\n * @prop params.filter The request filters, e.g. { title: 'hello, world' }\n * @prop params.meta Optional meta parameters\n *\n * @returns The current request state. Destructure as { data, total, error, isPending, isSuccess, hasNextPage, fetchNextPage }.\n *\n * @example\n *\n * import { useInfiniteGetList } from 'react-admin';\n *\n * const LatestNews = () => {\n * const { data, total, isPending, error, hasNextPage, fetchNextPage } = useInfiniteGetList(\n * 'posts',\n * { pagination: { page: 1, perPage: 10 }, sort: { field: 'published_at', order: 'DESC' } }\n * );\n * if (isPending) { return ; }\n * if (error) { return

ERROR

; }\n * return (\n * <>\n *
    \n * {data?.pages.map(page => {\n * return page.data.map(post => (\n *
  • {post.title}
  • \n * ));\n * })}\n *
\n *
\n * \n *
\n * \n * );\n * };\n */\nexport var useInfiniteGetList = function (resource, params, options) {\n var _a, _b, _c, _d, _e;\n if (params === void 0) { params = {}; }\n if (options === void 0) { options = {}; }\n var _f = params.pagination, pagination = _f === void 0 ? { page: 1, perPage: 25 } : _f, _g = params.sort, sort = _g === void 0 ? { field: 'id', order: 'DESC' } : _g, _h = params.filter, filter = _h === void 0 ? {} : _h, meta = params.meta;\n var dataProvider = useDataProvider();\n var queryClient = useQueryClient();\n var _j = options.onSuccess, onSuccess = _j === void 0 ? noop : _j, _k = options.onError, onError = _k === void 0 ? noop : _k, _l = options.onSettled, onSettled = _l === void 0 ? noop : _l, queryOptions = __rest(options, [\"onSuccess\", \"onError\", \"onSettled\"]);\n var onSuccessEvent = useEvent(onSuccess);\n var onErrorEvent = useEvent(onError);\n var onSettledEvent = useEvent(onSettled);\n var result = useInfiniteQuery(__assign(__assign({ queryKey: [\n resource,\n 'getInfiniteList',\n { pagination: pagination, sort: sort, filter: filter, meta: meta },\n ], queryFn: function (queryParams) {\n var _a = queryParams.pageParam, pageParam = _a === void 0 ? pagination.page : _a;\n return dataProvider\n .getList(resource, {\n pagination: {\n page: pageParam,\n perPage: pagination.perPage,\n },\n sort: sort,\n filter: filter,\n meta: meta,\n signal: dataProvider.supportAbortSignal === true\n ? queryParams.signal\n : undefined,\n })\n .then(function (_a) {\n var data = _a.data, pageInfo = _a.pageInfo, total = _a.total, meta = _a.meta;\n return ({\n data: data,\n total: total,\n pageParam: pageParam,\n pageInfo: pageInfo,\n meta: meta,\n });\n });\n }, initialPageParam: pagination.page }, queryOptions), { getNextPageParam: function (lastLoadedPage) {\n if (lastLoadedPage.pageInfo) {\n return lastLoadedPage.pageInfo.hasNextPage\n ? lastLoadedPage.pageParam + 1\n : undefined;\n }\n var totalPages = Math.ceil((lastLoadedPage.total || 0) / pagination.perPage);\n return lastLoadedPage.pageParam < totalPages\n ? Number(lastLoadedPage.pageParam) + 1\n : undefined;\n }, getPreviousPageParam: function (lastLoadedPage) {\n if (lastLoadedPage.pageInfo) {\n return lastLoadedPage.pageInfo.hasPreviousPage\n ? lastLoadedPage.pageParam - 1\n : undefined;\n }\n return lastLoadedPage.pageParam === 1\n ? undefined\n : lastLoadedPage.pageParam - 1;\n } }));\n var metaValue = useRef(meta);\n var resourceValue = useRef(resource);\n useEffect(function () {\n metaValue.current = meta;\n }, [meta]);\n useEffect(function () {\n resourceValue.current = resource;\n }, [resource]);\n useEffect(function () {\n if (result.data === undefined ||\n result.error != null ||\n result.isFetching)\n return;\n // optimistically populate the getOne cache\n var allPagesDataLength = result.data.pages.reduce(function (acc, page) { return acc + page.data.length; }, 0);\n if (allPagesDataLength <= MAX_DATA_LENGTH_TO_CACHE) {\n result.data.pages.forEach(function (page) {\n page.data.forEach(function (record) {\n queryClient.setQueryData([\n resourceValue.current,\n 'getOne',\n { id: String(record.id), meta: metaValue.current },\n ], function (oldRecord) { return oldRecord !== null && oldRecord !== void 0 ? oldRecord : record; });\n });\n });\n }\n onSuccessEvent(result.data);\n }, [\n onSuccessEvent,\n queryClient,\n result.data,\n result.error,\n result.isFetching,\n ]);\n useEffect(function () {\n if (result.error == null || result.isFetching)\n return;\n onErrorEvent(result.error);\n }, [onErrorEvent, result.error, result.isFetching]);\n useEffect(function () {\n if (result.status === 'pending' || result.isFetching)\n return;\n onSettledEvent(result.data, result.error);\n }, [\n onSettledEvent,\n result.data,\n result.error,\n result.status,\n result.isFetching,\n ]);\n return (result.data\n ? __assign(__assign({}, result), { data: result.data, total: (_c = (_b = (_a = result.data) === null || _a === void 0 ? void 0 : _a.pages[0]) === null || _b === void 0 ? void 0 : _b.total) !== null && _c !== void 0 ? _c : undefined, meta: (_e = (_d = result.data) === null || _d === void 0 ? void 0 : _d.pages[0]) === null || _e === void 0 ? void 0 : _e.meta }) : result);\n};\nvar noop = function () { return undefined; };\n//# sourceMappingURL=useInfiniteGetList.js.map","import { createContext } from 'react';\nexport var TakeUndoableMutationContext = createContext(function () { });\n//# sourceMappingURL=TakeUndoableMutationContext.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport * as React from 'react';\nimport { useState, useCallback } from 'react';\nimport { AddUndoableMutationContext } from './AddUndoableMutationContext';\nimport { TakeUndoableMutationContext } from './TakeUndoableMutationContext';\n/**\n * Exposes and manages a queue of undoable mutations\n *\n * This context is used in CoreAdminContext so that every react-admin app\n * can use the useAddUndoableMutation and useTakeUndoableMutation hooks.\n *\n * Note: We need a separate queue for mutations (instead of using the\n * notifications queue) because the mutations are not dequeued when the\n * notification is displayed, but when it is dismissed.\n */\nexport var UndoableMutationsContextProvider = function (_a) {\n var children = _a.children;\n var _b = useState([]), mutations = _b[0], setMutations = _b[1];\n /**\n * Add a new mutation (pushes a new mutation to the queue).\n *\n * Used by optimistic data provider hooks, e.g., useDelete\n */\n var addMutation = useCallback(function (mutation) {\n setMutations(function (mutations) { return __spreadArray(__spreadArray([], mutations, true), [mutation], false); });\n }, []);\n /**\n * Get the next mutation to execute (shifts the first mutation from the queue) and returns it.\n *\n * Used by the Notification component to process or undo the mutation\n */\n var takeMutation = useCallback(function () {\n if (mutations.length === 0)\n return;\n var mutation = mutations[0], rest = mutations.slice(1);\n setMutations(rest);\n return mutation;\n }, [mutations]);\n return (React.createElement(TakeUndoableMutationContext.Provider, { value: takeMutation },\n React.createElement(AddUndoableMutationContext.Provider, { value: addMutation }, children)));\n};\n//# sourceMappingURL=UndoableMutationsContextProvider.js.map","import { useContext } from 'react';\nimport { TakeUndoableMutationContext } from './TakeUndoableMutationContext';\nexport var useTakeUndoableMutation = function () {\n return useContext(TakeUndoableMutationContext);\n};\n//# sourceMappingURL=useTakeUndoableMutation.js.map","import { createContext } from 'react';\nexport var PreferencesEditorContext = createContext(undefined);\n//# sourceMappingURL=PreferencesEditorContext.js.map","import * as React from 'react';\nimport { useCallback, useMemo, useState } from 'react';\nimport { PreferencesEditorContext, } from './PreferencesEditorContext';\nexport var PreferencesEditorContextProvider = function (_a) {\n var children = _a.children;\n var _b = useState(false), isEnabled = _b[0], setIsEnabled = _b[1];\n var _c = useState(null), editor = _c[0], setEditor = _c[1];\n var _d = useState(null), preferenceKey = _d[0], setPreferenceKey = _d[1];\n var _e = useState(null), path = _e[0], setPath = _e[1];\n var _f = useState(null), title = _f[0], setTitleString = _f[1];\n var _g = useState(), titleOptions = _g[0], setTitleOptions = _g[1];\n var enable = useCallback(function () { return setIsEnabled(true); }, []);\n var disable = useCallback(function () {\n setIsEnabled(false);\n setEditor(null);\n }, []);\n var setTitle = useCallback(function (title, titleOptions) {\n setTitleString(title);\n setTitleOptions(titleOptions);\n }, []);\n var context = useMemo(function () {\n return {\n editor: editor,\n setEditor: setEditor,\n preferenceKey: preferenceKey,\n setPreferenceKey: setPreferenceKey,\n title: title,\n titleOptions: titleOptions,\n setTitle: setTitle,\n isEnabled: isEnabled,\n disable: disable,\n enable: enable,\n path: path,\n setPath: setPath,\n };\n }, [\n disable,\n enable,\n editor,\n preferenceKey,\n isEnabled,\n path,\n setPath,\n title,\n titleOptions,\n setTitle,\n ]);\n return (React.createElement(PreferencesEditorContext.Provider, { value: context }, children));\n};\n//# sourceMappingURL=PreferencesEditorContextProvider.js.map","import * as React from 'react';\nimport { useMemo } from 'react';\nimport { QueryClientProvider, QueryClient } from '@tanstack/react-query';\nimport { AdminRouter } from '../routing';\nimport { AuthContext, convertLegacyAuthProvider } from '../auth';\nimport { DataProviderContext, UndoableMutationsContextProvider, convertLegacyDataProvider, defaultDataProvider, } from '../dataProvider';\nimport { StoreContextProvider, memoryStore } from '../store';\nimport { PreferencesEditorContextProvider } from '../preferences/PreferencesEditorContextProvider';\nimport { I18nContextProvider } from '../i18n';\nimport { ResourceDefinitionContextProvider } from './ResourceDefinitionContext';\nimport { NotificationContextProvider } from '../notification';\nvar defaultStore = memoryStore();\nexport var CoreAdminContext = function (props) {\n var authProvider = props.authProvider, basename = props.basename, _a = props.dataProvider, dataProvider = _a === void 0 ? defaultDataProvider : _a, i18nProvider = props.i18nProvider, _b = props.store, store = _b === void 0 ? defaultStore : _b, children = props.children, queryClient = props.queryClient;\n if (!dataProvider) {\n throw new Error(\"Missing dataProvider prop.\\nReact-admin requires a valid dataProvider function to work.\");\n }\n var finalQueryClient = useMemo(function () { return queryClient || new QueryClient(); }, [queryClient]);\n var finalAuthProvider = useMemo(function () {\n return authProvider instanceof Function\n ? convertLegacyAuthProvider(authProvider)\n : authProvider;\n }, [authProvider]);\n var finalDataProvider = useMemo(function () {\n return dataProvider instanceof Function\n ? convertLegacyDataProvider(dataProvider)\n : dataProvider;\n }, [dataProvider]);\n return (React.createElement(AuthContext.Provider, { value: finalAuthProvider },\n React.createElement(DataProviderContext.Provider, { value: finalDataProvider },\n React.createElement(StoreContextProvider, { value: store },\n React.createElement(PreferencesEditorContextProvider, null,\n React.createElement(QueryClientProvider, { client: finalQueryClient },\n React.createElement(AdminRouter, { basename: basename },\n React.createElement(I18nContextProvider, { value: i18nProvider },\n React.createElement(NotificationContextProvider, null,\n React.createElement(UndoableMutationsContextProvider, null,\n React.createElement(ResourceDefinitionContextProvider, null, children)))))))))));\n};\n//# sourceMappingURL=CoreAdminContext.js.map","'use client';\nimport { createContext, Component, createElement, useContext, useState, useMemo, forwardRef } from 'react';\n\nconst ErrorBoundaryContext = createContext(null);\n\nconst initialState = {\n didCatch: false,\n error: null\n};\nclass ErrorBoundary extends Component {\n constructor(props) {\n super(props);\n this.resetErrorBoundary = this.resetErrorBoundary.bind(this);\n this.state = initialState;\n }\n static getDerivedStateFromError(error) {\n return {\n didCatch: true,\n error\n };\n }\n resetErrorBoundary() {\n const {\n error\n } = this.state;\n if (error !== null) {\n var _this$props$onReset, _this$props;\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n (_this$props$onReset = (_this$props = this.props).onReset) === null || _this$props$onReset === void 0 ? void 0 : _this$props$onReset.call(_this$props, {\n args,\n reason: \"imperative-api\"\n });\n this.setState(initialState);\n }\n }\n componentDidCatch(error, info) {\n var _this$props$onError, _this$props2;\n (_this$props$onError = (_this$props2 = this.props).onError) === null || _this$props$onError === void 0 ? void 0 : _this$props$onError.call(_this$props2, error, info);\n }\n componentDidUpdate(prevProps, prevState) {\n const {\n didCatch\n } = this.state;\n const {\n resetKeys\n } = this.props;\n\n // There's an edge case where if the thing that triggered the error happens to *also* be in the resetKeys array,\n // we'd end up resetting the error boundary immediately.\n // This would likely trigger a second error to be thrown.\n // So we make sure that we don't check the resetKeys on the first call of cDU after the error is set.\n\n if (didCatch && prevState.error !== null && hasArrayChanged(prevProps.resetKeys, resetKeys)) {\n var _this$props$onReset2, _this$props3;\n (_this$props$onReset2 = (_this$props3 = this.props).onReset) === null || _this$props$onReset2 === void 0 ? void 0 : _this$props$onReset2.call(_this$props3, {\n next: resetKeys,\n prev: prevProps.resetKeys,\n reason: \"keys\"\n });\n this.setState(initialState);\n }\n }\n render() {\n const {\n children,\n fallbackRender,\n FallbackComponent,\n fallback\n } = this.props;\n const {\n didCatch,\n error\n } = this.state;\n let childToRender = children;\n if (didCatch) {\n const props = {\n error,\n resetErrorBoundary: this.resetErrorBoundary\n };\n if (typeof fallbackRender === \"function\") {\n childToRender = fallbackRender(props);\n } else if (FallbackComponent) {\n childToRender = createElement(FallbackComponent, props);\n } else if (fallback !== undefined) {\n childToRender = fallback;\n } else {\n throw error;\n }\n }\n return createElement(ErrorBoundaryContext.Provider, {\n value: {\n didCatch,\n error,\n resetErrorBoundary: this.resetErrorBoundary\n }\n }, childToRender);\n }\n}\nfunction hasArrayChanged() {\n let a = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];\n let b = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];\n return a.length !== b.length || a.some((item, index) => !Object.is(item, b[index]));\n}\n\nfunction assertErrorBoundaryContext(value) {\n if (value == null || typeof value.didCatch !== \"boolean\" || typeof value.resetErrorBoundary !== \"function\") {\n throw new Error(\"ErrorBoundaryContext not found\");\n }\n}\n\nfunction useErrorBoundary() {\n const context = useContext(ErrorBoundaryContext);\n assertErrorBoundaryContext(context);\n const [state, setState] = useState({\n error: null,\n hasError: false\n });\n const memoized = useMemo(() => ({\n resetBoundary: () => {\n context.resetErrorBoundary();\n setState({\n error: null,\n hasError: false\n });\n },\n showBoundary: error => setState({\n error,\n hasError: true\n })\n }), [context.resetErrorBoundary]);\n if (state.hasError) {\n throw state.error;\n }\n return memoized;\n}\n\nfunction withErrorBoundary(component, errorBoundaryProps) {\n const Wrapped = forwardRef((props, ref) => createElement(ErrorBoundary, errorBoundaryProps, createElement(component, {\n ...props,\n ref\n })));\n\n // Format for display in DevTools\n const name = component.displayName || component.name || \"Unknown\";\n Wrapped.displayName = \"withErrorBoundary(\".concat(name, \")\");\n return Wrapped;\n}\n\nexport { ErrorBoundary, ErrorBoundaryContext, useErrorBoundary, withErrorBoundary };\n","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useEffect, useMemo } from 'react';\nimport { useQuery, } from '@tanstack/react-query';\nimport useAuthProvider from './useAuthProvider';\nimport useLogoutIfAccessDenied from './useLogoutIfAccessDenied';\nimport { useEvent } from '../util';\nvar emptyParams = {};\n/**\n * Hook for getting user permissions\n *\n * Calls the authProvider.getPermissions() method using react-query.\n * If the authProvider returns a rejected promise, returns empty permissions.\n *\n * The return value updates according to the request state:\n *\n * - start: { isPending: true }\n * - success: { permissions: [any], isPending: false }\n * - error: { error: [error from provider], isPending: false }\n *\n * Useful to enable features based on user permissions\n *\n * @param {Object} params Any params you want to pass to the authProvider\n *\n * @returns The current auth check state. Destructure as { permissions, error, isPending, refetch }.\n *\n * @example\n * import { usePermissions } from 'react-admin';\n *\n * const PostDetail = () => {\n * const { isPending, permissions } = usePermissions();\n * if (!isPending && permissions == 'editor') {\n * return \n * } else {\n * return \n * }\n * };\n */\nvar usePermissions = function (params, queryParams) {\n if (params === void 0) { params = emptyParams; }\n if (queryParams === void 0) { queryParams = {\n staleTime: 5 * 60 * 1000,\n }; }\n var authProvider = useAuthProvider();\n var logoutIfAccessDenied = useLogoutIfAccessDenied();\n var _a = queryParams !== null && queryParams !== void 0 ? queryParams : {}, onSuccess = _a.onSuccess, onError = _a.onError, onSettled = _a.onSettled, queryOptions = __rest(_a, [\"onSuccess\", \"onError\", \"onSettled\"]);\n var queryResult = useQuery(__assign({ queryKey: ['auth', 'getPermissions', params], queryFn: function (_a) {\n var signal = _a.signal;\n return __awaiter(void 0, void 0, void 0, function () {\n var permissions;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n if (!authProvider || !authProvider.getPermissions) {\n return [2 /*return*/, []];\n }\n return [4 /*yield*/, authProvider.getPermissions(__assign(__assign({}, params), { signal: signal }))];\n case 1:\n permissions = _b.sent();\n return [2 /*return*/, permissions !== null && permissions !== void 0 ? permissions : null];\n }\n });\n });\n } }, queryOptions));\n var onSuccessEvent = useEvent(onSuccess !== null && onSuccess !== void 0 ? onSuccess : noop);\n var onSettledEvent = useEvent(onSettled !== null && onSettled !== void 0 ? onSettled : noop);\n var onErrorEvent = useEvent(onError !== null && onError !== void 0 ? onError : (function (error) {\n if (process.env.NODE_ENV === 'development') {\n console.error(error);\n }\n logoutIfAccessDenied(error);\n }));\n useEffect(function () {\n if (queryResult.data === undefined || queryResult.isFetching)\n return;\n onSuccessEvent(queryResult.data);\n }, [onSuccessEvent, queryResult.data, queryResult.isFetching]);\n useEffect(function () {\n if (queryResult.error == null || queryResult.isFetching)\n return;\n onErrorEvent(queryResult.error);\n }, [onErrorEvent, queryResult.error, queryResult.isFetching]);\n useEffect(function () {\n if (queryResult.status === 'pending' || queryResult.isFetching)\n return;\n onSettledEvent(queryResult.data, queryResult.error);\n }, [\n onSettledEvent,\n queryResult.data,\n queryResult.error,\n queryResult.status,\n queryResult.isFetching,\n ]);\n var result = useMemo(function () { return (__assign(__assign({}, queryResult), { permissions: queryResult.data })); }, [queryResult]);\n return !authProvider || !authProvider.getPermissions\n ? fakeQueryResult\n : result;\n};\nexport default usePermissions;\nvar noop = function () { };\nvar fakeQueryResult = {\n permissions: undefined,\n data: undefined,\n dataUpdatedAt: 0,\n error: null,\n errorUpdatedAt: 0,\n errorUpdateCount: 0,\n failureCount: 0,\n failureReason: null,\n fetchStatus: 'idle',\n isError: false,\n isInitialLoading: false,\n isLoading: false,\n isLoadingError: false,\n isFetched: true,\n isFetchedAfterMount: true,\n isFetching: false,\n isPaused: false,\n isPlaceholderData: false,\n isPending: false,\n isRefetchError: false,\n isRefetching: false,\n isStale: false,\n isSuccess: true,\n status: 'success',\n refetch: function () { return Promise.resolve(fakeQueryResult); },\n};\n//# sourceMappingURL=usePermissions.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nimport * as React from 'react';\nimport { Children, Fragment, useCallback, useEffect, useState, } from 'react';\nimport useLogout from '../auth/useLogout';\nimport usePermissions from '../auth/usePermissions';\nimport { useResourceDefinitionContext } from './useResourceDefinitionContext';\n/**\n * This hook inspects the CoreAdminRouter children and returns them separated in three groups:\n * - Custom routes without layout\n * - Custom routes with layout\n * - Resources\n *\n * It also returns a status:\n * - loading: still loading children from a function child\n * - empty: no resources were provided among children\n * - ready: admin is ready to be rendered\n *\n * @example\n * const {\n * customRoutesWithLayout,\n * customRoutesWithoutLayout,\n * resources,\n * status,\n * } = useConfigureAdminRouterFromChildren(children);\n */\nexport var useConfigureAdminRouterFromChildren = function (children) {\n var _a = usePermissions(), permissions = _a.permissions, isPending = _a.isPending;\n // Whenever children are updated, update our custom routes and resources\n var _b = useRoutesAndResourcesFromChildren(children, permissions, isPending), routesAndResources = _b[0], status = _b[1];\n // Whenever the resources change, we must ensure they're all registered\n useRegisterResources(routesAndResources.resources, permissions);\n return {\n customRoutesWithLayout: routesAndResources.customRoutesWithLayout,\n customRoutesWithoutLayout: routesAndResources.customRoutesWithoutLayout,\n status: status,\n resources: routesAndResources.resources,\n };\n};\n/**\n * A hook that determine the routes and resources from React nodes and permissions.\n * Returns a tuple with the routes and resources as a single object, and the status.\n * @param children React nodes to inspect\n * @param permissions The permissions\n */\nvar useRoutesAndResourcesFromChildren = function (children, permissions, isLoading) {\n // Gather custom routes and resources that were declared as direct children of CoreAdminRouter\n // e.g. Not returned from the child function (if any)\n // We need to know right away whether some resources were declared to correctly\n // initialize the status at the next stop\n var doLogout = useLogout();\n var _a = useRoutesAndResourcesState(getRoutesAndResourceFromNodes(children)), routesAndResources = _a[0], setRoutesAndResources = _a[1], mergeRoutesAndResources = _a[2];\n var _b = useState(function () {\n return getStatus(__assign({ children: children }, routesAndResources));\n }), status = _b[0], setStatus = _b[1];\n if (!status) {\n throw new Error('Status should be defined');\n }\n useEffect(function () {\n var resolveChildFunction = function (childFunc) { return __awaiter(void 0, void 0, void 0, function () {\n var childrenFuncResult;\n return __generator(this, function (_a) {\n try {\n childrenFuncResult = childFunc(permissions);\n if (childrenFuncResult === null || childrenFuncResult === void 0 ? void 0 : childrenFuncResult.then) {\n childrenFuncResult.then(function (resolvedChildren) {\n mergeRoutesAndResources(getRoutesAndResourceFromNodes(resolvedChildren));\n setStatus('ready');\n });\n }\n else {\n mergeRoutesAndResources(getRoutesAndResourceFromNodes(childrenFuncResult));\n setStatus('ready');\n }\n }\n catch (error) {\n console.error(error);\n doLogout();\n }\n return [2 /*return*/];\n });\n }); };\n var updateFromChildren = function () { return __awaiter(void 0, void 0, void 0, function () {\n var functionChild, newRoutesAndResources;\n return __generator(this, function (_a) {\n functionChild = getSingleChildFunction(children);\n newRoutesAndResources = getRoutesAndResourceFromNodes(children);\n setRoutesAndResources(newRoutesAndResources);\n setStatus(!!functionChild\n ? 'loading'\n : newRoutesAndResources.resources.length > 0 ||\n newRoutesAndResources.customRoutesWithLayout.length >\n 0 ||\n newRoutesAndResources.customRoutesWithoutLayout.length >\n 0\n ? 'ready'\n : 'empty');\n if (functionChild) {\n resolveChildFunction(functionChild);\n }\n return [2 /*return*/];\n });\n }); };\n if (!isLoading) {\n updateFromChildren();\n }\n }, [\n children,\n doLogout,\n isLoading,\n mergeRoutesAndResources,\n permissions,\n setRoutesAndResources,\n setStatus,\n ]);\n return [routesAndResources, status];\n};\n/*\n * A hook that store the routes and resources just like setState but also provides an additional function\n * to merge new routes and resources with the existing ones.\n */\nvar useRoutesAndResourcesState = function (initialState) {\n var _a = useState(initialState), routesAndResources = _a[0], setRoutesAndResources = _a[1];\n var mergeRoutesAndResources = useCallback(function (newRoutesAndResources) {\n setRoutesAndResources(function (previous) { return ({\n customRoutesWithLayout: previous.customRoutesWithLayout.concat(newRoutesAndResources.customRoutesWithLayout),\n customRoutesWithoutLayout: previous.customRoutesWithoutLayout.concat(newRoutesAndResources.customRoutesWithoutLayout),\n resources: previous.resources.concat(newRoutesAndResources.resources),\n }); });\n }, []);\n return [routesAndResources, setRoutesAndResources, mergeRoutesAndResources];\n};\n/**\n * A hook that register resources and unregister them when the calling component is unmounted.\n * @param resources: An array of Resource elements\n * @param permissions: The permissions\n */\nvar useRegisterResources = function (resources, permissions) {\n var _a = useResourceDefinitionContext(), register = _a.register, unregister = _a.unregister;\n useEffect(function () {\n resources.forEach(function (resource) {\n if (typeof resource.type.registerResource === 'function') {\n var definition = resource.type.registerResource(resource.props, permissions);\n register(definition);\n }\n else {\n throw new Error('When using a custom Resource element, it must have a static registerResource method accepting its props and returning a ResourceDefinition');\n }\n });\n return function () {\n resources.forEach(function (resource) {\n if (typeof resource.type.registerResource === 'function') {\n var definition = resource.type.registerResource(resource.props, permissions);\n unregister(definition);\n }\n else {\n throw new Error('When using a custom Resource element, it must have a static registerResource method accepting its props and returning a ResourceDefinition');\n }\n });\n };\n }, [permissions, register, resources, unregister]);\n};\nvar getStatus = function (_a) {\n var children = _a.children, resources = _a.resources, customRoutesWithLayout = _a.customRoutesWithLayout, customRoutesWithoutLayout = _a.customRoutesWithoutLayout;\n return getSingleChildFunction(children)\n ? 'loading'\n : resources.length > 0 ||\n customRoutesWithLayout.length > 0 ||\n customRoutesWithoutLayout.length > 0\n ? 'ready'\n : 'empty';\n};\n/**\n * Inspect the children of a CoreAdminRouter to see if one of them is a function.\n * Throws an error if there are more than one function child.\n * Returns the function child if one was provided, or null otherwise.\n */\nvar getSingleChildFunction = function (children) {\n var childrenArray = Array.isArray(children) ? children : [children];\n var functionChildren = childrenArray.filter(function (child) { return typeof child === 'function'; });\n if (functionChildren.length > 1) {\n throw new Error('You can only provide one function child to AdminRouter');\n }\n if (functionChildren.length === 0) {\n return null;\n }\n return functionChildren[0];\n};\n/**\n * Inspect the children and return an object with the following keys:\n * - customRoutesWithLayout: an array of the custom routes to render inside the layout\n * - customRoutesWithoutLayout: an array of custom routes to render outside the layout\n * - resources: an array of resources elements\n */\nvar getRoutesAndResourceFromNodes = function (children) {\n var customRoutesWithLayout = [];\n var customRoutesWithoutLayout = [];\n var resources = [];\n if (typeof children === 'function') {\n return {\n customRoutesWithLayout: [],\n customRoutesWithoutLayout: [],\n resources: [],\n };\n }\n // @ts-ignore\n Children.forEach(children, function (element) {\n if (!React.isValidElement(element)) {\n // Ignore non-elements. This allows people to more easily inline\n // conditionals in their route config.\n return;\n }\n if (element.type === Fragment) {\n var customRoutesFromFragment = getRoutesAndResourceFromNodes(element.props.children);\n customRoutesWithLayout.push.apply(customRoutesWithLayout, customRoutesFromFragment.customRoutesWithLayout);\n customRoutesWithoutLayout.push.apply(customRoutesWithoutLayout, customRoutesFromFragment.customRoutesWithoutLayout);\n resources.push.apply(resources, customRoutesFromFragment.resources);\n }\n if (element.type.raName === 'CustomRoutes') {\n var customRoutesElement = element;\n if (customRoutesElement.props.noLayout) {\n customRoutesWithoutLayout.push(customRoutesElement.props.children);\n }\n else {\n customRoutesWithLayout.push(customRoutesElement.props.children);\n }\n }\n else if (element.type.raName === 'Resource') {\n resources.push(element);\n }\n });\n return {\n customRoutesWithLayout: customRoutesWithLayout,\n customRoutesWithoutLayout: customRoutesWithoutLayout,\n resources: resources,\n };\n};\n//# sourceMappingURL=useConfigureAdminRouterFromChildren.js.map","import { createContext, useContext } from 'react';\nexport var HasDashboardContext = createContext(false);\nexport var HasDashboardContextProvider = HasDashboardContext.Provider;\n/**\n * Returns true if the app has a dashboard defined at the level.\n *\n * @private\n * @example\n * import { useHasDashboard } from 'react-admin';\n *\n * const MyMenu = () => {\n * const hasDashboard = useHasDashboard();\n * return (\n * \n * {hasDashboard && }\n * \n * \n * \n * );\n * }\n */\nexport var useHasDashboard = function () { return useContext(HasDashboardContext); };\n//# sourceMappingURL=HasDashboardContext.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useMemo } from 'react';\nimport { useQuery } from '@tanstack/react-query';\nimport useAuthProvider from './useAuthProvider';\nimport { useRecordContext } from '../controller';\n/**\n * Checks whether users can access the provided resources.\n *\n * `useCanAccessResources` returns an object describing the state of the request:\n *\n * - start: { isPending: true }\n * - success: { canAccess: Object, isPending: false }\n * - error: { error: [error from provider], isPending: false }\n *\n * @param {Object} params Any params you want to pass to the authProvider\n * @param {string} params.action The action to check access for\n * @param {string[]} params.resources The list of resources to check access for\n * @param {Object} params.record Optional. The record to check access for\n *\n * @returns Return the react-query result and a canAccess property which is a map of the resources and their access status { [resource: string]: boolean }\n *\n * @example\n * import { useCanAccessResources } from 'react-admin';\n *\n * const UserList = ({ record }) => {\n * const { isPending, canAccess } = useCanAccessResources({\n * action: 'read',\n * resources: ['users.id', 'users.name', 'users.email'],\n * record\n * });\n *\n * if (isPending) {\n * return null;\n * }\n * return (\n * canAccess.users.name ? record.name : ''}\n * secondaryText={record => canAccess.users.email ? record.email : ''}\n * tertiaryText={record => canAccess.users.id ? record.id : ''}\n * />\n * );\n * };\n */\nexport var useCanAccessResources = function (params) {\n var authProvider = useAuthProvider();\n var record = useRecordContext(params);\n var action = params.action, resources = params.resources, options = __rest(params, [\"action\", \"resources\"]);\n var queryResult = useQuery(__assign({ queryKey: ['auth', 'canAccess', resources, action, record], queryFn: function (_a) {\n var signal = _a.signal;\n return __awaiter(void 0, void 0, void 0, function () {\n var queries, result;\n return __generator(this, function (_b) {\n switch (_b.label) {\n case 0: return [4 /*yield*/, Promise.all(resources.map(function (resource) { return __awaiter(void 0, void 0, void 0, function () {\n var canAccess;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!authProvider || !authProvider.canAccess) {\n return [2 /*return*/, { canAccess: true, resource: resource }];\n }\n return [4 /*yield*/, authProvider.canAccess({\n resource: resource,\n action: action,\n record: record,\n signal: authProvider.supportAbortSignal\n ? signal\n : undefined,\n })];\n case 1:\n canAccess = _a.sent();\n return [2 /*return*/, { canAccess: canAccess, resource: resource }];\n }\n });\n }); }))];\n case 1:\n queries = _b.sent();\n result = queries.reduce(function (acc, _a) {\n var resource = _a.resource, canAccess = _a.canAccess;\n acc[resource] = canAccess;\n return acc;\n }, {});\n return [2 /*return*/, result];\n }\n });\n });\n } }, options));\n var result = useMemo(function () {\n return __assign({ canAccess: queryResult.data }, queryResult);\n }, [queryResult]);\n var resultWithoutAuthProvider = useMemo(function () {\n return {\n canAccess: resources.reduce(function (acc, resource) {\n acc[resource] = true;\n return acc;\n }, {}),\n isPending: false,\n isError: false,\n error: null,\n };\n }, [resources]);\n return !authProvider || !authProvider.canAccess\n ? resultWithoutAuthProvider\n : result;\n};\n//# sourceMappingURL=useCanAccessResources.js.map","import { useCanAccessResources } from '../auth/useCanAccessResources';\nimport { useAuthenticated } from '../auth';\nimport { useResourceDefinitions } from './useResourceDefinitions';\n/**\n * A hook that returns the first resource for which users have access to the list page.\n * It calls the `authProvider.canAccess` if available to check the permissions.\n */\nexport var useFirstResourceWithListAccess = function () {\n var isPendingAuthenticated = useAuthenticated().isPending;\n var resources = useResourceDefinitions();\n var resourcesNames = Object.keys(resources).filter(function (resource) { return resources[resource].hasList; });\n var _a = useCanAccessResources({\n action: 'list',\n resources: resourcesNames,\n enabled: !isPendingAuthenticated,\n }), canAccess = _a.canAccess, isPending = _a.isPending;\n var firstResourceWithListAccess = resourcesNames.find(function (resource) { return canAccess && canAccess[resource] === true; });\n return { resource: firstResourceWithListAccess, isPending: isPending };\n};\n//# sourceMappingURL=useFirstResourceWithListAccess.js.map","import * as React from 'react';\nimport { Navigate } from 'react-router';\nimport { useFirstResourceWithListAccess } from './useFirstResourceWithListAccess';\nimport { useCreatePath } from '../routing';\n/**\n * This component will inspect the registered resources and navigate to the first one for which users have access to the list page.\n * @param props\n * @param props.loading The component to display while the component is loading.\n */\nexport var NavigateToFirstResource = function (_a) {\n var LoadingPage = _a.loading;\n var _b = useFirstResourceWithListAccess(), resource = _b.resource, isPending = _b.isPending;\n var createPath = useCreatePath();\n if (isPending) {\n return React.createElement(LoadingPage, null);\n }\n if (resource) {\n return (React.createElement(Navigate, { to: createPath({\n resource: resource,\n type: 'list',\n }), replace: true }));\n }\n};\n//# sourceMappingURL=NavigateToFirstResource.js.map","import * as React from 'react';\nimport { Children } from 'react';\nimport { Route, Routes } from 'react-router-dom';\nimport { WithPermissions, LogoutOnMount, useAuthState } from '../auth';\nimport { useScrollToTop } from '../routing';\nimport { useConfigureAdminRouterFromChildren } from './useConfigureAdminRouterFromChildren';\nimport { HasDashboardContextProvider } from './HasDashboardContext';\nimport { NavigateToFirstResource } from './NavigateToFirstResource';\nexport var CoreAdminRoutes = function (props) {\n useScrollToTop();\n var _a = useConfigureAdminRouterFromChildren(props.children), customRoutesWithLayout = _a.customRoutesWithLayout, customRoutesWithoutLayout = _a.customRoutesWithoutLayout, status = _a.status, resources = _a.resources;\n var Layout = props.layout, CatchAll = props.catchAll, dashboard = props.dashboard, LoadingPage = props.loading, requireAuth = props.requireAuth, Ready = props.ready, _b = props.authenticationError, AuthenticationError = _b === void 0 ? Noop : _b, _c = props.accessDenied, AccessDenied = _c === void 0 ? Noop : _c;\n var _d = useAuthState(undefined, \n // do not log the user out on failure to allow access to custom routes with no layout\n false, { enabled: requireAuth }), authenticated = _d.authenticated, isPendingAuthenticated = _d.isPending;\n if (status === 'empty') {\n if (!Ready) {\n throw new Error('The admin is empty. Please provide an empty component, or pass Resource or CustomRoutes as children.');\n }\n return React.createElement(Ready, null);\n }\n // Note: custom routes with no layout are always rendered, regardless of the auth status\n if (status === 'loading' || (requireAuth && isPendingAuthenticated)) {\n return (React.createElement(Routes, null,\n customRoutesWithoutLayout,\n React.createElement(Route, { path: \"*\", element: React.createElement(\"div\", { style: { height: '100vh' } },\n React.createElement(LoadingPage, null)) })));\n }\n if (requireAuth && (isPendingAuthenticated || !authenticated)) {\n return (React.createElement(Routes, null,\n customRoutesWithoutLayout,\n React.createElement(Route, { path: \"*\", element: React.createElement(LogoutOnMount, null) })));\n }\n return (React.createElement(Routes, null,\n customRoutesWithoutLayout,\n React.createElement(Route, { path: \"/*\", element: React.createElement(HasDashboardContextProvider, { value: !!dashboard },\n React.createElement(Layout, null,\n React.createElement(Routes, null,\n customRoutesWithLayout,\n Children.map(resources, function (resource) { return (React.createElement(Route, { key: resource.props.name, path: \"\".concat(resource.props.name, \"/*\"), element: resource })); }),\n React.createElement(Route, { path: \"/\", element: dashboard ? (React.createElement(WithPermissions, { authParams: defaultAuthParams, component: dashboard, loading: LoadingPage })) : (React.createElement(NavigateToFirstResource, { loading: LoadingPage })) }),\n React.createElement(Route, { path: \"/authentication-error\", element: React.createElement(AuthenticationError, null) }),\n React.createElement(Route, { path: \"/access-denied\", element: React.createElement(AccessDenied, null) }),\n React.createElement(Route, { path: \"*\", element: React.createElement(CatchAll, null) })))) })));\n};\n// FIXME in v6: make dashboard anonymous by default to remove this hack\nvar defaultAuthParams = { params: { route: 'dashboard' } };\nvar Noop = function () { return null; };\n//# sourceMappingURL=CoreAdminRoutes.js.map","import { createContext, useContext } from 'react';\nexport var DefaultTitleContext = createContext('React Admin');\nexport var DefaultTitleContextProvider = DefaultTitleContext.Provider;\n/**\n * Get the application title defined at the `` level\n *\n * @example\n * import { useDefaultTitle } from 'react-admin';\n *\n * const AppBar = () => {\n * const defaultTitle = useDefaultTitle();\n * return {defaultTitle};\n * }\n */\nexport var useDefaultTitle = function () { return useContext(DefaultTitleContext); };\n//# sourceMappingURL=DefaultTitleContext.js.map","import * as React from 'react';\nimport { useEffect, isValidElement, createElement, useState, } from 'react';\nimport { Routes, Route } from 'react-router-dom';\nimport { ErrorBoundary } from 'react-error-boundary';\nimport { CoreAdminRoutes } from './CoreAdminRoutes';\nimport { useResetErrorBoundaryOnLocationChange } from '../routing';\nimport { Ready } from '../util';\nimport { DefaultTitleContextProvider } from './DefaultTitleContext';\nvar DefaultLayout = function (_a) {\n var children = _a.children;\n return (React.createElement(React.Fragment, null, children));\n};\nvar DefaultError = function (_a) {\n var error = _a.error, errorInfo = _a.errorInfo, resetErrorBoundary = _a.resetErrorBoundary;\n useResetErrorBoundaryOnLocationChange(resetErrorBoundary);\n return (React.createElement(\"div\", null,\n React.createElement(\"h1\", null, \"Error\"),\n React.createElement(\"pre\", null,\n error.message, errorInfo === null || errorInfo === void 0 ? void 0 :\n errorInfo.componentStack)));\n};\nexport var CoreAdminUI = function (props) {\n var _a = useState({}), errorInfo = _a[0], setErrorInfo = _a[1];\n var _b = props.authCallbackPage, LoginCallbackPage = _b === void 0 ? false : _b, _c = props.catchAll, catchAll = _c === void 0 ? Noop : _c, children = props.children, dashboard = props.dashboard, _d = props.disableTelemetry, disableTelemetry = _d === void 0 ? false : _d, _e = props.error, ErrorComponent = _e === void 0 ? DefaultError : _e, _f = props.layout, layout = _f === void 0 ? DefaultLayout : _f, _g = props.loading, loading = _g === void 0 ? Noop : _g, _h = props.loginPage, LoginPage = _h === void 0 ? false : _h, _j = props.ready, ready = _j === void 0 ? Ready : _j, _k = props.requireAuth, requireAuth = _k === void 0 ? false : _k, _l = props.title, title = _l === void 0 ? 'React Admin' : _l, _m = props.authenticationError, authenticationError = _m === void 0 ? Noop : _m, _o = props.accessDenied, accessDenied = _o === void 0 ? Noop : _o;\n useEffect(function () {\n if (disableTelemetry ||\n process.env.NODE_ENV !== 'production' ||\n typeof window === 'undefined' ||\n typeof window.location === 'undefined' ||\n typeof Image === 'undefined') {\n return;\n }\n var img = new Image();\n img.src = \"https://react-admin-telemetry.marmelab.com/react-admin-telemetry?domain=\".concat(window.location.hostname);\n }, [disableTelemetry]);\n var handleError = function (error, info) { return setErrorInfo(info); };\n return (React.createElement(DefaultTitleContextProvider, { value: title },\n React.createElement(ErrorBoundary, { onError: handleError, fallbackRender: function (_a) {\n var error = _a.error, resetErrorBoundary = _a.resetErrorBoundary;\n return (React.createElement(\"div\", { style: { minHeight: '100vh' } },\n React.createElement(ErrorComponent, { error: error, errorInfo: errorInfo, resetErrorBoundary: resetErrorBoundary })));\n } },\n React.createElement(Routes, null,\n LoginPage !== false && LoginPage !== true ? (React.createElement(Route, { path: \"/login\", element: createOrGetElement(LoginPage) })) : null,\n LoginCallbackPage !== false &&\n LoginCallbackPage !== true ? (React.createElement(Route, { path: \"/auth-callback\", element: createOrGetElement(LoginCallbackPage) })) : null,\n React.createElement(Route, { path: \"/*\", element: React.createElement(CoreAdminRoutes, { catchAll: catchAll, dashboard: dashboard, layout: layout, loading: loading, requireAuth: requireAuth, ready: ready, authenticationError: authenticationError, accessDenied: accessDenied }, children) })))));\n};\nvar createOrGetElement = function (el) { return (isValidElement(el) ? el : createElement(el)); };\nvar Noop = function () { return null; };\n//# sourceMappingURL=CoreAdminUI.js.map","/**\n * This component allows you to provide custom routes to the Admin.\n * @param props The component props\n * @param props.children The custom routes.\n * @param props.noLayout A boolean indicating whether to render the routes outside the Layout. Defaults to false.\n * @returns Nothing. This is a configuration component.\n */\nexport var CustomRoutes = function (_props) {\n return null;\n};\nCustomRoutes.raName = 'CustomRoutes';\n//# sourceMappingURL=CustomRoutes.js.map","import * as React from 'react';\nimport { ResourceContext } from './ResourceContext';\n/**\n * Create a Resource Context with the resource name\n *\n * Some react-admin components rely on the resource name to be available in the context.\n * This component provides it.\n *\n * If the value is empty, the context is not provided.\n *\n * @param {string} value the resource name\n * @example\n *\n * import { ResourceContextProvider } from 'react-admin';\n *\n * const MyComponent = () => (\n * \n * \n * \n * );\n */\nexport var ResourceContextProvider = function (_a) {\n var children = _a.children, value = _a.value;\n return value ? (React.createElement(ResourceContext.Provider, { value: value }, children)) : (children);\n};\n//# sourceMappingURL=ResourceContextProvider.js.map","import * as React from 'react';\nimport { ResourceContextProvider } from './ResourceContextProvider';\n/**\n * Wrap children with a ResourceContext provider only if the value is defined.\n *\n * Allows a component to work outside of a resource context.\n *\n * @example\n *\n * import { OptionalResourceContextProvider, EditButton } from 'react-admin';\n *\n * const Button = ({ resource }) => (\n * \n * \n * \n * );\n */\nexport var OptionalResourceContextProvider = function (_a) {\n var value = _a.value, children = _a.children;\n return value ? (React.createElement(ResourceContextProvider, { value: value }, children)) : (children);\n};\n//# sourceMappingURL=OptionalResourceContextProvider.js.map","import * as React from 'react';\nimport { isValidElement } from 'react';\nimport { Route, Routes } from 'react-router-dom';\nimport { isValidElementType } from 'react-is';\nimport { ResourceContextProvider } from './ResourceContextProvider';\nimport { RestoreScrollPosition } from '../routing/RestoreScrollPosition';\nexport var Resource = function (props) {\n var create = props.create, edit = props.edit, list = props.list, name = props.name, show = props.show;\n return (React.createElement(ResourceContextProvider, { value: name },\n React.createElement(Routes, null,\n create && (React.createElement(Route, { path: \"create/*\", element: getElement(create) })),\n show && React.createElement(Route, { path: \":id/show/*\", element: getElement(show) }),\n edit && React.createElement(Route, { path: \":id/*\", element: getElement(edit) }),\n list && (React.createElement(Route, { path: \"/*\", element: React.createElement(RestoreScrollPosition, { storeKey: \"\".concat(name, \".list.scrollPosition\") }, getElement(list)) })),\n props.children)));\n};\nvar getElement = function (ElementOrComponent) {\n if (isValidElement(ElementOrComponent)) {\n return ElementOrComponent;\n }\n if (isValidElementType(ElementOrComponent)) {\n var Element_1 = ElementOrComponent;\n return React.createElement(Element_1, null);\n }\n return null;\n};\nResource.raName = 'Resource';\nResource.registerResource = function (_a) {\n var create = _a.create, edit = _a.edit, icon = _a.icon, list = _a.list, name = _a.name, options = _a.options, show = _a.show, recordRepresentation = _a.recordRepresentation, hasCreate = _a.hasCreate, hasEdit = _a.hasEdit, hasShow = _a.hasShow;\n return ({\n name: name,\n options: options,\n hasList: !!list,\n hasCreate: !!create || !!hasCreate,\n hasEdit: !!edit || !!hasEdit,\n hasShow: !!show || !!hasShow,\n icon: icon,\n recordRepresentation: recordRepresentation,\n });\n};\n//# sourceMappingURL=Resource.js.map","import { createContext, useContext } from 'react';\n/**\n * Context that provides a function that accept a source and return getters for the modified source and label.\n *\n * This allows some special inputs to prefix or suffix the source of their children.\n *\n * @example\n * const sourceContext = {\n * getSource: source => `coordinates.${source}`,\n * getLabel: source => `resources.posts.fields.${source}`,\n * }\n * const CoordinatesInput = () => {\n * return (\n * \n * \n * \n * \n * );\n * };\n */\nexport var SourceContext = createContext(undefined);\nvar defaultContextValue = {\n getSource: function (source) { return source; },\n getLabel: function (source) { return source; },\n};\nexport var SourceContextProvider = SourceContext.Provider;\nexport var useSourceContext = function () {\n var context = useContext(SourceContext);\n if (!context) {\n return defaultContextValue;\n }\n return context;\n};\nexport var useOptionalSourceContext = function () { return useContext(SourceContext); };\n//# sourceMappingURL=SourceContext.js.map","\"use strict\";\n/*!\n * inflection\n * Copyright(c) 2011 Ben Lin \n * MIT Licensed\n *\n * @fileoverview\n * A port of inflection-js to node.js module.\n */\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.pluralize = pluralize;\nexports.singularize = singularize;\nexports.inflect = inflect;\nexports.camelize = camelize;\nexports.underscore = underscore;\nexports.humanize = humanize;\nexports.capitalize = capitalize;\nexports.dasherize = dasherize;\nexports.titleize = titleize;\nexports.demodulize = demodulize;\nexports.tableize = tableize;\nexports.classify = classify;\nexports.foreignKey = foreignKey;\nexports.ordinalize = ordinalize;\nexports.transform = transform;\n/**\n * @description This is a list of nouns that use the same form for both singular and plural.\n * This list should remain entirely in lower case to correctly match Strings.\n */\nconst uncountableWords = [\n // 'access',\n 'accommodation',\n 'adulthood',\n 'advertising',\n 'advice',\n 'aggression',\n 'aid',\n 'air',\n 'aircraft',\n 'alcohol',\n 'anger',\n 'applause',\n 'arithmetic',\n // 'art',\n 'assistance',\n 'athletics',\n // 'attention',\n 'bacon',\n 'baggage',\n // 'ballet',\n // 'beauty',\n 'beef',\n // 'beer',\n // 'behavior',\n 'biology',\n // 'billiards',\n 'blood',\n 'botany',\n // 'bowels',\n 'bread',\n // 'business',\n 'butter',\n 'carbon',\n 'cardboard',\n 'cash',\n 'chalk',\n 'chaos',\n 'chess',\n 'crossroads',\n 'countryside',\n // 'damage',\n 'dancing',\n // 'danger',\n 'deer',\n // 'delight',\n // 'dessert',\n 'dignity',\n 'dirt',\n // 'distribution',\n 'dust',\n 'economics',\n 'education',\n 'electricity',\n // 'employment',\n // 'energy',\n 'engineering',\n 'enjoyment',\n // 'entertainment',\n 'envy',\n 'equipment',\n 'ethics',\n 'evidence',\n 'evolution',\n // 'failure',\n // 'faith',\n 'fame',\n 'fiction',\n // 'fish',\n 'flour',\n 'flu',\n 'food',\n // 'freedom',\n // 'fruit',\n 'fuel',\n 'fun',\n // 'funeral',\n 'furniture',\n 'gallows',\n 'garbage',\n 'garlic',\n // 'gas',\n 'genetics',\n // 'glass',\n 'gold',\n 'golf',\n 'gossip',\n // 'grass',\n 'gratitude',\n 'grief',\n // 'ground',\n 'guilt',\n 'gymnastics',\n // 'hair',\n 'happiness',\n 'hardware',\n 'harm',\n 'hate',\n 'hatred',\n 'health',\n 'heat',\n // 'height',\n 'help',\n 'homework',\n 'honesty',\n 'honey',\n 'hospitality',\n 'housework',\n 'humour',\n 'hunger',\n 'hydrogen',\n 'ice',\n 'importance',\n 'inflation',\n 'information',\n // 'injustice',\n 'innocence',\n // 'intelligence',\n 'iron',\n 'irony',\n 'jam',\n // 'jealousy',\n // 'jelly',\n 'jewelry',\n // 'joy',\n 'judo',\n // 'juice',\n // 'justice',\n 'karate',\n // 'kindness',\n 'knowledge',\n // 'labour',\n 'lack',\n // 'land',\n 'laughter',\n 'lava',\n 'leather',\n 'leisure',\n 'lightning',\n 'linguine',\n 'linguini',\n 'linguistics',\n 'literature',\n 'litter',\n 'livestock',\n 'logic',\n 'loneliness',\n // 'love',\n 'luck',\n 'luggage',\n 'macaroni',\n 'machinery',\n 'magic',\n // 'mail',\n 'management',\n 'mankind',\n 'marble',\n 'mathematics',\n 'mayonnaise',\n 'measles',\n // 'meat',\n // 'metal',\n 'methane',\n 'milk',\n 'minus',\n 'money',\n // 'moose',\n 'mud',\n 'music',\n 'mumps',\n 'nature',\n 'news',\n 'nitrogen',\n 'nonsense',\n 'nurture',\n 'nutrition',\n 'obedience',\n 'obesity',\n // 'oil',\n 'oxygen',\n // 'paper',\n // 'passion',\n 'pasta',\n 'patience',\n // 'permission',\n 'physics',\n 'poetry',\n 'pollution',\n 'poverty',\n // 'power',\n 'pride',\n // 'production',\n // 'progress',\n // 'pronunciation',\n 'psychology',\n 'publicity',\n 'punctuation',\n // 'quality',\n // 'quantity',\n 'quartz',\n 'racism',\n // 'rain',\n // 'recreation',\n 'relaxation',\n 'reliability',\n 'research',\n 'respect',\n 'revenge',\n 'rice',\n 'rubbish',\n 'rum',\n 'safety',\n // 'salad',\n // 'salt',\n // 'sand',\n // 'satire',\n 'scenery',\n 'seafood',\n 'seaside',\n 'series',\n 'shame',\n 'sheep',\n 'shopping',\n // 'silence',\n 'sleep',\n // 'slang'\n 'smoke',\n 'smoking',\n 'snow',\n 'soap',\n 'software',\n 'soil',\n // 'sorrow',\n // 'soup',\n 'spaghetti',\n // 'speed',\n 'species',\n // 'spelling',\n // 'sport',\n 'steam',\n // 'strength',\n 'stuff',\n 'stupidity',\n // 'success',\n // 'sugar',\n 'sunshine',\n 'symmetry',\n // 'tea',\n 'tennis',\n 'thirst',\n 'thunder',\n 'timber',\n // 'time',\n // 'toast',\n // 'tolerance',\n // 'trade',\n 'traffic',\n 'transportation',\n // 'travel',\n 'trust',\n // 'understanding',\n 'underwear',\n 'unemployment',\n 'unity',\n // 'usage',\n 'validity',\n 'veal',\n 'vegetation',\n 'vegetarianism',\n 'vengeance',\n 'violence',\n // 'vision',\n 'vitality',\n 'warmth',\n // 'water',\n 'wealth',\n 'weather',\n // 'weight',\n 'welfare',\n 'wheat',\n // 'whiskey',\n // 'width',\n 'wildlife',\n // 'wine',\n 'wisdom',\n // 'wood',\n // 'wool',\n // 'work',\n // 'yeast',\n 'yoga',\n 'zinc',\n 'zoology',\n];\n/**\n * @description These rules translate from the singular form of a noun to its plural form.\n */\nconst regex = {\n plural: {\n men: new RegExp('^(m|wom)en$', 'gi'),\n people: new RegExp('(pe)ople$', 'gi'),\n children: new RegExp('(child)ren$', 'gi'),\n tia: new RegExp('([ti])a$', 'gi'),\n analyses: new RegExp('((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$', 'gi'),\n databases: new RegExp('(database)s$', 'gi'),\n drives: new RegExp('(drive)s$', 'gi'),\n hives: new RegExp('(hi|ti)ves$', 'gi'),\n curves: new RegExp('(curve)s$', 'gi'),\n lrves: new RegExp('([lr])ves$', 'gi'),\n aves: new RegExp('([a])ves$', 'gi'),\n foves: new RegExp('([^fo])ves$', 'gi'),\n movies: new RegExp('(m)ovies$', 'gi'),\n aeiouyies: new RegExp('([^aeiouy]|qu)ies$', 'gi'),\n series: new RegExp('(s)eries$', 'gi'),\n xes: new RegExp('(x|ch|ss|sh)es$', 'gi'),\n mice: new RegExp('([m|l])ice$', 'gi'),\n buses: new RegExp('(bus)es$', 'gi'),\n oes: new RegExp('(o)es$', 'gi'),\n shoes: new RegExp('(shoe)s$', 'gi'),\n crises: new RegExp('(cris|ax|test)es$', 'gi'),\n octopuses: new RegExp('(octop|vir)uses$', 'gi'),\n aliases: new RegExp('(alias|canvas|status|campus)es$', 'gi'),\n summonses: new RegExp('^(summons|bonus)es$', 'gi'),\n oxen: new RegExp('^(ox)en', 'gi'),\n matrices: new RegExp('(matr)ices$', 'gi'),\n vertices: new RegExp('(vert|ind)ices$', 'gi'),\n feet: new RegExp('^feet$', 'gi'),\n teeth: new RegExp('^teeth$', 'gi'),\n geese: new RegExp('^geese$', 'gi'),\n quizzes: new RegExp('(quiz)zes$', 'gi'),\n whereases: new RegExp('^(whereas)es$', 'gi'),\n criteria: new RegExp('^(criteri)a$', 'gi'),\n genera: new RegExp('^genera$', 'gi'),\n ss: new RegExp('ss$', 'gi'),\n s: new RegExp('s$', 'gi'),\n },\n singular: {\n man: new RegExp('^(m|wom)an$', 'gi'),\n person: new RegExp('(pe)rson$', 'gi'),\n child: new RegExp('(child)$', 'gi'),\n drive: new RegExp('(drive)$', 'gi'),\n ox: new RegExp('^(ox)$', 'gi'),\n axis: new RegExp('(ax|test)is$', 'gi'),\n octopus: new RegExp('(octop|vir)us$', 'gi'),\n alias: new RegExp('(alias|status|canvas|campus)$', 'gi'),\n summons: new RegExp('^(summons|bonus)$', 'gi'),\n bus: new RegExp('(bu)s$', 'gi'),\n buffalo: new RegExp('(buffal|tomat|potat)o$', 'gi'),\n tium: new RegExp('([ti])um$', 'gi'),\n sis: new RegExp('sis$', 'gi'),\n ffe: new RegExp('(?:([^f])fe|([lr])f)$', 'gi'),\n focus: new RegExp('^(focus)$', 'gi'),\n hive: new RegExp('(hi|ti)ve$', 'gi'),\n aeiouyy: new RegExp('([^aeiouy]|qu)y$', 'gi'),\n x: new RegExp('(x|ch|ss|sh)$', 'gi'),\n matrix: new RegExp('(matr)ix$', 'gi'),\n vertex: new RegExp('(vert|ind)ex$', 'gi'),\n mouse: new RegExp('([m|l])ouse$', 'gi'),\n foot: new RegExp('^foot$', 'gi'),\n tooth: new RegExp('^tooth$', 'gi'),\n goose: new RegExp('^goose$', 'gi'),\n quiz: new RegExp('(quiz)$', 'gi'),\n whereas: new RegExp('^(whereas)$', 'gi'),\n criterion: new RegExp('^(criteri)on$', 'gi'),\n genus: new RegExp('^genus$', 'gi'),\n s: new RegExp('s$', 'gi'),\n common: new RegExp('$', 'gi'),\n },\n};\nconst pluralRules = [\n // do not replace if its already a plural word\n [regex.plural.men],\n [regex.plural.people],\n [regex.plural.children],\n [regex.plural.tia],\n [regex.plural.analyses],\n [regex.plural.databases],\n [regex.plural.drives],\n [regex.plural.hives],\n [regex.plural.curves],\n [regex.plural.lrves],\n [regex.plural.foves],\n [regex.plural.aeiouyies],\n [regex.plural.series],\n [regex.plural.movies],\n [regex.plural.xes],\n [regex.plural.mice],\n [regex.plural.buses],\n [regex.plural.oes],\n [regex.plural.shoes],\n [regex.plural.crises],\n [regex.plural.octopuses],\n [regex.plural.aliases],\n [regex.plural.summonses],\n [regex.plural.oxen],\n [regex.plural.matrices],\n [regex.plural.feet],\n [regex.plural.teeth],\n [regex.plural.geese],\n [regex.plural.quizzes],\n [regex.plural.whereases],\n [regex.plural.criteria],\n [regex.plural.genera],\n // original rule\n [regex.singular.man, '$1en'],\n [regex.singular.person, '$1ople'],\n [regex.singular.child, '$1ren'],\n [regex.singular.drive, '$1s'],\n [regex.singular.ox, '$1en'],\n [regex.singular.axis, '$1es'],\n [regex.singular.octopus, '$1uses'],\n [regex.singular.alias, '$1es'],\n [regex.singular.summons, '$1es'],\n [regex.singular.bus, '$1ses'],\n [regex.singular.buffalo, '$1oes'],\n [regex.singular.tium, '$1a'],\n [regex.singular.sis, 'ses'],\n [regex.singular.ffe, '$1$2ves'],\n [regex.singular.focus, '$1es'],\n [regex.singular.hive, '$1ves'],\n [regex.singular.aeiouyy, '$1ies'],\n [regex.singular.matrix, '$1ices'],\n [regex.singular.vertex, '$1ices'],\n [regex.singular.x, '$1es'],\n [regex.singular.mouse, '$1ice'],\n [regex.singular.foot, 'feet'],\n [regex.singular.tooth, 'teeth'],\n [regex.singular.goose, 'geese'],\n [regex.singular.quiz, '$1zes'],\n [regex.singular.whereas, '$1es'],\n [regex.singular.criterion, '$1a'],\n [regex.singular.genus, 'genera'],\n [regex.singular.s, 's'],\n [regex.singular.common, 's'],\n];\n/**\n * @description These rules translate from the plural form of a noun to its singular form.\n */\nconst singularRules = [\n // do not replace if its already a singular word\n [regex.singular.man],\n [regex.singular.person],\n [regex.singular.child],\n [regex.singular.drive],\n [regex.singular.ox],\n [regex.singular.axis],\n [regex.singular.octopus],\n [regex.singular.alias],\n [regex.singular.summons],\n [regex.singular.bus],\n [regex.singular.buffalo],\n [regex.singular.tium],\n [regex.singular.sis],\n [regex.singular.ffe],\n [regex.singular.focus],\n [regex.singular.hive],\n [regex.singular.aeiouyy],\n [regex.singular.x],\n [regex.singular.matrix],\n [regex.singular.mouse],\n [regex.singular.foot],\n [regex.singular.tooth],\n [regex.singular.goose],\n [regex.singular.quiz],\n [regex.singular.whereas],\n [regex.singular.criterion],\n [regex.singular.genus],\n // original rule\n [regex.plural.men, '$1an'],\n [regex.plural.people, '$1rson'],\n [regex.plural.children, '$1'],\n [regex.plural.databases, '$1'],\n [regex.plural.drives, '$1'],\n [regex.plural.genera, 'genus'],\n [regex.plural.criteria, '$1on'],\n [regex.plural.tia, '$1um'],\n [regex.plural.analyses, '$1$2sis'],\n [regex.plural.hives, '$1ve'],\n [regex.plural.curves, '$1'],\n [regex.plural.lrves, '$1f'],\n [regex.plural.aves, '$1ve'],\n [regex.plural.foves, '$1fe'],\n [regex.plural.movies, '$1ovie'],\n [regex.plural.aeiouyies, '$1y'],\n [regex.plural.series, '$1eries'],\n [regex.plural.xes, '$1'],\n [regex.plural.mice, '$1ouse'],\n [regex.plural.buses, '$1'],\n [regex.plural.oes, '$1'],\n [regex.plural.shoes, '$1'],\n [regex.plural.crises, '$1is'],\n [regex.plural.octopuses, '$1us'],\n [regex.plural.aliases, '$1'],\n [regex.plural.summonses, '$1'],\n [regex.plural.oxen, '$1'],\n [regex.plural.matrices, '$1ix'],\n [regex.plural.vertices, '$1ex'],\n [regex.plural.feet, 'foot'],\n [regex.plural.teeth, 'tooth'],\n [regex.plural.geese, 'goose'],\n [regex.plural.quizzes, '$1'],\n [regex.plural.whereases, '$1'],\n [regex.plural.ss, 'ss'],\n [regex.plural.s, ''],\n];\n/**\n * @description This is a list of words that should not be capitalized for title case.\n */\nconst nonTitlecasedWords = [\n 'and',\n 'or',\n 'nor',\n 'a',\n 'an',\n 'the',\n 'so',\n 'but',\n 'to',\n 'of',\n 'at',\n 'by',\n 'from',\n 'into',\n 'on',\n 'onto',\n 'off',\n 'out',\n 'in',\n 'over',\n 'with',\n 'for',\n];\n/**\n * @description These are regular expressions used for converting between String formats.\n */\nconst idSuffix = new RegExp('(_ids|_id)$', 'g');\nconst underbar = new RegExp('_', 'g');\nconst spaceOrUnderbar = new RegExp('[ _]', 'g');\nconst uppercase = new RegExp('([A-Z])', 'g');\nconst underbarPrefix = new RegExp('^_');\n/**\n * A helper method that applies rules based replacement to a String.\n * @param str String to modify and return based on the passed rules.\n * @param rules Regexp to match paired with String to use for replacement\n * @param skip Strings to skip if they match\n * @param override String to return as though this method succeeded (used to conform to APIs)\n * @returns Return passed String modified by passed rules.\n * @example\n *\n * applyRules( 'cows', singular_rules ); // === 'cow'\n */\nfunction applyRules(str, rules, skip, override) {\n if (override) {\n return override;\n }\n else {\n if (skip.includes(str.toLocaleLowerCase())) {\n return str;\n }\n for (const rule of rules) {\n if (str.match(rule[0])) {\n if (rule[1] !== undefined) {\n return str.replace(rule[0], rule[1]);\n }\n return str;\n }\n }\n }\n return str;\n}\n/**\n * This function adds pluralization support to every String object.\n * @param str The subject string.\n * @param plural Overrides normal output with said String.(optional)\n * @returns Singular English language nouns are returned in plural form.\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.pluralize( 'person' ); // === 'people'\n * inflection.pluralize( 'octopus' ); // === 'octopuses'\n * inflection.pluralize( 'Hat' ); // === 'Hats'\n * inflection.pluralize( 'person', 'guys' ); // === 'guys'\n */\nfunction pluralize(str, plural) {\n return applyRules(str, pluralRules, uncountableWords, plural);\n}\n/**\n * This function adds singularization support to every String object.\n * @param str The subject string.\n * @param singular Overrides normal output with said String.(optional)\n * @returns Plural English language nouns are returned in singular form.\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.singularize( 'people' ); // === 'person'\n * inflection.singularize( 'octopuses' ); // === 'octopus'\n * inflection.singularize( 'Hats' ); // === 'Hat'\n * inflection.singularize( 'guys', 'person' ); // === 'person'\n */\nfunction singularize(str, singular) {\n return applyRules(str, singularRules, uncountableWords, singular);\n}\n/**\n * This function will pluralize or singularlize a String appropriately based on a number value\n * @param str The subject string.\n * @param count The number to base pluralization off of.\n * @param singular Overrides normal output with said String.(optional)\n * @param plural Overrides normal output with said String.(optional)\n * @returns English language nouns are returned in the plural or singular form based on the count.\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.inflect( 'people' 1 ); // === 'person'\n * inflection.inflect( 'octopuses' 1 ); // === 'octopus'\n * inflection.inflect( 'Hats' 1 ); // === 'Hat'\n * inflection.inflect( 'guys', 1 , 'person' ); // === 'person'\n * inflection.inflect( 'inches', 1.5 ); // === 'inches'\n * inflection.inflect( 'person', 2 ); // === 'people'\n * inflection.inflect( 'octopus', 2 ); // === 'octopuses'\n * inflection.inflect( 'Hat', 2 ); // === 'Hats'\n * inflection.inflect( 'person', 2, null, 'guys' ); // === 'guys'\n */\nfunction inflect(str, count, singular, plural) {\n if (isNaN(count))\n return str;\n if (count === 1) {\n return applyRules(str, singularRules, uncountableWords, singular);\n }\n else {\n return applyRules(str, pluralRules, uncountableWords, plural);\n }\n}\n/**\n * This function adds camelization support to every String object.\n * @param str The subject string.\n * @param lowFirstLetter Default is to capitalize the first letter of the results.(optional)\n * Passing true will lowercase it.\n * @returns Lower case underscored words will be returned in camel case.\n * additionally '/' is translated to '::'\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.camelize( 'message_properties' ); // === 'MessageProperties'\n * inflection.camelize( 'message_properties', true ); // === 'messageProperties'\n */\nfunction camelize(str, lowFirstLetter) {\n const strPath = str.split('/');\n const j = strPath.length;\n let strArr, k, l, first;\n for (let i = 0; i < j; i++) {\n strArr = strPath[i].split('_');\n k = 0;\n l = strArr.length;\n for (; k < l; k++) {\n if (k !== 0) {\n strArr[k] = strArr[k].toLowerCase();\n }\n first = strArr[k].charAt(0);\n first =\n lowFirstLetter && i === 0 && k === 0\n ? first.toLowerCase()\n : first.toUpperCase();\n strArr[k] = first + strArr[k].substring(1);\n }\n strPath[i] = strArr.join('');\n }\n return strPath.join('::');\n}\n/**\n * This function adds underscore support to every String object.\n * @param str The subject string.\n * @param allUpperCase Default is to lowercase and add underscore prefix.(optional)\n * Passing true will return as entered.\n * @returns Camel cased words are returned as lower cased and underscored.\n * additionally '::' is translated to '/'.\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.underscore( 'MessageProperties' ); // === 'message_properties'\n * inflection.underscore( 'messageProperties' ); // === 'message_properties'\n * inflection.underscore( 'MP', true ); // === 'MP'\n */\nfunction underscore(str, allUpperCase) {\n if (allUpperCase && str === str.toUpperCase())\n return str;\n const strPath = str.split('::');\n const j = strPath.length;\n for (let i = 0; i < j; i++) {\n strPath[i] = strPath[i].replace(uppercase, '_$1');\n strPath[i] = strPath[i].replace(underbarPrefix, '');\n }\n return strPath.join('/').toLowerCase();\n}\n/**\n * This function adds humanize support to every String object.\n * @param str The subject string.\n * @param lowFirstLetter Default is to capitalize the first letter of the results.(optional)\n * Passing true will lowercase it.\n * @returns Lower case underscored words will be returned in humanized form.\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.humanize( 'message_properties' ); // === 'Message properties'\n * inflection.humanize( 'message_properties', true ); // === 'message properties'\n */\nfunction humanize(str, lowFirstLetter) {\n str = str.toLowerCase();\n str = str.replace(idSuffix, '');\n str = str.replace(underbar, ' ');\n if (!lowFirstLetter) {\n str = capitalize(str);\n }\n return str;\n}\n/**\n * This function adds capitalization support to every String object.\n * @param str The subject string.\n * @returns All characters will be lower case and the first will be upper.\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.capitalize( 'message_properties' ); // === 'Message_properties'\n * inflection.capitalize( 'message properties', true ); // === 'Message properties'\n */\nfunction capitalize(str) {\n str = str.toLowerCase();\n return str.substring(0, 1).toUpperCase() + str.substring(1);\n}\n/**\n * This function replaces underscores with dashes in the string.\n * @param str The subject string.\n * @returns Replaces all spaces or underscores with dashes.\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.dasherize( 'message_properties' ); // === 'message-properties'\n * inflection.dasherize( 'Message Properties' ); // === 'Message-Properties'\n */\nfunction dasherize(str) {\n return str.replace(spaceOrUnderbar, '-');\n}\n/**\n * This function adds titleize support to every String object.\n * @param str The subject string.\n * @returns Capitalizes words as you would for a book title.\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.titleize( 'message_properties' ); // === 'Message Properties'\n * inflection.titleize( 'message properties to keep' ); // === 'Message Properties to Keep'\n */\nfunction titleize(str) {\n str = str.toLowerCase().replace(underbar, ' ');\n const strArr = str.split(' ');\n const j = strArr.length;\n let d, l;\n for (let i = 0; i < j; i++) {\n d = strArr[i].split('-');\n l = d.length;\n for (let k = 0; k < l; k++) {\n if (nonTitlecasedWords.indexOf(d[k].toLowerCase()) < 0) {\n d[k] = capitalize(d[k]);\n }\n }\n strArr[i] = d.join('-');\n }\n str = strArr.join(' ');\n str = str.substring(0, 1).toUpperCase() + str.substring(1);\n return str;\n}\n/**\n * This function adds demodulize support to every String object.\n * @param str The subject string.\n * @returns Removes module names leaving only class names.(Ruby style)\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.demodulize( 'Message::Bus::Properties' ); // === 'Properties'\n */\nfunction demodulize(str) {\n const strArr = str.split('::');\n return strArr[strArr.length - 1];\n}\n/**\n * This function adds tableize support to every String object.\n * @param str The subject string.\n * @returns Return camel cased words into their underscored plural form.\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.tableize( 'MessageBusProperty' ); // === 'message_bus_properties'\n */\nfunction tableize(str) {\n str = underscore(str);\n str = pluralize(str);\n return str;\n}\n/**\n * This function adds classification support to every String object.\n * @param str The subject string.\n * @returns Underscored plural nouns become the camel cased singular form.\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.classify( 'message_bus_properties' ); // === 'MessageBusProperty'\n */\nfunction classify(str) {\n str = camelize(str);\n str = singularize(str);\n return str;\n}\n/**\n * This function adds foreign key support to every String object.\n * @param str The subject string.\n * @param dropIdUbar Default is to seperate id with an underbar at the end of the class name,\n you can pass true to skip it.(optional)\n * @returns Underscored plural nouns become the camel cased singular form.\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.foreign_key( 'MessageBusProperty' ); // === 'message_bus_property_id'\n * inflection.foreign_key( 'MessageBusProperty', true ); // === 'message_bus_propertyid'\n */\nfunction foreignKey(str, dropIdUbar) {\n str = demodulize(str);\n str = underscore(str) + (dropIdUbar ? '' : '_') + 'id';\n return str;\n}\n/**\n * This function adds ordinalize support to every String object.\n * @param str The subject string.\n * @returns Return all found numbers their sequence like '22nd'.\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.ordinalize( 'the 1 pitch' ); // === 'the 1st pitch'\n */\nfunction ordinalize(str) {\n const strArr = str.split(' ');\n const j = strArr.length;\n for (let i = 0; i < j; i++) {\n const k = parseInt(strArr[i], 10);\n if (!isNaN(k)) {\n const ltd = strArr[i].substring(strArr[i].length - 2);\n const ld = strArr[i].substring(strArr[i].length - 1);\n let suf = 'th';\n if (ltd != '11' && ltd != '12' && ltd != '13') {\n if (ld === '1') {\n suf = 'st';\n }\n else if (ld === '2') {\n suf = 'nd';\n }\n else if (ld === '3') {\n suf = 'rd';\n }\n }\n strArr[i] += suf;\n }\n }\n return strArr.join(' ');\n}\nconst transformFunctions = {\n pluralize,\n singularize,\n camelize,\n underscore,\n humanize,\n capitalize,\n dasherize,\n titleize,\n demodulize,\n tableize,\n classify,\n foreignKey,\n ordinalize,\n};\n/**\n * This function performs multiple inflection methods on a string\n * @param str The subject string.\n * @param arr An array of inflection methods.\n * @returns\n * @example\n *\n * const inflection = require( 'inflection' );\n *\n * inflection.transform( 'all job', [ 'pluralize', 'capitalize', 'dasherize' ]); // === 'All-jobs'\n */\nfunction transform(str, arr) {\n const j = arr.length;\n for (let i = 0; i < j; i++) {\n const method = arr[i];\n const methodFn = transformFunctions[method];\n if (methodFn) {\n str = methodFn(str);\n }\n }\n return str;\n}\n","import { useResourceDefinitions } from './useResourceDefinitions';\nimport { useTranslate } from '../i18n';\nimport { humanize, inflect } from 'inflection';\n/**\n * A hook which returns function to get a translated resource name. It will use the label option of the `Resource` component if it was provided.\n *\n * @returns {GetResourceLabel} A function which takes a resource name and an optional number indicating the number of items (used for pluralization) and returns a translated string.\n * @example\n * const Menu = () => {\n * const resources = useResourceDefinitions();\n * const getResourceLabel = useGetResourceLabel();\n *\n * return (\n *
    \n * {Object.keys(resources).map(name => (\n *
  • \n * {getResourceLabel(name, 2)}\n *
  • \n * ))}\n *
\n * )\n * }\n */\nexport var useGetResourceLabel = function () {\n var translate = useTranslate();\n var definitions = useResourceDefinitions();\n return function (resource, count) {\n if (count === void 0) { count = 2; }\n var resourceDefinition = definitions[resource];\n var label = translate(\"resources.\".concat(resource, \".name\"), {\n smart_count: count,\n _: resourceDefinition &&\n resourceDefinition.options &&\n resourceDefinition.options.label\n ? translate(resourceDefinition.options.label, {\n smart_count: count,\n _: resourceDefinition.options.label,\n })\n : humanize(inflect(resource, count)),\n });\n return label;\n };\n};\n//# sourceMappingURL=useGetResourceLabel.js.map","import { useMemo } from 'react';\nimport defaults from 'lodash/defaults';\nimport { useResourceDefinitions } from './useResourceDefinitions';\nimport { useResourceContext } from './useResourceContext';\n/**\n * Hook to get the definition of a given resource\n *\n * @example // Get the current resource definition (based on ResourceContext)\n *\n * const definition = useResourceDefinition();\n * console.log(definition);\n * // {\n * // name: 'posts',\n * // hasList: true,\n * // hasEdit: true,\n * // hasShow: true,\n * // hasCreate: true,\n * // options: {},\n * // icon: PostIcon,\n * // }\n *\n * @example // Pass a resource prop to check a different resource definition\n *\n * const definition = useResourceDefinition({ resource: 'posts' });\n */\nexport var useResourceDefinition = function (props) {\n var resource = useResourceContext(props);\n var resourceDefinitions = useResourceDefinitions();\n var _a = props || {}, hasCreate = _a.hasCreate, hasEdit = _a.hasEdit, hasList = _a.hasList, hasShow = _a.hasShow, recordRepresentation = _a.recordRepresentation;\n var definition = useMemo(function () {\n return defaults({}, {\n hasCreate: hasCreate,\n hasEdit: hasEdit,\n hasList: hasList,\n hasShow: hasShow,\n recordRepresentation: recordRepresentation,\n }, resource ? resourceDefinitions[resource] : {});\n }, [\n resource,\n resourceDefinitions,\n hasCreate,\n hasEdit,\n hasList,\n hasShow,\n recordRepresentation,\n ]);\n return definition;\n};\n//# sourceMappingURL=useResourceDefinition.js.map","import * as React from 'react';\nimport { useCallback } from 'react';\nimport get from 'lodash/get';\nimport { useResourceDefinition } from './useResourceDefinition';\n/**\n * Get default string representation of a record\n *\n * @example // No customization\n * const getRecordRepresentation = useGetRecordRepresentation('posts');\n * getRecordRepresentation({ id: 1, title: 'Hello' }); // => \"#1\"\n *\n * @example // With \n * const getRecordRepresentation = useGetRecordRepresentation('posts');\n * getRecordRepresentation({ id: 1, title: 'Hello' }); // => \"Hello\"\n */\nexport var useGetRecordRepresentation = function (resource) {\n var recordRepresentation = useResourceDefinition({ resource: resource }).recordRepresentation;\n return useCallback(function (record) {\n if (!record)\n return '';\n if (typeof recordRepresentation === 'function') {\n return recordRepresentation(record);\n }\n if (typeof recordRepresentation === 'string') {\n return get(record, recordRepresentation);\n }\n if (React.isValidElement(recordRepresentation)) {\n return recordRepresentation;\n }\n if ((record === null || record === void 0 ? void 0 : record.name) != null && (record === null || record === void 0 ? void 0 : record.name) !== '') {\n return record.name;\n }\n if ((record === null || record === void 0 ? void 0 : record.title) != null && (record === null || record === void 0 ? void 0 : record.title) !== '') {\n return record.title;\n }\n if ((record === null || record === void 0 ? void 0 : record.label) != null && (record === null || record === void 0 ? void 0 : record.label) !== '') {\n return record.label;\n }\n if ((record === null || record === void 0 ? void 0 : record.reference) != null && (record === null || record === void 0 ? void 0 : record.reference) !== '') {\n return record.reference;\n }\n return \"#\".concat(record.id);\n }, [recordRepresentation]);\n};\n//# sourceMappingURL=useGetRecordRepresentation.js.map","import { useSourceContext } from './SourceContext';\n/**\n * Get the source prop for a field or input by checking if a source context is available.\n * @param {string} source The original source prop\n * @returns {string} The source prop, either the original one or the one modified by the SourceContext.\n * @example\n * const MyInput = ({ source, ...props }) => {\n * const finalSource = useWrappedSource(source);\n * return ;\n * };\n */\nexport var useWrappedSource = function (source) {\n var sourceContext = useSourceContext();\n return sourceContext.getSource(source);\n};\n//# sourceMappingURL=useWrappedSource.js.map","import { useCallback } from 'react';\nimport { useTranslate } from './useTranslate';\nimport { getFieldLabelTranslationArgs } from '../util';\nimport { useResourceContext, useOptionalSourceContext } from '../core';\nexport var useTranslateLabel = function () {\n var translate = useTranslate();\n var resourceFromContext = useResourceContext();\n var sourceContext = useOptionalSourceContext();\n return useCallback(function (_a) {\n var source = _a.source, label = _a.label, resource = _a.resource;\n if (label === false || label === '') {\n return null;\n }\n if (label && typeof label !== 'string') {\n return label;\n }\n return translate.apply(void 0, getFieldLabelTranslationArgs({\n label: label,\n defaultLabel: source\n ? sourceContext === null || sourceContext === void 0 ? void 0 : sourceContext.getLabel(source)\n : undefined,\n resource: resource,\n resourceFromContext: resourceFromContext,\n source: source,\n }));\n }, [resourceFromContext, translate, sourceContext]);\n};\n//# sourceMappingURL=useTranslateLabel.js.map","import * as React from 'react';\nimport { memo } from 'react';\nimport { useTranslateLabel } from '../i18n';\nexport var FieldTitle = function (props) {\n var source = props.source, label = props.label, resource = props.resource, isRequired = props.isRequired;\n var translateLabel = useTranslateLabel();\n if (label === true) {\n throw new Error('Label parameter must be a string, a ReactElement or false');\n }\n if (label === false || label === '') {\n return null;\n }\n if (label && typeof label !== 'string') {\n return label;\n }\n return (React.createElement(\"span\", null,\n translateLabel({\n label: label,\n resource: resource,\n source: source,\n }),\n isRequired && React.createElement(\"span\", { \"aria-hidden\": \"true\" }, \"\\u2009*\")));\n};\n// What? TypeScript loses the displayName if we don't set it explicitly\nFieldTitle.displayName = 'FieldTitle';\nexport default memo(FieldTitle);\n//# sourceMappingURL=FieldTitle.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nimport * as React from 'react';\nimport { useState } from 'react';\nvar styles = {\n root: {\n width: '100vw',\n height: '100vh',\n display: 'flex',\n flexDirection: 'column',\n fontFamily: '\"Roboto\", sans-serif',\n },\n main: {\n flex: 1,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n textAlign: 'center',\n flexDirection: 'column',\n background: 'linear-gradient(135deg, #00023b 0%, #00023b 50%, #313264 100%)',\n color: 'white',\n fontSize: '1.5em',\n fontWeight: 'bold',\n },\n secondary: {\n height: '20vh',\n background: '#e8e8e8',\n color: 'black',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'space-evenly',\n },\n link: {\n textAlign: 'center',\n width: 150,\n display: 'block',\n textDecoration: 'none',\n color: 'black',\n opacity: 0.7,\n },\n linkHovered: {\n opacity: 1,\n },\n image: {\n width: 50,\n },\n logo: {\n height: 100,\n },\n};\nvar Button = function (_a) {\n var img = _a.img, label = _a.label, href = _a.href;\n var _b = useState(false), hovered = _b[0], setHovered = _b[1];\n return (React.createElement(\"div\", null,\n React.createElement(\"a\", { href: href, style: hovered\n ? __assign(__assign({}, styles.link), styles.linkHovered) : styles.link, onMouseEnter: function () { return setHovered(true); }, onMouseLeave: function () { return setHovered(false); } },\n React.createElement(\"img\", { src: img, alt: label, style: styles.image }),\n React.createElement(\"br\", null),\n label)));\n};\nexport default (function () {\n return process.env.NODE_ENV === 'production' ? (React.createElement(\"span\", null)) : (React.createElement(\"div\", { style: styles.root },\n React.createElement(\"div\", { style: styles.main },\n React.createElement(\"img\", { style: styles.logo, src: \"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDIzLjAuMSwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkNhbHF1ZV8xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4PSIwcHgiIHk9IjBweCIKCSB2aWV3Qm94PSIwIDAgMTMxIDEzMSIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgMTMxIDEzMTsiIHhtbDpzcGFjZT0icHJlc2VydmUiPgo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPgoJLnN0MHtmaWxsOiMyMjI0NTg7fQoJLnN0MXtmaWxsOiM1MTUzN0Q7fQoJLnN0MntmaWxsOiNBM0E0Qjk7fQoJLnN0M3tmaWxsOiMwMDAyM0I7fQoJLnN0NHtmaWxsOiNGRkZGRkY7fQoJLnN0NXtlbmFibGUtYmFja2dyb3VuZDpuZXcgICAgO30KPC9zdHlsZT4KPHRpdGxlPkxvZ29fc29tYnJlX2FpPC90aXRsZT4KPGcgaWQ9IlJlY3RhbmdsZV81NiI+Cgk8Zz4KCQk8cmVjdCB4PSIxOS4xIiB5PSIxOSIgdHJhbnNmb3JtPSJtYXRyaXgoMC41IC0wLjg2NiAwLjg2NiAwLjUgLTIzLjkyMjYgODkuNTQ2KSIgY2xhc3M9InN0MCIgd2lkdGg9IjkyLjkiIGhlaWdodD0iOTIuOSIvPgoJCTxwYXRoIGNsYXNzPSJzdDEiIGQ9Ik04MywxMzAuM0wwLjgsODIuOUw0OC4yLDAuN2w4Mi4yLDQ3LjVMODMsMTMwLjN6IE0zLjUsODIuMWw3OC43LDQ1LjVsNDUuNS03OC43TDQ5LDMuNEwzLjUsODIuMXoiLz4KCTwvZz4KPC9nPgo8ZyBpZD0iUmVjdGFuZ2xlXzU2LTIiPgoJPGc+CgkJPHJlY3QgeD0iMTkiIHk9IjE5LjEiIHRyYW5zZm9ybT0ibWF0cml4KDAuODY2IC0wLjUgMC41IDAuODY2IC0yMy45Nzc3IDQxLjUyNykiIGNsYXNzPSJzdDAiIHdpZHRoPSI5Mi45IiBoZWlnaHQ9IjkyLjkiLz4KCQk8cGF0aCBjbGFzcz0ic3QyIiBkPSJNNDcuOSwxMzFMMCw0OEw4My4xLDBsNDgsODMuMUw0Ny45LDEzMXogTTQuMSw0OS4xbDQ1LDc3LjlsNzcuOS00NUw4Miw0LjFMNC4xLDQ5LjF6Ii8+Cgk8L2c+CjwvZz4KPGcgaWQ9IlJlY3RhbmdsZV81Ni0zIj4KCTxnPgoJCTxyZWN0IHg9IjE5LjEiIHk9IjE5IiBjbGFzcz0ic3QzIiB3aWR0aD0iOTIuOSIgaGVpZ2h0PSI5Mi45Ii8+CgkJPHBhdGggY2xhc3M9InN0NCIgZD0iTTExNC41LDExNC41SDE2LjZWMTYuNWg5Ny45VjExNC41eiBNMjEuNiwxMDkuNWg4Ny45VjIxLjVIMjEuNlYxMDkuNXoiLz4KCTwvZz4KPC9nPgo8ZyBpZD0iUmEiPgoJPGcgY2xhc3M9InN0NSI+CgkJPHBhdGggY2xhc3M9InN0NCIgZD0iTTU5LDg2LjdsLTYuNy0xOS4yaC0xLjJIMzguOXYxOS4yaC01LjZWMzguNWgxOC41YzMuNiwwLDYuMywwLjYsOC4xLDEuOGMxLjgsMS4yLDMsMi44LDMuNSw0LjgKCQkJYzAuNSwyLDAuOCw0LjYsMC44LDcuOGMwLDMuNS0wLjQsNi40LTEuMyw4LjdjLTAuOCwyLjMtMi42LDMuOS01LjMsNC44TDY1LDg2LjdINTl6IE01NS43LDYxLjZjMS4yLTAuNywyLTEuNywyLjQtMwoJCQljMC40LTEuMywwLjYtMy4yLDAuNi01LjZjMC0yLjUtMC4yLTQuMy0wLjUtNS42Yy0wLjMtMS4zLTEuMS0yLjItMi4zLTIuOWMtMS4yLTAuNy0zLTEtNS41LTFIMzguOXYxOS4xSDUwCgkJCUM1Mi41LDYyLjYsNTQuNCw2Mi4zLDU1LjcsNjEuNnoiLz4KCQk8cGF0aCBjbGFzcz0ic3Q0IiBkPSJNNzQuMyw4NWMtMS42LTEuNS0yLjUtNC4yLTIuNS04LjJjMC0yLjcsMC4zLTQuOCwwLjktNi4zYzAuNi0xLjUsMS42LTIuNiwzLTMuM2MxLjQtMC43LDMuNC0xLDYtMQoJCQljMS4zLDAsNS4xLDAuMSwxMS40LDAuM3YtMi40YzAtMi45LTAuMi01LTAuNy02LjJjLTAuNS0xLjItMS4zLTItMi42LTIuNGMtMS4yLTAuMy0zLjMtMC41LTYuMy0wLjVjLTEuMywwLTMsMC4xLTQuOSwwLjIKCQkJYy0yLDAuMS0zLjYsMC4zLTQuOCwwLjV2LTQuM2MzLjMtMC43LDcuMS0xLDExLjQtMWMzLjcsMCw2LjUsMC40LDguNCwxLjJjMS44LDAuOCwzLjEsMi4yLDMuOCw0LjFjMC43LDEuOSwxLDQuNywxLDguNHYyMi41aC00LjgKCQkJbC0wLjMtNWgtMC4zYy0wLjgsMi4yLTIuMiwzLjctNC4xLDQuNGMtMS45LDAuNy00LjEsMS4xLTYuNiwxLjFDNzguNiw4Ny4yLDc2LDg2LjUsNzQuMyw4NXogTTg5LjEsODJjMS4yLTAuNCwyLjItMS4yLDIuOC0yLjQKCQkJYzAuOS0xLjgsMS4zLTQuMywxLjMtNy4zdi0yaC0xMGMtMS43LDAtMywwLjItMy44LDAuNWMtMC44LDAuMy0xLjQsMC45LTEuNywxLjhjLTAuMywwLjktMC41LDIuMi0wLjUsNGMwLDEuOCwwLjIsMy4xLDAuNiwzLjkKCQkJYzAuNCwwLjgsMS4xLDEuNCwyLDEuOGMxLDAuMywyLjUsMC41LDQuNSwwLjVDODYuMiw4Mi42LDg3LjgsODIuNCw4OS4xLDgyeiIvPgoJPC9nPgo8L2c+Cjwvc3ZnPgo=\", alt: \"react-admin logo\" }),\n React.createElement(\"h1\", null, \"Welcome to React-admin\"),\n React.createElement(\"div\", null,\n \"Your application is properly configured.\",\n React.createElement(\"br\", null),\n \"Now you can add a as child of .\")),\n React.createElement(\"div\", { style: styles.secondary },\n React.createElement(Button, { href: \"https://marmelab.com/react-admin/documentation.html\", img: \"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDIzLjAuMCwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSIyNHB4IgoJIGhlaWdodD0iMjRweCIgdmlld0JveD0iMCAwIDI0IDI0IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCAyNCAyNCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxnIGlkPSJCb3VuZGluZ19Cb3giPgoJPHJlY3QgZmlsbD0ibm9uZSIgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0Ii8+CjwvZz4KPGcgaWQ9IkZsYXQiPgoJPGcgaWQ9InVpX3g1Rl9zcGVjX3g1Rl9oZWFkZXJfY29weV8yIj4KCTwvZz4KCTxnPgoJCTxwYXRoIGQ9Ik0yMSw1Yy0xLjExLTAuMzUtMi4zMy0wLjUtMy41LTAuNWMtMS45NSwwLTQuMDUsMC40LTUuNSwxLjVjLTEuNDUtMS4xLTMuNTUtMS41LTUuNS0xLjVTMi40NSw0LjksMSw2djE0LjY1CgkJCWMwLDAuMjUsMC4yNSwwLjUsMC41LDAuNWMwLjEsMCwwLjE1LTAuMDUsMC4yNS0wLjA1QzMuMSwyMC40NSw1LjA1LDIwLDYuNSwyMGMxLjk1LDAsNC4wNSwwLjQsNS41LDEuNWMxLjM1LTAuODUsMy44LTEuNSw1LjUtMS41CgkJCWMxLjY1LDAsMy4zNSwwLjMsNC43NSwxLjA1YzAuMSwwLjA1LDAuMTUsMC4wNSwwLjI1LDAuMDVjMC4yNSwwLDAuNS0wLjI1LDAuNS0wLjVWNkMyMi40LDUuNTUsMjEuNzUsNS4yNSwyMSw1eiBNMywxOC41VjcKCQkJYzEuMS0wLjM1LDIuMy0wLjUsMy41LTAuNWMxLjM0LDAsMy4xMywwLjQxLDQuNSwwLjk5djExLjVDOS42MywxOC40MSw3Ljg0LDE4LDYuNSwxOEM1LjMsMTgsNC4xLDE4LjE1LDMsMTguNXogTTIxLDE4LjUKCQkJYy0xLjEtMC4zNS0yLjMtMC41LTMuNS0wLjVjLTEuMzQsMC0zLjEzLDAuNDEtNC41LDAuOTlWNy40OWMxLjM3LTAuNTksMy4xNi0wLjk5LDQuNS0wLjk5YzEuMiwwLDIuNCwwLjE1LDMuNSwwLjVWMTguNXoiLz4KCQk8cGF0aCBvcGFjaXR5PSIwLjMiIGQ9Ik0xMSw3LjQ5QzkuNjMsNi45MSw3Ljg0LDYuNSw2LjUsNi41QzUuMyw2LjUsNC4xLDYuNjUsMyw3djExLjVDNC4xLDE4LjE1LDUuMywxOCw2LjUsMTgKCQkJYzEuMzQsMCwzLjEzLDAuNDEsNC41LDAuOTlWNy40OXoiLz4KCTwvZz4KCTxnPgoJCTxwYXRoIGQ9Ik0xNy41LDEwLjVjMC44OCwwLDEuNzMsMC4wOSwyLjUsMC4yNlY5LjI0QzE5LjIxLDkuMDksMTguMzYsOSwxNy41LDljLTEuMjgsMC0yLjQ2LDAuMTYtMy41LDAuNDd2MS41NwoJCQlDMTQuOTksMTAuNjksMTYuMTgsMTAuNSwxNy41LDEwLjV6Ii8+CgkJPHBhdGggZD0iTTE3LjUsMTMuMTZjMC44OCwwLDEuNzMsMC4wOSwyLjUsMC4yNlYxMS45Yy0wLjc5LTAuMTUtMS42NC0wLjI0LTIuNS0wLjI0Yy0xLjI4LDAtMi40NiwwLjE2LTMuNSwwLjQ3djEuNTcKCQkJQzE0Ljk5LDEzLjM2LDE2LjE4LDEzLjE2LDE3LjUsMTMuMTZ6Ii8+CgkJPHBhdGggZD0iTTE3LjUsMTUuODNjMC44OCwwLDEuNzMsMC4wOSwyLjUsMC4yNnYtMS41MmMtMC43OS0wLjE1LTEuNjQtMC4yNC0yLjUtMC4yNGMtMS4yOCwwLTIuNDYsMC4xNi0zLjUsMC40N3YxLjU3CgkJCUMxNC45OSwxNi4wMiwxNi4xOCwxNS44MywxNy41LDE1LjgzeiIvPgoJPC9nPgo8L2c+Cjwvc3ZnPgo=\", label: \"Documentation\" }),\n React.createElement(Button, { href: \"https://github.com/marmelab/react-admin/tree/master/examples\", img: \"data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBmaWxsPSJub25lIiBkPSJNMCAwaDI0djI0SDBWMHoiLz48cGF0aCBkPSJNOS40IDE2LjZMNC44IDEybDQuNi00LjZMOCA2bC02IDYgNiA2IDEuNC0xLjR6bTUuMiAwbDQuNi00LjYtNC42LTQuNkwxNiA2bDYgNi02IDYtMS40LTEuNHoiLz48L3N2Zz4=\", label: \"Examples\" }),\n React.createElement(Button, { href: \"https://stackoverflow.com/questions/tagged/react-admin\", img: \"data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPCEtLSBHZW5lcmF0b3I6IEFkb2JlIElsbHVzdHJhdG9yIDIzLjAuMSwgU1ZHIEV4cG9ydCBQbHVnLUluIC4gU1ZHIFZlcnNpb246IDYuMDAgQnVpbGQgMCkgIC0tPgo8c3ZnIHZlcnNpb249IjEuMSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgeD0iMHB4IiB5PSIwcHgiIHdpZHRoPSIyNHB4IgoJIGhlaWdodD0iMjRweCIgdmlld0JveD0iMCAwIDI0IDI0IiBlbmFibGUtYmFja2dyb3VuZD0ibmV3IDAgMCAyNCAyNCIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+CjxnIGlkPSJCb3VuZGluZ19Cb3giPgoJPHJlY3QgZmlsbD0ibm9uZSIgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0Ii8+CjwvZz4KPGcgaWQ9IkZsYXQiPgoJPGcgaWQ9InVpX3g1Rl9zcGVjX3g1Rl9oZWFkZXJfY29weV8yIj4KCTwvZz4KCTxnPgoJCTxjaXJjbGUgb3BhY2l0eT0iMC4zIiBjeD0iOSIgY3k9IjgiIHI9IjIiLz4KCQk8cGF0aCBvcGFjaXR5PSIwLjMiIGQ9Ik05LDE1Yy0yLjcsMC01LjgsMS4yOS02LDIuMDFMMywxOGgxMnYtMUMxNC44LDE2LjI5LDExLjcsMTUsOSwxNXoiLz4KCQk8cGF0aCBkPSJNMTYuNjcsMTMuMTNDMTguMDQsMTQuMDYsMTksMTUuMzIsMTksMTd2M2g0di0zQzIzLDE0LjgyLDE5LjQzLDEzLjUzLDE2LjY3LDEzLjEzeiIvPgoJCTxwYXRoIGQ9Ik0xNSwxMmMyLjIxLDAsNC0xLjc5LDQtNGMwLTIuMjEtMS43OS00LTQtNGMtMC40NywwLTAuOTEsMC4xLTEuMzMsMC4yNEMxNC41LDUuMjcsMTUsNi41OCwxNSw4cy0wLjUsMi43My0xLjMzLDMuNzYKCQkJQzE0LjA5LDExLjksMTQuNTMsMTIsMTUsMTJ6Ii8+CgkJPHBhdGggZD0iTTksMTJjMi4yMSwwLDQtMS43OSw0LTRjMC0yLjIxLTEuNzktNC00LTRTNSw1Ljc5LDUsOEM1LDEwLjIxLDYuNzksMTIsOSwxMnogTTksNmMxLjEsMCwyLDAuOSwyLDJjMCwxLjEtMC45LDItMiwyCgkJCVM3LDkuMSw3LDhDNyw2LjksNy45LDYsOSw2eiIvPgoJCTxwYXRoIGQ9Ik05LDEzYy0yLjY3LDAtOCwxLjM0LTgsNHYzaDE2di0zQzE3LDE0LjM0LDExLjY3LDEzLDksMTN6IE0xNSwxOEgzbDAtMC45OUMzLjIsMTYuMjksNi4zLDE1LDksMTVzNS44LDEuMjksNiwyVjE4eiIvPgoJPC9nPgo8L2c+Cjwvc3ZnPgo=\", label: \"Community\" }))));\n});\n//# sourceMappingURL=Ready.js.map","export default (function (condition, message) {\n if (condition && process.env.NODE_ENV !== 'production') {\n console.warn(message); // eslint-disable-line\n }\n});\n//# sourceMappingURL=warning.js.map","import { transform } from 'inflection';\n/**\n * Returns an array of arguments to use with the translate function for the label of a field.\n * The label will be computed from the resource and source props.\n *\n * Usage:\n * \n * {translate(...getFieldLabelTranslationArgs({ label, resource, source }))}\n * \n *\n * @see useTranslateLabel for a ready-to-use hook\n */\nexport var getFieldLabelTranslationArgs = function (options) {\n if (!options)\n return [''];\n var label = options.label, defaultLabel = options.defaultLabel, resource = options.resource, resourceFromContext = options.resourceFromContext, source = options.source;\n if (typeof label !== 'undefined')\n return [label, { _: label }];\n if (typeof source === 'undefined')\n return [''];\n var _a = getSourceParts(source), sourceWithoutDigits = _a.sourceWithoutDigits, sourceSuffix = _a.sourceSuffix;\n var defaultLabelTranslation = transform(sourceSuffix.replace(/\\./g, ' '), ['underscore', 'humanize']);\n if (resource) {\n return [\n getResourceFieldLabelKey(resource, sourceWithoutDigits),\n { _: defaultLabelTranslation },\n ];\n }\n if (defaultLabel) {\n return [defaultLabel, { _: defaultLabelTranslation }];\n }\n return [\n getResourceFieldLabelKey(resourceFromContext || 'undefined', sourceWithoutDigits),\n { _: defaultLabelTranslation },\n ];\n};\nexport default getFieldLabelTranslationArgs;\nexport var getResourceFieldLabelKey = function (resource, source) {\n return \"resources.\".concat(resource, \".fields.\").concat(source);\n};\n/**\n * Uses the source string to guess a translation message and a default label.\n *\n * @example\n * getSourceParts('pictures') // { sourceWithoutDigits: 'pictures', sourceSuffix: 'pictures' }\n * getSourceParts('pictures.url') // { sourceWithoutDigits: 'pictures.url', sourceSuffix: 'pictures.url' }\n * getSourceParts('pictures.0.url') // { sourceWithoutDigits: 'pictures.url', sourceSuffix: 'url' }\n * getSourceParts('pictures.12.urls.5.protocol') // { sourceWithoutDigits: 'pictures.urls.protocol', sourceSuffix: 'protocol' }\n */\nvar getSourceParts = function (source) {\n // remove digits, e.g. 'book.authors.2.categories.3.identifier.name' => 'book.authors.categories.identifier.name'\n var sourceWithoutDigits = source.replace(/\\.\\d+\\./g, '.');\n // get final part, e.g. 'book.authors.2.categories.3.identifier.name' => 'identifier.name'\n // we're not using a regexp here to avoid code scanning alert \"Polynomial regular expression used on uncontrolled data\"\n var parts = source.split('.');\n var lastPartWithDigits;\n parts.forEach(function (part, index) {\n if (onlyDigits(part)) {\n lastPartWithDigits = index;\n }\n });\n var sourceSuffix = lastPartWithDigits != null\n ? parts.slice(lastPartWithDigits + 1).join('.')\n : source;\n return { sourceWithoutDigits: sourceWithoutDigits, sourceSuffix: sourceSuffix };\n};\n// 48 and 57 are the char codes for \"0\" and \"9\", respectively\nvar onlyDigits = function (s) {\n for (var i = s.length - 1; i >= 0; i--) {\n var d = s.charCodeAt(i);\n if (d < 48 || d > 57)\n return false;\n }\n return true;\n};\n//# sourceMappingURL=getFieldLabelTranslationArgs.js.map","// https://github.com/gregberge/react-merge-refs\nexport function mergeRefs(refs) {\n return function (value) {\n refs.forEach(function (ref) {\n if (typeof ref === 'function') {\n ref(value);\n }\n else if (ref != null) {\n ref.current = value;\n }\n });\n };\n}\n//# sourceMappingURL=mergeRefs.js.map","import * as React from 'react';\nimport { useCallback } from 'react';\n// allow the hook to work in SSR\nvar useLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\n/**\n * Alternative to useCallback that doesn't update the callback when dependencies change\n *\n * @see https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback\n * @see https://github.com/facebook/react/issues/14099#issuecomment-440013892\n */\nexport var useEvent = function (fn) {\n var ref = React.useRef(function () {\n throw new Error('Cannot call an event handler while rendering.');\n });\n useLayoutEffect(function () {\n ref.current = fn;\n });\n return useCallback(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return ref.current.apply(ref, args);\n }, []);\n};\n//# sourceMappingURL=useEvent.js.map","import * as React from 'react';\nimport { useCallback, useRef } from 'react';\nimport debounce from 'lodash/debounce';\nimport { useEvent } from './useEvent';\n// allow the hook to work in SSR\nvar useLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect;\n/**\n * Hook somewhat equivalent to useEvent, but with a debounce\n * Returns a debounced callback which will not change across re-renders unless the\n * callback or delay changes\n * @see https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback\n * @see https://github.com/facebook/react/issues/14099#issuecomment-440013892\n */\nexport var useDebouncedEvent = function (callback, delay) {\n // Create a ref that stores the debounced callback\n var debouncedCallbackRef = useRef(function () {\n throw new Error('Cannot call an event handler while rendering.');\n });\n // Keep a stable ref to the callback (in case it's an inline function for instance)\n var stableCallback = useEvent(callback);\n // Whenever callback or delay changes, we need to update the debounced callback\n useLayoutEffect(function () {\n debouncedCallbackRef.current = debounce(stableCallback, delay);\n }, [stableCallback, delay]);\n // The function returned by useCallback will invoke the debounced callback\n // Its dependencies array is empty, so it never changes across re-renders\n return useCallback(function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return debouncedCallbackRef.current.apply(debouncedCallbackRef, args);\n }, []);\n};\n//# sourceMappingURL=useDebouncedEvent.js.map","import get from 'lodash/get';\nimport { useRecordContext } from '../controller';\n/**\n * A hook that gets the value of a field of the current record.\n * @param params The hook parameters\n * @param params.source The field source\n * @param params.record The record to use. Uses the record from the RecordContext if not provided\n * @param params.defaultValue The value to return when the field value is empty\n * @returns The field value\n *\n * @example\n * const MyField = (props: { source: string }) => {\n * const value = useFieldValue(props);\n * return {value};\n * }\n */\nexport var useFieldValue = function (params) {\n var defaultValue = params.defaultValue, source = params.source;\n // We use the record from the RecordContext and do not rely on the SourceContext on purpose to\n // avoid having the wrong source targeting the record.\n // Indeed, some components may create a sub record context (SimpleFormIterator, TranslatableInputs, etc.). In this case,\n // it they used the SourceContext as well, they would have the wrong source.\n // Inputs needs the SourceContext as they rely on the Form value and you can't have nested forms.\n // Fields needs the RecordContext as they rely on the Record value and you can have nested RecordContext.\n var record = useRecordContext(params);\n return get(record, source, defaultValue);\n};\n//# sourceMappingURL=useFieldValue.js.map","import debounce from 'lodash/debounce';\n/**\n * A version of lodash/debounce that always returns a promise but wait for the debounced function to return to resolve it.\n * @param func The function to debounce\n * @param wait The debounce delay\n * @returns A debounced function that returns a promise\n */\nexport function asyncDebounce(func, wait) {\n var resolveSet = new Set();\n var rejectSet = new Set();\n var debounced = debounce(function (args) {\n func.apply(void 0, args).then(function () {\n var res = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n res[_i] = arguments[_i];\n }\n resolveSet.forEach(function (resolve) { return resolve.apply(void 0, res); });\n })\n .catch(function () {\n var res = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n res[_i] = arguments[_i];\n }\n rejectSet.forEach(function (reject) { return reject.apply(void 0, res); });\n })\n .finally(function () {\n resolveSet.clear();\n rejectSet.clear();\n });\n }, wait);\n return function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return new Promise(function (resolve, reject) {\n resolveSet.add(resolve);\n rejectSet.add(reject);\n debounced(args);\n });\n };\n}\n//# sourceMappingURL=asyncDebounce.js.map","var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nimport { useEffect, useRef } from 'react';\nimport { useEvent } from './useEvent';\n/**\n * Checks if the application code has changed and calls the provided onNewVersionAvailable function when needed.\n *\n * It checks for code update by downloading the provided URL (default to the HTML page) and\n * comparing the hash of the response with the hash of the current page.\n *\n * @param {UseCheckForApplicationUpdateOptions} options The options\n * @param {Function} options.onNewVersionAvailable The function to call when a new version of the application is available.\n * @param {string} options.url Optional. The URL to download to check for code update. Defaults to the current URL.\n * @param {RequestInit} options.fetchOptions Optional. The options passed to fetch function when checking for update.\n * @param {number} options.interval Optional. The interval in milliseconds between two checks. Defaults to 3600000 (1 hour).\n * @param {boolean} options.disabled Optional. Whether the check should be disabled. Defaults to false.\n */\nexport var useCheckForApplicationUpdate = function (options) {\n var _a = options.url, url = _a === void 0 ? window.location.href : _a, fetchOptions = options.fetchOptions, _b = options.interval, delay = _b === void 0 ? ONE_HOUR : _b, onNewVersionAvailableProp = options.onNewVersionAvailable, _c = options.disabled, disabled = _c === void 0 ? process.env.NODE_ENV !== 'production' : _c;\n var currentHash = useRef();\n var onNewVersionAvailable = useEvent(onNewVersionAvailableProp);\n useEffect(function () {\n if (disabled)\n return;\n getHashForUrl(url, fetchOptions).then(function (hash) {\n if (hash != null) {\n currentHash.current = hash;\n }\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [disabled, url, JSON.stringify(fetchOptions)]);\n useEffect(function () {\n if (disabled)\n return;\n var interval = setInterval(function () {\n getHashForUrl(url, fetchOptions)\n .then(function (hash) {\n if (hash != null && currentHash.current !== hash) {\n // Store the latest hash to avoid calling the onNewVersionAvailable function multiple times\n // or when users have closed the notification\n currentHash.current = hash;\n onNewVersionAvailable();\n }\n })\n .catch(function () {\n // Ignore errors to avoid issues when connectivity is lost\n });\n }, delay);\n return function () { return clearInterval(interval); };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n delay,\n onNewVersionAvailable,\n disabled,\n url,\n // eslint-disable-next-line react-hooks/exhaustive-deps\n JSON.stringify(fetchOptions),\n ]);\n};\nvar getHashForUrl = function (url, fetchOptions) { return __awaiter(void 0, void 0, void 0, function () {\n var response, text, e_1;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 3, , 4]);\n return [4 /*yield*/, fetch(url, fetchOptions)];\n case 1:\n response = _a.sent();\n if (!response.ok)\n return [2 /*return*/, null];\n return [4 /*yield*/, response.text()];\n case 2:\n text = _a.sent();\n return [2 /*return*/, hash(text)];\n case 3:\n e_1 = _a.sent();\n return [2 /*return*/, null];\n case 4: return [2 /*return*/];\n }\n });\n}); };\n// Simple hash function, taken from https://stackoverflow.com/a/52171480/3723993, suggested by Copilot\nvar hash = function (value, seed) {\n if (seed === void 0) { seed = 0; }\n var h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;\n for (var i = 0, ch = void 0; i < value.length; i++) {\n ch = value.charCodeAt(i);\n h1 = Math.imul(h1 ^ ch, 2654435761);\n h2 = Math.imul(h2 ^ ch, 1597334677);\n }\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);\n h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);\n h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n return 4294967296 * (2097151 & h2) + (h1 >>> 0);\n};\nvar ONE_HOUR = 1000 * 60 * 60;\n//# sourceMappingURL=useCheckForApplicationUpdate.js.map","import { useState, useEffect } from 'react';\nimport isEqual from 'lodash/isEqual';\nimport { useEvent } from '../util';\nimport { useStoreContext } from './useStoreContext';\n/**\n * Read and write a value from the Store\n *\n * useState-like hook using the global Store for persistence.\n * Each time a store value is changed, all components using this value will be re-rendered.\n *\n * @param {string} key Name of the store key. Separate with dots to namespace, e.g. 'posts.list.columns'.\n * @param {any} defaultValue Default value\n *\n * @return {Object} A value and a setter for the value, in an array - just like for useState()\n *\n * @example\n * import { useStore } from 'react-admin';\n *\n * const PostList = () => {\n * const [density] = useStore('posts.list.density', 'small');\n *\n * return (\n * \n * \n * ...\n * \n * \n * );\n * }\n *\n * // Clicking on this button will trigger a rerender of the PostList!\n * const ChangeDensity: FC = () => {\n * const [density, setDensity] = useStore('posts.list.density', 'small');\n *\n * const changeDensity = (): void => {\n * setDensity(density === 'small' ? 'medium' : 'small');\n * };\n *\n * return (\n * \n * );\n * };\n */\nexport var useStore = function (key, defaultValue) {\n var _a = useStoreContext(), getItem = _a.getItem, setItem = _a.setItem, subscribe = _a.subscribe;\n var _b = useState(function () { return getItem(key, defaultValue); }), value = _b[0], setValue = _b[1];\n // subscribe to changes on this key, and change the state when they happen\n useEffect(function () {\n var storedValue = getItem(key, defaultValue);\n if (!isEqual(value, storedValue)) {\n setValue(storedValue);\n }\n var unsubscribe = subscribe(key, function (newValue) {\n setValue(typeof newValue === 'undefined' ? defaultValue : newValue);\n });\n return function () { return unsubscribe(); };\n }, [key, subscribe, defaultValue, getItem, value]);\n var set = useEvent(function (valueParam, runtimeDefaultValue) {\n var newValue = typeof valueParam === 'function' ? valueParam(value) : valueParam;\n // we only set the value in the Store;\n // the value in the local state will be updated\n // by the useEffect during the next render\n setItem(key, typeof newValue === 'undefined'\n ? typeof runtimeDefaultValue === 'undefined'\n ? defaultValue\n : runtimeDefaultValue\n : newValue);\n });\n return [value, set];\n};\n//# sourceMappingURL=useStore.js.map","import { useCallback } from 'react';\nimport { useStoreContext } from './useStoreContext';\n/**\n * Get a callback to remove an item from the store\n *\n * @example\n * import { useRemoveFromStore } from 'react-admin';\n *\n * const ResetDatagridPrefs = () {\n * const removeItem = useRemoveFromStore();\n *\n * const handleClick = () => {\n * removeItem('datagrid.prefs');\n * };\n *\n * return ;\n * }\n */\nexport var useRemoveFromStore = function (hookTimeKey) {\n var removeItem = useStoreContext().removeItem;\n return useCallback(function (key) {\n if (typeof key === 'undefined' &&\n typeof hookTimeKey === 'undefined') {\n throw new Error('You must provide a key to remove an item from the store');\n }\n // @ts-ignore\n return removeItem(key !== null && key !== void 0 ? key : hookTimeKey);\n }, [removeItem, hookTimeKey]);\n};\n//# sourceMappingURL=useRemoveFromStore.js.map","import { useCallback } from 'react';\nimport { useStoreContext } from './useStoreContext';\n/**\n * Get a callback to remove all item with a certain key prefix from the store\n *\n * @example\n * import { useRemoveItemsFromStore } from 'react-admin';\n *\n * const ResetDatagridPrefs = () {\n * const removeItems = useRemoveItemsFromStore();\n *\n * const handleClick = () => {\n * removeItems('datagrid.prefs');\n * };\n *\n * return ;\n * }\n */\nexport var useRemoveItemsFromStore = function (hookTimeKeyPrefix) {\n var removeItems = useStoreContext().removeItems;\n return useCallback(function (keyPrefix) {\n if (typeof keyPrefix === 'undefined' &&\n typeof hookTimeKeyPrefix === 'undefined') {\n throw new Error('You must provide a key to remove an item from the store');\n }\n // @ts-ignore\n return removeItems(keyPrefix !== null && keyPrefix !== void 0 ? keyPrefix : hookTimeKeyPrefix);\n }, [removeItems, hookTimeKeyPrefix]);\n};\n//# sourceMappingURL=useRemoveItemsFromStore.js.map","import { useStoreContext } from './useStoreContext';\n/**\n * Get a callback to remove all items from the store\n *\n * @example\n * import { useResetStore } from 'react-admin';\n *\n * const ResetPrefs = () {\n * const reset = useResetStore();\n *\n * const handleClick = () => {\n * reset();\n * };\n *\n * return ;\n * }\n */\nexport var useResetStore = function () {\n var reset = useStoreContext().reset;\n return reset;\n};\n//# sourceMappingURL=useResetStore.js.map","import { useCallback, useEffect, useRef } from 'react';\nimport { useLocation, useNavigate } from 'react-router-dom';\nimport { useQueryClient } from '@tanstack/react-query';\nimport useAuthProvider, { defaultAuthParams } from './useAuthProvider';\nimport { useResetStore } from '../store';\nimport { useBasename } from '../routing';\nimport { removeDoubleSlashes } from '../routing/useCreatePath';\n/**\n * Get a callback for calling the authProvider.logout() method,\n * redirect to the login page, and clear the store.\n *\n * @see useAuthProvider\n *\n * @returns {Function} logout callback\n *\n * @example\n *\n * import { useLogout } from 'react-admin';\n *\n * const LogoutButton = () => {\n * const logout = useLogout();\n * const handleClick = () => logout();\n * return ;\n * }\n */\nvar useLogout = function () {\n var authProvider = useAuthProvider();\n var queryClient = useQueryClient();\n var resetStore = useResetStore();\n var navigate = useNavigate();\n // useNavigate forces rerenders on every navigation, even if we don't use the result\n // see https://github.com/remix-run/react-router/issues/7634\n // so we use a ref to bail out of rerenders when we don't need to\n var navigateRef = useRef(navigate);\n var location = useLocation();\n var locationRef = useRef(location);\n var basename = useBasename();\n var loginUrl = removeDoubleSlashes(\"\".concat(basename, \"/\").concat(defaultAuthParams.loginUrl));\n /*\n * We need the current location to pass in the router state\n * so that the login hook knows where to redirect to as next route after login.\n *\n * But if we used the location from useLocation as a dependency of the logout\n * function, it would be rebuilt each time the user changes location.\n * Consequently, that would force a rerender of all components using this hook\n * upon navigation (CoreAdminRouter for example).\n *\n * To avoid that, we store the location in a ref.\n */\n useEffect(function () {\n locationRef.current = location;\n navigateRef.current = navigate;\n }, [location, navigate]);\n var logout = useCallback(function (params, redirectTo, redirectToCurrentLocationAfterLogin) {\n if (params === void 0) { params = {}; }\n if (redirectTo === void 0) { redirectTo = loginUrl; }\n if (redirectToCurrentLocationAfterLogin === void 0) { redirectToCurrentLocationAfterLogin = true; }\n if (authProvider) {\n return authProvider\n .logout(params)\n .then(function (redirectToFromProvider) {\n if (redirectToFromProvider === false ||\n redirectTo === false) {\n resetStore();\n queryClient.clear();\n // do not redirect\n return;\n }\n var finalRedirectTo = redirectToFromProvider || redirectTo;\n if (finalRedirectTo === null || finalRedirectTo === void 0 ? void 0 : finalRedirectTo.startsWith('http')) {\n // absolute link (e.g. https://my.oidc.server/login)\n resetStore();\n queryClient.clear();\n window.location.href = finalRedirectTo;\n return finalRedirectTo;\n }\n // redirectTo is an internal location that may contain a query string, e.g. '/login?foo=bar'\n // we must split it to pass a structured location to navigate()\n var redirectToParts = finalRedirectTo.split('?');\n var newLocation = {\n pathname: redirectToParts[0],\n };\n var newLocationOptions = {};\n if (redirectToCurrentLocationAfterLogin &&\n locationRef.current &&\n locationRef.current.pathname) {\n newLocationOptions = {\n state: {\n nextPathname: locationRef.current.pathname,\n nextSearch: locationRef.current.search,\n },\n };\n }\n if (redirectToParts[1]) {\n newLocation.search = redirectToParts[1];\n }\n navigateRef.current(newLocation, newLocationOptions);\n resetStore();\n queryClient.clear();\n return redirectToFromProvider;\n });\n }\n else {\n navigateRef.current({\n pathname: loginUrl,\n }, {\n state: {\n nextPathname: locationRef.current &&\n locationRef.current.pathname,\n },\n });\n resetStore();\n queryClient.clear();\n return Promise.resolve();\n }\n }, [authProvider, resetStore, loginUrl, queryClient]);\n return logout;\n};\nexport default useLogout;\n//# sourceMappingURL=useLogout.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useEffect, useMemo } from 'react';\nimport { useQuery, } from '@tanstack/react-query';\nimport useAuthProvider, { defaultAuthParams } from './useAuthProvider';\nimport useLogout from './useLogout';\nimport { removeDoubleSlashes, useBasename } from '../routing';\nimport { useNotify } from '../notification';\nimport { useEvent } from '../util';\nvar emptyParams = {};\n/**\n * Hook for getting the authentication status\n *\n * Calls the authProvider.checkAuth() method asynchronously.\n *\n * The return value updates according to the authProvider request state:\n *\n * - isPending: true just after mount, while the authProvider is being called. false once the authProvider has answered.\n * - authenticated: true while loading. then true or false depending on the authProvider response.\n *\n * To avoid rendering a component and force waiting for the authProvider response, use the useAuthState() hook\n * instead of the useAuthenticated() hook.\n *\n * You can render different content depending on the authenticated status.\n *\n * @see useAuthenticated()\n *\n * @param {Object} params Any params you want to pass to the authProvider\n *\n * @param {Boolean} logoutOnFailure: Optional. Whether the user should be logged out if the authProvider fails to authenticate them. False by default.\n *\n * @returns The current auth check state. Destructure as { authenticated, error, isPending }.\n *\n * @example\n * import { useAuthState, Loading } from 'react-admin';\n *\n * const MyPage = () => {\n * const { isPending, authenticated } = useAuthState();\n * if (isPending) {\n * return ;\n * }\n * if (authenticated) {\n * return ;\n * }\n * return ;\n * };\n */\nvar useAuthState = function (params, logoutOnFailure, queryOptions) {\n if (params === void 0) { params = emptyParams; }\n if (logoutOnFailure === void 0) { logoutOnFailure = false; }\n if (queryOptions === void 0) { queryOptions = emptyParams; }\n var authProvider = useAuthProvider();\n var logout = useLogout();\n var basename = useBasename();\n var notify = useNotify();\n var onSuccess = queryOptions.onSuccess, onError = queryOptions.onError, onSettled = queryOptions.onSettled, options = __rest(queryOptions, [\"onSuccess\", \"onError\", \"onSettled\"]);\n var queryResult = useQuery(__assign({ queryKey: ['auth', 'checkAuth', params], queryFn: function (_a) {\n var signal = _a.signal;\n // The authProvider is optional in react-admin\n if (!authProvider) {\n return true;\n }\n return authProvider\n .checkAuth(__assign(__assign({}, params), { signal: signal }))\n .then(function () { return true; })\n .catch(function (error) {\n // This is necessary because react-query requires the error to be defined\n if (error != null) {\n throw error;\n }\n throw new Error();\n });\n }, retry: false }, options));\n var onSuccessEvent = useEvent(onSuccess !== null && onSuccess !== void 0 ? onSuccess : noop);\n var onSettledEvent = useEvent(onSettled !== null && onSettled !== void 0 ? onSettled : noop);\n var onErrorEvent = useEvent(onError !== null && onError !== void 0 ? onError : (function (error) {\n if (!logoutOnFailure)\n return;\n var loginUrl = removeDoubleSlashes(\"\".concat(basename, \"/\").concat(defaultAuthParams.loginUrl));\n logout({}, error && error.redirectTo != null\n ? error.redirectTo\n : loginUrl);\n var shouldSkipNotify = error && error.message === false;\n !shouldSkipNotify &&\n notify(getErrorMessage(error, 'ra.auth.auth_check_error'), {\n type: 'error',\n });\n }));\n useEffect(function () {\n if (queryResult.data === undefined || queryResult.isFetching)\n return;\n if (queryOptions.enabled === false)\n return;\n onSuccessEvent(queryResult.data);\n }, [\n onSuccessEvent,\n queryResult.data,\n queryResult.isFetching,\n queryOptions.enabled,\n ]);\n useEffect(function () {\n if (queryResult.error == null || queryResult.isFetching)\n return;\n if (queryOptions.enabled === false)\n return;\n onErrorEvent(queryResult.error);\n }, [\n onErrorEvent,\n queryResult.error,\n queryResult.isFetching,\n queryOptions.enabled,\n ]);\n useEffect(function () {\n if (queryResult.status === 'pending' || queryResult.isFetching)\n return;\n if (queryOptions.enabled === false)\n return;\n onSettledEvent(queryResult.data, queryResult.error);\n }, [\n onSettledEvent,\n queryResult.data,\n queryResult.error,\n queryResult.status,\n queryResult.isFetching,\n queryOptions.enabled,\n ]);\n var result = useMemo(function () {\n return __assign(__assign({}, queryResult), { authenticated: queryResult.error ? false : queryResult.data });\n }, [queryResult]);\n return authProvider != null\n ? result\n : noAuthProviderQueryResult;\n};\nexport default useAuthState;\nvar getErrorMessage = function (error, defaultMessage) {\n return typeof error === 'string'\n ? error\n : typeof error === 'undefined' || !error.message\n ? defaultMessage\n : error.message;\n};\nvar noop = function () { };\nvar noAuthProviderQueryResult = {\n authenticated: true,\n data: true,\n dataUpdatedAt: 0,\n error: null,\n errorUpdatedAt: 0,\n errorUpdateCount: 0,\n failureCount: 0,\n failureReason: null,\n fetchStatus: 'idle',\n isError: false,\n isInitialLoading: false,\n isLoading: false,\n isLoadingError: false,\n isFetched: true,\n isFetchedAfterMount: true,\n isFetching: false,\n isPaused: false,\n isPlaceholderData: false,\n isPending: false,\n isRefetchError: false,\n isRefetching: false,\n isStale: false,\n isSuccess: true,\n status: 'success',\n refetch: function () { return Promise.resolve(noAuthProviderQueryResult); },\n};\n//# sourceMappingURL=useAuthState.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport useAuthState from './useAuthState';\n/**\n * Restrict access to authenticated users.\n * Redirect anonymous users to the login page.\n *\n * Use it in your custom page components to require\n * authentication.\n *\n * You can set additional `authParams` at will if your authProvider\n * requires it.\n *\n * @example\n * import { Admin, CustomRoutes, useAuthenticated } from 'react-admin';\n *\n * const FooPage = () => {\n * const { isPending } = useAuthenticated();\n * if (isPending) return null;\n * return ;\n * }\n *\n * const customRoutes = [\n * } />\n * ];\n *\n * const App = () => (\n * \n * {customRoutes}\n * \n * );\n */\nexport var useAuthenticated = function (_a) {\n if (_a === void 0) { _a = {}; }\n var params = _a.params, _b = _a.logoutOnFailure, logoutOnFailure = _b === void 0 ? true : _b, options = __rest(_a, [\"params\", \"logoutOnFailure\"]);\n return useAuthState(params !== null && params !== void 0 ? params : emptyParams, logoutOnFailure, options);\n};\nvar emptyParams = {};\n//# sourceMappingURL=useAuthenticated.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport * as React from 'react';\nimport { Children, createElement } from 'react';\nimport warning from '../util/warning';\nimport { useAuthenticated } from './useAuthenticated';\nimport usePermissions from './usePermissions';\nvar isEmptyChildren = function (children) { return Children.count(children) === 0; };\n/**\n * After checking that the user is authenticated,\n * retrieves the user's permissions for a specific context.\n *\n * Useful for Route components ; used internally by Resource.\n * Use it to decorate your custom page components to require\n * a custom role. It will pass the permissions as a prop to your\n * component.\n *\n * You can set additional `authParams` at will if your authProvider\n * requires it.\n *\n * @example\n * import { Admin, CustomRoutes, WithPermissions } from 'react-admin';\n *\n * const Foo = ({ permissions }) => (\n * {permissions === 'admin' ?

Sensitive data

: null}\n *

Not sensitive data

\n * );\n *\n * const customRoutes = [\n * }\n * />\n * } />\n * ];\n * const App = () => (\n * \n * {customRoutes}\n * \n * );\n */\nvar WithPermissions = function (props) {\n var authParams = props.authParams, children = props.children, render = props.render, component = props.component, _a = props.loading, Loading = _a === void 0 ? null : _a, staticContext = props.staticContext, rest = __rest(props, [\"authParams\", \"children\", \"render\", \"component\", \"loading\", \"staticContext\"]);\n warning((render && children && !isEmptyChildren(children)) ||\n (render && component) ||\n (component && children && !isEmptyChildren(children)), 'You should only use one of the `component`, `render` and `children` props in ');\n var isAuthenticationPending = useAuthenticated(authParams).isPending;\n var _b = usePermissions(authParams, {\n enabled: !isAuthenticationPending,\n }), permissions = _b.permissions, isPendingPermissions = _b.isPending;\n // We must check both pending states here as if the authProvider does not implement getPermissions, isPendingPermissions will always be false\n if (isAuthenticationPending || isPendingPermissions) {\n return Loading ? React.createElement(Loading, null) : null;\n }\n if (component) {\n return createElement(component, __assign({ permissions: permissions }, rest));\n }\n // @deprecated\n if (render) {\n return render(__assign({ permissions: permissions }, rest));\n }\n // @deprecated\n if (children) {\n return children(__assign({ permissions: permissions }, rest));\n }\n};\nexport default WithPermissions;\n//# sourceMappingURL=WithPermissions.js.map","import { useCallback } from 'react';\nimport { useLocation, useNavigate } from 'react-router-dom';\nimport { useNotificationContext } from '../notification';\nimport { useBasename } from '../routing';\nimport useAuthProvider, { defaultAuthParams } from './useAuthProvider';\nimport { removeDoubleSlashes } from '../routing/useCreatePath';\nimport { useQueryClient } from '@tanstack/react-query';\n/**\n * Get a callback for calling the authProvider.login() method\n * and redirect to the previous authenticated page (or the home page) on success.\n *\n * @see useAuthProvider\n *\n * @returns {Function} login callback\n *\n * @example\n *\n * import { useLogin } from 'react-admin';\n *\n * const LoginButton = () => {\n * const [loading, setLoading] = useState(false);\n * const login = useLogin();\n * const handleClick = {\n * setLoading(true);\n * login({ username: 'john', password: 'p@ssw0rd' }, '/posts')\n * .then(() => setLoading(false));\n * }\n * return ;\n * }\n */\nvar useLogin = function () {\n var authProvider = useAuthProvider();\n var queryClient = useQueryClient();\n var location = useLocation();\n var locationState = location.state;\n var navigate = useNavigate();\n var basename = useBasename();\n var resetNotifications = useNotificationContext().resetNotifications;\n var nextPathName = locationState && locationState.nextPathname;\n var nextSearch = locationState && locationState.nextSearch;\n var afterLoginUrl = removeDoubleSlashes(\"\".concat(basename, \"/\").concat(defaultAuthParams.afterLoginUrl));\n var login = useCallback(function (params, pathName) {\n if (params === void 0) { params = {}; }\n if (authProvider) {\n return authProvider.login(params).then(function (ret) {\n resetNotifications();\n queryClient.invalidateQueries({\n queryKey: ['auth', 'getPermissions'],\n });\n if (ret && ret.hasOwnProperty('redirectTo')) {\n if (ret) {\n navigate(ret.redirectTo);\n }\n }\n else {\n var redirectUrl = pathName\n ? pathName\n : nextPathName + nextSearch || afterLoginUrl;\n navigate(redirectUrl);\n }\n return ret;\n });\n }\n else {\n resetNotifications();\n navigate(afterLoginUrl);\n return Promise.resolve();\n }\n }, [\n authProvider,\n queryClient,\n navigate,\n nextPathName,\n nextSearch,\n resetNotifications,\n afterLoginUrl,\n ]);\n return login;\n};\nexport default useLogin;\n//# sourceMappingURL=useLogin.js.map","export var AUTH_LOGIN = 'AUTH_LOGIN';\nexport var AUTH_CHECK = 'AUTH_CHECK';\nexport var AUTH_ERROR = 'AUTH_ERROR';\nexport var AUTH_LOGOUT = 'AUTH_LOGOUT';\nexport var AUTH_GET_PERMISSIONS = 'AUTH_GET_PERMISSIONS';\n//# sourceMappingURL=types.js.map","import { AUTH_LOGIN, AUTH_LOGOUT, AUTH_CHECK, AUTH_ERROR, AUTH_GET_PERMISSIONS, } from './types';\n/**\n * Turn a function-based authProvider to an object-based one\n *\n * Allows using legacy authProviders transparently.\n *\n * @param {Function} legacyAuthProvider A legacy authProvider (type, params) => Promise\n *\n * @returns {Object} An authProvider that react-admin can use\n */\nexport default (function (legacyAuthProvider) {\n var authProvider = function () {\n var args = [];\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n return legacyAuthProvider.apply(null, args);\n };\n authProvider.login = function (params) { return legacyAuthProvider(AUTH_LOGIN, params); };\n authProvider.logout = function (params) { return legacyAuthProvider(AUTH_LOGOUT, params); };\n authProvider.checkAuth = function (params) { return legacyAuthProvider(AUTH_CHECK, params); };\n authProvider.checkError = function (error) { return legacyAuthProvider(AUTH_ERROR, error); };\n authProvider.getPermissions = function (params) {\n return legacyAuthProvider(AUTH_GET_PERMISSIONS, params);\n };\n return authProvider;\n});\n//# sourceMappingURL=convertLegacyAuthProvider.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nimport { useMemo } from 'react';\nimport { useQuery, } from '@tanstack/react-query';\nimport useAuthProvider from './useAuthProvider';\nimport { useResourceContext } from '../core';\nimport { useRecordContext } from '../controller';\n/**\n * A hook that calls the authProvider.canAccess() method using react-query for a provided resource and action (and optionally a record).\n *\n * The return value updates according to the request state:\n *\n * - start: { isPending: true }\n * - success: { canAccess: true | false, isPending: false }\n * - error: { error: [error from provider], isPending: false }\n *\n * Useful to enable or disable features based on users permissions.\n *\n * @param {Object} params Any params you want to pass to the authProvider\n * @param {string} params.resource The resource to check access for\n * @param {string} params.action The action to check access for\n * @param {Object} params.record Optional. The record to check access for\n *\n * @returns Return the react-query result and a canAccess property which is a boolean indicating the access status\n *\n * @example\n * import { useCanAccess } from 'react-admin';\n *\n * const PostDetail = () => {\n * const { isPending, canAccess, error } = useCanAccess({\n * resource: 'posts',\n * action: 'read',\n * });\n * if (isPending || !canAccess) {\n * return null;\n * }\n * if (error) {\n * return
{error.message}
;\n * }\n * return ;\n * };\n */\nexport var useCanAccess = function (params) {\n var authProvider = useAuthProvider();\n var resource = useResourceContext(params);\n if (!resource) {\n throw new Error('useCanAccess must be used inside a component or provide a resource prop');\n }\n var record = useRecordContext(params);\n var authProviderHasCanAccess = !!(authProvider === null || authProvider === void 0 ? void 0 : authProvider.canAccess);\n var queryResult = useQuery(__assign({ queryKey: ['auth', 'canAccess', __assign(__assign({}, params), { record: record, resource: resource })], queryFn: function (_a) {\n var signal = _a.signal;\n return __awaiter(void 0, void 0, void 0, function () {\n return __generator(this, function (_b) {\n if (!authProvider || !authProvider.canAccess) {\n return [2 /*return*/, true];\n }\n return [2 /*return*/, authProvider.canAccess(__assign(__assign({}, params), { record: record, resource: resource, signal: authProvider.supportAbortSignal ? signal : undefined }))];\n });\n });\n }, enabled: authProviderHasCanAccess }, params));\n var result = useMemo(function () {\n // Don't check for the authProvider or authProvider.canAccess method in the useMemo\n // to avoid unnecessary re-renders\n return __assign(__assign({}, queryResult), { canAccess: queryResult.data });\n }, [queryResult]);\n return authProviderHasCanAccess\n ? result\n : emptyQueryObserverResult;\n};\nvar emptyQueryObserverResult = {\n canAccess: true,\n data: true,\n dataUpdatedAt: 0,\n error: null,\n errorUpdatedAt: 0,\n errorUpdateCount: 0,\n failureCount: 0,\n failureReason: null,\n fetchStatus: 'idle',\n isError: false,\n isInitialLoading: false,\n isLoading: false,\n isLoadingError: false,\n isFetched: true,\n isFetchedAfterMount: true,\n isFetching: false,\n isPaused: false,\n isPlaceholderData: false,\n isPending: false,\n isRefetchError: false,\n isRefetching: false,\n isStale: false,\n isSuccess: true,\n status: 'success',\n refetch: function () { return Promise.resolve(emptyQueryObserverResult); },\n};\n//# sourceMappingURL=useCanAccess.js.map","import { useEffect } from 'react';\nimport useLogout from './useLogout';\n/**\n * Log the user out and redirect them to login.\n *\n * To be used as a catch-all route for anonymous users in a secure app.\n *\n * @see CoreAdminRoutes\n */\nexport var LogoutOnMount = function () {\n var logout = useLogout();\n useEffect(function () {\n logout();\n }, [logout]);\n return null;\n};\n//# sourceMappingURL=LogoutOnMount.js.map","import { useCallback } from 'react';\nimport useAuthProvider, { defaultAuthParams } from './useAuthProvider';\nimport useLogout from './useLogout';\nimport { useNotify } from '../notification';\nimport { useBasename } from '../routing';\nimport { removeDoubleSlashes } from '../routing/useCreatePath';\n/**\n * Get a callback for calling the authProvider.checkAuth() method.\n * In case of rejection, redirects to the login page, displays a notification,\n * and throws an error.\n *\n * This is a low level hook. See those more specialized hooks\n * for common authentication tasks, based on useCheckAuth.\n *\n * @see useAuthenticated\n * @see useAuthState\n *\n * @returns {Function} checkAuth callback\n *\n * @example\n *\n * import { useCheckAuth } from 'react-admin';\n *\n * const MyProtectedPage = () => {\n * const checkAuth = useCheckAuth();\n * useEffect(() => {\n * checkAuth().catch(() => {});\n * }, []);\n * return

Private content: EZAEZEZAET

\n * } // tip: use useAuthenticated() hook instead\n *\n * const MyPage = () => {\n * const checkAuth = useCheckAuth();\n * const [authenticated, setAuthenticated] = useState(true); // optimistic auth\n * useEffect(() => {\n * checkAuth({}, false)\n * .then(() => setAuthenticated(true))\n * .catch(() => setAuthenticated(false));\n * }, []);\n * return authenticated ? : ;\n * } // tip: use useAuthState() hook instead\n */\nexport var useCheckAuth = function () {\n var authProvider = useAuthProvider();\n var notify = useNotify();\n var logout = useLogout();\n var basename = useBasename();\n var loginUrl = removeDoubleSlashes(\"\".concat(basename, \"/\").concat(defaultAuthParams.loginUrl));\n var checkAuth = useCallback(function (params, logoutOnFailure, redirectTo) {\n if (params === void 0) { params = {}; }\n if (logoutOnFailure === void 0) { logoutOnFailure = true; }\n if (redirectTo === void 0) { redirectTo = loginUrl; }\n return authProvider\n ? authProvider.checkAuth(params).catch(function (error) {\n if (logoutOnFailure) {\n logout({}, error && error.redirectTo != null\n ? error.redirectTo\n : redirectTo);\n var shouldSkipNotify = error && error.message === false;\n !shouldSkipNotify &&\n notify(getErrorMessage(error, 'ra.auth.auth_check_error'), { type: 'error' });\n }\n throw error;\n })\n : checkAuthWithoutAuthProvider();\n }, [authProvider, logout, notify, loginUrl]);\n return checkAuth;\n};\nvar checkAuthWithoutAuthProvider = function () { return Promise.resolve(); };\nvar getErrorMessage = function (error, defaultMessage) {\n return typeof error === 'string'\n ? error\n : typeof error === 'undefined' || !error.message\n ? defaultMessage\n : error.message;\n};\n//# sourceMappingURL=useCheckAuth.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n};\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useEffect, useMemo } from 'react';\nimport { useQuery, } from '@tanstack/react-query';\nimport useAuthProvider from './useAuthProvider';\nimport { useEvent } from '../util';\nvar defaultIdentity = {\n id: '',\n};\nvar defaultQueryParams = {\n staleTime: 5 * 60 * 1000,\n};\n/**\n * Return the current user identity by calling authProvider.getIdentity() on mount\n *\n * The return value updates according to the call state:\n *\n * - mount: { isPending: true }\n * - success: { identity, refetch: () => {}, isPending: false }\n * - error: { error: Error, isPending: false }\n *\n * The implementation is left to the authProvider.\n *\n * @returns The current user identity. Destructure as { isPending, identity, error, refetch }.\n *\n * @example\n * import { useGetIdentity, useGetOne } from 'react-admin';\n *\n * const PostDetail = ({ id }) => {\n * const { data: post, isPending: postLoading } = useGetOne('posts', { id });\n * const { identity, isPending: identityLoading } = useGetIdentity();\n * if (postLoading || identityLoading) return <>Loading...;\n * if (!post.lockedBy || post.lockedBy === identity.id) {\n * // post isn't locked, or is locked by me\n * return \n * } else {\n * // post is locked by someone else and cannot be edited\n * return \n * }\n * }\n */\nexport var useGetIdentity = function (options) {\n if (options === void 0) { options = defaultQueryParams; }\n var authProvider = useAuthProvider();\n var onSuccess = options.onSuccess, onError = options.onError, onSettled = options.onSettled, queryOptions = __rest(options, [\"onSuccess\", \"onError\", \"onSettled\"]);\n var result = useQuery(__assign({ queryKey: ['auth', 'getIdentity'], queryFn: function (_a) {\n var signal = _a.signal;\n return __awaiter(void 0, void 0, void 0, function () {\n return __generator(this, function (_b) {\n if (authProvider &&\n typeof authProvider.getIdentity === 'function') {\n return [2 /*return*/, authProvider.getIdentity({ signal: signal })];\n }\n else {\n return [2 /*return*/, defaultIdentity];\n }\n return [2 /*return*/];\n });\n });\n } }, queryOptions));\n var onSuccessEvent = useEvent(onSuccess !== null && onSuccess !== void 0 ? onSuccess : noop);\n var onErrorEvent = useEvent(onError !== null && onError !== void 0 ? onError : noop);\n var onSettledEvent = useEvent(onSettled !== null && onSettled !== void 0 ? onSettled : noop);\n useEffect(function () {\n if (result.data === undefined || result.isFetching)\n return;\n onSuccessEvent(result.data);\n }, [onSuccessEvent, result.data, result.isFetching]);\n useEffect(function () {\n if (result.error == null || result.isFetching)\n return;\n onErrorEvent(result.error);\n }, [onErrorEvent, result.error, result.isFetching]);\n useEffect(function () {\n if (result.status === 'pending' || result.isFetching)\n return;\n onSettledEvent(result.data, result.error);\n }, [\n onSettledEvent,\n result.data,\n result.error,\n result.status,\n result.isFetching,\n ]);\n return useMemo(function () { return (__assign(__assign({}, result), { identity: result.data })); }, [result]);\n};\nexport default useGetIdentity;\nvar noop = function () { };\n//# sourceMappingURL=useGetIdentity.js.map","var __assign = (this && this.__assign) || function () {\n __assign = Object.assign || function(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))\n t[p] = s[p];\n }\n return t;\n };\n return __assign.apply(this, arguments);\n};\nvar __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useEffect } from 'react';\nimport { useQuery } from '@tanstack/react-query';\nimport { useLocation } from 'react-router';\nimport { useRedirect } from '../routing';\nimport useAuthProvider from './useAuthProvider';\nimport { useEvent } from '../util';\n/**\n * This hook calls the `authProvider.handleCallback()` method on mount. This is meant to be used in a route called\n * by an external authentication service (e.g. Auth0) after the user has logged in.\n * By default, it redirects to application home page upon success, or to the `redirectTo` location returned by `authProvider. handleCallback`.\n *\n * @returns An object containing { isPending, data, error, refetch }.\n */\nexport var useHandleAuthCallback = function (options) {\n var authProvider = useAuthProvider();\n var redirect = useRedirect();\n var location = useLocation();\n var locationState = location.state;\n var nextPathName = locationState && locationState.nextPathname;\n var nextSearch = locationState && locationState.nextSearch;\n var defaultRedirectUrl = nextPathName ? nextPathName + nextSearch : '/';\n var _a = options !== null && options !== void 0 ? options : {}, onSuccess = _a.onSuccess, onError = _a.onError, onSettled = _a.onSettled, queryOptions = __rest(_a, [\"onSuccess\", \"onError\", \"onSettled\"]);\n var handleCallbackPromise;\n var queryResult = useQuery(__assign({ queryKey: ['auth', 'handleCallback'], queryFn: function (_a) {\n var signal = _a.signal;\n if (!handleCallbackPromise) {\n handleCallbackPromise =\n authProvider &&\n typeof authProvider.handleCallback === 'function'\n ? authProvider\n .handleCallback({ signal: signal })\n .then(function (result) { return result !== null && result !== void 0 ? result : null; })\n : Promise.resolve();\n }\n return handleCallbackPromise;\n }, retry: false }, queryOptions));\n var onSuccessEvent = useEvent(onSuccess !== null && onSuccess !== void 0 ? onSuccess : (function (data) {\n var _a;\n // AuthProviders relying on a third party services redirect back to the app can't\n // use the location state to store the path on which the user was before the login.\n // So we support a fallback on the localStorage.\n var previousLocation = localStorage.getItem(PreviousLocationStorageKey);\n var redirectTo = (_a = data === null || data === void 0 ? void 0 : data.redirectTo) !== null && _a !== void 0 ? _a : previousLocation;\n if (redirectTo === false) {\n return;\n }\n redirect(redirectTo !== null && redirectTo !== void 0 ? redirectTo : defaultRedirectUrl);\n }));\n var onErrorEvent = useEvent(onError !== null && onError !== void 0 ? onError : noop);\n var onSettledEvent = useEvent(onSettled !== null && onSettled !== void 0 ? onSettled : noop);\n useEffect(function () {\n if (queryResult.error == null || queryResult.isFetching)\n return;\n onErrorEvent(queryResult.error);\n }, [onErrorEvent, queryResult.error, queryResult.isFetching]);\n useEffect(function () {\n if (queryResult.data === undefined || queryResult.isFetching)\n return;\n onSuccessEvent(queryResult.data);\n }, [onSuccessEvent, queryResult.data, queryResult.isFetching]);\n useEffect(function () {\n if (queryResult.status === 'pending' || queryResult.isFetching)\n return;\n onSettledEvent(queryResult.data, queryResult.error);\n }, [\n onSettledEvent,\n queryResult.data,\n queryResult.error,\n queryResult.status,\n queryResult.isFetching,\n ]);\n return queryResult;\n};\n/**\n * Key used to store the previous location in localStorage.\n * Used by the useHandleAuthCallback hook to redirect the user to their previous location after a successful login.\n */\nexport var PreviousLocationStorageKey = '@react-admin/nextPathname';\nvar noop = function () { };\n//# sourceMappingURL=useHandleAuthCallback.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useQueryClient } from '@tanstack/react-query';\nimport { useResourceContext } from '../core';\nimport useAuthProvider from './useAuthProvider';\n/**\n * A hook that returns true if the authProvider is currently checking the authentication status or the user's access rights.\n * @param params\n * @param params.action The action to check access for\n * @param params.resource The resource to check access for (optional). Defaults to the resource of the current ResourceContext.\n * @returns {boolean} true if the authProvider is currently checking the authentication status or the user's access rights, false otherwise.\n */\nexport var useIsAuthPending = function (params) {\n var action = params.action, props = __rest(params, [\"action\"]);\n var queryClient = useQueryClient();\n var authProvider = useAuthProvider();\n var resource = useResourceContext(props);\n if (!authProvider) {\n return false;\n }\n var authQueryState = queryClient.getQueryState(['auth', 'checkAuth', {}]);\n var canAccessQueryState = queryClient.getQueryState([\n 'auth',\n 'canAccess',\n { action: action, resource: resource },\n ]);\n if ((authQueryState === null || authQueryState === void 0 ? void 0 : authQueryState.status) === 'pending' ||\n (authProvider.canAccess && (canAccessQueryState === null || canAccessQueryState === void 0 ? void 0 : canAccessQueryState.status) === 'pending')) {\n return true;\n }\n return false;\n};\n//# sourceMappingURL=useIsAuthPending.js.map","var __rest = (this && this.__rest) || function (s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n};\nimport { useEffect } from 'react';\nimport { useNavigate } from 'react-router';\nimport { useCanAccess, } from './useCanAccess';\nimport { useBasename } from '../routing';\n/**\n * A hook that calls the authProvider.canAccess() method for a provided resource and action (and optionally a record).\n * It redirects to the /access-denied page if the user doesn't have the required permissions.\n * It redirects to the /authentication-error page if the authProvider.canAccess throws an error.\n *\n * The return value updates according to the request state:\n *\n * - start: { isPending: true }\n * - success: { isPending: false }\n * - error: { error: [error from provider], isPending: false }\n *\n * Useful to enable or disable features based on users permissions.\n *\n * @param {Object} params Any params you want to pass to the authProvider\n * @param {string} params.resource The resource to check access for\n * @param {string} params.action The action to check access for\n * @param {Object} params.record Optional. The record to check access for\n *\n * @returns Return the react-query result.\n *\n * @example\n * import { useRequireAccess } from 'react-admin';\n *\n * const PostDetail = () => {\n * const { isPending } = useRequireAccess({\n * resource: 'posts',\n * action: 'read',\n * });\n * if (isPending) {\n * return null;\n * }\n *\n * return ;\n * };\n */\nexport var useRequireAccess = function (params) {\n var _a = useCanAccess(params), canAccess = _a.canAccess, data = _a.data, error = _a.error, rest = __rest(_a, [\"canAccess\", \"data\", \"error\"]);\n var navigate = useNavigate();\n var basename = useBasename();\n useEffect(function () {\n if (rest.isPending)\n return;\n if (canAccess === false) {\n navigate(\"\".concat(basename, \"/access-denied\"));\n }\n }, [basename, canAccess, navigate, rest.isPending]);\n useEffect(function () {\n if (error) {\n navigate(\"\".concat(basename, \"/authentication-error\"));\n }\n }, [basename, navigate, error]);\n return rest;\n};\n//# sourceMappingURL=useRequireAccess.js.map","import * as React from 'react';\nimport { createContext, useContext } from 'react';\nexport var PreferenceKeyContext = createContext('');\nexport var PreferenceKeyContextProvider = function (_a) {\n var _b = _a.value, value = _b === void 0 ? '' : _b, children = _a.children;\n return (React.createElement(PreferenceKeyContext.Provider, { value: value }, children));\n};\nexport var usePreferenceKey = function () {\n return useContext(PreferenceKeyContext);\n};\n//# sourceMappingURL=PreferenceKeyContext.js.map","import { useStore } from '../store/useStore';\nimport { usePreferenceKey } from './PreferenceKeyContext';\n/**\n * Get a preference value from the store\n *\n * Relies on the store, using a key namespaced with the preference key from the PreferenceKeyContext\n * @example\n *\n * // when used inside a PreferenceKeyContext of value 'my-app'\n * const [theme, setTheme] = usePreference('theme', 'light');\n * // this is equivalent to\n * const [theme, setTheme] = useStore('my-app.theme', 'light');\n */\nexport var usePreference = function (key, defaultValue) {\n var preferenceKey = usePreferenceKey();\n if (!preferenceKey) {\n throw new Error(\"usePreference cannot be used outside of a Configurable component. Did you forget to wrap your component with ? If you don't want to use Configurable, you can use the useStore hook instead.\");\n }\n return useStore(preferenceKey && key ? \"\".concat(preferenceKey, \".\").concat(key) : preferenceKey !== null && preferenceKey !== void 0 ? preferenceKey : key, defaultValue);\n};\n//# sourceMappingURL=usePreference.js.map","import { useContext } from 'react';\nimport { PreferencesEditorContext, } from './PreferencesEditorContext';\nexport var usePreferencesEditor = function () {\n var context = useContext(PreferencesEditorContext);\n if (!context) {\n throw new Error('usePreferencesEditor must be used within a PreferencesEditorContextProvider');\n }\n return context;\n};\n//# sourceMappingURL=usePreferencesEditor.js.map","var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n};\nimport { useState, useEffect } from 'react';\nimport { usePreference } from './usePreference';\n/**\n * Get the props for a preference input that changes the value on blur\n *\n * Relies on `usePreference`, so it's using the PreferenceKeyContext\n *\n * @example\n * const FontSizePreferenceInput = () => {\n * const field = usePreferenceInput('ui.font.size', 10);\n * return (\n *
\n * \n * \n *
\n * );\n * }\n */\nexport var usePreferenceInput = function (key, defaultValue) {\n var _a = usePreference(key, defaultValue), valueFromStore = _a[0], setValueFromStore = _a[1];\n var _b = useState(valueFromStore), value = _b[0], setValue = _b[1];\n useEffect(function () {\n setValue(valueFromStore || defaultValue);\n }, [valueFromStore, defaultValue]);\n var onChange = function (event) {\n setValue(event.target.value === '' ? defaultValue : event.target.value);\n };\n var onBlur = function () {\n setValueFromStore(value);\n };\n var onKeyDown = function (event) {\n var _a;\n if (event.key === 'Enter') {\n setValueFromStore(value);\n var form = event.target.form;\n if (form) {\n var index = __spreadArray([], form, true).indexOf(event.target);\n (_a = form.elements[index + 1]) === null || _a === void 0 ? void 0 : _a.focus();\n }\n event.preventDefault();\n }\n };\n return { value: value, onChange: onChange, onBlur: onBlur, onKeyDown: onKeyDown };\n};\n//# sourceMappingURL=usePreferenceInput.js.map","import { useEffect } from 'react';\nimport { usePreferencesEditor } from './usePreferencesEditor';\n/**\n * Set inspector title on mount\n *\n * @example\n * useSetInspectorTitle('Datagrid');\n */\nexport var useSetInspectorTitle = function (title, options) {\n var preferencesEditorContext = usePreferencesEditor();\n if (!preferencesEditorContext) {\n throw new Error('useSetInspectorTitle cannot be called outside of a PreferencesEditorContext');\n }\n var setTitle = preferencesEditorContext.setTitle;\n useEffect(function () {\n setTitle(title, options);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [title, JSON.stringify(options), setTitle]);\n};\n//# sourceMappingURL=useSetInspectorTitle.js.map","const common = {\n black: '#000',\n white: '#fff'\n};\nexport default common;","const red = {\n 50: '#ffebee',\n 100: '#ffcdd2',\n 200: '#ef9a9a',\n 300: '#e57373',\n 400: '#ef5350',\n 500: '#f44336',\n 600: '#e53935',\n 700: '#d32f2f',\n 800: '#c62828',\n 900: '#b71c1c',\n A100: '#ff8a80',\n A200: '#ff5252',\n A400: '#ff1744',\n A700: '#d50000'\n};\nexport default red;","const purple = {\n 50: '#f3e5f5',\n 100: '#e1bee7',\n 200: '#ce93d8',\n 300: '#ba68c8',\n 400: '#ab47bc',\n 500: '#9c27b0',\n 600: '#8e24aa',\n 700: '#7b1fa2',\n 800: '#6a1b9a',\n 900: '#4a148c',\n A100: '#ea80fc',\n A200: '#e040fb',\n A400: '#d500f9',\n A700: '#aa00ff'\n};\nexport default purple;","const blue = {\n 50: '#e3f2fd',\n 100: '#bbdefb',\n 200: '#90caf9',\n 300: '#64b5f6',\n 400: '#42a5f5',\n 500: '#2196f3',\n 600: '#1e88e5',\n 700: '#1976d2',\n 800: '#1565c0',\n 900: '#0d47a1',\n A100: '#82b1ff',\n A200: '#448aff',\n A400: '#2979ff',\n A700: '#2962ff'\n};\nexport default blue;","const lightBlue = {\n 50: '#e1f5fe',\n 100: '#b3e5fc',\n 200: '#81d4fa',\n 300: '#4fc3f7',\n 400: '#29b6f6',\n 500: '#03a9f4',\n 600: '#039be5',\n 700: '#0288d1',\n 800: '#0277bd',\n 900: '#01579b',\n A100: '#80d8ff',\n A200: '#40c4ff',\n A400: '#00b0ff',\n A700: '#0091ea'\n};\nexport default lightBlue;","const green = {\n 50: '#e8f5e9',\n 100: '#c8e6c9',\n 200: '#a5d6a7',\n 300: '#81c784',\n 400: '#66bb6a',\n 500: '#4caf50',\n 600: '#43a047',\n 700: '#388e3c',\n 800: '#2e7d32',\n 900: '#1b5e20',\n A100: '#b9f6ca',\n A200: '#69f0ae',\n A400: '#00e676',\n A700: '#00c853'\n};\nexport default green;","const orange = {\n 50: '#fff3e0',\n 100: '#ffe0b2',\n 200: '#ffcc80',\n 300: '#ffb74d',\n 400: '#ffa726',\n 500: '#ff9800',\n 600: '#fb8c00',\n 700: '#f57c00',\n 800: '#ef6c00',\n 900: '#e65100',\n A100: '#ffd180',\n A200: '#ffab40',\n A400: '#ff9100',\n A700: '#ff6d00'\n};\nexport default orange;","const grey = {\n 50: '#fafafa',\n 100: '#f5f5f5',\n 200: '#eeeeee',\n 300: '#e0e0e0',\n 400: '#bdbdbd',\n 500: '#9e9e9e',\n 600: '#757575',\n 700: '#616161',\n 800: '#424242',\n 900: '#212121',\n A100: '#f5f5f5',\n A200: '#eeeeee',\n A400: '#bdbdbd',\n A700: '#616161'\n};\nexport default grey;","export default '$$material';","import _formatMuiErrorMessage from \"@mui/utils/formatMuiErrorMessage\";\nimport deepmerge from '@mui/utils/deepmerge';\nimport { darken, getContrastRatio, lighten } from '@mui/system/colorManipulator';\nimport common from \"../colors/common.js\";\nimport grey from \"../colors/grey.js\";\nimport purple from \"../colors/purple.js\";\nimport red from \"../colors/red.js\";\nimport orange from \"../colors/orange.js\";\nimport blue from \"../colors/blue.js\";\nimport lightBlue from \"../colors/lightBlue.js\";\nimport green from \"../colors/green.js\";\nfunction getLight() {\n return {\n // The colors used to style the text.\n text: {\n // The most important text.\n primary: 'rgba(0, 0, 0, 0.87)',\n // Secondary text.\n secondary: 'rgba(0, 0, 0, 0.6)',\n // Disabled text have even lower visual prominence.\n disabled: 'rgba(0, 0, 0, 0.38)'\n },\n // The color used to divide different elements.\n divider: 'rgba(0, 0, 0, 0.12)',\n // The background colors used to style the surfaces.\n // Consistency between these values is important.\n background: {\n paper: common.white,\n default: common.white\n },\n // The colors used to style the action elements.\n action: {\n // The color of an active action like an icon button.\n active: 'rgba(0, 0, 0, 0.54)',\n // The color of an hovered action.\n hover: 'rgba(0, 0, 0, 0.04)',\n hoverOpacity: 0.04,\n // The color of a selected action.\n selected: 'rgba(0, 0, 0, 0.08)',\n selectedOpacity: 0.08,\n // The color of a disabled action.\n disabled: 'rgba(0, 0, 0, 0.26)',\n // The background color of a disabled action.\n disabledBackground: 'rgba(0, 0, 0, 0.12)',\n disabledOpacity: 0.38,\n focus: 'rgba(0, 0, 0, 0.12)',\n focusOpacity: 0.12,\n activatedOpacity: 0.12\n }\n };\n}\nexport const light = getLight();\nfunction getDark() {\n return {\n text: {\n primary: common.white,\n secondary: 'rgba(255, 255, 255, 0.7)',\n disabled: 'rgba(255, 255, 255, 0.5)',\n icon: 'rgba(255, 255, 255, 0.5)'\n },\n divider: 'rgba(255, 255, 255, 0.12)',\n background: {\n paper: '#121212',\n default: '#121212'\n },\n action: {\n active: common.white,\n hover: 'rgba(255, 255, 255, 0.08)',\n hoverOpacity: 0.08,\n selected: 'rgba(255, 255, 255, 0.16)',\n selectedOpacity: 0.16,\n disabled: 'rgba(255, 255, 255, 0.3)',\n disabledBackground: 'rgba(255, 255, 255, 0.12)',\n disabledOpacity: 0.38,\n focus: 'rgba(255, 255, 255, 0.12)',\n focusOpacity: 0.12,\n activatedOpacity: 0.24\n }\n };\n}\nexport const dark = getDark();\nfunction addLightOrDark(intent, direction, shade, tonalOffset) {\n const tonalOffsetLight = tonalOffset.light || tonalOffset;\n const tonalOffsetDark = tonalOffset.dark || tonalOffset * 1.5;\n if (!intent[direction]) {\n if (intent.hasOwnProperty(shade)) {\n intent[direction] = intent[shade];\n } else if (direction === 'light') {\n intent.light = lighten(intent.main, tonalOffsetLight);\n } else if (direction === 'dark') {\n intent.dark = darken(intent.main, tonalOffsetDark);\n }\n }\n}\nfunction getDefaultPrimary(mode = 'light') {\n if (mode === 'dark') {\n return {\n main: blue[200],\n light: blue[50],\n dark: blue[400]\n };\n }\n return {\n main: blue[700],\n light: blue[400],\n dark: blue[800]\n };\n}\nfunction getDefaultSecondary(mode = 'light') {\n if (mode === 'dark') {\n return {\n main: purple[200],\n light: purple[50],\n dark: purple[400]\n };\n }\n return {\n main: purple[500],\n light: purple[300],\n dark: purple[700]\n };\n}\nfunction getDefaultError(mode = 'light') {\n if (mode === 'dark') {\n return {\n main: red[500],\n light: red[300],\n dark: red[700]\n };\n }\n return {\n main: red[700],\n light: red[400],\n dark: red[800]\n };\n}\nfunction getDefaultInfo(mode = 'light') {\n if (mode === 'dark') {\n return {\n main: lightBlue[400],\n light: lightBlue[300],\n dark: lightBlue[700]\n };\n }\n return {\n main: lightBlue[700],\n light: lightBlue[500],\n dark: lightBlue[900]\n };\n}\nfunction getDefaultSuccess(mode = 'light') {\n if (mode === 'dark') {\n return {\n main: green[400],\n light: green[300],\n dark: green[700]\n };\n }\n return {\n main: green[800],\n light: green[500],\n dark: green[900]\n };\n}\nfunction getDefaultWarning(mode = 'light') {\n if (mode === 'dark') {\n return {\n main: orange[400],\n light: orange[300],\n dark: orange[700]\n };\n }\n return {\n main: '#ed6c02',\n // closest to orange[800] that pass 3:1.\n light: orange[500],\n dark: orange[900]\n };\n}\nexport default function createPalette(palette) {\n const {\n mode = 'light',\n contrastThreshold = 3,\n tonalOffset = 0.2,\n ...other\n } = palette;\n const primary = palette.primary || getDefaultPrimary(mode);\n const secondary = palette.secondary || getDefaultSecondary(mode);\n const error = palette.error || getDefaultError(mode);\n const info = palette.info || getDefaultInfo(mode);\n const success = palette.success || getDefaultSuccess(mode);\n const warning = palette.warning || getDefaultWarning(mode);\n\n // Use the same logic as\n // Bootstrap: https://github.com/twbs/bootstrap/blob/1d6e3710dd447de1a200f29e8fa521f8a0908f70/scss/_functions.scss#L59\n // and material-components-web https://github.com/material-components/material-components-web/blob/ac46b8863c4dab9fc22c4c662dc6bd1b65dd652f/packages/mdc-theme/_functions.scss#L54\n function getContrastText(background) {\n const contrastText = getContrastRatio(background, dark.text.primary) >= contrastThreshold ? dark.text.primary : light.text.primary;\n if (process.env.NODE_ENV !== 'production') {\n const contrast = getContrastRatio(background, contrastText);\n if (contrast < 3) {\n console.error([`MUI: The contrast ratio of ${contrast}:1 for ${contrastText} on ${background}`, 'falls below the WCAG recommended absolute minimum contrast ratio of 3:1.', 'https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast'].join('\\n'));\n }\n }\n return contrastText;\n }\n const augmentColor = ({\n color,\n name,\n mainShade = 500,\n lightShade = 300,\n darkShade = 700\n }) => {\n color = {\n ...color\n };\n if (!color.main && color[mainShade]) {\n color.main = color[mainShade];\n }\n if (!color.hasOwnProperty('main')) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? `MUI: The color${name ? ` (${name})` : ''} provided to augmentColor(color) is invalid.\\n` + `The color object needs to have a \\`main\\` property or a \\`${mainShade}\\` property.` : _formatMuiErrorMessage(11, name ? ` (${name})` : '', mainShade));\n }\n if (typeof color.main !== 'string') {\n throw new Error(process.env.NODE_ENV !== \"production\" ? `MUI: The color${name ? ` (${name})` : ''} provided to augmentColor(color) is invalid.\\n` + `\\`color.main\\` should be a string, but \\`${JSON.stringify(color.main)}\\` was provided instead.\\n` + '\\n' + 'Did you intend to use one of the following approaches?\\n' + '\\n' + 'import { green } from \"@mui/material/colors\";\\n' + '\\n' + 'const theme1 = createTheme({ palette: {\\n' + ' primary: green,\\n' + '} });\\n' + '\\n' + 'const theme2 = createTheme({ palette: {\\n' + ' primary: { main: green[500] },\\n' + '} });' : _formatMuiErrorMessage(12, name ? ` (${name})` : '', JSON.stringify(color.main)));\n }\n addLightOrDark(color, 'light', lightShade, tonalOffset);\n addLightOrDark(color, 'dark', darkShade, tonalOffset);\n if (!color.contrastText) {\n color.contrastText = getContrastText(color.main);\n }\n return color;\n };\n let modeHydrated;\n if (mode === 'light') {\n modeHydrated = getLight();\n } else if (mode === 'dark') {\n modeHydrated = getDark();\n }\n if (process.env.NODE_ENV !== 'production') {\n if (!modeHydrated) {\n console.error(`MUI: The palette mode \\`${mode}\\` is not supported.`);\n }\n }\n const paletteOutput = deepmerge({\n // A collection of common colors.\n common: {\n ...common\n },\n // prevent mutable object.\n // The palette mode, can be light or dark.\n mode,\n // The colors used to represent primary interface elements for a user.\n primary: augmentColor({\n color: primary,\n name: 'primary'\n }),\n // The colors used to represent secondary interface elements for a user.\n secondary: augmentColor({\n color: secondary,\n name: 'secondary',\n mainShade: 'A400',\n lightShade: 'A200',\n darkShade: 'A700'\n }),\n // The colors used to represent interface elements that the user should be made aware of.\n error: augmentColor({\n color: error,\n name: 'error'\n }),\n // The colors used to represent potentially dangerous actions or important messages.\n warning: augmentColor({\n color: warning,\n name: 'warning'\n }),\n // The colors used to present information to the user that is neutral and not necessarily important.\n info: augmentColor({\n color: info,\n name: 'info'\n }),\n // The colors used to indicate the successful completion of an action that user triggered.\n success: augmentColor({\n color: success,\n name: 'success'\n }),\n // The grey colors.\n grey,\n // Used by `getContrastText()` to maximize the contrast between\n // the background and the text.\n contrastThreshold,\n // Takes a background color and returns the text color that maximizes the contrast.\n getContrastText,\n // Generate a rich color object.\n augmentColor,\n // Used by the functions below to shift a color's luminance by approximately\n // two indexes within its tonal palette.\n // E.g., shift from Red 500 to Red 300 or Red 700.\n tonalOffset,\n // The light and dark mode object.\n ...modeHydrated\n }, other);\n return paletteOutput;\n}","export default function prepareTypographyVars(typography) {\n const vars = {};\n const entries = Object.entries(typography);\n entries.forEach(entry => {\n const [key, value] = entry;\n if (typeof value === 'object') {\n vars[key] = `${value.fontStyle ? `${value.fontStyle} ` : ''}${value.fontVariant ? `${value.fontVariant} ` : ''}${value.fontWeight ? `${value.fontWeight} ` : ''}${value.fontStretch ? `${value.fontStretch} ` : ''}${value.fontSize || ''}${value.lineHeight ? `/${value.lineHeight} ` : ''}${value.fontFamily || ''}`;\n }\n });\n return vars;\n}","export default function createMixins(breakpoints, mixins) {\n return {\n toolbar: {\n minHeight: 56,\n [breakpoints.up('xs')]: {\n '@media (orientation: landscape)': {\n minHeight: 48\n }\n },\n [breakpoints.up('sm')]: {\n minHeight: 64\n }\n },\n ...mixins\n };\n}","import deepmerge from '@mui/utils/deepmerge';\nfunction round(value) {\n return Math.round(value * 1e5) / 1e5;\n}\nconst caseAllCaps = {\n textTransform: 'uppercase'\n};\nconst defaultFontFamily = '\"Roboto\", \"Helvetica\", \"Arial\", sans-serif';\n\n/**\n * @see @link{https://m2.material.io/design/typography/the-type-system.html}\n * @see @link{https://m2.material.io/design/typography/understanding-typography.html}\n */\nexport default function createTypography(palette, typography) {\n const {\n fontFamily = defaultFontFamily,\n // The default font size of the Material Specification.\n fontSize = 14,\n // px\n fontWeightLight = 300,\n fontWeightRegular = 400,\n fontWeightMedium = 500,\n fontWeightBold = 700,\n // Tell MUI what's the font-size on the html element.\n // 16px is the default font-size used by browsers.\n htmlFontSize = 16,\n // Apply the CSS properties to all the variants.\n allVariants,\n pxToRem: pxToRem2,\n ...other\n } = typeof typography === 'function' ? typography(palette) : typography;\n if (process.env.NODE_ENV !== 'production') {\n if (typeof fontSize !== 'number') {\n console.error('MUI: `fontSize` is required to be a number.');\n }\n if (typeof htmlFontSize !== 'number') {\n console.error('MUI: `htmlFontSize` is required to be a number.');\n }\n }\n const coef = fontSize / 14;\n const pxToRem = pxToRem2 || (size => `${size / htmlFontSize * coef}rem`);\n const buildVariant = (fontWeight, size, lineHeight, letterSpacing, casing) => ({\n fontFamily,\n fontWeight,\n fontSize: pxToRem(size),\n // Unitless following https://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/\n lineHeight,\n // The letter spacing was designed for the Roboto font-family. Using the same letter-spacing\n // across font-families can cause issues with the kerning.\n ...(fontFamily === defaultFontFamily ? {\n letterSpacing: `${round(letterSpacing / size)}em`\n } : {}),\n ...casing,\n ...allVariants\n });\n const variants = {\n h1: buildVariant(fontWeightLight, 96, 1.167, -1.5),\n h2: buildVariant(fontWeightLight, 60, 1.2, -0.5),\n h3: buildVariant(fontWeightRegular, 48, 1.167, 0),\n h4: buildVariant(fontWeightRegular, 34, 1.235, 0.25),\n h5: buildVariant(fontWeightRegular, 24, 1.334, 0),\n h6: buildVariant(fontWeightMedium, 20, 1.6, 0.15),\n subtitle1: buildVariant(fontWeightRegular, 16, 1.75, 0.15),\n subtitle2: buildVariant(fontWeightMedium, 14, 1.57, 0.1),\n body1: buildVariant(fontWeightRegular, 16, 1.5, 0.15),\n body2: buildVariant(fontWeightRegular, 14, 1.43, 0.15),\n button: buildVariant(fontWeightMedium, 14, 1.75, 0.4, caseAllCaps),\n caption: buildVariant(fontWeightRegular, 12, 1.66, 0.4),\n overline: buildVariant(fontWeightRegular, 12, 2.66, 1, caseAllCaps),\n // TODO v6: Remove handling of 'inherit' variant from the theme as it is already handled in Material UI's Typography component. Also, remember to remove the associated types.\n inherit: {\n fontFamily: 'inherit',\n fontWeight: 'inherit',\n fontSize: 'inherit',\n lineHeight: 'inherit',\n letterSpacing: 'inherit'\n }\n };\n return deepmerge({\n htmlFontSize,\n pxToRem,\n fontFamily,\n fontSize,\n fontWeightLight,\n fontWeightRegular,\n fontWeightMedium,\n fontWeightBold,\n ...variants\n }, other, {\n clone: false // No need to clone deep\n });\n}","const shadowKeyUmbraOpacity = 0.2;\nconst shadowKeyPenumbraOpacity = 0.14;\nconst shadowAmbientShadowOpacity = 0.12;\nfunction createShadow(...px) {\n return [`${px[0]}px ${px[1]}px ${px[2]}px ${px[3]}px rgba(0,0,0,${shadowKeyUmbraOpacity})`, `${px[4]}px ${px[5]}px ${px[6]}px ${px[7]}px rgba(0,0,0,${shadowKeyPenumbraOpacity})`, `${px[8]}px ${px[9]}px ${px[10]}px ${px[11]}px rgba(0,0,0,${shadowAmbientShadowOpacity})`].join(',');\n}\n\n// Values from https://github.com/material-components/material-components-web/blob/be8747f94574669cb5e7add1a7c54fa41a89cec7/packages/mdc-elevation/_variables.scss\nconst shadows = ['none', createShadow(0, 2, 1, -1, 0, 1, 1, 0, 0, 1, 3, 0), createShadow(0, 3, 1, -2, 0, 2, 2, 0, 0, 1, 5, 0), createShadow(0, 3, 3, -2, 0, 3, 4, 0, 0, 1, 8, 0), createShadow(0, 2, 4, -1, 0, 4, 5, 0, 0, 1, 10, 0), createShadow(0, 3, 5, -1, 0, 5, 8, 0, 0, 1, 14, 0), createShadow(0, 3, 5, -1, 0, 6, 10, 0, 0, 1, 18, 0), createShadow(0, 4, 5, -2, 0, 7, 10, 1, 0, 2, 16, 1), createShadow(0, 5, 5, -3, 0, 8, 10, 1, 0, 3, 14, 2), createShadow(0, 5, 6, -3, 0, 9, 12, 1, 0, 3, 16, 2), createShadow(0, 6, 6, -3, 0, 10, 14, 1, 0, 4, 18, 3), createShadow(0, 6, 7, -4, 0, 11, 15, 1, 0, 4, 20, 3), createShadow(0, 7, 8, -4, 0, 12, 17, 2, 0, 5, 22, 4), createShadow(0, 7, 8, -4, 0, 13, 19, 2, 0, 5, 24, 4), createShadow(0, 7, 9, -4, 0, 14, 21, 2, 0, 5, 26, 4), createShadow(0, 8, 9, -5, 0, 15, 22, 2, 0, 6, 28, 5), createShadow(0, 8, 10, -5, 0, 16, 24, 2, 0, 6, 30, 5), createShadow(0, 8, 11, -5, 0, 17, 26, 2, 0, 6, 32, 5), createShadow(0, 9, 11, -5, 0, 18, 28, 2, 0, 7, 34, 6), createShadow(0, 9, 12, -6, 0, 19, 29, 2, 0, 7, 36, 6), createShadow(0, 10, 13, -6, 0, 20, 31, 3, 0, 8, 38, 7), createShadow(0, 10, 13, -6, 0, 21, 33, 3, 0, 8, 40, 7), createShadow(0, 10, 14, -6, 0, 22, 35, 3, 0, 8, 42, 7), createShadow(0, 11, 14, -7, 0, 23, 36, 3, 0, 9, 44, 8), createShadow(0, 11, 15, -7, 0, 24, 38, 3, 0, 9, 46, 8)];\nexport default shadows;","// Follow https://material.google.com/motion/duration-easing.html#duration-easing-natural-easing-curves\n// to learn the context in which each easing should be used.\nexport const easing = {\n // This is the most common easing curve.\n easeInOut: 'cubic-bezier(0.4, 0, 0.2, 1)',\n // Objects enter the screen at full velocity from off-screen and\n // slowly decelerate to a resting point.\n easeOut: 'cubic-bezier(0.0, 0, 0.2, 1)',\n // Objects leave the screen at full velocity. They do not decelerate when off-screen.\n easeIn: 'cubic-bezier(0.4, 0, 1, 1)',\n // The sharp curve is used by objects that may return to the screen at any time.\n sharp: 'cubic-bezier(0.4, 0, 0.6, 1)'\n};\n\n// Follow https://m2.material.io/guidelines/motion/duration-easing.html#duration-easing-common-durations\n// to learn when use what timing\nexport const duration = {\n shortest: 150,\n shorter: 200,\n short: 250,\n // most basic recommended timing\n standard: 300,\n // this is to be used in complex animations\n complex: 375,\n // recommended when something is entering screen\n enteringScreen: 225,\n // recommended when something is leaving screen\n leavingScreen: 195\n};\nfunction formatMs(milliseconds) {\n return `${Math.round(milliseconds)}ms`;\n}\nfunction getAutoHeightDuration(height) {\n if (!height) {\n return 0;\n }\n const constant = height / 36;\n\n // https://www.desmos.com/calculator/vbrp3ggqet\n return Math.min(Math.round((4 + 15 * constant ** 0.25 + constant / 5) * 10), 3000);\n}\nexport default function createTransitions(inputTransitions) {\n const mergedEasing = {\n ...easing,\n ...inputTransitions.easing\n };\n const mergedDuration = {\n ...duration,\n ...inputTransitions.duration\n };\n const create = (props = ['all'], options = {}) => {\n const {\n duration: durationOption = mergedDuration.standard,\n easing: easingOption = mergedEasing.easeInOut,\n delay = 0,\n ...other\n } = options;\n if (process.env.NODE_ENV !== 'production') {\n const isString = value => typeof value === 'string';\n const isNumber = value => !Number.isNaN(parseFloat(value));\n if (!isString(props) && !Array.isArray(props)) {\n console.error('MUI: Argument \"props\" must be a string or Array.');\n }\n if (!isNumber(durationOption) && !isString(durationOption)) {\n console.error(`MUI: Argument \"duration\" must be a number or a string but found ${durationOption}.`);\n }\n if (!isString(easingOption)) {\n console.error('MUI: Argument \"easing\" must be a string.');\n }\n if (!isNumber(delay) && !isString(delay)) {\n console.error('MUI: Argument \"delay\" must be a number or a string.');\n }\n if (typeof options !== 'object') {\n console.error(['MUI: Secong argument of transition.create must be an object.', \"Arguments should be either `create('prop1', options)` or `create(['prop1', 'prop2'], options)`\"].join('\\n'));\n }\n if (Object.keys(other).length !== 0) {\n console.error(`MUI: Unrecognized argument(s) [${Object.keys(other).join(',')}].`);\n }\n }\n return (Array.isArray(props) ? props : [props]).map(animatedProp => `${animatedProp} ${typeof durationOption === 'string' ? durationOption : formatMs(durationOption)} ${easingOption} ${typeof delay === 'string' ? delay : formatMs(delay)}`).join(',');\n };\n return {\n getAutoHeightDuration,\n create,\n ...inputTransitions,\n easing: mergedEasing,\n duration: mergedDuration\n };\n}","// We need to centralize the zIndex definitions as they work\n// like global values in the browser.\nconst zIndex = {\n mobileStepper: 1000,\n fab: 1050,\n speedDial: 1050,\n appBar: 1100,\n drawer: 1200,\n modal: 1300,\n snackbar: 1400,\n tooltip: 1500\n};\nexport default zIndex;","/* eslint-disable import/prefer-default-export */\nimport { isPlainObject } from '@mui/utils/deepmerge';\nfunction isSerializable(val) {\n return isPlainObject(val) || typeof val === 'undefined' || typeof val === 'string' || typeof val === 'boolean' || typeof val === 'number' || Array.isArray(val);\n}\n\n/**\n * `baseTheme` usually comes from `createTheme()` or `extendTheme()`.\n *\n * This function is intended to be used with zero-runtime CSS-in-JS like Pigment CSS\n * For example, in a Next.js project:\n *\n * ```js\n * // next.config.js\n * const { extendTheme } = require('@mui/material/styles');\n *\n * const theme = extendTheme();\n * // `.toRuntimeSource` is Pigment CSS specific to create a theme that is available at runtime.\n * theme.toRuntimeSource = stringifyTheme;\n *\n * module.exports = withPigment({\n * theme,\n * });\n * ```\n */\nexport function stringifyTheme(baseTheme = {}) {\n const serializableTheme = {\n ...baseTheme\n };\n function serializeTheme(object) {\n const array = Object.entries(object);\n // eslint-disable-next-line no-plusplus\n for (let index = 0; index < array.length; index++) {\n const [key, value] = array[index];\n if (!isSerializable(value) || key.startsWith('unstable_')) {\n delete object[key];\n } else if (isPlainObject(value)) {\n object[key] = {\n ...value\n };\n serializeTheme(object[key]);\n }\n }\n }\n serializeTheme(serializableTheme);\n return `import { unstable_createBreakpoints as createBreakpoints, createTransitions } from '@mui/material/styles';\n\nconst theme = ${JSON.stringify(serializableTheme, null, 2)};\n\ntheme.breakpoints = createBreakpoints(theme.breakpoints || {});\ntheme.transitions = createTransitions(theme.transitions || {});\n\nexport default theme;`;\n}","import _formatMuiErrorMessage from \"@mui/utils/formatMuiErrorMessage\";\nimport deepmerge from '@mui/utils/deepmerge';\nimport styleFunctionSx, { unstable_defaultSxConfig as defaultSxConfig } from '@mui/system/styleFunctionSx';\nimport systemCreateTheme from '@mui/system/createTheme';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nimport createMixins from \"./createMixins.js\";\nimport createPalette from \"./createPalette.js\";\nimport createTypography from \"./createTypography.js\";\nimport shadows from \"./shadows.js\";\nimport createTransitions from \"./createTransitions.js\";\nimport zIndex from \"./zIndex.js\";\nimport { stringifyTheme } from \"./stringifyTheme.js\";\nfunction createThemeNoVars(options = {}, ...args) {\n const {\n breakpoints: breakpointsInput,\n mixins: mixinsInput = {},\n spacing: spacingInput,\n palette: paletteInput = {},\n transitions: transitionsInput = {},\n typography: typographyInput = {},\n shape: shapeInput,\n ...other\n } = options;\n if (options.vars &&\n // The error should throw only for the root theme creation because user is not allowed to use a custom node `vars`.\n // `generateThemeVars` is the closest identifier for checking that the `options` is a result of `createTheme` with CSS variables so that user can create new theme for nested ThemeProvider.\n options.generateThemeVars === undefined) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? 'MUI: `vars` is a private field used for CSS variables support.\\n' +\n // #host-reference\n 'Please use another name or follow the [docs](https://mui.com/material-ui/customization/css-theme-variables/usage/) to enable the feature.' : _formatMuiErrorMessage(20));\n }\n const palette = createPalette(paletteInput);\n const systemTheme = systemCreateTheme(options);\n let muiTheme = deepmerge(systemTheme, {\n mixins: createMixins(systemTheme.breakpoints, mixinsInput),\n palette,\n // Don't use [...shadows] until you've verified its transpiled code is not invoking the iterator protocol.\n shadows: shadows.slice(),\n typography: createTypography(palette, typographyInput),\n transitions: createTransitions(transitionsInput),\n zIndex: {\n ...zIndex\n }\n });\n muiTheme = deepmerge(muiTheme, other);\n muiTheme = args.reduce((acc, argument) => deepmerge(acc, argument), muiTheme);\n if (process.env.NODE_ENV !== 'production') {\n // TODO v6: Refactor to use globalStateClassesMapping from @mui/utils once `readOnly` state class is used in Rating component.\n const stateClasses = ['active', 'checked', 'completed', 'disabled', 'error', 'expanded', 'focused', 'focusVisible', 'required', 'selected'];\n const traverse = (node, component) => {\n let key;\n\n // eslint-disable-next-line guard-for-in\n for (key in node) {\n const child = node[key];\n if (stateClasses.includes(key) && Object.keys(child).length > 0) {\n if (process.env.NODE_ENV !== 'production') {\n const stateClass = generateUtilityClass('', key);\n console.error([`MUI: The \\`${component}\\` component increases ` + `the CSS specificity of the \\`${key}\\` internal state.`, 'You can not override it like this: ', JSON.stringify(node, null, 2), '', `Instead, you need to use the '&.${stateClass}' syntax:`, JSON.stringify({\n root: {\n [`&.${stateClass}`]: child\n }\n }, null, 2), '', 'https://mui.com/r/state-classes-guide'].join('\\n'));\n }\n // Remove the style to prevent global conflicts.\n node[key] = {};\n }\n }\n };\n Object.keys(muiTheme.components).forEach(component => {\n const styleOverrides = muiTheme.components[component].styleOverrides;\n if (styleOverrides && component.startsWith('Mui')) {\n traverse(styleOverrides, component);\n }\n });\n }\n muiTheme.unstable_sxConfig = {\n ...defaultSxConfig,\n ...other?.unstable_sxConfig\n };\n muiTheme.unstable_sx = function sx(props) {\n return styleFunctionSx({\n sx: props,\n theme: this\n });\n };\n muiTheme.toRuntimeSource = stringifyTheme; // for Pigment CSS integration\n\n return muiTheme;\n}\nlet warnedOnce = false;\nexport function createMuiTheme(...args) {\n if (process.env.NODE_ENV !== 'production') {\n if (!warnedOnce) {\n warnedOnce = true;\n console.error(['MUI: the createMuiTheme function was renamed to createTheme.', '', \"You should use `import { createTheme } from '@mui/material/styles'`\"].join('\\n'));\n }\n }\n return createThemeNoVars(...args);\n}\nexport default createThemeNoVars;","// Inspired by https://github.com/material-components/material-components-ios/blob/bca36107405594d5b7b16265a5b0ed698f85a5ee/components/Elevation/src/UIColor%2BMaterialElevation.m#L61\nexport default function getOverlayAlpha(elevation) {\n let alphaValue;\n if (elevation < 1) {\n alphaValue = 5.11916 * elevation ** 2;\n } else {\n alphaValue = 4.5 * Math.log(elevation + 1) + 2;\n }\n return Math.round(alphaValue * 10) / 1000;\n}","import createPalette from \"./createPalette.js\";\nimport getOverlayAlpha from \"./getOverlayAlpha.js\";\nconst defaultDarkOverlays = [...Array(25)].map((_, index) => {\n if (index === 0) {\n return 'none';\n }\n const overlay = getOverlayAlpha(index);\n return `linear-gradient(rgba(255 255 255 / ${overlay}), rgba(255 255 255 / ${overlay}))`;\n});\nexport function getOpacity(mode) {\n return {\n inputPlaceholder: mode === 'dark' ? 0.5 : 0.42,\n inputUnderline: mode === 'dark' ? 0.7 : 0.42,\n switchTrackDisabled: mode === 'dark' ? 0.2 : 0.12,\n switchTrack: mode === 'dark' ? 0.3 : 0.38\n };\n}\nexport function getOverlays(mode) {\n return mode === 'dark' ? defaultDarkOverlays : [];\n}\nexport default function createColorScheme(options) {\n const {\n palette: paletteInput = {\n mode: 'light'\n },\n // need to cast to avoid module augmentation test\n opacity,\n overlays,\n ...rest\n } = options;\n const palette = createPalette(paletteInput);\n return {\n palette,\n opacity: {\n ...getOpacity(palette.mode),\n ...opacity\n },\n overlays: overlays || getOverlays(palette.mode),\n ...rest\n };\n}","export default function shouldSkipGeneratingVar(keys) {\n return !!keys[0].match(/(cssVarPrefix|colorSchemeSelector|rootSelector|typography|mixins|breakpoints|direction|transitions)/) || !!keys[0].match(/sxConfig$/) ||\n // ends with sxConfig\n keys[0] === 'palette' && !!keys[1]?.match(/(mode|contrastThreshold|tonalOffset)/);\n}","/**\n * @internal These variables should not appear in the :root stylesheet when the `defaultColorScheme=\"dark\"`\n */\nconst excludeVariablesFromRoot = cssVarPrefix => [...[...Array(25)].map((_, index) => `--${cssVarPrefix ? `${cssVarPrefix}-` : ''}overlays-${index}`), `--${cssVarPrefix ? `${cssVarPrefix}-` : ''}palette-AppBar-darkBg`, `--${cssVarPrefix ? `${cssVarPrefix}-` : ''}palette-AppBar-darkColor`];\nexport default excludeVariablesFromRoot;","import excludeVariablesFromRoot from \"./excludeVariablesFromRoot.js\";\nexport default theme => (colorScheme, css) => {\n const root = theme.rootSelector || ':root';\n const selector = theme.colorSchemeSelector;\n let rule = selector;\n if (selector === 'class') {\n rule = '.%s';\n }\n if (selector === 'data') {\n rule = '[data-%s]';\n }\n if (selector?.startsWith('data-') && !selector.includes('%s')) {\n // 'data-mui-color-scheme' -> '[data-mui-color-scheme=\"%s\"]'\n rule = `[${selector}=\"%s\"]`;\n }\n if (theme.defaultColorScheme === colorScheme) {\n if (colorScheme === 'dark') {\n const excludedVariables = {};\n excludeVariablesFromRoot(theme.cssVarPrefix).forEach(cssVar => {\n excludedVariables[cssVar] = css[cssVar];\n delete css[cssVar];\n });\n if (rule === 'media') {\n return {\n [root]: css,\n [`@media (prefers-color-scheme: dark)`]: {\n [root]: excludedVariables\n }\n };\n }\n if (rule) {\n return {\n [rule.replace('%s', colorScheme)]: excludedVariables,\n [`${root}, ${rule.replace('%s', colorScheme)}`]: css\n };\n }\n return {\n [root]: {\n ...css,\n ...excludedVariables\n }\n };\n }\n if (rule && rule !== 'media') {\n return `${root}, ${rule.replace('%s', String(colorScheme))}`;\n }\n } else if (colorScheme) {\n if (rule === 'media') {\n return {\n [`@media (prefers-color-scheme: ${String(colorScheme)})`]: {\n [root]: css\n }\n };\n }\n if (rule) {\n return rule.replace('%s', String(colorScheme));\n }\n }\n return root;\n};","import _formatMuiErrorMessage from \"@mui/utils/formatMuiErrorMessage\";\nimport deepmerge from '@mui/utils/deepmerge';\nimport { unstable_createGetCssVar as systemCreateGetCssVar, createSpacing } from '@mui/system';\nimport { createUnarySpacing } from '@mui/system/spacing';\nimport { prepareCssVars, prepareTypographyVars, createGetColorSchemeSelector } from '@mui/system/cssVars';\nimport styleFunctionSx, { unstable_defaultSxConfig as defaultSxConfig } from '@mui/system/styleFunctionSx';\nimport { private_safeColorChannel as safeColorChannel, private_safeAlpha as safeAlpha, private_safeDarken as safeDarken, private_safeLighten as safeLighten, private_safeEmphasize as safeEmphasize, hslToRgb } from '@mui/system/colorManipulator';\nimport createThemeNoVars from \"./createThemeNoVars.js\";\nimport createColorScheme, { getOpacity, getOverlays } from \"./createColorScheme.js\";\nimport defaultShouldSkipGeneratingVar from \"./shouldSkipGeneratingVar.js\";\nimport defaultGetSelector from \"./createGetSelector.js\";\nimport { stringifyTheme } from \"./stringifyTheme.js\";\nfunction assignNode(obj, keys) {\n keys.forEach(k => {\n if (!obj[k]) {\n obj[k] = {};\n }\n });\n}\nfunction setColor(obj, key, defaultValue) {\n if (!obj[key] && defaultValue) {\n obj[key] = defaultValue;\n }\n}\nfunction toRgb(color) {\n if (typeof color !== 'string' || !color.startsWith('hsl')) {\n return color;\n }\n return hslToRgb(color);\n}\nfunction setColorChannel(obj, key) {\n if (!(`${key}Channel` in obj)) {\n // custom channel token is not provided, generate one.\n // if channel token can't be generated, show a warning.\n obj[`${key}Channel`] = safeColorChannel(toRgb(obj[key]), `MUI: Can't create \\`palette.${key}Channel\\` because \\`palette.${key}\\` is not one of these formats: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color().` + '\\n' + `To suppress this warning, you need to explicitly provide the \\`palette.${key}Channel\\` as a string (in rgb format, for example \"12 12 12\") or undefined if you want to remove the channel token.`);\n }\n}\nfunction getSpacingVal(spacingInput) {\n if (typeof spacingInput === 'number') {\n return `${spacingInput}px`;\n }\n if (typeof spacingInput === 'string' || typeof spacingInput === 'function' || Array.isArray(spacingInput)) {\n return spacingInput;\n }\n return '8px';\n}\nconst silent = fn => {\n try {\n return fn();\n } catch (error) {\n // ignore error\n }\n return undefined;\n};\nexport const createGetCssVar = (cssVarPrefix = 'mui') => systemCreateGetCssVar(cssVarPrefix);\nfunction attachColorScheme(colorSchemes, scheme, restTheme, colorScheme) {\n if (!scheme) {\n return undefined;\n }\n scheme = scheme === true ? {} : scheme;\n const mode = colorScheme === 'dark' ? 'dark' : 'light';\n if (!restTheme) {\n colorSchemes[colorScheme] = createColorScheme({\n ...scheme,\n palette: {\n mode,\n ...scheme?.palette\n }\n });\n return undefined;\n }\n const {\n palette,\n ...muiTheme\n } = createThemeNoVars({\n ...restTheme,\n palette: {\n mode,\n ...scheme?.palette\n }\n });\n colorSchemes[colorScheme] = {\n ...scheme,\n palette,\n opacity: {\n ...getOpacity(mode),\n ...scheme?.opacity\n },\n overlays: scheme?.overlays || getOverlays(mode)\n };\n return muiTheme;\n}\n\n/**\n * A default `createThemeWithVars` comes with a single color scheme, either `light` or `dark` based on the `defaultColorScheme`.\n * This is better suited for apps that only need a single color scheme.\n *\n * To enable built-in `light` and `dark` color schemes, either:\n * 1. provide a `colorSchemeSelector` to define how the color schemes will change.\n * 2. provide `colorSchemes.dark` will set `colorSchemeSelector: 'media'` by default.\n */\nexport default function createThemeWithVars(options = {}, ...args) {\n const {\n colorSchemes: colorSchemesInput = {\n light: true\n },\n defaultColorScheme: defaultColorSchemeInput,\n disableCssColorScheme = false,\n cssVarPrefix = 'mui',\n shouldSkipGeneratingVar = defaultShouldSkipGeneratingVar,\n colorSchemeSelector: selector = colorSchemesInput.light && colorSchemesInput.dark ? 'media' : undefined,\n rootSelector = ':root',\n ...input\n } = options;\n const firstColorScheme = Object.keys(colorSchemesInput)[0];\n const defaultColorScheme = defaultColorSchemeInput || (colorSchemesInput.light && firstColorScheme !== 'light' ? 'light' : firstColorScheme);\n const getCssVar = createGetCssVar(cssVarPrefix);\n const {\n [defaultColorScheme]: defaultSchemeInput,\n light: builtInLight,\n dark: builtInDark,\n ...customColorSchemes\n } = colorSchemesInput;\n const colorSchemes = {\n ...customColorSchemes\n };\n let defaultScheme = defaultSchemeInput;\n\n // For built-in light and dark color schemes, ensure that the value is valid if they are the default color scheme.\n if (defaultColorScheme === 'dark' && !('dark' in colorSchemesInput) || defaultColorScheme === 'light' && !('light' in colorSchemesInput)) {\n defaultScheme = true;\n }\n if (!defaultScheme) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? `MUI: The \\`colorSchemes.${defaultColorScheme}\\` option is either missing or invalid.` : _formatMuiErrorMessage(21, defaultColorScheme));\n }\n\n // Create the palette for the default color scheme, either `light`, `dark`, or custom color scheme.\n const muiTheme = attachColorScheme(colorSchemes, defaultScheme, input, defaultColorScheme);\n if (builtInLight && !colorSchemes.light) {\n attachColorScheme(colorSchemes, builtInLight, undefined, 'light');\n }\n if (builtInDark && !colorSchemes.dark) {\n attachColorScheme(colorSchemes, builtInDark, undefined, 'dark');\n }\n let theme = {\n defaultColorScheme,\n ...muiTheme,\n cssVarPrefix,\n colorSchemeSelector: selector,\n rootSelector,\n getCssVar,\n colorSchemes,\n font: {\n ...prepareTypographyVars(muiTheme.typography),\n ...muiTheme.font\n },\n spacing: getSpacingVal(input.spacing)\n };\n Object.keys(theme.colorSchemes).forEach(key => {\n const palette = theme.colorSchemes[key].palette;\n const setCssVarColor = cssVar => {\n const tokens = cssVar.split('-');\n const color = tokens[1];\n const colorToken = tokens[2];\n return getCssVar(cssVar, palette[color][colorToken]);\n };\n\n // attach black & white channels to common node\n if (palette.mode === 'light') {\n setColor(palette.common, 'background', '#fff');\n setColor(palette.common, 'onBackground', '#000');\n }\n if (palette.mode === 'dark') {\n setColor(palette.common, 'background', '#000');\n setColor(palette.common, 'onBackground', '#fff');\n }\n\n // assign component variables\n assignNode(palette, ['Alert', 'AppBar', 'Avatar', 'Button', 'Chip', 'FilledInput', 'LinearProgress', 'Skeleton', 'Slider', 'SnackbarContent', 'SpeedDialAction', 'StepConnector', 'StepContent', 'Switch', 'TableCell', 'Tooltip']);\n if (palette.mode === 'light') {\n setColor(palette.Alert, 'errorColor', safeDarken(palette.error.light, 0.6));\n setColor(palette.Alert, 'infoColor', safeDarken(palette.info.light, 0.6));\n setColor(palette.Alert, 'successColor', safeDarken(palette.success.light, 0.6));\n setColor(palette.Alert, 'warningColor', safeDarken(palette.warning.light, 0.6));\n setColor(palette.Alert, 'errorFilledBg', setCssVarColor('palette-error-main'));\n setColor(palette.Alert, 'infoFilledBg', setCssVarColor('palette-info-main'));\n setColor(palette.Alert, 'successFilledBg', setCssVarColor('palette-success-main'));\n setColor(palette.Alert, 'warningFilledBg', setCssVarColor('palette-warning-main'));\n setColor(palette.Alert, 'errorFilledColor', silent(() => palette.getContrastText(palette.error.main)));\n setColor(palette.Alert, 'infoFilledColor', silent(() => palette.getContrastText(palette.info.main)));\n setColor(palette.Alert, 'successFilledColor', silent(() => palette.getContrastText(palette.success.main)));\n setColor(palette.Alert, 'warningFilledColor', silent(() => palette.getContrastText(palette.warning.main)));\n setColor(palette.Alert, 'errorStandardBg', safeLighten(palette.error.light, 0.9));\n setColor(palette.Alert, 'infoStandardBg', safeLighten(palette.info.light, 0.9));\n setColor(palette.Alert, 'successStandardBg', safeLighten(palette.success.light, 0.9));\n setColor(palette.Alert, 'warningStandardBg', safeLighten(palette.warning.light, 0.9));\n setColor(palette.Alert, 'errorIconColor', setCssVarColor('palette-error-main'));\n setColor(palette.Alert, 'infoIconColor', setCssVarColor('palette-info-main'));\n setColor(palette.Alert, 'successIconColor', setCssVarColor('palette-success-main'));\n setColor(palette.Alert, 'warningIconColor', setCssVarColor('palette-warning-main'));\n setColor(palette.AppBar, 'defaultBg', setCssVarColor('palette-grey-100'));\n setColor(palette.Avatar, 'defaultBg', setCssVarColor('palette-grey-400'));\n setColor(palette.Button, 'inheritContainedBg', setCssVarColor('palette-grey-300'));\n setColor(palette.Button, 'inheritContainedHoverBg', setCssVarColor('palette-grey-A100'));\n setColor(palette.Chip, 'defaultBorder', setCssVarColor('palette-grey-400'));\n setColor(palette.Chip, 'defaultAvatarColor', setCssVarColor('palette-grey-700'));\n setColor(palette.Chip, 'defaultIconColor', setCssVarColor('palette-grey-700'));\n setColor(palette.FilledInput, 'bg', 'rgba(0, 0, 0, 0.06)');\n setColor(palette.FilledInput, 'hoverBg', 'rgba(0, 0, 0, 0.09)');\n setColor(palette.FilledInput, 'disabledBg', 'rgba(0, 0, 0, 0.12)');\n setColor(palette.LinearProgress, 'primaryBg', safeLighten(palette.primary.main, 0.62));\n setColor(palette.LinearProgress, 'secondaryBg', safeLighten(palette.secondary.main, 0.62));\n setColor(palette.LinearProgress, 'errorBg', safeLighten(palette.error.main, 0.62));\n setColor(palette.LinearProgress, 'infoBg', safeLighten(palette.info.main, 0.62));\n setColor(palette.LinearProgress, 'successBg', safeLighten(palette.success.main, 0.62));\n setColor(palette.LinearProgress, 'warningBg', safeLighten(palette.warning.main, 0.62));\n setColor(palette.Skeleton, 'bg', `rgba(${setCssVarColor('palette-text-primaryChannel')} / 0.11)`);\n setColor(palette.Slider, 'primaryTrack', safeLighten(palette.primary.main, 0.62));\n setColor(palette.Slider, 'secondaryTrack', safeLighten(palette.secondary.main, 0.62));\n setColor(palette.Slider, 'errorTrack', safeLighten(palette.error.main, 0.62));\n setColor(palette.Slider, 'infoTrack', safeLighten(palette.info.main, 0.62));\n setColor(palette.Slider, 'successTrack', safeLighten(palette.success.main, 0.62));\n setColor(palette.Slider, 'warningTrack', safeLighten(palette.warning.main, 0.62));\n const snackbarContentBackground = safeEmphasize(palette.background.default, 0.8);\n setColor(palette.SnackbarContent, 'bg', snackbarContentBackground);\n setColor(palette.SnackbarContent, 'color', silent(() => palette.getContrastText(snackbarContentBackground)));\n setColor(palette.SpeedDialAction, 'fabHoverBg', safeEmphasize(palette.background.paper, 0.15));\n setColor(palette.StepConnector, 'border', setCssVarColor('palette-grey-400'));\n setColor(palette.StepContent, 'border', setCssVarColor('palette-grey-400'));\n setColor(palette.Switch, 'defaultColor', setCssVarColor('palette-common-white'));\n setColor(palette.Switch, 'defaultDisabledColor', setCssVarColor('palette-grey-100'));\n setColor(palette.Switch, 'primaryDisabledColor', safeLighten(palette.primary.main, 0.62));\n setColor(palette.Switch, 'secondaryDisabledColor', safeLighten(palette.secondary.main, 0.62));\n setColor(palette.Switch, 'errorDisabledColor', safeLighten(palette.error.main, 0.62));\n setColor(palette.Switch, 'infoDisabledColor', safeLighten(palette.info.main, 0.62));\n setColor(palette.Switch, 'successDisabledColor', safeLighten(palette.success.main, 0.62));\n setColor(palette.Switch, 'warningDisabledColor', safeLighten(palette.warning.main, 0.62));\n setColor(palette.TableCell, 'border', safeLighten(safeAlpha(palette.divider, 1), 0.88));\n setColor(palette.Tooltip, 'bg', safeAlpha(palette.grey[700], 0.92));\n }\n if (palette.mode === 'dark') {\n setColor(palette.Alert, 'errorColor', safeLighten(palette.error.light, 0.6));\n setColor(palette.Alert, 'infoColor', safeLighten(palette.info.light, 0.6));\n setColor(palette.Alert, 'successColor', safeLighten(palette.success.light, 0.6));\n setColor(palette.Alert, 'warningColor', safeLighten(palette.warning.light, 0.6));\n setColor(palette.Alert, 'errorFilledBg', setCssVarColor('palette-error-dark'));\n setColor(palette.Alert, 'infoFilledBg', setCssVarColor('palette-info-dark'));\n setColor(palette.Alert, 'successFilledBg', setCssVarColor('palette-success-dark'));\n setColor(palette.Alert, 'warningFilledBg', setCssVarColor('palette-warning-dark'));\n setColor(palette.Alert, 'errorFilledColor', silent(() => palette.getContrastText(palette.error.dark)));\n setColor(palette.Alert, 'infoFilledColor', silent(() => palette.getContrastText(palette.info.dark)));\n setColor(palette.Alert, 'successFilledColor', silent(() => palette.getContrastText(palette.success.dark)));\n setColor(palette.Alert, 'warningFilledColor', silent(() => palette.getContrastText(palette.warning.dark)));\n setColor(palette.Alert, 'errorStandardBg', safeDarken(palette.error.light, 0.9));\n setColor(palette.Alert, 'infoStandardBg', safeDarken(palette.info.light, 0.9));\n setColor(palette.Alert, 'successStandardBg', safeDarken(palette.success.light, 0.9));\n setColor(palette.Alert, 'warningStandardBg', safeDarken(palette.warning.light, 0.9));\n setColor(palette.Alert, 'errorIconColor', setCssVarColor('palette-error-main'));\n setColor(palette.Alert, 'infoIconColor', setCssVarColor('palette-info-main'));\n setColor(palette.Alert, 'successIconColor', setCssVarColor('palette-success-main'));\n setColor(palette.Alert, 'warningIconColor', setCssVarColor('palette-warning-main'));\n setColor(palette.AppBar, 'defaultBg', setCssVarColor('palette-grey-900'));\n setColor(palette.AppBar, 'darkBg', setCssVarColor('palette-background-paper')); // specific for dark mode\n setColor(palette.AppBar, 'darkColor', setCssVarColor('palette-text-primary')); // specific for dark mode\n setColor(palette.Avatar, 'defaultBg', setCssVarColor('palette-grey-600'));\n setColor(palette.Button, 'inheritContainedBg', setCssVarColor('palette-grey-800'));\n setColor(palette.Button, 'inheritContainedHoverBg', setCssVarColor('palette-grey-700'));\n setColor(palette.Chip, 'defaultBorder', setCssVarColor('palette-grey-700'));\n setColor(palette.Chip, 'defaultAvatarColor', setCssVarColor('palette-grey-300'));\n setColor(palette.Chip, 'defaultIconColor', setCssVarColor('palette-grey-300'));\n setColor(palette.FilledInput, 'bg', 'rgba(255, 255, 255, 0.09)');\n setColor(palette.FilledInput, 'hoverBg', 'rgba(255, 255, 255, 0.13)');\n setColor(palette.FilledInput, 'disabledBg', 'rgba(255, 255, 255, 0.12)');\n setColor(palette.LinearProgress, 'primaryBg', safeDarken(palette.primary.main, 0.5));\n setColor(palette.LinearProgress, 'secondaryBg', safeDarken(palette.secondary.main, 0.5));\n setColor(palette.LinearProgress, 'errorBg', safeDarken(palette.error.main, 0.5));\n setColor(palette.LinearProgress, 'infoBg', safeDarken(palette.info.main, 0.5));\n setColor(palette.LinearProgress, 'successBg', safeDarken(palette.success.main, 0.5));\n setColor(palette.LinearProgress, 'warningBg', safeDarken(palette.warning.main, 0.5));\n setColor(palette.Skeleton, 'bg', `rgba(${setCssVarColor('palette-text-primaryChannel')} / 0.13)`);\n setColor(palette.Slider, 'primaryTrack', safeDarken(palette.primary.main, 0.5));\n setColor(palette.Slider, 'secondaryTrack', safeDarken(palette.secondary.main, 0.5));\n setColor(palette.Slider, 'errorTrack', safeDarken(palette.error.main, 0.5));\n setColor(palette.Slider, 'infoTrack', safeDarken(palette.info.main, 0.5));\n setColor(palette.Slider, 'successTrack', safeDarken(palette.success.main, 0.5));\n setColor(palette.Slider, 'warningTrack', safeDarken(palette.warning.main, 0.5));\n const snackbarContentBackground = safeEmphasize(palette.background.default, 0.98);\n setColor(palette.SnackbarContent, 'bg', snackbarContentBackground);\n setColor(palette.SnackbarContent, 'color', silent(() => palette.getContrastText(snackbarContentBackground)));\n setColor(palette.SpeedDialAction, 'fabHoverBg', safeEmphasize(palette.background.paper, 0.15));\n setColor(palette.StepConnector, 'border', setCssVarColor('palette-grey-600'));\n setColor(palette.StepContent, 'border', setCssVarColor('palette-grey-600'));\n setColor(palette.Switch, 'defaultColor', setCssVarColor('palette-grey-300'));\n setColor(palette.Switch, 'defaultDisabledColor', setCssVarColor('palette-grey-600'));\n setColor(palette.Switch, 'primaryDisabledColor', safeDarken(palette.primary.main, 0.55));\n setColor(palette.Switch, 'secondaryDisabledColor', safeDarken(palette.secondary.main, 0.55));\n setColor(palette.Switch, 'errorDisabledColor', safeDarken(palette.error.main, 0.55));\n setColor(palette.Switch, 'infoDisabledColor', safeDarken(palette.info.main, 0.55));\n setColor(palette.Switch, 'successDisabledColor', safeDarken(palette.success.main, 0.55));\n setColor(palette.Switch, 'warningDisabledColor', safeDarken(palette.warning.main, 0.55));\n setColor(palette.TableCell, 'border', safeDarken(safeAlpha(palette.divider, 1), 0.68));\n setColor(palette.Tooltip, 'bg', safeAlpha(palette.grey[700], 0.92));\n }\n\n // MUI X - DataGrid needs this token.\n setColorChannel(palette.background, 'default');\n\n // added for consistency with the `background.default` token\n setColorChannel(palette.background, 'paper');\n setColorChannel(palette.common, 'background');\n setColorChannel(palette.common, 'onBackground');\n setColorChannel(palette, 'divider');\n Object.keys(palette).forEach(color => {\n const colors = palette[color];\n\n // The default palettes (primary, secondary, error, info, success, and warning) errors are handled by the above `createTheme(...)`.\n\n if (color !== 'tonalOffset' && colors && typeof colors === 'object') {\n // Silent the error for custom palettes.\n if (colors.main) {\n setColor(palette[color], 'mainChannel', safeColorChannel(toRgb(colors.main)));\n }\n if (colors.light) {\n setColor(palette[color], 'lightChannel', safeColorChannel(toRgb(colors.light)));\n }\n if (colors.dark) {\n setColor(palette[color], 'darkChannel', safeColorChannel(toRgb(colors.dark)));\n }\n if (colors.contrastText) {\n setColor(palette[color], 'contrastTextChannel', safeColorChannel(toRgb(colors.contrastText)));\n }\n if (color === 'text') {\n // Text colors: text.primary, text.secondary\n setColorChannel(palette[color], 'primary');\n setColorChannel(palette[color], 'secondary');\n }\n if (color === 'action') {\n // Action colors: action.active, action.selected\n if (colors.active) {\n setColorChannel(palette[color], 'active');\n }\n if (colors.selected) {\n setColorChannel(palette[color], 'selected');\n }\n }\n }\n });\n });\n theme = args.reduce((acc, argument) => deepmerge(acc, argument), theme);\n const parserConfig = {\n prefix: cssVarPrefix,\n disableCssColorScheme,\n shouldSkipGeneratingVar,\n getSelector: defaultGetSelector(theme)\n };\n const {\n vars,\n generateThemeVars,\n generateStyleSheets\n } = prepareCssVars(theme, parserConfig);\n theme.vars = vars;\n Object.entries(theme.colorSchemes[theme.defaultColorScheme]).forEach(([key, value]) => {\n theme[key] = value;\n });\n theme.generateThemeVars = generateThemeVars;\n theme.generateStyleSheets = generateStyleSheets;\n theme.generateSpacing = function generateSpacing() {\n return createSpacing(input.spacing, createUnarySpacing(this));\n };\n theme.getColorSchemeSelector = createGetColorSchemeSelector(selector);\n theme.spacing = theme.generateSpacing();\n theme.shouldSkipGeneratingVar = shouldSkipGeneratingVar;\n theme.unstable_sxConfig = {\n ...defaultSxConfig,\n ...input?.unstable_sxConfig\n };\n theme.unstable_sx = function sx(props) {\n return styleFunctionSx({\n sx: props,\n theme: this\n });\n };\n theme.toRuntimeSource = stringifyTheme; // for Pigment CSS integration\n\n return theme;\n}","import createPalette from \"./createPalette.js\";\nimport createThemeWithVars from \"./createThemeWithVars.js\";\nimport createThemeNoVars from \"./createThemeNoVars.js\";\nexport { createMuiTheme } from \"./createThemeNoVars.js\";\n// eslint-disable-next-line consistent-return\nfunction attachColorScheme(theme, scheme, colorScheme) {\n if (!theme.colorSchemes) {\n return undefined;\n }\n if (colorScheme) {\n theme.colorSchemes[scheme] = {\n ...(colorScheme !== true && colorScheme),\n palette: createPalette({\n ...(colorScheme === true ? {} : colorScheme.palette),\n mode: scheme\n }) // cast type to skip module augmentation test\n };\n }\n}\n\n/**\n * Generate a theme base on the options received.\n * @param options Takes an incomplete theme object and adds the missing parts.\n * @param args Deep merge the arguments with the about to be returned theme.\n * @returns A complete, ready-to-use theme object.\n */\nexport default function createTheme(options = {},\n// cast type to skip module augmentation test\n...args) {\n const {\n palette,\n cssVariables = false,\n colorSchemes: initialColorSchemes = !palette ? {\n light: true\n } : undefined,\n defaultColorScheme: initialDefaultColorScheme = palette?.mode,\n ...rest\n } = options;\n const defaultColorSchemeInput = initialDefaultColorScheme || 'light';\n const defaultScheme = initialColorSchemes?.[defaultColorSchemeInput];\n const colorSchemesInput = {\n ...initialColorSchemes,\n ...(palette ? {\n [defaultColorSchemeInput]: {\n ...(typeof defaultScheme !== 'boolean' && defaultScheme),\n palette\n }\n } : undefined)\n };\n if (cssVariables === false) {\n if (!('colorSchemes' in options)) {\n // Behaves exactly as v5\n return createThemeNoVars(options, ...args);\n }\n let paletteOptions = palette;\n if (!('palette' in options)) {\n if (colorSchemesInput[defaultColorSchemeInput]) {\n if (colorSchemesInput[defaultColorSchemeInput] !== true) {\n paletteOptions = colorSchemesInput[defaultColorSchemeInput].palette;\n } else if (defaultColorSchemeInput === 'dark') {\n // @ts-ignore to prevent the module augmentation test from failing\n paletteOptions = {\n mode: 'dark'\n };\n }\n }\n }\n const theme = createThemeNoVars({\n ...options,\n palette: paletteOptions\n }, ...args);\n theme.defaultColorScheme = defaultColorSchemeInput;\n theme.colorSchemes = colorSchemesInput;\n if (theme.palette.mode === 'light') {\n theme.colorSchemes.light = {\n ...(colorSchemesInput.light !== true && colorSchemesInput.light),\n palette: theme.palette\n };\n attachColorScheme(theme, 'dark', colorSchemesInput.dark);\n }\n if (theme.palette.mode === 'dark') {\n theme.colorSchemes.dark = {\n ...(colorSchemesInput.dark !== true && colorSchemesInput.dark),\n palette: theme.palette\n };\n attachColorScheme(theme, 'light', colorSchemesInput.light);\n }\n return theme;\n }\n if (!palette && !('light' in colorSchemesInput) && defaultColorSchemeInput === 'light') {\n colorSchemesInput.light = true;\n }\n return createThemeWithVars({\n ...rest,\n colorSchemes: colorSchemesInput,\n defaultColorScheme: defaultColorSchemeInput,\n ...(typeof cssVariables !== 'boolean' && cssVariables)\n }, ...args);\n}","'use client';\n\nimport createTheme from \"./createTheme.js\";\nconst defaultTheme = createTheme();\nexport default defaultTheme;","'use client';\n\nimport * as React from 'react';\nimport { useTheme as useThemeSystem } from '@mui/system';\nimport defaultTheme from \"./defaultTheme.js\";\nimport THEME_ID from \"./identifier.js\";\nexport default function useTheme() {\n const theme = useThemeSystem(defaultTheme);\n if (process.env.NODE_ENV !== 'production') {\n // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useDebugValue(theme);\n }\n return theme[THEME_ID] || theme;\n}","'use client';\n\nimport systemUseThemeProps from '@mui/system/useThemeProps';\nimport defaultTheme from \"./defaultTheme.js\";\nimport THEME_ID from \"./identifier.js\";\nexport default function useThemeProps({\n props,\n name\n}) {\n return systemUseThemeProps({\n props,\n name,\n defaultTheme,\n themeId: THEME_ID\n });\n}","// copied from @mui/system/createStyled\nfunction slotShouldForwardProp(prop) {\n return prop !== 'ownerState' && prop !== 'theme' && prop !== 'sx' && prop !== 'as';\n}\nexport default slotShouldForwardProp;","import slotShouldForwardProp from \"./slotShouldForwardProp.js\";\nconst rootShouldForwardProp = prop => slotShouldForwardProp(prop) && prop !== 'classes';\nexport default rootShouldForwardProp;","'use client';\n\nimport createStyled from '@mui/system/createStyled';\nimport defaultTheme from \"./defaultTheme.js\";\nimport THEME_ID from \"./identifier.js\";\nimport rootShouldForwardProp from \"./rootShouldForwardProp.js\";\nexport { default as slotShouldForwardProp } from \"./slotShouldForwardProp.js\";\nexport { default as rootShouldForwardProp } from \"./rootShouldForwardProp.js\";\nconst styled = createStyled({\n themeId: THEME_ID,\n defaultTheme,\n rootShouldForwardProp\n});\nexport default styled;","'use client';\n\nimport * as React from 'react';\nimport { ThemeProvider as SystemThemeProvider } from '@mui/system';\nimport THEME_ID from \"./identifier.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default function ThemeProviderNoVars({\n theme: themeInput,\n ...props\n}) {\n const scopedTheme = THEME_ID in themeInput ? themeInput[THEME_ID] : undefined;\n return /*#__PURE__*/_jsx(SystemThemeProvider, {\n ...props,\n themeId: scopedTheme ? THEME_ID : undefined,\n theme: scopedTheme || themeInput\n });\n}","import * as React from 'react';\nimport SystemInitColorSchemeScript from '@mui/system/InitColorSchemeScript';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport const defaultConfig = {\n attribute: 'data-mui-color-scheme',\n colorSchemeStorageKey: 'mui-color-scheme',\n defaultLightColorScheme: 'light',\n defaultDarkColorScheme: 'dark',\n modeStorageKey: 'mui-mode'\n};\nexport default (function InitColorSchemeScript(props) {\n return /*#__PURE__*/_jsx(SystemInitColorSchemeScript, {\n ...defaultConfig,\n ...props\n });\n});","'use client';\n\nimport * as React from 'react';\nimport styleFunctionSx from '@mui/system/styleFunctionSx';\nimport { unstable_createCssVarsProvider as createCssVarsProvider } from '@mui/system';\nimport createTheme from \"./createTheme.js\";\nimport createTypography from \"./createTypography.js\";\nimport THEME_ID from \"./identifier.js\";\nimport { defaultConfig } from \"../InitColorSchemeScript/InitColorSchemeScript.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst {\n CssVarsProvider: InternalCssVarsProvider,\n useColorScheme,\n getInitColorSchemeScript: deprecatedGetInitColorSchemeScript\n} = createCssVarsProvider({\n themeId: THEME_ID,\n // @ts-ignore ignore module augmentation tests\n theme: () => createTheme({\n cssVariables: true\n }),\n colorSchemeStorageKey: defaultConfig.colorSchemeStorageKey,\n modeStorageKey: defaultConfig.modeStorageKey,\n defaultColorScheme: {\n light: defaultConfig.defaultLightColorScheme,\n dark: defaultConfig.defaultDarkColorScheme\n },\n resolveTheme: theme => {\n const newTheme = {\n ...theme,\n typography: createTypography(theme.palette, theme.typography)\n };\n newTheme.unstable_sx = function sx(props) {\n return styleFunctionSx({\n sx: props,\n theme: this\n });\n };\n return newTheme;\n }\n});\nlet warnedOnce = false;\n\n// TODO: remove in v7\n// eslint-disable-next-line @typescript-eslint/naming-convention\nfunction Experimental_CssVarsProvider(props) {\n if (process.env.NODE_ENV !== 'production') {\n if (!warnedOnce) {\n console.warn(['MUI: The Experimental_CssVarsProvider component has been ported into ThemeProvider.', '', \"You should use `import { ThemeProvider } from '@mui/material/styles'` instead.\", 'For more details, check out https://mui.com/material-ui/customization/css-theme-variables/usage/'].join('\\n'));\n warnedOnce = true;\n }\n }\n return /*#__PURE__*/_jsx(InternalCssVarsProvider, {\n ...props\n });\n}\nlet warnedInitScriptOnce = false;\n\n// TODO: remove in v7\nconst getInitColorSchemeScript = params => {\n if (!warnedInitScriptOnce) {\n console.warn(['MUI: The getInitColorSchemeScript function has been deprecated.', '', \"You should use `import InitColorSchemeScript from '@mui/material/InitColorSchemeScript'`\", 'and replace the function call with `` instead.'].join('\\n'));\n warnedInitScriptOnce = true;\n }\n return deprecatedGetInitColorSchemeScript(params);\n};\n\n/**\n * TODO: remove this export in v7\n * @deprecated\n * The `CssVarsProvider` component has been deprecated and ported into `ThemeProvider`.\n *\n * You should use `ThemeProvider` and `createTheme()` instead:\n *\n * ```diff\n * - import { CssVarsProvider, extendTheme } from '@mui/material/styles';\n * + import { ThemeProvider, createTheme } from '@mui/material/styles';\n *\n * - const theme = extendTheme();\n * + const theme = createTheme({\n * + cssVariables: true,\n * + colorSchemes: { light: true, dark: true },\n * + });\n *\n * - \n * + \n * ```\n *\n * To see the full documentation, check out https://mui.com/material-ui/customization/css-theme-variables/usage/.\n */\nexport const CssVarsProvider = InternalCssVarsProvider;\nexport { useColorScheme, getInitColorSchemeScript, Experimental_CssVarsProvider };","'use client';\n\nimport * as React from 'react';\nimport ThemeProviderNoVars from \"./ThemeProviderNoVars.js\";\nimport { CssVarsProvider } from \"./ThemeProviderWithVars.js\";\nimport THEME_ID from \"./identifier.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default function ThemeProvider({\n theme,\n ...props\n}) {\n if (typeof theme === 'function') {\n return /*#__PURE__*/_jsx(ThemeProviderNoVars, {\n theme: theme,\n ...props\n });\n }\n const muiTheme = THEME_ID in theme ? theme[THEME_ID] : theme;\n if (!('colorSchemes' in muiTheme)) {\n return /*#__PURE__*/_jsx(ThemeProviderNoVars, {\n theme: theme,\n ...props\n });\n }\n return /*#__PURE__*/_jsx(CssVarsProvider, {\n theme: theme,\n ...props\n });\n}","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { GlobalStyles as SystemGlobalStyles } from '@mui/system';\nimport defaultTheme from \"../styles/defaultTheme.js\";\nimport THEME_ID from \"../styles/identifier.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction GlobalStyles(props) {\n return /*#__PURE__*/_jsx(SystemGlobalStyles, {\n ...props,\n defaultTheme: defaultTheme,\n themeId: THEME_ID\n });\n}\nprocess.env.NODE_ENV !== \"production\" ? GlobalStyles.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The styles you want to apply globally.\n */\n styles: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.array, PropTypes.func, PropTypes.number, PropTypes.object, PropTypes.string, PropTypes.bool])\n} : void 0;\nexport default GlobalStyles;","import * as React from 'react';\nimport { extendSxProp } from '@mui/system/styleFunctionSx';\nimport useTheme from \"../styles/useTheme.js\";\nimport GlobalStyles from \"../GlobalStyles/index.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport { css, keyframes } from '@mui/system';\nexport { default as styled } from \"../styles/styled.js\";\nexport function globalCss(styles) {\n return function GlobalStylesWrapper(props) {\n return (\n /*#__PURE__*/\n // Pigment CSS `globalCss` support callback with theme inside an object but `GlobalStyles` support theme as a callback value.\n _jsx(GlobalStyles, {\n styles: typeof styles === 'function' ? theme => styles({\n theme,\n ...props\n }) : styles\n })\n );\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function internal_createExtendSxProp() {\n return extendSxProp;\n}\nexport { useTheme };","import { unstable_memoTheme } from '@mui/system';\nconst memoTheme = unstable_memoTheme;\nexport default memoTheme;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport SystemDefaultPropsProvider, { useDefaultProps as useSystemDefaultProps } from '@mui/system/DefaultPropsProvider';\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction DefaultPropsProvider(props) {\n return /*#__PURE__*/_jsx(SystemDefaultPropsProvider, {\n ...props\n });\n}\nprocess.env.NODE_ENV !== \"production\" ? DefaultPropsProvider.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the TypeScript types and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * @ignore\n */\n children: PropTypes.node,\n /**\n * @ignore\n */\n value: PropTypes.object.isRequired\n} : void 0;\nexport default DefaultPropsProvider;\nexport function useDefaultProps(params) {\n return useSystemDefaultProps(params);\n}","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getSvgIconUtilityClass(slot) {\n return generateUtilityClass('MuiSvgIcon', slot);\n}\nconst svgIconClasses = generateUtilityClasses('MuiSvgIcon', ['root', 'colorPrimary', 'colorSecondary', 'colorAction', 'colorError', 'colorDisabled', 'fontSizeInherit', 'fontSizeSmall', 'fontSizeMedium', 'fontSizeLarge']);\nexport default svgIconClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport capitalize from \"../utils/capitalize.js\";\nimport { styled } from \"../zero-styled/index.js\";\nimport memoTheme from \"../utils/memoTheme.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport { getSvgIconUtilityClass } from \"./svgIconClasses.js\";\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n color,\n fontSize,\n classes\n } = ownerState;\n const slots = {\n root: ['root', color !== 'inherit' && `color${capitalize(color)}`, `fontSize${capitalize(fontSize)}`]\n };\n return composeClasses(slots, getSvgIconUtilityClass, classes);\n};\nconst SvgIconRoot = styled('svg', {\n name: 'MuiSvgIcon',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.color !== 'inherit' && styles[`color${capitalize(ownerState.color)}`], styles[`fontSize${capitalize(ownerState.fontSize)}`]];\n }\n})(memoTheme(({\n theme\n}) => ({\n userSelect: 'none',\n width: '1em',\n height: '1em',\n display: 'inline-block',\n flexShrink: 0,\n transition: theme.transitions?.create?.('fill', {\n duration: (theme.vars ?? theme).transitions?.duration?.shorter\n }),\n variants: [{\n props: props => !props.hasSvgAsChild,\n style: {\n // the will define the property that has `currentColor`\n // for example heroicons uses fill=\"none\" and stroke=\"currentColor\"\n fill: 'currentColor'\n }\n }, {\n props: {\n fontSize: 'inherit'\n },\n style: {\n fontSize: 'inherit'\n }\n }, {\n props: {\n fontSize: 'small'\n },\n style: {\n fontSize: theme.typography?.pxToRem?.(20) || '1.25rem'\n }\n }, {\n props: {\n fontSize: 'medium'\n },\n style: {\n fontSize: theme.typography?.pxToRem?.(24) || '1.5rem'\n }\n }, {\n props: {\n fontSize: 'large'\n },\n style: {\n fontSize: theme.typography?.pxToRem?.(35) || '2.1875rem'\n }\n },\n // TODO v5 deprecate color prop, v6 remove for sx\n ...Object.entries((theme.vars ?? theme).palette).filter(([, value]) => value && value.main).map(([color]) => ({\n props: {\n color\n },\n style: {\n color: (theme.vars ?? theme).palette?.[color]?.main\n }\n })), {\n props: {\n color: 'action'\n },\n style: {\n color: (theme.vars ?? theme).palette?.action?.active\n }\n }, {\n props: {\n color: 'disabled'\n },\n style: {\n color: (theme.vars ?? theme).palette?.action?.disabled\n }\n }, {\n props: {\n color: 'inherit'\n },\n style: {\n color: undefined\n }\n }]\n})));\nconst SvgIcon = /*#__PURE__*/React.forwardRef(function SvgIcon(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiSvgIcon'\n });\n const {\n children,\n className,\n color = 'inherit',\n component = 'svg',\n fontSize = 'medium',\n htmlColor,\n inheritViewBox = false,\n titleAccess,\n viewBox = '0 0 24 24',\n ...other\n } = props;\n const hasSvgAsChild = /*#__PURE__*/React.isValidElement(children) && children.type === 'svg';\n const ownerState = {\n ...props,\n color,\n component,\n fontSize,\n instanceFontSize: inProps.fontSize,\n inheritViewBox,\n viewBox,\n hasSvgAsChild\n };\n const more = {};\n if (!inheritViewBox) {\n more.viewBox = viewBox;\n }\n const classes = useUtilityClasses(ownerState);\n return /*#__PURE__*/_jsxs(SvgIconRoot, {\n as: component,\n className: clsx(classes.root, className),\n focusable: \"false\",\n color: htmlColor,\n \"aria-hidden\": titleAccess ? undefined : true,\n role: titleAccess ? 'img' : undefined,\n ref: ref,\n ...more,\n ...other,\n ...(hasSvgAsChild && children.props),\n ownerState: ownerState,\n children: [hasSvgAsChild ? children.props.children : children, titleAccess ? /*#__PURE__*/_jsx(\"title\", {\n children: titleAccess\n }) : null]\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? SvgIcon.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Node passed into the SVG element.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The color of the component.\n * It supports both default and custom theme colors, which can be added as shown in the\n * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).\n * You can use the `htmlColor` prop to apply a color attribute to the SVG element.\n * @default 'inherit'\n */\n color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['inherit', 'action', 'disabled', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * The fontSize applied to the icon. Defaults to 24px, but can be configure to inherit font size.\n * @default 'medium'\n */\n fontSize: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['inherit', 'large', 'medium', 'small']), PropTypes.string]),\n /**\n * Applies a color attribute to the SVG element.\n */\n htmlColor: PropTypes.string,\n /**\n * If `true`, the root node will inherit the custom `component`'s viewBox and the `viewBox`\n * prop will be ignored.\n * Useful when you want to reference a custom `component` and have `SvgIcon` pass that\n * `component`'s viewBox to the root node.\n * @default false\n */\n inheritViewBox: PropTypes.bool,\n /**\n * The shape-rendering attribute. The behavior of the different options is described on the\n * [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/shape-rendering).\n * If you are having issues with blurry icons you should investigate this prop.\n */\n shapeRendering: PropTypes.string,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * Provides a human-readable title for the element that contains it.\n * https://www.w3.org/TR/SVG-access/#Equivalent\n */\n titleAccess: PropTypes.string,\n /**\n * Allows you to redefine what the coordinates without units mean inside an SVG element.\n * For example, if the SVG element is 500 (width) by 200 (height),\n * and you pass viewBox=\"0 0 50 20\",\n * this means that the coordinates inside the SVG will go from the top left corner (0,0)\n * to bottom right (50,20) and each unit will be worth 10px.\n * @default '0 0 24 24'\n */\n viewBox: PropTypes.string\n} : void 0;\nSvgIcon.muiName = 'SvgIcon';\nexport default SvgIcon;","'use client';\n\nimport * as React from 'react';\nimport SvgIcon from \"../SvgIcon/index.js\";\n\n/**\n * Private module reserved for @mui packages.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default function createSvgIcon(path, displayName) {\n function Component(props, ref) {\n return /*#__PURE__*/_jsx(SvgIcon, {\n \"data-testid\": `${displayName}Icon`,\n ref: ref,\n ...props,\n children: path\n });\n }\n if (process.env.NODE_ENV !== 'production') {\n // Need to set `displayName` on the inner component for React.memo.\n // React prior to 16.14 ignores `displayName` on the wrapper.\n Component.displayName = `${displayName}Icon`;\n }\n Component.muiName = SvgIcon.muiName;\n return /*#__PURE__*/React.memo(/*#__PURE__*/React.forwardRef(Component));\n}","import clsx from 'clsx';\nexport default function mergeSlotProps(externalSlotProps, defaultSlotProps) {\n if (!externalSlotProps) {\n return defaultSlotProps;\n }\n if (typeof externalSlotProps === 'function' || typeof defaultSlotProps === 'function') {\n return ownerState => {\n const defaultSlotPropsValue = typeof defaultSlotProps === 'function' ? defaultSlotProps(ownerState) : defaultSlotProps;\n const externalSlotPropsValue = typeof externalSlotProps === 'function' ? externalSlotProps({\n ...ownerState,\n ...defaultSlotPropsValue\n }) : externalSlotProps;\n const className = clsx(ownerState?.className, defaultSlotPropsValue?.className, externalSlotPropsValue?.className);\n return {\n ...defaultSlotPropsValue,\n ...externalSlotPropsValue,\n ...(!!className && {\n className\n }),\n ...(defaultSlotPropsValue?.style && externalSlotPropsValue?.style && {\n style: {\n ...defaultSlotPropsValue.style,\n ...externalSlotPropsValue.style\n }\n }),\n ...(defaultSlotPropsValue?.sx && externalSlotPropsValue?.sx && {\n sx: [...(Array.isArray(defaultSlotPropsValue.sx) ? defaultSlotPropsValue.sx : [defaultSlotPropsValue.sx]), ...(Array.isArray(externalSlotPropsValue.sx) ? externalSlotPropsValue.sx : [externalSlotPropsValue.sx])]\n })\n };\n };\n }\n const typedDefaultSlotProps = defaultSlotProps;\n const className = clsx(typedDefaultSlotProps?.className, externalSlotProps?.className);\n return {\n ...defaultSlotProps,\n ...externalSlotProps,\n ...(!!className && {\n className\n }),\n ...(typedDefaultSlotProps?.style && externalSlotProps?.style && {\n style: {\n ...typedDefaultSlotProps.style,\n ...externalSlotProps.style\n }\n }),\n ...(typedDefaultSlotProps?.sx && externalSlotProps?.sx && {\n sx: [...(Array.isArray(typedDefaultSlotProps.sx) ? typedDefaultSlotProps.sx : [typedDefaultSlotProps.sx]), ...(Array.isArray(externalSlotProps.sx) ? externalSlotProps.sx : [externalSlotProps.sx])]\n })\n };\n}","export const reflow = node => node.scrollTop;\nexport function getTransitionProps(props, options) {\n const {\n timeout,\n easing,\n style = {}\n } = props;\n return {\n duration: style.transitionDuration ?? (typeof timeout === 'number' ? timeout : timeout[options.mode] || 0),\n easing: style.transitionTimingFunction ?? (typeof easing === 'object' ? easing[options.mode] : easing),\n delay: style.transitionDelay\n };\n}","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getPaperUtilityClass(slot) {\n return generateUtilityClass('MuiPaper', slot);\n}\nconst paperClasses = generateUtilityClasses('MuiPaper', ['root', 'rounded', 'outlined', 'elevation', 'elevation0', 'elevation1', 'elevation2', 'elevation3', 'elevation4', 'elevation5', 'elevation6', 'elevation7', 'elevation8', 'elevation9', 'elevation10', 'elevation11', 'elevation12', 'elevation13', 'elevation14', 'elevation15', 'elevation16', 'elevation17', 'elevation18', 'elevation19', 'elevation20', 'elevation21', 'elevation22', 'elevation23', 'elevation24']);\nexport default paperClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport integerPropType from '@mui/utils/integerPropType';\nimport chainPropTypes from '@mui/utils/chainPropTypes';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { alpha } from '@mui/system/colorManipulator';\nimport { styled, useTheme } from \"../zero-styled/index.js\";\nimport memoTheme from \"../utils/memoTheme.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport getOverlayAlpha from \"../styles/getOverlayAlpha.js\";\nimport { getPaperUtilityClass } from \"./paperClasses.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n square,\n elevation,\n variant,\n classes\n } = ownerState;\n const slots = {\n root: ['root', variant, !square && 'rounded', variant === 'elevation' && `elevation${elevation}`]\n };\n return composeClasses(slots, getPaperUtilityClass, classes);\n};\nconst PaperRoot = styled('div', {\n name: 'MuiPaper',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, styles[ownerState.variant], !ownerState.square && styles.rounded, ownerState.variant === 'elevation' && styles[`elevation${ownerState.elevation}`]];\n }\n})(memoTheme(({\n theme\n}) => ({\n backgroundColor: (theme.vars || theme).palette.background.paper,\n color: (theme.vars || theme).palette.text.primary,\n transition: theme.transitions.create('box-shadow'),\n variants: [{\n props: ({\n ownerState\n }) => !ownerState.square,\n style: {\n borderRadius: theme.shape.borderRadius\n }\n }, {\n props: {\n variant: 'outlined'\n },\n style: {\n border: `1px solid ${(theme.vars || theme).palette.divider}`\n }\n }, {\n props: {\n variant: 'elevation'\n },\n style: {\n boxShadow: 'var(--Paper-shadow)',\n backgroundImage: 'var(--Paper-overlay)'\n }\n }]\n})));\nconst Paper = /*#__PURE__*/React.forwardRef(function Paper(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiPaper'\n });\n const theme = useTheme();\n const {\n className,\n component = 'div',\n elevation = 1,\n square = false,\n variant = 'elevation',\n ...other\n } = props;\n const ownerState = {\n ...props,\n component,\n elevation,\n square,\n variant\n };\n const classes = useUtilityClasses(ownerState);\n if (process.env.NODE_ENV !== 'production') {\n if (theme.shadows[elevation] === undefined) {\n console.error([`MUI: The elevation provided is not available in the theme.`, `Please make sure that \\`theme.shadows[${elevation}]\\` is defined.`].join('\\n'));\n }\n }\n return /*#__PURE__*/_jsx(PaperRoot, {\n as: component,\n ownerState: ownerState,\n className: clsx(classes.root, className),\n ref: ref,\n ...other,\n style: {\n ...(variant === 'elevation' && {\n '--Paper-shadow': (theme.vars || theme).shadows[elevation],\n ...(theme.vars && {\n '--Paper-overlay': theme.vars.overlays?.[elevation]\n }),\n ...(!theme.vars && theme.palette.mode === 'dark' && {\n '--Paper-overlay': `linear-gradient(${alpha('#fff', getOverlayAlpha(elevation))}, ${alpha('#fff', getOverlayAlpha(elevation))})`\n })\n }),\n ...other.style\n }\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Paper.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * Shadow depth, corresponds to `dp` in the spec.\n * It accepts values between 0 and 24 inclusive.\n * @default 1\n */\n elevation: chainPropTypes(integerPropType, props => {\n const {\n elevation,\n variant\n } = props;\n if (elevation > 0 && variant === 'outlined') {\n return new Error(`MUI: Combining \\`elevation={${elevation}}\\` with \\`variant=\"${variant}\"\\` has no effect. Either use \\`elevation={0}\\` or use a different \\`variant\\`.`);\n }\n return null;\n }),\n /**\n * If `true`, rounded corners are disabled.\n * @default false\n */\n square: PropTypes.bool,\n /**\n * @ignore\n */\n style: PropTypes.object,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The variant to use.\n * @default 'elevation'\n */\n variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['elevation', 'outlined']), PropTypes.string])\n} : void 0;\nexport default Paper;","'use client';\n\nimport useForkRef from '@mui/utils/useForkRef';\nimport appendOwnerState from '@mui/utils/appendOwnerState';\nimport resolveComponentProps from '@mui/utils/resolveComponentProps';\nimport mergeSlotProps from '@mui/utils/mergeSlotProps';\n/**\n * An internal function to create a Material UI slot.\n *\n * This is an advanced version of Base UI `useSlotProps` because Material UI allows leaf component to be customized via `component` prop\n * while Base UI does not need to support leaf component customization.\n *\n * @param {string} name: name of the slot\n * @param {object} parameters\n * @returns {[Slot, slotProps]} The slot's React component and the slot's props\n *\n * Note: the returned slot's props\n * - will never contain `component` prop.\n * - might contain `as` prop.\n */\nexport default function useSlot(\n/**\n * The slot's name. All Material UI components should have `root` slot.\n *\n * If the name is `root`, the logic behaves differently from other slots,\n * e.g. the `externalForwardedProps` are spread to `root` slot but not other slots.\n */\nname, parameters) {\n const {\n className,\n elementType: initialElementType,\n ownerState,\n externalForwardedProps,\n internalForwardedProps,\n shouldForwardComponentProp = false,\n ...useSlotPropsParams\n } = parameters;\n const {\n component: rootComponent,\n slots = {\n [name]: undefined\n },\n slotProps = {\n [name]: undefined\n },\n ...other\n } = externalForwardedProps;\n const elementType = slots[name] || initialElementType;\n\n // `slotProps[name]` can be a callback that receives the component's ownerState.\n // `resolvedComponentsProps` is always a plain object.\n const resolvedComponentsProps = resolveComponentProps(slotProps[name], ownerState);\n const {\n props: {\n component: slotComponent,\n ...mergedProps\n },\n internalRef\n } = mergeSlotProps({\n className,\n ...useSlotPropsParams,\n externalForwardedProps: name === 'root' ? other : undefined,\n externalSlotProps: resolvedComponentsProps\n });\n const ref = useForkRef(internalRef, resolvedComponentsProps?.ref, parameters.ref);\n const LeafComponent = name === 'root' ? slotComponent || rootComponent : slotComponent;\n const props = appendOwnerState(elementType, {\n ...(name === 'root' && !rootComponent && !slots[name] && internalForwardedProps),\n ...(name !== 'root' && !slots[name] && internalForwardedProps),\n ...mergedProps,\n ...(LeafComponent && !shouldForwardComponentProp && {\n as: LeafComponent\n }),\n ...(LeafComponent && shouldForwardComponentProp && {\n component: LeafComponent\n }),\n ref\n }, ownerState);\n return [elementType, props];\n}","'use client';\n\nimport * as React from 'react';\nimport useLazyRef from '@mui/utils/useLazyRef';\n/**\n * Lazy initialization container for the Ripple instance. This improves\n * performance by delaying mounting the ripple until it's needed.\n */\nexport class LazyRipple {\n /** React ref to the ripple instance */\n\n /** If the ripple component should be mounted */\n\n /** Promise that resolves when the ripple component is mounted */\n\n /** If the ripple component has been mounted */\n\n /** React state hook setter */\n\n static create() {\n return new LazyRipple();\n }\n static use() {\n /* eslint-disable */\n const ripple = useLazyRef(LazyRipple.create).current;\n const [shouldMount, setShouldMount] = React.useState(false);\n ripple.shouldMount = shouldMount;\n ripple.setShouldMount = setShouldMount;\n React.useEffect(ripple.mountEffect, [shouldMount]);\n /* eslint-enable */\n\n return ripple;\n }\n constructor() {\n this.ref = {\n current: null\n };\n this.mounted = null;\n this.didMount = false;\n this.shouldMount = false;\n this.setShouldMount = null;\n }\n mount() {\n if (!this.mounted) {\n this.mounted = createControlledPromise();\n this.shouldMount = true;\n this.setShouldMount(this.shouldMount);\n }\n return this.mounted;\n }\n mountEffect = () => {\n if (this.shouldMount && !this.didMount) {\n if (this.ref.current !== null) {\n this.didMount = true;\n this.mounted.resolve();\n }\n }\n };\n\n /* Ripple API */\n\n start(...args) {\n this.mount().then(() => this.ref.current?.start(...args));\n }\n stop(...args) {\n this.mount().then(() => this.ref.current?.stop(...args));\n }\n pulsate(...args) {\n this.mount().then(() => this.ref.current?.pulsate(...args));\n }\n}\nexport default function useLazyRipple() {\n return LazyRipple.use();\n}\nfunction createControlledPromise() {\n let resolve;\n let reject;\n const p = new Promise((resolveFn, rejectFn) => {\n resolve = resolveFn;\n reject = rejectFn;\n });\n p.resolve = resolve;\n p.reject = reject;\n return p;\n}","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction Ripple(props) {\n const {\n className,\n classes,\n pulsate = false,\n rippleX,\n rippleY,\n rippleSize,\n in: inProp,\n onExited,\n timeout\n } = props;\n const [leaving, setLeaving] = React.useState(false);\n const rippleClassName = clsx(className, classes.ripple, classes.rippleVisible, pulsate && classes.ripplePulsate);\n const rippleStyles = {\n width: rippleSize,\n height: rippleSize,\n top: -(rippleSize / 2) + rippleY,\n left: -(rippleSize / 2) + rippleX\n };\n const childClassName = clsx(classes.child, leaving && classes.childLeaving, pulsate && classes.childPulsate);\n if (!inProp && !leaving) {\n setLeaving(true);\n }\n React.useEffect(() => {\n if (!inProp && onExited != null) {\n // react-transition-group#onExited\n const timeoutId = setTimeout(onExited, timeout);\n return () => {\n clearTimeout(timeoutId);\n };\n }\n return undefined;\n }, [onExited, inProp, timeout]);\n return /*#__PURE__*/_jsx(\"span\", {\n className: rippleClassName,\n style: rippleStyles,\n children: /*#__PURE__*/_jsx(\"span\", {\n className: childClassName\n })\n });\n}\nprocess.env.NODE_ENV !== \"production\" ? Ripple.propTypes /* remove-proptypes */ = {\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object.isRequired,\n className: PropTypes.string,\n /**\n * @ignore - injected from TransitionGroup\n */\n in: PropTypes.bool,\n /**\n * @ignore - injected from TransitionGroup\n */\n onExited: PropTypes.func,\n /**\n * If `true`, the ripple pulsates, typically indicating the keyboard focus state of an element.\n */\n pulsate: PropTypes.bool,\n /**\n * Diameter of the ripple.\n */\n rippleSize: PropTypes.number,\n /**\n * Horizontal position of the ripple center.\n */\n rippleX: PropTypes.number,\n /**\n * Vertical position of the ripple center.\n */\n rippleY: PropTypes.number,\n /**\n * exit delay\n */\n timeout: PropTypes.number.isRequired\n} : void 0;\nexport default Ripple;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getTouchRippleUtilityClass(slot) {\n return generateUtilityClass('MuiTouchRipple', slot);\n}\nconst touchRippleClasses = generateUtilityClasses('MuiTouchRipple', ['root', 'ripple', 'rippleVisible', 'ripplePulsate', 'child', 'childLeaving', 'childPulsate']);\nexport default touchRippleClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { TransitionGroup } from 'react-transition-group';\nimport clsx from 'clsx';\nimport useTimeout from '@mui/utils/useTimeout';\nimport { keyframes, styled } from \"../zero-styled/index.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport Ripple from \"./Ripple.js\";\nimport touchRippleClasses from \"./touchRippleClasses.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst DURATION = 550;\nexport const DELAY_RIPPLE = 80;\nconst enterKeyframe = keyframes`\n 0% {\n transform: scale(0);\n opacity: 0.1;\n }\n\n 100% {\n transform: scale(1);\n opacity: 0.3;\n }\n`;\nconst exitKeyframe = keyframes`\n 0% {\n opacity: 1;\n }\n\n 100% {\n opacity: 0;\n }\n`;\nconst pulsateKeyframe = keyframes`\n 0% {\n transform: scale(1);\n }\n\n 50% {\n transform: scale(0.92);\n }\n\n 100% {\n transform: scale(1);\n }\n`;\nexport const TouchRippleRoot = styled('span', {\n name: 'MuiTouchRipple',\n slot: 'Root'\n})({\n overflow: 'hidden',\n pointerEvents: 'none',\n position: 'absolute',\n zIndex: 0,\n top: 0,\n right: 0,\n bottom: 0,\n left: 0,\n borderRadius: 'inherit'\n});\n\n// This `styled()` function invokes keyframes. `styled-components` only supports keyframes\n// in string templates. Do not convert these styles in JS object as it will break.\nexport const TouchRippleRipple = styled(Ripple, {\n name: 'MuiTouchRipple',\n slot: 'Ripple'\n})`\n opacity: 0;\n position: absolute;\n\n &.${touchRippleClasses.rippleVisible} {\n opacity: 0.3;\n transform: scale(1);\n animation-name: ${enterKeyframe};\n animation-duration: ${DURATION}ms;\n animation-timing-function: ${({\n theme\n}) => theme.transitions.easing.easeInOut};\n }\n\n &.${touchRippleClasses.ripplePulsate} {\n animation-duration: ${({\n theme\n}) => theme.transitions.duration.shorter}ms;\n }\n\n & .${touchRippleClasses.child} {\n opacity: 1;\n display: block;\n width: 100%;\n height: 100%;\n border-radius: 50%;\n background-color: currentColor;\n }\n\n & .${touchRippleClasses.childLeaving} {\n opacity: 0;\n animation-name: ${exitKeyframe};\n animation-duration: ${DURATION}ms;\n animation-timing-function: ${({\n theme\n}) => theme.transitions.easing.easeInOut};\n }\n\n & .${touchRippleClasses.childPulsate} {\n position: absolute;\n /* @noflip */\n left: 0px;\n top: 0;\n animation-name: ${pulsateKeyframe};\n animation-duration: 2500ms;\n animation-timing-function: ${({\n theme\n}) => theme.transitions.easing.easeInOut};\n animation-iteration-count: infinite;\n animation-delay: 200ms;\n }\n`;\n\n/**\n * @ignore - internal component.\n *\n * TODO v5: Make private\n */\nconst TouchRipple = /*#__PURE__*/React.forwardRef(function TouchRipple(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiTouchRipple'\n });\n const {\n center: centerProp = false,\n classes = {},\n className,\n ...other\n } = props;\n const [ripples, setRipples] = React.useState([]);\n const nextKey = React.useRef(0);\n const rippleCallback = React.useRef(null);\n React.useEffect(() => {\n if (rippleCallback.current) {\n rippleCallback.current();\n rippleCallback.current = null;\n }\n }, [ripples]);\n\n // Used to filter out mouse emulated events on mobile.\n const ignoringMouseDown = React.useRef(false);\n // We use a timer in order to only show the ripples for touch \"click\" like events.\n // We don't want to display the ripple for touch scroll events.\n const startTimer = useTimeout();\n\n // This is the hook called once the previous timeout is ready.\n const startTimerCommit = React.useRef(null);\n const container = React.useRef(null);\n const startCommit = React.useCallback(params => {\n const {\n pulsate,\n rippleX,\n rippleY,\n rippleSize,\n cb\n } = params;\n setRipples(oldRipples => [...oldRipples, /*#__PURE__*/_jsx(TouchRippleRipple, {\n classes: {\n ripple: clsx(classes.ripple, touchRippleClasses.ripple),\n rippleVisible: clsx(classes.rippleVisible, touchRippleClasses.rippleVisible),\n ripplePulsate: clsx(classes.ripplePulsate, touchRippleClasses.ripplePulsate),\n child: clsx(classes.child, touchRippleClasses.child),\n childLeaving: clsx(classes.childLeaving, touchRippleClasses.childLeaving),\n childPulsate: clsx(classes.childPulsate, touchRippleClasses.childPulsate)\n },\n timeout: DURATION,\n pulsate: pulsate,\n rippleX: rippleX,\n rippleY: rippleY,\n rippleSize: rippleSize\n }, nextKey.current)]);\n nextKey.current += 1;\n rippleCallback.current = cb;\n }, [classes]);\n const start = React.useCallback((event = {}, options = {}, cb = () => {}) => {\n const {\n pulsate = false,\n center = centerProp || options.pulsate,\n fakeElement = false // For test purposes\n } = options;\n if (event?.type === 'mousedown' && ignoringMouseDown.current) {\n ignoringMouseDown.current = false;\n return;\n }\n if (event?.type === 'touchstart') {\n ignoringMouseDown.current = true;\n }\n const element = fakeElement ? null : container.current;\n const rect = element ? element.getBoundingClientRect() : {\n width: 0,\n height: 0,\n left: 0,\n top: 0\n };\n\n // Get the size of the ripple\n let rippleX;\n let rippleY;\n let rippleSize;\n if (center || event === undefined || event.clientX === 0 && event.clientY === 0 || !event.clientX && !event.touches) {\n rippleX = Math.round(rect.width / 2);\n rippleY = Math.round(rect.height / 2);\n } else {\n const {\n clientX,\n clientY\n } = event.touches && event.touches.length > 0 ? event.touches[0] : event;\n rippleX = Math.round(clientX - rect.left);\n rippleY = Math.round(clientY - rect.top);\n }\n if (center) {\n rippleSize = Math.sqrt((2 * rect.width ** 2 + rect.height ** 2) / 3);\n\n // For some reason the animation is broken on Mobile Chrome if the size is even.\n if (rippleSize % 2 === 0) {\n rippleSize += 1;\n }\n } else {\n const sizeX = Math.max(Math.abs((element ? element.clientWidth : 0) - rippleX), rippleX) * 2 + 2;\n const sizeY = Math.max(Math.abs((element ? element.clientHeight : 0) - rippleY), rippleY) * 2 + 2;\n rippleSize = Math.sqrt(sizeX ** 2 + sizeY ** 2);\n }\n\n // Touche devices\n if (event?.touches) {\n // check that this isn't another touchstart due to multitouch\n // otherwise we will only clear a single timer when unmounting while two\n // are running\n if (startTimerCommit.current === null) {\n // Prepare the ripple effect.\n startTimerCommit.current = () => {\n startCommit({\n pulsate,\n rippleX,\n rippleY,\n rippleSize,\n cb\n });\n };\n // Delay the execution of the ripple effect.\n // We have to make a tradeoff with this delay value.\n startTimer.start(DELAY_RIPPLE, () => {\n if (startTimerCommit.current) {\n startTimerCommit.current();\n startTimerCommit.current = null;\n }\n });\n }\n } else {\n startCommit({\n pulsate,\n rippleX,\n rippleY,\n rippleSize,\n cb\n });\n }\n }, [centerProp, startCommit, startTimer]);\n const pulsate = React.useCallback(() => {\n start({}, {\n pulsate: true\n });\n }, [start]);\n const stop = React.useCallback((event, cb) => {\n startTimer.clear();\n\n // The touch interaction occurs too quickly.\n // We still want to show ripple effect.\n if (event?.type === 'touchend' && startTimerCommit.current) {\n startTimerCommit.current();\n startTimerCommit.current = null;\n startTimer.start(0, () => {\n stop(event, cb);\n });\n return;\n }\n startTimerCommit.current = null;\n setRipples(oldRipples => {\n if (oldRipples.length > 0) {\n return oldRipples.slice(1);\n }\n return oldRipples;\n });\n rippleCallback.current = cb;\n }, [startTimer]);\n React.useImperativeHandle(ref, () => ({\n pulsate,\n start,\n stop\n }), [pulsate, start, stop]);\n return /*#__PURE__*/_jsx(TouchRippleRoot, {\n className: clsx(touchRippleClasses.root, classes.root, className),\n ref: container,\n ...other,\n children: /*#__PURE__*/_jsx(TransitionGroup, {\n component: null,\n exit: true,\n children: ripples\n })\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? TouchRipple.propTypes /* remove-proptypes */ = {\n /**\n * If `true`, the ripple starts at the center of the component\n * rather than at the point of interaction.\n */\n center: PropTypes.bool,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string\n} : void 0;\nexport default TouchRipple;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getButtonBaseUtilityClass(slot) {\n return generateUtilityClass('MuiButtonBase', slot);\n}\nconst buttonBaseClasses = generateUtilityClasses('MuiButtonBase', ['root', 'disabled', 'focusVisible']);\nexport default buttonBaseClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport refType from '@mui/utils/refType';\nimport elementTypeAcceptingRef from '@mui/utils/elementTypeAcceptingRef';\nimport composeClasses from '@mui/utils/composeClasses';\nimport isFocusVisible from '@mui/utils/isFocusVisible';\nimport { styled } from \"../zero-styled/index.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport useForkRef from \"../utils/useForkRef.js\";\nimport useEventCallback from \"../utils/useEventCallback.js\";\nimport useLazyRipple from \"../useLazyRipple/index.js\";\nimport TouchRipple from \"./TouchRipple.js\";\nimport buttonBaseClasses, { getButtonBaseUtilityClass } from \"./buttonBaseClasses.js\";\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n disabled,\n focusVisible,\n focusVisibleClassName,\n classes\n } = ownerState;\n const slots = {\n root: ['root', disabled && 'disabled', focusVisible && 'focusVisible']\n };\n const composedClasses = composeClasses(slots, getButtonBaseUtilityClass, classes);\n if (focusVisible && focusVisibleClassName) {\n composedClasses.root += ` ${focusVisibleClassName}`;\n }\n return composedClasses;\n};\nexport const ButtonBaseRoot = styled('button', {\n name: 'MuiButtonBase',\n slot: 'Root',\n overridesResolver: (props, styles) => styles.root\n})({\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n position: 'relative',\n boxSizing: 'border-box',\n WebkitTapHighlightColor: 'transparent',\n backgroundColor: 'transparent',\n // Reset default value\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0,\n border: 0,\n margin: 0,\n // Remove the margin in Safari\n borderRadius: 0,\n padding: 0,\n // Remove the padding in Firefox\n cursor: 'pointer',\n userSelect: 'none',\n verticalAlign: 'middle',\n MozAppearance: 'none',\n // Reset\n WebkitAppearance: 'none',\n // Reset\n textDecoration: 'none',\n // So we take precedent over the style of a native element.\n color: 'inherit',\n '&::-moz-focus-inner': {\n borderStyle: 'none' // Remove Firefox dotted outline.\n },\n [`&.${buttonBaseClasses.disabled}`]: {\n pointerEvents: 'none',\n // Disable link interactions\n cursor: 'default'\n },\n '@media print': {\n colorAdjust: 'exact'\n }\n});\n\n/**\n * `ButtonBase` contains as few styles as possible.\n * It aims to be a simple building block for creating a button.\n * It contains a load of style reset and some focus/ripple logic.\n */\nconst ButtonBase = /*#__PURE__*/React.forwardRef(function ButtonBase(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiButtonBase'\n });\n const {\n action,\n centerRipple = false,\n children,\n className,\n component = 'button',\n disabled = false,\n disableRipple = false,\n disableTouchRipple = false,\n focusRipple = false,\n focusVisibleClassName,\n LinkComponent = 'a',\n onBlur,\n onClick,\n onContextMenu,\n onDragLeave,\n onFocus,\n onFocusVisible,\n onKeyDown,\n onKeyUp,\n onMouseDown,\n onMouseLeave,\n onMouseUp,\n onTouchEnd,\n onTouchMove,\n onTouchStart,\n tabIndex = 0,\n TouchRippleProps,\n touchRippleRef,\n type,\n ...other\n } = props;\n const buttonRef = React.useRef(null);\n const ripple = useLazyRipple();\n const handleRippleRef = useForkRef(ripple.ref, touchRippleRef);\n const [focusVisible, setFocusVisible] = React.useState(false);\n if (disabled && focusVisible) {\n setFocusVisible(false);\n }\n React.useImperativeHandle(action, () => ({\n focusVisible: () => {\n setFocusVisible(true);\n buttonRef.current.focus();\n }\n }), []);\n const enableTouchRipple = ripple.shouldMount && !disableRipple && !disabled;\n React.useEffect(() => {\n if (focusVisible && focusRipple && !disableRipple) {\n ripple.pulsate();\n }\n }, [disableRipple, focusRipple, focusVisible, ripple]);\n const handleMouseDown = useRippleHandler(ripple, 'start', onMouseDown, disableTouchRipple);\n const handleContextMenu = useRippleHandler(ripple, 'stop', onContextMenu, disableTouchRipple);\n const handleDragLeave = useRippleHandler(ripple, 'stop', onDragLeave, disableTouchRipple);\n const handleMouseUp = useRippleHandler(ripple, 'stop', onMouseUp, disableTouchRipple);\n const handleMouseLeave = useRippleHandler(ripple, 'stop', event => {\n if (focusVisible) {\n event.preventDefault();\n }\n if (onMouseLeave) {\n onMouseLeave(event);\n }\n }, disableTouchRipple);\n const handleTouchStart = useRippleHandler(ripple, 'start', onTouchStart, disableTouchRipple);\n const handleTouchEnd = useRippleHandler(ripple, 'stop', onTouchEnd, disableTouchRipple);\n const handleTouchMove = useRippleHandler(ripple, 'stop', onTouchMove, disableTouchRipple);\n const handleBlur = useRippleHandler(ripple, 'stop', event => {\n if (!isFocusVisible(event.target)) {\n setFocusVisible(false);\n }\n if (onBlur) {\n onBlur(event);\n }\n }, false);\n const handleFocus = useEventCallback(event => {\n // Fix for https://github.com/facebook/react/issues/7769\n if (!buttonRef.current) {\n buttonRef.current = event.currentTarget;\n }\n if (isFocusVisible(event.target)) {\n setFocusVisible(true);\n if (onFocusVisible) {\n onFocusVisible(event);\n }\n }\n if (onFocus) {\n onFocus(event);\n }\n });\n const isNonNativeButton = () => {\n const button = buttonRef.current;\n return component && component !== 'button' && !(button.tagName === 'A' && button.href);\n };\n const handleKeyDown = useEventCallback(event => {\n // Check if key is already down to avoid repeats being counted as multiple activations\n if (focusRipple && !event.repeat && focusVisible && event.key === ' ') {\n ripple.stop(event, () => {\n ripple.start(event);\n });\n }\n if (event.target === event.currentTarget && isNonNativeButton() && event.key === ' ') {\n event.preventDefault();\n }\n if (onKeyDown) {\n onKeyDown(event);\n }\n\n // Keyboard accessibility for non interactive elements\n if (event.target === event.currentTarget && isNonNativeButton() && event.key === 'Enter' && !disabled) {\n event.preventDefault();\n if (onClick) {\n onClick(event);\n }\n }\n });\n const handleKeyUp = useEventCallback(event => {\n // calling preventDefault in keyUp on a
`.\n * If you wish to change that mapping, you can provide your own.\n * Alternatively, you can use the `component` prop.\n * @default {\n * h1: 'h1',\n * h2: 'h2',\n * h3: 'h3',\n * h4: 'h4',\n * h5: 'h5',\n * h6: 'h6',\n * subtitle1: 'h6',\n * subtitle2: 'h6',\n * body1: 'p',\n * body2: 'p',\n * inherit: 'p',\n * }\n */\n variantMapping: PropTypes /* @typescript-to-proptypes-ignore */.object\n} : void 0;\nexport default Typography;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getAppBarUtilityClass(slot) {\n return generateUtilityClass('MuiAppBar', slot);\n}\nconst appBarClasses = generateUtilityClasses('MuiAppBar', ['root', 'positionFixed', 'positionAbsolute', 'positionSticky', 'positionStatic', 'positionRelative', 'colorDefault', 'colorPrimary', 'colorSecondary', 'colorInherit', 'colorTransparent', 'colorError', 'colorInfo', 'colorSuccess', 'colorWarning']);\nexport default appBarClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { styled } from \"../zero-styled/index.js\";\nimport memoTheme from \"../utils/memoTheme.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport capitalize from \"../utils/capitalize.js\";\nimport createSimplePaletteValueFilter from \"../utils/createSimplePaletteValueFilter.js\";\nimport Paper from \"../Paper/index.js\";\nimport { getAppBarUtilityClass } from \"./appBarClasses.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n color,\n position,\n classes\n } = ownerState;\n const slots = {\n root: ['root', `color${capitalize(color)}`, `position${capitalize(position)}`]\n };\n return composeClasses(slots, getAppBarUtilityClass, classes);\n};\n\n// var2 is the fallback.\n// Ex. var1: 'var(--a)', var2: 'var(--b)'; return: 'var(--a, var(--b))'\nconst joinVars = (var1, var2) => var1 ? `${var1?.replace(')', '')}, ${var2})` : var2;\nconst AppBarRoot = styled(Paper, {\n name: 'MuiAppBar',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, styles[`position${capitalize(ownerState.position)}`], styles[`color${capitalize(ownerState.color)}`]];\n }\n})(memoTheme(({\n theme\n}) => ({\n display: 'flex',\n flexDirection: 'column',\n width: '100%',\n boxSizing: 'border-box',\n // Prevent padding issue with the Modal and fixed positioned AppBar.\n flexShrink: 0,\n variants: [{\n props: {\n position: 'fixed'\n },\n style: {\n position: 'fixed',\n zIndex: (theme.vars || theme).zIndex.appBar,\n top: 0,\n left: 'auto',\n right: 0,\n '@media print': {\n // Prevent the app bar to be visible on each printed page.\n position: 'absolute'\n }\n }\n }, {\n props: {\n position: 'absolute'\n },\n style: {\n position: 'absolute',\n zIndex: (theme.vars || theme).zIndex.appBar,\n top: 0,\n left: 'auto',\n right: 0\n }\n }, {\n props: {\n position: 'sticky'\n },\n style: {\n position: 'sticky',\n zIndex: (theme.vars || theme).zIndex.appBar,\n top: 0,\n left: 'auto',\n right: 0\n }\n }, {\n props: {\n position: 'static'\n },\n style: {\n position: 'static'\n }\n }, {\n props: {\n position: 'relative'\n },\n style: {\n position: 'relative'\n }\n }, {\n props: {\n color: 'inherit'\n },\n style: {\n '--AppBar-color': 'inherit'\n }\n }, {\n props: {\n color: 'default'\n },\n style: {\n '--AppBar-background': theme.vars ? theme.vars.palette.AppBar.defaultBg : theme.palette.grey[100],\n '--AppBar-color': theme.vars ? theme.vars.palette.text.primary : theme.palette.getContrastText(theme.palette.grey[100]),\n ...theme.applyStyles('dark', {\n '--AppBar-background': theme.vars ? theme.vars.palette.AppBar.defaultBg : theme.palette.grey[900],\n '--AppBar-color': theme.vars ? theme.vars.palette.text.primary : theme.palette.getContrastText(theme.palette.grey[900])\n })\n }\n }, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter(['contrastText'])).map(([color]) => ({\n props: {\n color\n },\n style: {\n '--AppBar-background': (theme.vars ?? theme).palette[color].main,\n '--AppBar-color': (theme.vars ?? theme).palette[color].contrastText\n }\n })), {\n props: props => props.enableColorOnDark === true && !['inherit', 'transparent'].includes(props.color),\n style: {\n backgroundColor: 'var(--AppBar-background)',\n color: 'var(--AppBar-color)'\n }\n }, {\n props: props => props.enableColorOnDark === false && !['inherit', 'transparent'].includes(props.color),\n style: {\n backgroundColor: 'var(--AppBar-background)',\n color: 'var(--AppBar-color)',\n ...theme.applyStyles('dark', {\n backgroundColor: theme.vars ? joinVars(theme.vars.palette.AppBar.darkBg, 'var(--AppBar-background)') : null,\n color: theme.vars ? joinVars(theme.vars.palette.AppBar.darkColor, 'var(--AppBar-color)') : null\n })\n }\n }, {\n props: {\n color: 'transparent'\n },\n style: {\n '--AppBar-background': 'transparent',\n '--AppBar-color': 'inherit',\n backgroundColor: 'var(--AppBar-background)',\n color: 'var(--AppBar-color)',\n ...theme.applyStyles('dark', {\n backgroundImage: 'none'\n })\n }\n }]\n})));\nconst AppBar = /*#__PURE__*/React.forwardRef(function AppBar(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiAppBar'\n });\n const {\n className,\n color = 'primary',\n enableColorOnDark = false,\n position = 'fixed',\n ...other\n } = props;\n const ownerState = {\n ...props,\n color,\n position,\n enableColorOnDark\n };\n const classes = useUtilityClasses(ownerState);\n return /*#__PURE__*/_jsx(AppBarRoot, {\n square: true,\n component: \"header\",\n ownerState: ownerState,\n elevation: 4,\n className: clsx(classes.root, className, position === 'fixed' && 'mui-fixed'),\n ref: ref,\n ...other\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? AppBar.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The color of the component.\n * It supports both default and custom theme colors, which can be added as shown in the\n * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).\n * @default 'primary'\n */\n color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary', 'transparent', 'error', 'info', 'success', 'warning']), PropTypes.string]),\n /**\n * If true, the `color` prop is applied in dark mode.\n * @default false\n */\n enableColorOnDark: PropTypes.bool,\n /**\n * The positioning type. The behavior of the different options is described\n * [in the MDN web docs](https://developer.mozilla.org/en-US/docs/Web/CSS/position).\n * Note: `sticky` is not universally supported and will fall back to `static` when unavailable.\n * @default 'fixed'\n */\n position: PropTypes.oneOf(['absolute', 'fixed', 'relative', 'static', 'sticky']),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default AppBar;","'use client';\n\n/* eslint-disable no-constant-condition */\nimport * as React from 'react';\nimport { unstable_setRef as setRef, unstable_useEventCallback as useEventCallback, unstable_useControlled as useControlled, unstable_useId as useId, usePreviousProps } from '@mui/utils';\n\n// https://stackoverflow.com/questions/990904/remove-accents-diacritics-in-a-string-in-javascript\nfunction stripDiacritics(string) {\n return string.normalize('NFD').replace(/[\\u0300-\\u036f]/g, '');\n}\nexport function createFilterOptions(config = {}) {\n const {\n ignoreAccents = true,\n ignoreCase = true,\n limit,\n matchFrom = 'any',\n stringify,\n trim = false\n } = config;\n return (options, {\n inputValue,\n getOptionLabel\n }) => {\n let input = trim ? inputValue.trim() : inputValue;\n if (ignoreCase) {\n input = input.toLowerCase();\n }\n if (ignoreAccents) {\n input = stripDiacritics(input);\n }\n const filteredOptions = !input ? options : options.filter(option => {\n let candidate = (stringify || getOptionLabel)(option);\n if (ignoreCase) {\n candidate = candidate.toLowerCase();\n }\n if (ignoreAccents) {\n candidate = stripDiacritics(candidate);\n }\n return matchFrom === 'start' ? candidate.startsWith(input) : candidate.includes(input);\n });\n return typeof limit === 'number' ? filteredOptions.slice(0, limit) : filteredOptions;\n };\n}\nconst defaultFilterOptions = createFilterOptions();\n\n// Number of options to jump in list box when `Page Up` and `Page Down` keys are used.\nconst pageSize = 5;\nconst defaultIsActiveElementInListbox = listboxRef => listboxRef.current !== null && listboxRef.current.parentElement?.contains(document.activeElement);\nconst MULTIPLE_DEFAULT_VALUE = [];\nfunction getInputValue(value, multiple, getOptionLabel) {\n if (multiple || value == null) {\n return '';\n }\n const optionLabel = getOptionLabel(value);\n return typeof optionLabel === 'string' ? optionLabel : '';\n}\nfunction useAutocomplete(props) {\n const {\n // eslint-disable-next-line @typescript-eslint/naming-convention\n unstable_isActiveElementInListbox = defaultIsActiveElementInListbox,\n // eslint-disable-next-line @typescript-eslint/naming-convention\n unstable_classNamePrefix = 'Mui',\n autoComplete = false,\n autoHighlight = false,\n autoSelect = false,\n blurOnSelect = false,\n clearOnBlur = !props.freeSolo,\n clearOnEscape = false,\n componentName = 'useAutocomplete',\n defaultValue = props.multiple ? MULTIPLE_DEFAULT_VALUE : null,\n disableClearable = false,\n disableCloseOnSelect = false,\n disabled: disabledProp,\n disabledItemsFocusable = false,\n disableListWrap = false,\n filterOptions = defaultFilterOptions,\n filterSelectedOptions = false,\n freeSolo = false,\n getOptionDisabled,\n getOptionKey,\n getOptionLabel: getOptionLabelProp = option => option.label ?? option,\n groupBy,\n handleHomeEndKeys = !props.freeSolo,\n id: idProp,\n includeInputInList = false,\n inputValue: inputValueProp,\n isOptionEqualToValue = (option, value) => option === value,\n multiple = false,\n onChange,\n onClose,\n onHighlightChange,\n onInputChange,\n onOpen,\n open: openProp,\n openOnFocus = false,\n options,\n readOnly = false,\n selectOnFocus = !props.freeSolo,\n value: valueProp\n } = props;\n const id = useId(idProp);\n let getOptionLabel = getOptionLabelProp;\n getOptionLabel = option => {\n const optionLabel = getOptionLabelProp(option);\n if (typeof optionLabel !== 'string') {\n if (process.env.NODE_ENV !== 'production') {\n const erroneousReturn = optionLabel === undefined ? 'undefined' : `${typeof optionLabel} (${optionLabel})`;\n console.error(`MUI: The \\`getOptionLabel\\` method of ${componentName} returned ${erroneousReturn} instead of a string for ${JSON.stringify(option)}.`);\n }\n return String(optionLabel);\n }\n return optionLabel;\n };\n const ignoreFocus = React.useRef(false);\n const firstFocus = React.useRef(true);\n const inputRef = React.useRef(null);\n const listboxRef = React.useRef(null);\n const [anchorEl, setAnchorEl] = React.useState(null);\n const [focusedTag, setFocusedTag] = React.useState(-1);\n const defaultHighlighted = autoHighlight ? 0 : -1;\n const highlightedIndexRef = React.useRef(defaultHighlighted);\n\n // Calculate the initial inputValue on mount only.\n // Using useRef since defaultValue doesn't need to update inputValue dynamically.\n const initialInputValue = React.useRef(getInputValue(defaultValue, multiple, getOptionLabel)).current;\n const [value, setValueState] = useControlled({\n controlled: valueProp,\n default: defaultValue,\n name: componentName\n });\n const [inputValue, setInputValueState] = useControlled({\n controlled: inputValueProp,\n default: initialInputValue,\n name: componentName,\n state: 'inputValue'\n });\n const [focused, setFocused] = React.useState(false);\n const resetInputValue = React.useCallback((event, newValue, reason) => {\n // retain current `inputValue` if new option isn't selected and `clearOnBlur` is false\n // When `multiple` is enabled, `newValue` is an array of all selected items including the newly selected item\n const isOptionSelected = multiple ? value.length < newValue.length : newValue !== null;\n if (!isOptionSelected && !clearOnBlur) {\n return;\n }\n const newInputValue = getInputValue(newValue, multiple, getOptionLabel);\n if (inputValue === newInputValue) {\n return;\n }\n setInputValueState(newInputValue);\n if (onInputChange) {\n onInputChange(event, newInputValue, reason);\n }\n }, [getOptionLabel, inputValue, multiple, onInputChange, setInputValueState, clearOnBlur, value]);\n const [open, setOpenState] = useControlled({\n controlled: openProp,\n default: false,\n name: componentName,\n state: 'open'\n });\n const [inputPristine, setInputPristine] = React.useState(true);\n const inputValueIsSelectedValue = !multiple && value != null && inputValue === getOptionLabel(value);\n const popupOpen = open && !readOnly;\n const filteredOptions = popupOpen ? filterOptions(options.filter(option => {\n if (filterSelectedOptions && (multiple ? value : [value]).some(value2 => value2 !== null && isOptionEqualToValue(option, value2))) {\n return false;\n }\n return true;\n }),\n // we use the empty string to manipulate `filterOptions` to not filter any options\n // i.e. the filter predicate always returns true\n {\n inputValue: inputValueIsSelectedValue && inputPristine ? '' : inputValue,\n getOptionLabel\n }) : [];\n const previousProps = usePreviousProps({\n filteredOptions,\n value,\n inputValue\n });\n React.useEffect(() => {\n const valueChange = value !== previousProps.value;\n if (focused && !valueChange) {\n return;\n }\n\n // Only reset the input's value when freeSolo if the component's value changes.\n if (freeSolo && !valueChange) {\n return;\n }\n resetInputValue(null, value, 'reset');\n }, [value, resetInputValue, focused, previousProps.value, freeSolo]);\n const listboxAvailable = open && filteredOptions.length > 0 && !readOnly;\n const focusTag = useEventCallback(tagToFocus => {\n if (tagToFocus === -1) {\n inputRef.current.focus();\n } else {\n anchorEl.querySelector(`[data-tag-index=\"${tagToFocus}\"]`).focus();\n }\n });\n\n // Ensure the focusedTag is never inconsistent\n React.useEffect(() => {\n if (multiple && focusedTag > value.length - 1) {\n setFocusedTag(-1);\n focusTag(-1);\n }\n }, [value, multiple, focusedTag, focusTag]);\n function validOptionIndex(index, direction) {\n if (!listboxRef.current || index < 0 || index >= filteredOptions.length) {\n return -1;\n }\n let nextFocus = index;\n while (true) {\n const option = listboxRef.current.querySelector(`[data-option-index=\"${nextFocus}\"]`);\n\n // Same logic as MenuList.js\n const nextFocusDisabled = disabledItemsFocusable ? false : !option || option.disabled || option.getAttribute('aria-disabled') === 'true';\n if (option && option.hasAttribute('tabindex') && !nextFocusDisabled) {\n // The next option is available\n return nextFocus;\n }\n\n // The next option is disabled, move to the next element.\n // with looped index\n if (direction === 'next') {\n nextFocus = (nextFocus + 1) % filteredOptions.length;\n } else {\n nextFocus = (nextFocus - 1 + filteredOptions.length) % filteredOptions.length;\n }\n\n // We end up with initial index, that means we don't have available options.\n // All of them are disabled\n if (nextFocus === index) {\n return -1;\n }\n }\n }\n const setHighlightedIndex = useEventCallback(({\n event,\n index,\n reason = 'auto'\n }) => {\n highlightedIndexRef.current = index;\n\n // does the index exist?\n if (index === -1) {\n inputRef.current.removeAttribute('aria-activedescendant');\n } else {\n inputRef.current.setAttribute('aria-activedescendant', `${id}-option-${index}`);\n }\n if (onHighlightChange) {\n onHighlightChange(event, index === -1 ? null : filteredOptions[index], reason);\n }\n if (!listboxRef.current) {\n return;\n }\n const prev = listboxRef.current.querySelector(`[role=\"option\"].${unstable_classNamePrefix}-focused`);\n if (prev) {\n prev.classList.remove(`${unstable_classNamePrefix}-focused`);\n prev.classList.remove(`${unstable_classNamePrefix}-focusVisible`);\n }\n let listboxNode = listboxRef.current;\n if (listboxRef.current.getAttribute('role') !== 'listbox') {\n listboxNode = listboxRef.current.parentElement.querySelector('[role=\"listbox\"]');\n }\n\n // \"No results\"\n if (!listboxNode) {\n return;\n }\n if (index === -1) {\n listboxNode.scrollTop = 0;\n return;\n }\n const option = listboxRef.current.querySelector(`[data-option-index=\"${index}\"]`);\n if (!option) {\n return;\n }\n option.classList.add(`${unstable_classNamePrefix}-focused`);\n if (reason === 'keyboard') {\n option.classList.add(`${unstable_classNamePrefix}-focusVisible`);\n }\n\n // Scroll active descendant into view.\n // Logic copied from https://www.w3.org/WAI/content-assets/wai-aria-practices/patterns/combobox/examples/js/select-only.js\n // In case of mouse clicks and touch (in mobile devices) we avoid scrolling the element and keep both behaviors same.\n // Consider this API instead once it has a better browser support:\n // .scrollIntoView({ scrollMode: 'if-needed', block: 'nearest' });\n if (listboxNode.scrollHeight > listboxNode.clientHeight && reason !== 'mouse' && reason !== 'touch') {\n const element = option;\n const scrollBottom = listboxNode.clientHeight + listboxNode.scrollTop;\n const elementBottom = element.offsetTop + element.offsetHeight;\n if (elementBottom > scrollBottom) {\n listboxNode.scrollTop = elementBottom - listboxNode.clientHeight;\n } else if (element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0) < listboxNode.scrollTop) {\n listboxNode.scrollTop = element.offsetTop - element.offsetHeight * (groupBy ? 1.3 : 0);\n }\n }\n });\n const changeHighlightedIndex = useEventCallback(({\n event,\n diff,\n direction = 'next',\n reason = 'auto'\n }) => {\n if (!popupOpen) {\n return;\n }\n const getNextIndex = () => {\n const maxIndex = filteredOptions.length - 1;\n if (diff === 'reset') {\n return defaultHighlighted;\n }\n if (diff === 'start') {\n return 0;\n }\n if (diff === 'end') {\n return maxIndex;\n }\n const newIndex = highlightedIndexRef.current + diff;\n if (newIndex < 0) {\n if (newIndex === -1 && includeInputInList) {\n return -1;\n }\n if (disableListWrap && highlightedIndexRef.current !== -1 || Math.abs(diff) > 1) {\n return 0;\n }\n return maxIndex;\n }\n if (newIndex > maxIndex) {\n if (newIndex === maxIndex + 1 && includeInputInList) {\n return -1;\n }\n if (disableListWrap || Math.abs(diff) > 1) {\n return maxIndex;\n }\n return 0;\n }\n return newIndex;\n };\n const nextIndex = validOptionIndex(getNextIndex(), direction);\n setHighlightedIndex({\n index: nextIndex,\n reason,\n event\n });\n\n // Sync the content of the input with the highlighted option.\n if (autoComplete && diff !== 'reset') {\n if (nextIndex === -1) {\n inputRef.current.value = inputValue;\n } else {\n const option = getOptionLabel(filteredOptions[nextIndex]);\n inputRef.current.value = option;\n\n // The portion of the selected suggestion that has not been typed by the user,\n // a completion string, appears inline after the input cursor in the textbox.\n const index = option.toLowerCase().indexOf(inputValue.toLowerCase());\n if (index === 0 && inputValue.length > 0) {\n inputRef.current.setSelectionRange(inputValue.length, option.length);\n }\n }\n }\n });\n const getPreviousHighlightedOptionIndex = () => {\n const isSameValue = (value1, value2) => {\n const label1 = value1 ? getOptionLabel(value1) : '';\n const label2 = value2 ? getOptionLabel(value2) : '';\n return label1 === label2;\n };\n if (highlightedIndexRef.current !== -1 && previousProps.filteredOptions && previousProps.filteredOptions.length !== filteredOptions.length && previousProps.inputValue === inputValue && (multiple ? value.length === previousProps.value.length && previousProps.value.every((val, i) => getOptionLabel(value[i]) === getOptionLabel(val)) : isSameValue(previousProps.value, value))) {\n const previousHighlightedOption = previousProps.filteredOptions[highlightedIndexRef.current];\n if (previousHighlightedOption) {\n return filteredOptions.findIndex(option => {\n return getOptionLabel(option) === getOptionLabel(previousHighlightedOption);\n });\n }\n }\n return -1;\n };\n const syncHighlightedIndex = React.useCallback(() => {\n if (!popupOpen) {\n return;\n }\n\n // Check if the previously highlighted option still exists in the updated filtered options list and if the value and inputValue haven't changed\n // If it exists and the value and the inputValue haven't changed, just update its index, otherwise continue execution\n const previousHighlightedOptionIndex = getPreviousHighlightedOptionIndex();\n if (previousHighlightedOptionIndex !== -1) {\n highlightedIndexRef.current = previousHighlightedOptionIndex;\n return;\n }\n const valueItem = multiple ? value[0] : value;\n\n // The popup is empty, reset\n if (filteredOptions.length === 0 || valueItem == null) {\n changeHighlightedIndex({\n diff: 'reset'\n });\n return;\n }\n if (!listboxRef.current) {\n return;\n }\n\n // Synchronize the value with the highlighted index\n if (valueItem != null) {\n const currentOption = filteredOptions[highlightedIndexRef.current];\n\n // Keep the current highlighted index if possible\n if (multiple && currentOption && value.findIndex(val => isOptionEqualToValue(currentOption, val)) !== -1) {\n return;\n }\n const itemIndex = filteredOptions.findIndex(optionItem => isOptionEqualToValue(optionItem, valueItem));\n if (itemIndex === -1) {\n changeHighlightedIndex({\n diff: 'reset'\n });\n } else {\n setHighlightedIndex({\n index: itemIndex\n });\n }\n return;\n }\n\n // Prevent the highlighted index to leak outside the boundaries.\n if (highlightedIndexRef.current >= filteredOptions.length - 1) {\n setHighlightedIndex({\n index: filteredOptions.length - 1\n });\n return;\n }\n\n // Restore the focus to the previous index.\n setHighlightedIndex({\n index: highlightedIndexRef.current\n });\n // Ignore filteredOptions (and options, isOptionEqualToValue, getOptionLabel) not to break the scroll position\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [\n // Only sync the highlighted index when the option switch between empty and not\n filteredOptions.length,\n // Don't sync the highlighted index with the value when multiple\n // eslint-disable-next-line react-hooks/exhaustive-deps\n multiple ? false : value, filterSelectedOptions, changeHighlightedIndex, setHighlightedIndex, popupOpen, inputValue, multiple]);\n const handleListboxRef = useEventCallback(node => {\n setRef(listboxRef, node);\n if (!node) {\n return;\n }\n syncHighlightedIndex();\n });\n if (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useEffect(() => {\n if (!inputRef.current || inputRef.current.nodeName !== 'INPUT') {\n if (inputRef.current && inputRef.current.nodeName === 'TEXTAREA') {\n console.warn([`A textarea element was provided to ${componentName} where input was expected.`, `This is not a supported scenario but it may work under certain conditions.`, `A textarea keyboard navigation may conflict with Autocomplete controls (for example enter and arrow keys).`, `Make sure to test keyboard navigation and add custom event handlers if necessary.`].join('\\n'));\n } else {\n console.error([`MUI: Unable to find the input element. It was resolved to ${inputRef.current} while an HTMLInputElement was expected.`, `Instead, ${componentName} expects an input element.`, '', componentName === 'useAutocomplete' ? 'Make sure you have bound getInputProps correctly and that the normal ref/effect resolutions order is guaranteed.' : 'Make sure you have customized the input component correctly.'].join('\\n'));\n }\n }\n }, [componentName]);\n }\n React.useEffect(() => {\n syncHighlightedIndex();\n }, [syncHighlightedIndex]);\n const handleOpen = event => {\n if (open) {\n return;\n }\n setOpenState(true);\n setInputPristine(true);\n if (onOpen) {\n onOpen(event);\n }\n };\n const handleClose = (event, reason) => {\n if (!open) {\n return;\n }\n setOpenState(false);\n if (onClose) {\n onClose(event, reason);\n }\n };\n const handleValue = (event, newValue, reason, details) => {\n if (multiple) {\n if (value.length === newValue.length && value.every((val, i) => val === newValue[i])) {\n return;\n }\n } else if (value === newValue) {\n return;\n }\n if (onChange) {\n onChange(event, newValue, reason, details);\n }\n setValueState(newValue);\n };\n const isTouch = React.useRef(false);\n const selectNewValue = (event, option, reasonProp = 'selectOption', origin = 'options') => {\n let reason = reasonProp;\n let newValue = option;\n if (multiple) {\n newValue = Array.isArray(value) ? value.slice() : [];\n if (process.env.NODE_ENV !== 'production') {\n const matches = newValue.filter(val => isOptionEqualToValue(option, val));\n if (matches.length > 1) {\n console.error([`MUI: The \\`isOptionEqualToValue\\` method of ${componentName} does not handle the arguments correctly.`, `The component expects a single value to match a given option but found ${matches.length} matches.`].join('\\n'));\n }\n }\n const itemIndex = newValue.findIndex(valueItem => isOptionEqualToValue(option, valueItem));\n if (itemIndex === -1) {\n newValue.push(option);\n } else if (origin !== 'freeSolo') {\n newValue.splice(itemIndex, 1);\n reason = 'removeOption';\n }\n }\n resetInputValue(event, newValue, reason);\n handleValue(event, newValue, reason, {\n option\n });\n if (!disableCloseOnSelect && (!event || !event.ctrlKey && !event.metaKey)) {\n handleClose(event, reason);\n }\n if (blurOnSelect === true || blurOnSelect === 'touch' && isTouch.current || blurOnSelect === 'mouse' && !isTouch.current) {\n inputRef.current.blur();\n }\n };\n function validTagIndex(index, direction) {\n if (index === -1) {\n return -1;\n }\n let nextFocus = index;\n while (true) {\n // Out of range\n if (direction === 'next' && nextFocus === value.length || direction === 'previous' && nextFocus === -1) {\n return -1;\n }\n const option = anchorEl.querySelector(`[data-tag-index=\"${nextFocus}\"]`);\n\n // Same logic as MenuList.js\n if (!option || !option.hasAttribute('tabindex') || option.disabled || option.getAttribute('aria-disabled') === 'true') {\n nextFocus += direction === 'next' ? 1 : -1;\n } else {\n return nextFocus;\n }\n }\n }\n const handleFocusTag = (event, direction) => {\n if (!multiple) {\n return;\n }\n if (inputValue === '') {\n handleClose(event, 'toggleInput');\n }\n let nextTag = focusedTag;\n if (focusedTag === -1) {\n if (inputValue === '' && direction === 'previous') {\n nextTag = value.length - 1;\n }\n } else {\n nextTag += direction === 'next' ? 1 : -1;\n if (nextTag < 0) {\n nextTag = 0;\n }\n if (nextTag === value.length) {\n nextTag = -1;\n }\n }\n nextTag = validTagIndex(nextTag, direction);\n setFocusedTag(nextTag);\n focusTag(nextTag);\n };\n const handleClear = event => {\n ignoreFocus.current = true;\n setInputValueState('');\n if (onInputChange) {\n onInputChange(event, '', 'clear');\n }\n handleValue(event, multiple ? [] : null, 'clear');\n };\n const handleKeyDown = other => event => {\n if (other.onKeyDown) {\n other.onKeyDown(event);\n }\n if (event.defaultMuiPrevented) {\n return;\n }\n if (focusedTag !== -1 && !['ArrowLeft', 'ArrowRight'].includes(event.key)) {\n setFocusedTag(-1);\n focusTag(-1);\n }\n\n // Wait until IME is settled.\n if (event.which !== 229) {\n switch (event.key) {\n case 'Home':\n if (popupOpen && handleHomeEndKeys) {\n // Prevent scroll of the page\n event.preventDefault();\n changeHighlightedIndex({\n diff: 'start',\n direction: 'next',\n reason: 'keyboard',\n event\n });\n }\n break;\n case 'End':\n if (popupOpen && handleHomeEndKeys) {\n // Prevent scroll of the page\n event.preventDefault();\n changeHighlightedIndex({\n diff: 'end',\n direction: 'previous',\n reason: 'keyboard',\n event\n });\n }\n break;\n case 'PageUp':\n // Prevent scroll of the page\n event.preventDefault();\n changeHighlightedIndex({\n diff: -pageSize,\n direction: 'previous',\n reason: 'keyboard',\n event\n });\n handleOpen(event);\n break;\n case 'PageDown':\n // Prevent scroll of the page\n event.preventDefault();\n changeHighlightedIndex({\n diff: pageSize,\n direction: 'next',\n reason: 'keyboard',\n event\n });\n handleOpen(event);\n break;\n case 'ArrowDown':\n // Prevent cursor move\n event.preventDefault();\n changeHighlightedIndex({\n diff: 1,\n direction: 'next',\n reason: 'keyboard',\n event\n });\n handleOpen(event);\n break;\n case 'ArrowUp':\n // Prevent cursor move\n event.preventDefault();\n changeHighlightedIndex({\n diff: -1,\n direction: 'previous',\n reason: 'keyboard',\n event\n });\n handleOpen(event);\n break;\n case 'ArrowLeft':\n handleFocusTag(event, 'previous');\n break;\n case 'ArrowRight':\n handleFocusTag(event, 'next');\n break;\n case 'Enter':\n if (highlightedIndexRef.current !== -1 && popupOpen) {\n const option = filteredOptions[highlightedIndexRef.current];\n const disabled = getOptionDisabled ? getOptionDisabled(option) : false;\n\n // Avoid early form validation, let the end-users continue filling the form.\n event.preventDefault();\n if (disabled) {\n return;\n }\n selectNewValue(event, option, 'selectOption');\n\n // Move the selection to the end.\n if (autoComplete) {\n inputRef.current.setSelectionRange(inputRef.current.value.length, inputRef.current.value.length);\n }\n } else if (freeSolo && inputValue !== '' && inputValueIsSelectedValue === false) {\n if (multiple) {\n // Allow people to add new values before they submit the form.\n event.preventDefault();\n }\n selectNewValue(event, inputValue, 'createOption', 'freeSolo');\n }\n break;\n case 'Escape':\n if (popupOpen) {\n // Avoid Opera to exit fullscreen mode.\n event.preventDefault();\n // Avoid the Modal to handle the event.\n event.stopPropagation();\n handleClose(event, 'escape');\n } else if (clearOnEscape && (inputValue !== '' || multiple && value.length > 0)) {\n // Avoid Opera to exit fullscreen mode.\n event.preventDefault();\n // Avoid the Modal to handle the event.\n event.stopPropagation();\n handleClear(event);\n }\n break;\n case 'Backspace':\n // Remove the value on the left of the \"cursor\"\n if (multiple && !readOnly && inputValue === '' && value.length > 0) {\n const index = focusedTag === -1 ? value.length - 1 : focusedTag;\n const newValue = value.slice();\n newValue.splice(index, 1);\n handleValue(event, newValue, 'removeOption', {\n option: value[index]\n });\n }\n break;\n case 'Delete':\n // Remove the value on the right of the \"cursor\"\n if (multiple && !readOnly && inputValue === '' && value.length > 0 && focusedTag !== -1) {\n const index = focusedTag;\n const newValue = value.slice();\n newValue.splice(index, 1);\n handleValue(event, newValue, 'removeOption', {\n option: value[index]\n });\n }\n break;\n default:\n }\n }\n };\n const handleFocus = event => {\n setFocused(true);\n if (openOnFocus && !ignoreFocus.current) {\n handleOpen(event);\n }\n };\n const handleBlur = event => {\n // Ignore the event when using the scrollbar with IE11\n if (unstable_isActiveElementInListbox(listboxRef)) {\n inputRef.current.focus();\n return;\n }\n setFocused(false);\n firstFocus.current = true;\n ignoreFocus.current = false;\n if (autoSelect && highlightedIndexRef.current !== -1 && popupOpen) {\n selectNewValue(event, filteredOptions[highlightedIndexRef.current], 'blur');\n } else if (autoSelect && freeSolo && inputValue !== '') {\n selectNewValue(event, inputValue, 'blur', 'freeSolo');\n } else if (clearOnBlur) {\n resetInputValue(event, value, 'blur');\n }\n handleClose(event, 'blur');\n };\n const handleInputChange = event => {\n const newValue = event.target.value;\n if (inputValue !== newValue) {\n setInputValueState(newValue);\n setInputPristine(false);\n if (onInputChange) {\n onInputChange(event, newValue, 'input');\n }\n }\n if (newValue === '') {\n if (!disableClearable && !multiple) {\n handleValue(event, null, 'clear');\n }\n } else {\n handleOpen(event);\n }\n };\n const handleOptionMouseMove = event => {\n const index = Number(event.currentTarget.getAttribute('data-option-index'));\n if (highlightedIndexRef.current !== index) {\n setHighlightedIndex({\n event,\n index,\n reason: 'mouse'\n });\n }\n };\n const handleOptionTouchStart = event => {\n setHighlightedIndex({\n event,\n index: Number(event.currentTarget.getAttribute('data-option-index')),\n reason: 'touch'\n });\n isTouch.current = true;\n };\n const handleOptionClick = event => {\n const index = Number(event.currentTarget.getAttribute('data-option-index'));\n selectNewValue(event, filteredOptions[index], 'selectOption');\n isTouch.current = false;\n };\n const handleTagDelete = index => event => {\n const newValue = value.slice();\n newValue.splice(index, 1);\n handleValue(event, newValue, 'removeOption', {\n option: value[index]\n });\n };\n const handlePopupIndicator = event => {\n if (open) {\n handleClose(event, 'toggleInput');\n } else {\n handleOpen(event);\n }\n };\n\n // Prevent input blur when interacting with the combobox\n const handleMouseDown = event => {\n // Prevent focusing the input if click is anywhere outside the Autocomplete\n if (!event.currentTarget.contains(event.target)) {\n return;\n }\n if (event.target.getAttribute('id') !== id) {\n event.preventDefault();\n }\n };\n\n // Focus the input when interacting with the combobox\n const handleClick = event => {\n // Prevent focusing the input if click is anywhere outside the Autocomplete\n if (!event.currentTarget.contains(event.target)) {\n return;\n }\n inputRef.current.focus();\n if (selectOnFocus && firstFocus.current && inputRef.current.selectionEnd - inputRef.current.selectionStart === 0) {\n inputRef.current.select();\n }\n firstFocus.current = false;\n };\n const handleInputMouseDown = event => {\n if (!disabledProp && (inputValue === '' || !open)) {\n handlePopupIndicator(event);\n }\n };\n let dirty = freeSolo && inputValue.length > 0;\n dirty = dirty || (multiple ? value.length > 0 : value !== null);\n let groupedOptions = filteredOptions;\n if (groupBy) {\n // used to keep track of key and indexes in the result array\n const indexBy = new Map();\n let warn = false;\n groupedOptions = filteredOptions.reduce((acc, option, index) => {\n const group = groupBy(option);\n if (acc.length > 0 && acc[acc.length - 1].group === group) {\n acc[acc.length - 1].options.push(option);\n } else {\n if (process.env.NODE_ENV !== 'production') {\n if (indexBy.get(group) && !warn) {\n console.warn(`MUI: The options provided combined with the \\`groupBy\\` method of ${componentName} returns duplicated headers.`, 'You can solve the issue by sorting the options with the output of `groupBy`.');\n warn = true;\n }\n indexBy.set(group, true);\n }\n acc.push({\n key: index,\n index,\n group,\n options: [option]\n });\n }\n return acc;\n }, []);\n }\n if (disabledProp && focused) {\n handleBlur();\n }\n return {\n getRootProps: (other = {}) => ({\n ...other,\n onKeyDown: handleKeyDown(other),\n onMouseDown: handleMouseDown,\n onClick: handleClick\n }),\n getInputLabelProps: () => ({\n id: `${id}-label`,\n htmlFor: id\n }),\n getInputProps: () => ({\n id,\n value: inputValue,\n onBlur: handleBlur,\n onFocus: handleFocus,\n onChange: handleInputChange,\n onMouseDown: handleInputMouseDown,\n // if open then this is handled imperatively so don't let react override\n // only have an opinion about this when closed\n 'aria-activedescendant': popupOpen ? '' : null,\n 'aria-autocomplete': autoComplete ? 'both' : 'list',\n 'aria-controls': listboxAvailable ? `${id}-listbox` : undefined,\n 'aria-expanded': listboxAvailable,\n // Disable browser's suggestion that might overlap with the popup.\n // Handle autocomplete but not autofill.\n autoComplete: 'off',\n ref: inputRef,\n autoCapitalize: 'none',\n spellCheck: 'false',\n role: 'combobox',\n disabled: disabledProp\n }),\n getClearProps: () => ({\n tabIndex: -1,\n type: 'button',\n onClick: handleClear\n }),\n getPopupIndicatorProps: () => ({\n tabIndex: -1,\n type: 'button',\n onClick: handlePopupIndicator\n }),\n getTagProps: ({\n index\n }) => ({\n key: index,\n 'data-tag-index': index,\n tabIndex: -1,\n ...(!readOnly && {\n onDelete: handleTagDelete(index)\n })\n }),\n getListboxProps: () => ({\n role: 'listbox',\n id: `${id}-listbox`,\n 'aria-labelledby': `${id}-label`,\n ref: handleListboxRef,\n onMouseDown: event => {\n // Prevent blur\n event.preventDefault();\n }\n }),\n getOptionProps: ({\n index,\n option\n }) => {\n const selected = (multiple ? value : [value]).some(value2 => value2 != null && isOptionEqualToValue(option, value2));\n const disabled = getOptionDisabled ? getOptionDisabled(option) : false;\n return {\n key: getOptionKey?.(option) ?? getOptionLabel(option),\n tabIndex: -1,\n role: 'option',\n id: `${id}-option-${index}`,\n onMouseMove: handleOptionMouseMove,\n onClick: handleOptionClick,\n onTouchStart: handleOptionTouchStart,\n 'data-option-index': index,\n 'aria-disabled': disabled,\n 'aria-selected': selected\n };\n },\n id,\n inputValue,\n value,\n dirty,\n expanded: popupOpen && anchorEl,\n popupOpen,\n focused: focused || focusedTag !== -1,\n anchorEl,\n setAnchorEl,\n focusedTag,\n groupedOptions\n };\n}\nexport default useAutocomplete;","'use client';\n\nimport * as React from 'react';\nimport * as ReactDOM from 'react-dom';\nimport PropTypes from 'prop-types';\nimport { exactProp, HTMLElementType, unstable_useEnhancedEffect as useEnhancedEffect, unstable_useForkRef as useForkRef, unstable_setRef as setRef, unstable_getReactElementRef as getReactElementRef } from '@mui/utils';\nfunction getContainer(container) {\n return typeof container === 'function' ? container() : container;\n}\n\n/**\n * Portals provide a first-class way to render children into a DOM node\n * that exists outside the DOM hierarchy of the parent component.\n *\n * Demos:\n *\n * - [Portal](https://mui.com/material-ui/react-portal/)\n *\n * API:\n *\n * - [Portal API](https://mui.com/material-ui/api/portal/)\n */\nconst Portal = /*#__PURE__*/React.forwardRef(function Portal(props, forwardedRef) {\n const {\n children,\n container,\n disablePortal = false\n } = props;\n const [mountNode, setMountNode] = React.useState(null);\n const handleRef = useForkRef(/*#__PURE__*/React.isValidElement(children) ? getReactElementRef(children) : null, forwardedRef);\n useEnhancedEffect(() => {\n if (!disablePortal) {\n setMountNode(getContainer(container) || document.body);\n }\n }, [container, disablePortal]);\n useEnhancedEffect(() => {\n if (mountNode && !disablePortal) {\n setRef(forwardedRef, mountNode);\n return () => {\n setRef(forwardedRef, null);\n };\n }\n return undefined;\n }, [forwardedRef, mountNode, disablePortal]);\n if (disablePortal) {\n if (/*#__PURE__*/React.isValidElement(children)) {\n const newProps = {\n ref: handleRef\n };\n return /*#__PURE__*/React.cloneElement(children, newProps);\n }\n return children;\n }\n return mountNode ? /*#__PURE__*/ReactDOM.createPortal(children, mountNode) : mountNode;\n});\nprocess.env.NODE_ENV !== \"production\" ? Portal.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the TypeScript types and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The children to render into the `container`.\n */\n children: PropTypes.node,\n /**\n * An HTML element or function that returns one.\n * The `container` will have the portal children appended to it.\n *\n * You can also provide a callback, which is called in a React layout effect.\n * This lets you set the container from a ref, and also makes server-side rendering possible.\n *\n * By default, it uses the body of the top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),\n /**\n * The `children` will be under the DOM hierarchy of the parent component.\n * @default false\n */\n disablePortal: PropTypes.bool\n} : void 0;\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line\n Portal['propTypes' + ''] = exactProp(Portal.propTypes);\n}\nexport default Portal;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getPopperUtilityClass(slot) {\n return generateUtilityClass('MuiPopper', slot);\n}\nconst popperClasses = generateUtilityClasses('MuiPopper', ['root']);\nexport default popperClasses;","'use client';\n\nimport * as React from 'react';\nimport { chainPropTypes, HTMLElementType, refType, unstable_ownerDocument as ownerDocument, unstable_useEnhancedEffect as useEnhancedEffect, unstable_useForkRef as useForkRef } from '@mui/utils';\nimport { createPopper } from '@popperjs/core';\nimport PropTypes from 'prop-types';\nimport composeClasses from '@mui/utils/composeClasses';\nimport useSlotProps from '@mui/utils/useSlotProps';\nimport Portal from \"../Portal/index.js\";\nimport { getPopperUtilityClass } from \"./popperClasses.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nfunction flipPlacement(placement, direction) {\n if (direction === 'ltr') {\n return placement;\n }\n switch (placement) {\n case 'bottom-end':\n return 'bottom-start';\n case 'bottom-start':\n return 'bottom-end';\n case 'top-end':\n return 'top-start';\n case 'top-start':\n return 'top-end';\n default:\n return placement;\n }\n}\nfunction resolveAnchorEl(anchorEl) {\n return typeof anchorEl === 'function' ? anchorEl() : anchorEl;\n}\nfunction isHTMLElement(element) {\n return element.nodeType !== undefined;\n}\nfunction isVirtualElement(element) {\n return !isHTMLElement(element);\n}\nconst useUtilityClasses = ownerState => {\n const {\n classes\n } = ownerState;\n const slots = {\n root: ['root']\n };\n return composeClasses(slots, getPopperUtilityClass, classes);\n};\nconst defaultPopperOptions = {};\nconst PopperTooltip = /*#__PURE__*/React.forwardRef(function PopperTooltip(props, forwardedRef) {\n const {\n anchorEl,\n children,\n direction,\n disablePortal,\n modifiers,\n open,\n placement: initialPlacement,\n popperOptions,\n popperRef: popperRefProp,\n slotProps = {},\n slots = {},\n TransitionProps,\n // @ts-ignore internal logic\n ownerState: ownerStateProp,\n // prevent from spreading to DOM, it can come from the parent component e.g. Select.\n ...other\n } = props;\n const tooltipRef = React.useRef(null);\n const ownRef = useForkRef(tooltipRef, forwardedRef);\n const popperRef = React.useRef(null);\n const handlePopperRef = useForkRef(popperRef, popperRefProp);\n const handlePopperRefRef = React.useRef(handlePopperRef);\n useEnhancedEffect(() => {\n handlePopperRefRef.current = handlePopperRef;\n }, [handlePopperRef]);\n React.useImperativeHandle(popperRefProp, () => popperRef.current, []);\n const rtlPlacement = flipPlacement(initialPlacement, direction);\n /**\n * placement initialized from prop but can change during lifetime if modifiers.flip.\n * modifiers.flip is essentially a flip for controlled/uncontrolled behavior\n */\n const [placement, setPlacement] = React.useState(rtlPlacement);\n const [resolvedAnchorElement, setResolvedAnchorElement] = React.useState(resolveAnchorEl(anchorEl));\n React.useEffect(() => {\n if (popperRef.current) {\n popperRef.current.forceUpdate();\n }\n });\n React.useEffect(() => {\n if (anchorEl) {\n setResolvedAnchorElement(resolveAnchorEl(anchorEl));\n }\n }, [anchorEl]);\n useEnhancedEffect(() => {\n if (!resolvedAnchorElement || !open) {\n return undefined;\n }\n const handlePopperUpdate = data => {\n setPlacement(data.placement);\n };\n if (process.env.NODE_ENV !== 'production') {\n if (resolvedAnchorElement && isHTMLElement(resolvedAnchorElement) && resolvedAnchorElement.nodeType === 1) {\n const box = resolvedAnchorElement.getBoundingClientRect();\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n console.warn(['MUI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n }\n }\n let popperModifiers = [{\n name: 'preventOverflow',\n options: {\n altBoundary: disablePortal\n }\n }, {\n name: 'flip',\n options: {\n altBoundary: disablePortal\n }\n }, {\n name: 'onUpdate',\n enabled: true,\n phase: 'afterWrite',\n fn: ({\n state\n }) => {\n handlePopperUpdate(state);\n }\n }];\n if (modifiers != null) {\n popperModifiers = popperModifiers.concat(modifiers);\n }\n if (popperOptions && popperOptions.modifiers != null) {\n popperModifiers = popperModifiers.concat(popperOptions.modifiers);\n }\n const popper = createPopper(resolvedAnchorElement, tooltipRef.current, {\n placement: rtlPlacement,\n ...popperOptions,\n modifiers: popperModifiers\n });\n handlePopperRefRef.current(popper);\n return () => {\n popper.destroy();\n handlePopperRefRef.current(null);\n };\n }, [resolvedAnchorElement, disablePortal, modifiers, open, popperOptions, rtlPlacement]);\n const childProps = {\n placement: placement\n };\n if (TransitionProps !== null) {\n childProps.TransitionProps = TransitionProps;\n }\n const classes = useUtilityClasses(props);\n const Root = slots.root ?? 'div';\n const rootProps = useSlotProps({\n elementType: Root,\n externalSlotProps: slotProps.root,\n externalForwardedProps: other,\n additionalProps: {\n role: 'tooltip',\n ref: ownRef\n },\n ownerState: props,\n className: classes.root\n });\n return /*#__PURE__*/_jsx(Root, {\n ...rootProps,\n children: typeof children === 'function' ? children(childProps) : children\n });\n});\n\n/**\n * @ignore - internal component.\n */\nconst Popper = /*#__PURE__*/React.forwardRef(function Popper(props, forwardedRef) {\n const {\n anchorEl,\n children,\n container: containerProp,\n direction = 'ltr',\n disablePortal = false,\n keepMounted = false,\n modifiers,\n open,\n placement = 'bottom',\n popperOptions = defaultPopperOptions,\n popperRef,\n style,\n transition = false,\n slotProps = {},\n slots = {},\n ...other\n } = props;\n const [exited, setExited] = React.useState(true);\n const handleEnter = () => {\n setExited(false);\n };\n const handleExited = () => {\n setExited(true);\n };\n if (!keepMounted && !open && (!transition || exited)) {\n return null;\n }\n\n // If the container prop is provided, use that\n // If the anchorEl prop is provided, use its parent body element as the container\n // If neither are provided let the Modal take care of choosing the container\n let container;\n if (containerProp) {\n container = containerProp;\n } else if (anchorEl) {\n const resolvedAnchorEl = resolveAnchorEl(anchorEl);\n container = resolvedAnchorEl && isHTMLElement(resolvedAnchorEl) ? ownerDocument(resolvedAnchorEl).body : ownerDocument(null).body;\n }\n const display = !open && keepMounted && (!transition || exited) ? 'none' : undefined;\n const transitionProps = transition ? {\n in: open,\n onEnter: handleEnter,\n onExited: handleExited\n } : undefined;\n return /*#__PURE__*/_jsx(Portal, {\n disablePortal: disablePortal,\n container: container,\n children: /*#__PURE__*/_jsx(PopperTooltip, {\n anchorEl: anchorEl,\n direction: direction,\n disablePortal: disablePortal,\n modifiers: modifiers,\n ref: forwardedRef,\n open: transition ? !exited : open,\n placement: placement,\n popperOptions: popperOptions,\n popperRef: popperRef,\n slotProps: slotProps,\n slots: slots,\n ...other,\n style: {\n // Prevents scroll issue, waiting for Popper.js to add this style once initiated.\n position: 'fixed',\n // Fix Popper.js display issue\n top: 0,\n left: 0,\n display,\n ...style\n },\n TransitionProps: transitionProps,\n children: children\n })\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Popper.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the TypeScript types and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * An HTML element, [virtualElement](https://popper.js.org/docs/v2/virtual-elements/),\n * or a function that returns either.\n * It's used to set the position of the popper.\n * The return value will passed as the reference object of the Popper instance.\n */\n anchorEl: chainPropTypes(PropTypes.oneOfType([HTMLElementType, PropTypes.object, PropTypes.func]), props => {\n if (props.open) {\n const resolvedAnchorEl = resolveAnchorEl(props.anchorEl);\n if (resolvedAnchorEl && isHTMLElement(resolvedAnchorEl) && resolvedAnchorEl.nodeType === 1) {\n const box = resolvedAnchorEl.getBoundingClientRect();\n if (process.env.NODE_ENV !== 'test' && box.top === 0 && box.left === 0 && box.right === 0 && box.bottom === 0) {\n return new Error(['MUI: The `anchorEl` prop provided to the component is invalid.', 'The anchor element should be part of the document layout.', \"Make sure the element is present in the document or that it's not display none.\"].join('\\n'));\n }\n } else if (!resolvedAnchorEl || typeof resolvedAnchorEl.getBoundingClientRect !== 'function' || isVirtualElement(resolvedAnchorEl) && resolvedAnchorEl.contextElement != null && resolvedAnchorEl.contextElement.nodeType !== 1) {\n return new Error(['MUI: The `anchorEl` prop provided to the component is invalid.', 'It should be an HTML element instance or a virtualElement ', '(https://popper.js.org/docs/v2/virtual-elements/).'].join('\\n'));\n }\n }\n return null;\n }),\n /**\n * Popper render function or node.\n */\n children: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.node, PropTypes.func]),\n /**\n * An HTML element or function that returns one.\n * The `container` will have the portal children appended to it.\n *\n * You can also provide a callback, which is called in a React layout effect.\n * This lets you set the container from a ref, and also makes server-side rendering possible.\n *\n * By default, it uses the body of the top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),\n /**\n * Direction of the text.\n * @default 'ltr'\n */\n direction: PropTypes.oneOf(['ltr', 'rtl']),\n /**\n * The `children` will be under the DOM hierarchy of the parent component.\n * @default false\n */\n disablePortal: PropTypes.bool,\n /**\n * Always keep the children in the DOM.\n * This prop can be useful in SEO situation or\n * when you want to maximize the responsiveness of the Popper.\n * @default false\n */\n keepMounted: PropTypes.bool,\n /**\n * Popper.js is based on a \"plugin-like\" architecture,\n * most of its features are fully encapsulated \"modifiers\".\n *\n * A modifier is a function that is called each time Popper.js needs to\n * compute the position of the popper.\n * For this reason, modifiers should be very performant to avoid bottlenecks.\n * To learn how to create a modifier, [read the modifiers documentation](https://popper.js.org/docs/v2/modifiers/).\n */\n modifiers: PropTypes.arrayOf(PropTypes.shape({\n data: PropTypes.object,\n effect: PropTypes.func,\n enabled: PropTypes.bool,\n fn: PropTypes.func,\n name: PropTypes.any,\n options: PropTypes.object,\n phase: PropTypes.oneOf(['afterMain', 'afterRead', 'afterWrite', 'beforeMain', 'beforeRead', 'beforeWrite', 'main', 'read', 'write']),\n requires: PropTypes.arrayOf(PropTypes.string),\n requiresIfExists: PropTypes.arrayOf(PropTypes.string)\n })),\n /**\n * If `true`, the component is shown.\n */\n open: PropTypes.bool.isRequired,\n /**\n * Popper placement.\n * @default 'bottom'\n */\n placement: PropTypes.oneOf(['auto-end', 'auto-start', 'auto', 'bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),\n /**\n * Options provided to the [`Popper.js`](https://popper.js.org/docs/v2/constructors/#options) instance.\n * @default {}\n */\n popperOptions: PropTypes.shape({\n modifiers: PropTypes.array,\n onFirstUpdate: PropTypes.func,\n placement: PropTypes.oneOf(['auto-end', 'auto-start', 'auto', 'bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),\n strategy: PropTypes.oneOf(['absolute', 'fixed'])\n }),\n /**\n * A ref that points to the used popper instance.\n */\n popperRef: refType,\n /**\n * The props used for each slot inside the Popper.\n * @default {}\n */\n slotProps: PropTypes.shape({\n root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside the Popper.\n * Either a string to use a HTML element or a component.\n * @default {}\n */\n slots: PropTypes.shape({\n root: PropTypes.elementType\n }),\n /**\n * Help supporting a react-transition-group/Transition component.\n * @default false\n */\n transition: PropTypes.bool\n} : void 0;\nexport default Popper;","'use client';\n\nimport { useRtl } from '@mui/system/RtlProvider';\nimport refType from '@mui/utils/refType';\nimport HTMLElementType from '@mui/utils/HTMLElementType';\nimport PropTypes from 'prop-types';\nimport * as React from 'react';\nimport BasePopper from \"./BasePopper.js\";\nimport { styled } from \"../zero-styled/index.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst PopperRoot = styled(BasePopper, {\n name: 'MuiPopper',\n slot: 'Root',\n overridesResolver: (props, styles) => styles.root\n})({});\n\n/**\n *\n * Demos:\n *\n * - [Autocomplete](https://mui.com/material-ui/react-autocomplete/)\n * - [Menu](https://mui.com/material-ui/react-menu/)\n * - [Popper](https://mui.com/material-ui/react-popper/)\n *\n * API:\n *\n * - [Popper API](https://mui.com/material-ui/api/popper/)\n */\nconst Popper = /*#__PURE__*/React.forwardRef(function Popper(inProps, ref) {\n const isRtl = useRtl();\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiPopper'\n });\n const {\n anchorEl,\n component,\n components,\n componentsProps,\n container,\n disablePortal,\n keepMounted,\n modifiers,\n open,\n placement,\n popperOptions,\n popperRef,\n transition,\n slots,\n slotProps,\n ...other\n } = props;\n const RootComponent = slots?.root ?? components?.Root;\n const otherProps = {\n anchorEl,\n container,\n disablePortal,\n keepMounted,\n modifiers,\n open,\n placement,\n popperOptions,\n popperRef,\n transition,\n ...other\n };\n return /*#__PURE__*/_jsx(PopperRoot, {\n as: component,\n direction: isRtl ? 'rtl' : 'ltr',\n slots: {\n root: RootComponent\n },\n slotProps: slotProps ?? componentsProps,\n ...otherProps,\n ref: ref\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Popper.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the TypeScript types and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * An HTML element, [virtualElement](https://popper.js.org/docs/v2/virtual-elements/),\n * or a function that returns either.\n * It's used to set the position of the popper.\n * The return value will passed as the reference object of the Popper instance.\n */\n anchorEl: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.object, PropTypes.func]),\n /**\n * Popper render function or node.\n */\n children: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.node, PropTypes.func]),\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * The components used for each slot inside the Popper.\n * Either a string to use a HTML element or a component.\n *\n * @deprecated use the `slots` prop instead. This prop will be removed in v7. [How to migrate](/material-ui/migration/migrating-from-deprecated-apis/).\n * @default {}\n */\n components: PropTypes.shape({\n Root: PropTypes.elementType\n }),\n /**\n * The props used for each slot inside the Popper.\n *\n * @deprecated use the `slotProps` prop instead. This prop will be removed in v7. [How to migrate](/material-ui/migration/migrating-from-deprecated-apis/).\n * @default {}\n */\n componentsProps: PropTypes.shape({\n root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * An HTML element or function that returns one.\n * The `container` will have the portal children appended to it.\n *\n * You can also provide a callback, which is called in a React layout effect.\n * This lets you set the container from a ref, and also makes server-side rendering possible.\n *\n * By default, it uses the body of the top-level document object,\n * so it's simply `document.body` most of the time.\n */\n container: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([HTMLElementType, PropTypes.func]),\n /**\n * The `children` will be under the DOM hierarchy of the parent component.\n * @default false\n */\n disablePortal: PropTypes.bool,\n /**\n * Always keep the children in the DOM.\n * This prop can be useful in SEO situation or\n * when you want to maximize the responsiveness of the Popper.\n * @default false\n */\n keepMounted: PropTypes.bool,\n /**\n * Popper.js is based on a \"plugin-like\" architecture,\n * most of its features are fully encapsulated \"modifiers\".\n *\n * A modifier is a function that is called each time Popper.js needs to\n * compute the position of the popper.\n * For this reason, modifiers should be very performant to avoid bottlenecks.\n * To learn how to create a modifier, [read the modifiers documentation](https://popper.js.org/docs/v2/modifiers/).\n */\n modifiers: PropTypes.arrayOf(PropTypes.shape({\n data: PropTypes.object,\n effect: PropTypes.func,\n enabled: PropTypes.bool,\n fn: PropTypes.func,\n name: PropTypes.any,\n options: PropTypes.object,\n phase: PropTypes.oneOf(['afterMain', 'afterRead', 'afterWrite', 'beforeMain', 'beforeRead', 'beforeWrite', 'main', 'read', 'write']),\n requires: PropTypes.arrayOf(PropTypes.string),\n requiresIfExists: PropTypes.arrayOf(PropTypes.string)\n })),\n /**\n * If `true`, the component is shown.\n */\n open: PropTypes.bool.isRequired,\n /**\n * Popper placement.\n * @default 'bottom'\n */\n placement: PropTypes.oneOf(['auto-end', 'auto-start', 'auto', 'bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),\n /**\n * Options provided to the [`Popper.js`](https://popper.js.org/docs/v2/constructors/#options) instance.\n * @default {}\n */\n popperOptions: PropTypes.shape({\n modifiers: PropTypes.array,\n onFirstUpdate: PropTypes.func,\n placement: PropTypes.oneOf(['auto-end', 'auto-start', 'auto', 'bottom-end', 'bottom-start', 'bottom', 'left-end', 'left-start', 'left', 'right-end', 'right-start', 'right', 'top-end', 'top-start', 'top']),\n strategy: PropTypes.oneOf(['absolute', 'fixed'])\n }),\n /**\n * A ref that points to the used popper instance.\n */\n popperRef: refType,\n /**\n * The props used for each slot inside the Popper.\n * @default {}\n */\n slotProps: PropTypes.shape({\n root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside the Popper.\n * Either a string to use a HTML element or a component.\n * @default {}\n */\n slots: PropTypes.shape({\n root: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * Help supporting a react-transition-group/Transition component.\n * @default false\n */\n transition: PropTypes.bool\n} : void 0;\nexport default Popper;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getListSubheaderUtilityClass(slot) {\n return generateUtilityClass('MuiListSubheader', slot);\n}\nconst listSubheaderClasses = generateUtilityClasses('MuiListSubheader', ['root', 'colorPrimary', 'colorInherit', 'gutters', 'inset', 'sticky']);\nexport default listSubheaderClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { styled } from \"../zero-styled/index.js\";\nimport memoTheme from \"../utils/memoTheme.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport capitalize from \"../utils/capitalize.js\";\nimport { getListSubheaderUtilityClass } from \"./listSubheaderClasses.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n color,\n disableGutters,\n inset,\n disableSticky\n } = ownerState;\n const slots = {\n root: ['root', color !== 'default' && `color${capitalize(color)}`, !disableGutters && 'gutters', inset && 'inset', !disableSticky && 'sticky']\n };\n return composeClasses(slots, getListSubheaderUtilityClass, classes);\n};\nconst ListSubheaderRoot = styled('li', {\n name: 'MuiListSubheader',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.color !== 'default' && styles[`color${capitalize(ownerState.color)}`], !ownerState.disableGutters && styles.gutters, ownerState.inset && styles.inset, !ownerState.disableSticky && styles.sticky];\n }\n})(memoTheme(({\n theme\n}) => ({\n boxSizing: 'border-box',\n lineHeight: '48px',\n listStyle: 'none',\n color: (theme.vars || theme).palette.text.secondary,\n fontFamily: theme.typography.fontFamily,\n fontWeight: theme.typography.fontWeightMedium,\n fontSize: theme.typography.pxToRem(14),\n variants: [{\n props: {\n color: 'primary'\n },\n style: {\n color: (theme.vars || theme).palette.primary.main\n }\n }, {\n props: {\n color: 'inherit'\n },\n style: {\n color: 'inherit'\n }\n }, {\n props: ({\n ownerState\n }) => !ownerState.disableGutters,\n style: {\n paddingLeft: 16,\n paddingRight: 16\n }\n }, {\n props: ({\n ownerState\n }) => ownerState.inset,\n style: {\n paddingLeft: 72\n }\n }, {\n props: ({\n ownerState\n }) => !ownerState.disableSticky,\n style: {\n position: 'sticky',\n top: 0,\n zIndex: 1,\n backgroundColor: (theme.vars || theme).palette.background.paper\n }\n }]\n})));\nconst ListSubheader = /*#__PURE__*/React.forwardRef(function ListSubheader(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiListSubheader'\n });\n const {\n className,\n color = 'default',\n component = 'li',\n disableGutters = false,\n disableSticky = false,\n inset = false,\n ...other\n } = props;\n const ownerState = {\n ...props,\n color,\n component,\n disableGutters,\n disableSticky,\n inset\n };\n const classes = useUtilityClasses(ownerState);\n return /*#__PURE__*/_jsx(ListSubheaderRoot, {\n as: component,\n className: clsx(classes.root, className),\n ref: ref,\n ownerState: ownerState,\n ...other\n });\n});\nif (ListSubheader) {\n ListSubheader.muiSkipListHighlight = true;\n}\nprocess.env.NODE_ENV !== \"production\" ? ListSubheader.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The color of the component. It supports those theme colors that make sense for this component.\n * @default 'default'\n */\n color: PropTypes.oneOf(['default', 'inherit', 'primary']),\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * If `true`, the List Subheader will not have gutters.\n * @default false\n */\n disableGutters: PropTypes.bool,\n /**\n * If `true`, the List Subheader will not stick to the top during scroll.\n * @default false\n */\n disableSticky: PropTypes.bool,\n /**\n * If `true`, the List Subheader is indented.\n * @default false\n */\n inset: PropTypes.bool,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default ListSubheader;","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from \"../../utils/createSvgIcon.js\";\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon(/*#__PURE__*/_jsx(\"path\", {\n d: \"M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z\"\n}), 'Cancel');","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getChipUtilityClass(slot) {\n return generateUtilityClass('MuiChip', slot);\n}\nconst chipClasses = generateUtilityClasses('MuiChip', ['root', 'sizeSmall', 'sizeMedium', 'colorDefault', 'colorError', 'colorInfo', 'colorPrimary', 'colorSecondary', 'colorSuccess', 'colorWarning', 'disabled', 'clickable', 'clickableColorPrimary', 'clickableColorSecondary', 'deletable', 'deletableColorPrimary', 'deletableColorSecondary', 'outlined', 'filled', 'outlinedPrimary', 'outlinedSecondary', 'filledPrimary', 'filledSecondary', 'avatar', 'avatarSmall', 'avatarMedium', 'avatarColorPrimary', 'avatarColorSecondary', 'icon', 'iconSmall', 'iconMedium', 'iconColorPrimary', 'iconColorSecondary', 'label', 'labelSmall', 'labelMedium', 'deleteIcon', 'deleteIconSmall', 'deleteIconMedium', 'deleteIconColorPrimary', 'deleteIconColorSecondary', 'deleteIconOutlinedColorPrimary', 'deleteIconOutlinedColorSecondary', 'deleteIconFilledColorPrimary', 'deleteIconFilledColorSecondary', 'focusVisible']);\nexport default chipClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { alpha } from '@mui/system/colorManipulator';\nimport CancelIcon from \"../internal/svg-icons/Cancel.js\";\nimport useForkRef from \"../utils/useForkRef.js\";\nimport unsupportedProp from \"../utils/unsupportedProp.js\";\nimport capitalize from \"../utils/capitalize.js\";\nimport ButtonBase from \"../ButtonBase/index.js\";\nimport { styled } from \"../zero-styled/index.js\";\nimport memoTheme from \"../utils/memoTheme.js\";\nimport createSimplePaletteValueFilter from \"../utils/createSimplePaletteValueFilter.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport chipClasses, { getChipUtilityClass } from \"./chipClasses.js\";\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n disabled,\n size,\n color,\n iconColor,\n onDelete,\n clickable,\n variant\n } = ownerState;\n const slots = {\n root: ['root', variant, disabled && 'disabled', `size${capitalize(size)}`, `color${capitalize(color)}`, clickable && 'clickable', clickable && `clickableColor${capitalize(color)}`, onDelete && 'deletable', onDelete && `deletableColor${capitalize(color)}`, `${variant}${capitalize(color)}`],\n label: ['label', `label${capitalize(size)}`],\n avatar: ['avatar', `avatar${capitalize(size)}`, `avatarColor${capitalize(color)}`],\n icon: ['icon', `icon${capitalize(size)}`, `iconColor${capitalize(iconColor)}`],\n deleteIcon: ['deleteIcon', `deleteIcon${capitalize(size)}`, `deleteIconColor${capitalize(color)}`, `deleteIcon${capitalize(variant)}Color${capitalize(color)}`]\n };\n return composeClasses(slots, getChipUtilityClass, classes);\n};\nconst ChipRoot = styled('div', {\n name: 'MuiChip',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n const {\n color,\n iconColor,\n clickable,\n onDelete,\n size,\n variant\n } = ownerState;\n return [{\n [`& .${chipClasses.avatar}`]: styles.avatar\n }, {\n [`& .${chipClasses.avatar}`]: styles[`avatar${capitalize(size)}`]\n }, {\n [`& .${chipClasses.avatar}`]: styles[`avatarColor${capitalize(color)}`]\n }, {\n [`& .${chipClasses.icon}`]: styles.icon\n }, {\n [`& .${chipClasses.icon}`]: styles[`icon${capitalize(size)}`]\n }, {\n [`& .${chipClasses.icon}`]: styles[`iconColor${capitalize(iconColor)}`]\n }, {\n [`& .${chipClasses.deleteIcon}`]: styles.deleteIcon\n }, {\n [`& .${chipClasses.deleteIcon}`]: styles[`deleteIcon${capitalize(size)}`]\n }, {\n [`& .${chipClasses.deleteIcon}`]: styles[`deleteIconColor${capitalize(color)}`]\n }, {\n [`& .${chipClasses.deleteIcon}`]: styles[`deleteIcon${capitalize(variant)}Color${capitalize(color)}`]\n }, styles.root, styles[`size${capitalize(size)}`], styles[`color${capitalize(color)}`], clickable && styles.clickable, clickable && color !== 'default' && styles[`clickableColor${capitalize(color)})`], onDelete && styles.deletable, onDelete && color !== 'default' && styles[`deletableColor${capitalize(color)}`], styles[variant], styles[`${variant}${capitalize(color)}`]];\n }\n})(memoTheme(({\n theme\n}) => {\n const textColor = theme.palette.mode === 'light' ? theme.palette.grey[700] : theme.palette.grey[300];\n return {\n maxWidth: '100%',\n fontFamily: theme.typography.fontFamily,\n fontSize: theme.typography.pxToRem(13),\n display: 'inline-flex',\n alignItems: 'center',\n justifyContent: 'center',\n height: 32,\n color: (theme.vars || theme).palette.text.primary,\n backgroundColor: (theme.vars || theme).palette.action.selected,\n borderRadius: 32 / 2,\n whiteSpace: 'nowrap',\n transition: theme.transitions.create(['background-color', 'box-shadow']),\n // reset cursor explicitly in case ButtonBase is used\n cursor: 'unset',\n // We disable the focus ring for mouse, touch and keyboard users.\n outline: 0,\n textDecoration: 'none',\n border: 0,\n // Remove `button` border\n padding: 0,\n // Remove `button` padding\n verticalAlign: 'middle',\n boxSizing: 'border-box',\n [`&.${chipClasses.disabled}`]: {\n opacity: (theme.vars || theme).palette.action.disabledOpacity,\n pointerEvents: 'none'\n },\n [`& .${chipClasses.avatar}`]: {\n marginLeft: 5,\n marginRight: -6,\n width: 24,\n height: 24,\n color: theme.vars ? theme.vars.palette.Chip.defaultAvatarColor : textColor,\n fontSize: theme.typography.pxToRem(12)\n },\n [`& .${chipClasses.avatarColorPrimary}`]: {\n color: (theme.vars || theme).palette.primary.contrastText,\n backgroundColor: (theme.vars || theme).palette.primary.dark\n },\n [`& .${chipClasses.avatarColorSecondary}`]: {\n color: (theme.vars || theme).palette.secondary.contrastText,\n backgroundColor: (theme.vars || theme).palette.secondary.dark\n },\n [`& .${chipClasses.avatarSmall}`]: {\n marginLeft: 4,\n marginRight: -4,\n width: 18,\n height: 18,\n fontSize: theme.typography.pxToRem(10)\n },\n [`& .${chipClasses.icon}`]: {\n marginLeft: 5,\n marginRight: -6\n },\n [`& .${chipClasses.deleteIcon}`]: {\n WebkitTapHighlightColor: 'transparent',\n color: theme.vars ? `rgba(${theme.vars.palette.text.primaryChannel} / 0.26)` : alpha(theme.palette.text.primary, 0.26),\n fontSize: 22,\n cursor: 'pointer',\n margin: '0 5px 0 -6px',\n '&:hover': {\n color: theme.vars ? `rgba(${theme.vars.palette.text.primaryChannel} / 0.4)` : alpha(theme.palette.text.primary, 0.4)\n }\n },\n variants: [{\n props: {\n size: 'small'\n },\n style: {\n height: 24,\n [`& .${chipClasses.icon}`]: {\n fontSize: 18,\n marginLeft: 4,\n marginRight: -4\n },\n [`& .${chipClasses.deleteIcon}`]: {\n fontSize: 16,\n marginRight: 4,\n marginLeft: -4\n }\n }\n }, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter(['contrastText'])).map(([color]) => {\n return {\n props: {\n color\n },\n style: {\n backgroundColor: (theme.vars || theme).palette[color].main,\n color: (theme.vars || theme).palette[color].contrastText,\n [`& .${chipClasses.deleteIcon}`]: {\n color: theme.vars ? `rgba(${theme.vars.palette[color].contrastTextChannel} / 0.7)` : alpha(theme.palette[color].contrastText, 0.7),\n '&:hover, &:active': {\n color: (theme.vars || theme).palette[color].contrastText\n }\n }\n }\n };\n }), {\n props: props => props.iconColor === props.color,\n style: {\n [`& .${chipClasses.icon}`]: {\n color: theme.vars ? theme.vars.palette.Chip.defaultIconColor : textColor\n }\n }\n }, {\n props: props => props.iconColor === props.color && props.color !== 'default',\n style: {\n [`& .${chipClasses.icon}`]: {\n color: 'inherit'\n }\n }\n }, {\n props: {\n onDelete: true\n },\n style: {\n [`&.${chipClasses.focusVisible}`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.action.selectedChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.action.selected, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)\n }\n }\n }, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter(['dark'])).map(([color]) => {\n return {\n props: {\n color,\n onDelete: true\n },\n style: {\n [`&.${chipClasses.focusVisible}`]: {\n background: (theme.vars || theme).palette[color].dark\n }\n }\n };\n }), {\n props: {\n clickable: true\n },\n style: {\n userSelect: 'none',\n WebkitTapHighlightColor: 'transparent',\n cursor: 'pointer',\n '&:hover': {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.action.selectedChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(theme.palette.action.selected, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity)\n },\n [`&.${chipClasses.focusVisible}`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.action.selectedChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.action.selected, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)\n },\n '&:active': {\n boxShadow: (theme.vars || theme).shadows[1]\n }\n }\n }, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter(['dark'])).map(([color]) => ({\n props: {\n color,\n clickable: true\n },\n style: {\n [`&:hover, &.${chipClasses.focusVisible}`]: {\n backgroundColor: (theme.vars || theme).palette[color].dark\n }\n }\n })), {\n props: {\n variant: 'outlined'\n },\n style: {\n backgroundColor: 'transparent',\n border: theme.vars ? `1px solid ${theme.vars.palette.Chip.defaultBorder}` : `1px solid ${theme.palette.mode === 'light' ? theme.palette.grey[400] : theme.palette.grey[700]}`,\n [`&.${chipClasses.clickable}:hover`]: {\n backgroundColor: (theme.vars || theme).palette.action.hover\n },\n [`&.${chipClasses.focusVisible}`]: {\n backgroundColor: (theme.vars || theme).palette.action.focus\n },\n [`& .${chipClasses.avatar}`]: {\n marginLeft: 4\n },\n [`& .${chipClasses.avatarSmall}`]: {\n marginLeft: 2\n },\n [`& .${chipClasses.icon}`]: {\n marginLeft: 4\n },\n [`& .${chipClasses.iconSmall}`]: {\n marginLeft: 2\n },\n [`& .${chipClasses.deleteIcon}`]: {\n marginRight: 5\n },\n [`& .${chipClasses.deleteIconSmall}`]: {\n marginRight: 3\n }\n }\n }, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()) // no need to check for mainChannel as it's calculated from main\n .map(([color]) => ({\n props: {\n variant: 'outlined',\n color\n },\n style: {\n color: (theme.vars || theme).palette[color].main,\n border: `1px solid ${theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / 0.7)` : alpha(theme.palette[color].main, 0.7)}`,\n [`&.${chipClasses.clickable}:hover`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette[color].main, theme.palette.action.hoverOpacity)\n },\n [`&.${chipClasses.focusVisible}`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / ${theme.vars.palette.action.focusOpacity})` : alpha(theme.palette[color].main, theme.palette.action.focusOpacity)\n },\n [`& .${chipClasses.deleteIcon}`]: {\n color: theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / 0.7)` : alpha(theme.palette[color].main, 0.7),\n '&:hover, &:active': {\n color: (theme.vars || theme).palette[color].main\n }\n }\n }\n }))]\n };\n}));\nconst ChipLabel = styled('span', {\n name: 'MuiChip',\n slot: 'Label',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n const {\n size\n } = ownerState;\n return [styles.label, styles[`label${capitalize(size)}`]];\n }\n})({\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n paddingLeft: 12,\n paddingRight: 12,\n whiteSpace: 'nowrap',\n variants: [{\n props: {\n variant: 'outlined'\n },\n style: {\n paddingLeft: 11,\n paddingRight: 11\n }\n }, {\n props: {\n size: 'small'\n },\n style: {\n paddingLeft: 8,\n paddingRight: 8\n }\n }, {\n props: {\n size: 'small',\n variant: 'outlined'\n },\n style: {\n paddingLeft: 7,\n paddingRight: 7\n }\n }]\n});\nfunction isDeleteKeyboardEvent(keyboardEvent) {\n return keyboardEvent.key === 'Backspace' || keyboardEvent.key === 'Delete';\n}\n\n/**\n * Chips represent complex entities in small blocks, such as a contact.\n */\nconst Chip = /*#__PURE__*/React.forwardRef(function Chip(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiChip'\n });\n const {\n avatar: avatarProp,\n className,\n clickable: clickableProp,\n color = 'default',\n component: ComponentProp,\n deleteIcon: deleteIconProp,\n disabled = false,\n icon: iconProp,\n label,\n onClick,\n onDelete,\n onKeyDown,\n onKeyUp,\n size = 'medium',\n variant = 'filled',\n tabIndex,\n skipFocusWhenDisabled = false,\n // TODO v6: Rename to `focusableWhenDisabled`.\n ...other\n } = props;\n const chipRef = React.useRef(null);\n const handleRef = useForkRef(chipRef, ref);\n const handleDeleteIconClick = event => {\n // Stop the event from bubbling up to the `Chip`\n event.stopPropagation();\n if (onDelete) {\n onDelete(event);\n }\n };\n const handleKeyDown = event => {\n // Ignore events from children of `Chip`.\n if (event.currentTarget === event.target && isDeleteKeyboardEvent(event)) {\n // Will be handled in keyUp, otherwise some browsers\n // might init navigation\n event.preventDefault();\n }\n if (onKeyDown) {\n onKeyDown(event);\n }\n };\n const handleKeyUp = event => {\n // Ignore events from children of `Chip`.\n if (event.currentTarget === event.target) {\n if (onDelete && isDeleteKeyboardEvent(event)) {\n onDelete(event);\n }\n }\n if (onKeyUp) {\n onKeyUp(event);\n }\n };\n const clickable = clickableProp !== false && onClick ? true : clickableProp;\n const component = clickable || onDelete ? ButtonBase : ComponentProp || 'div';\n const ownerState = {\n ...props,\n component,\n disabled,\n size,\n color,\n iconColor: /*#__PURE__*/React.isValidElement(iconProp) ? iconProp.props.color || color : color,\n onDelete: !!onDelete,\n clickable,\n variant\n };\n const classes = useUtilityClasses(ownerState);\n const moreProps = component === ButtonBase ? {\n component: ComponentProp || 'div',\n focusVisibleClassName: classes.focusVisible,\n ...(onDelete && {\n disableRipple: true\n })\n } : {};\n let deleteIcon = null;\n if (onDelete) {\n deleteIcon = deleteIconProp && /*#__PURE__*/React.isValidElement(deleteIconProp) ? (/*#__PURE__*/React.cloneElement(deleteIconProp, {\n className: clsx(deleteIconProp.props.className, classes.deleteIcon),\n onClick: handleDeleteIconClick\n })) : /*#__PURE__*/_jsx(CancelIcon, {\n className: clsx(classes.deleteIcon),\n onClick: handleDeleteIconClick\n });\n }\n let avatar = null;\n if (avatarProp && /*#__PURE__*/React.isValidElement(avatarProp)) {\n avatar = /*#__PURE__*/React.cloneElement(avatarProp, {\n className: clsx(classes.avatar, avatarProp.props.className)\n });\n }\n let icon = null;\n if (iconProp && /*#__PURE__*/React.isValidElement(iconProp)) {\n icon = /*#__PURE__*/React.cloneElement(iconProp, {\n className: clsx(classes.icon, iconProp.props.className)\n });\n }\n if (process.env.NODE_ENV !== 'production') {\n if (avatar && icon) {\n console.error('MUI: The Chip component can not handle the avatar ' + 'and the icon prop at the same time. Pick one.');\n }\n }\n return /*#__PURE__*/_jsxs(ChipRoot, {\n as: component,\n className: clsx(classes.root, className),\n disabled: clickable && disabled ? true : undefined,\n onClick: onClick,\n onKeyDown: handleKeyDown,\n onKeyUp: handleKeyUp,\n ref: handleRef,\n tabIndex: skipFocusWhenDisabled && disabled ? -1 : tabIndex,\n ownerState: ownerState,\n ...moreProps,\n ...other,\n children: [avatar || icon, /*#__PURE__*/_jsx(ChipLabel, {\n className: clsx(classes.label),\n ownerState: ownerState,\n children: label\n }), deleteIcon]\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Chip.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The Avatar element to display.\n */\n avatar: PropTypes.element,\n /**\n * This prop isn't supported.\n * Use the `component` prop if you need to change the children structure.\n */\n children: unsupportedProp,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * If `true`, the chip will appear clickable, and will raise when pressed,\n * even if the onClick prop is not defined.\n * If `false`, the chip will not appear clickable, even if onClick prop is defined.\n * This can be used, for example,\n * along with the component prop to indicate an anchor Chip is clickable.\n * Note: this controls the UI and does not affect the onClick event.\n */\n clickable: PropTypes.bool,\n /**\n * The color of the component.\n * It supports both default and custom theme colors, which can be added as shown in the\n * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).\n * @default 'default'\n */\n color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['default', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * Override the default delete icon element. Shown only if `onDelete` is set.\n */\n deleteIcon: PropTypes.element,\n /**\n * If `true`, the component is disabled.\n * @default false\n */\n disabled: PropTypes.bool,\n /**\n * Icon element.\n */\n icon: PropTypes.element,\n /**\n * The content of the component.\n */\n label: PropTypes.node,\n /**\n * @ignore\n */\n onClick: PropTypes.func,\n /**\n * Callback fired when the delete icon is clicked.\n * If set, the delete icon will be shown.\n */\n onDelete: PropTypes.func,\n /**\n * @ignore\n */\n onKeyDown: PropTypes.func,\n /**\n * @ignore\n */\n onKeyUp: PropTypes.func,\n /**\n * The size of the component.\n * @default 'medium'\n */\n size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),\n /**\n * If `true`, allows the disabled chip to escape focus.\n * If `false`, allows the disabled chip to receive focus.\n * @default false\n */\n skipFocusWhenDisabled: PropTypes.bool,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * @ignore\n */\n tabIndex: PropTypes.number,\n /**\n * The variant to use.\n * @default 'filled'\n */\n variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['filled', 'outlined']), PropTypes.string])\n} : void 0;\nexport default Chip;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { unstable_debounce as debounce, unstable_useForkRef as useForkRef, unstable_useEnhancedEffect as useEnhancedEffect, unstable_ownerWindow as ownerWindow } from '@mui/utils';\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nfunction getStyleValue(value) {\n return parseInt(value, 10) || 0;\n}\nconst styles = {\n shadow: {\n // Visibility needed to hide the extra text area on iPads\n visibility: 'hidden',\n // Remove from the content flow\n position: 'absolute',\n // Ignore the scrollbar width\n overflow: 'hidden',\n height: 0,\n top: 0,\n left: 0,\n // Create a new layer, increase the isolation of the computed values\n transform: 'translateZ(0)'\n }\n};\nfunction isObjectEmpty(object) {\n // eslint-disable-next-line\n for (const _ in object) {\n return false;\n }\n return true;\n}\nfunction isEmpty(obj) {\n return isObjectEmpty(obj) || obj.outerHeightStyle === 0 && !obj.overflowing;\n}\n\n/**\n *\n * Demos:\n *\n * - [Textarea Autosize](https://mui.com/material-ui/react-textarea-autosize/)\n *\n * API:\n *\n * - [TextareaAutosize API](https://mui.com/material-ui/api/textarea-autosize/)\n */\nconst TextareaAutosize = /*#__PURE__*/React.forwardRef(function TextareaAutosize(props, forwardedRef) {\n const {\n onChange,\n maxRows,\n minRows = 1,\n style,\n value,\n ...other\n } = props;\n const {\n current: isControlled\n } = React.useRef(value != null);\n const textareaRef = React.useRef(null);\n const handleRef = useForkRef(forwardedRef, textareaRef);\n const heightRef = React.useRef(null);\n const hiddenTextareaRef = React.useRef(null);\n const calculateTextareaStyles = React.useCallback(() => {\n const textarea = textareaRef.current;\n const hiddenTextarea = hiddenTextareaRef.current;\n if (!textarea || !hiddenTextarea) {\n return undefined;\n }\n const containerWindow = ownerWindow(textarea);\n const computedStyle = containerWindow.getComputedStyle(textarea);\n\n // If input's width is shrunk and it's not visible, don't sync height.\n if (computedStyle.width === '0px') {\n return {\n outerHeightStyle: 0,\n overflowing: false\n };\n }\n hiddenTextarea.style.width = computedStyle.width;\n hiddenTextarea.value = textarea.value || props.placeholder || 'x';\n if (hiddenTextarea.value.slice(-1) === '\\n') {\n // Certain fonts which overflow the line height will cause the textarea\n // to report a different scrollHeight depending on whether the last line\n // is empty. Make it non-empty to avoid this issue.\n hiddenTextarea.value += ' ';\n }\n const boxSizing = computedStyle.boxSizing;\n const padding = getStyleValue(computedStyle.paddingBottom) + getStyleValue(computedStyle.paddingTop);\n const border = getStyleValue(computedStyle.borderBottomWidth) + getStyleValue(computedStyle.borderTopWidth);\n\n // The height of the inner content\n const innerHeight = hiddenTextarea.scrollHeight;\n\n // Measure height of a textarea with a single row\n hiddenTextarea.value = 'x';\n const singleRowHeight = hiddenTextarea.scrollHeight;\n\n // The height of the outer content\n let outerHeight = innerHeight;\n if (minRows) {\n outerHeight = Math.max(Number(minRows) * singleRowHeight, outerHeight);\n }\n if (maxRows) {\n outerHeight = Math.min(Number(maxRows) * singleRowHeight, outerHeight);\n }\n outerHeight = Math.max(outerHeight, singleRowHeight);\n\n // Take the box sizing into account for applying this value as a style.\n const outerHeightStyle = outerHeight + (boxSizing === 'border-box' ? padding + border : 0);\n const overflowing = Math.abs(outerHeight - innerHeight) <= 1;\n return {\n outerHeightStyle,\n overflowing\n };\n }, [maxRows, minRows, props.placeholder]);\n const syncHeight = React.useCallback(() => {\n const textarea = textareaRef.current;\n const textareaStyles = calculateTextareaStyles();\n if (!textarea || !textareaStyles || isEmpty(textareaStyles)) {\n return;\n }\n const outerHeightStyle = textareaStyles.outerHeightStyle;\n if (heightRef.current !== outerHeightStyle) {\n heightRef.current = outerHeightStyle;\n textarea.style.height = `${outerHeightStyle}px`;\n }\n textarea.style.overflow = textareaStyles.overflowing ? 'hidden' : '';\n }, [calculateTextareaStyles]);\n const frameRef = React.useRef(-1);\n useEnhancedEffect(() => {\n const debounceHandleResize = debounce(() => syncHeight());\n const textarea = textareaRef?.current;\n if (!textarea) {\n return undefined;\n }\n const containerWindow = ownerWindow(textarea);\n containerWindow.addEventListener('resize', debounceHandleResize);\n let resizeObserver;\n if (typeof ResizeObserver !== 'undefined') {\n resizeObserver = new ResizeObserver(() => {\n // avoid \"ResizeObserver loop completed with undelivered notifications\" error\n // by temporarily unobserving the textarea element while manipulating the height\n // and reobserving one frame later\n resizeObserver.unobserve(textarea);\n cancelAnimationFrame(frameRef.current);\n syncHeight();\n frameRef.current = requestAnimationFrame(() => {\n resizeObserver.observe(textarea);\n });\n });\n resizeObserver.observe(textarea);\n }\n return () => {\n debounceHandleResize.clear();\n cancelAnimationFrame(frameRef.current);\n containerWindow.removeEventListener('resize', debounceHandleResize);\n if (resizeObserver) {\n resizeObserver.disconnect();\n }\n };\n }, [calculateTextareaStyles, syncHeight]);\n useEnhancedEffect(() => {\n syncHeight();\n });\n const handleChange = event => {\n if (!isControlled) {\n syncHeight();\n }\n if (onChange) {\n onChange(event);\n }\n };\n return /*#__PURE__*/_jsxs(React.Fragment, {\n children: [/*#__PURE__*/_jsx(\"textarea\", {\n value: value,\n onChange: handleChange,\n ref: handleRef\n // Apply the rows prop to get a \"correct\" first SSR paint\n ,\n rows: minRows,\n style: style,\n ...other\n }), /*#__PURE__*/_jsx(\"textarea\", {\n \"aria-hidden\": true,\n className: props.className,\n readOnly: true,\n ref: hiddenTextareaRef,\n tabIndex: -1,\n style: {\n ...styles.shadow,\n ...style,\n paddingTop: 0,\n paddingBottom: 0\n }\n })]\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? TextareaAutosize.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the TypeScript types and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * Maximum number of rows to display.\n */\n maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n /**\n * Minimum number of rows to display.\n * @default 1\n */\n minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n /**\n * @ignore\n */\n onChange: PropTypes.func,\n /**\n * @ignore\n */\n placeholder: PropTypes.string,\n /**\n * @ignore\n */\n style: PropTypes.object,\n /**\n * @ignore\n */\n value: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.string), PropTypes.number, PropTypes.string])\n} : void 0;\nexport default TextareaAutosize;","/**\n * Determines if a given element is a DOM element name (i.e. not a React component).\n */\nfunction isHostComponent(element) {\n return typeof element === 'string';\n}\nexport default isHostComponent;","export default function formControlState({\n props,\n states,\n muiFormControl\n}) {\n return states.reduce((acc, state) => {\n acc[state] = props[state];\n if (muiFormControl) {\n if (typeof props[state] === 'undefined') {\n acc[state] = muiFormControl[state];\n }\n }\n return acc;\n }, {});\n}","'use client';\n\nimport * as React from 'react';\n/**\n * @ignore - internal component.\n */\nconst FormControlContext = /*#__PURE__*/React.createContext(undefined);\nif (process.env.NODE_ENV !== 'production') {\n FormControlContext.displayName = 'FormControlContext';\n}\nexport default FormControlContext;","'use client';\n\nimport * as React from 'react';\nimport FormControlContext from \"./FormControlContext.js\";\nexport default function useFormControl() {\n return React.useContext(FormControlContext);\n}","// Supports determination of isControlled().\n// Controlled input accepts its current value as a prop.\n//\n// @see https://facebook.github.io/react/docs/forms.html#controlled-components\n// @param value\n// @returns {boolean} true if string (including '') or number (including zero)\nexport function hasValue(value) {\n return value != null && !(Array.isArray(value) && value.length === 0);\n}\n\n// Determine if field is empty or filled.\n// Response determines if label is presented above field or as placeholder.\n//\n// @param obj\n// @param SSR\n// @returns {boolean} False when not present or empty string.\n// True when any number or string with length.\nexport function isFilled(obj, SSR = false) {\n return obj && (hasValue(obj.value) && obj.value !== '' || SSR && hasValue(obj.defaultValue) && obj.defaultValue !== '');\n}\n\n// Determine if an Input is adorned on start.\n// It's corresponding to the left with LTR.\n//\n// @param obj\n// @returns {boolean} False when no adornments.\n// True when adorned at the start.\nexport function isAdornedStart(obj) {\n return obj.startAdornment;\n}","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getInputBaseUtilityClass(slot) {\n return generateUtilityClass('MuiInputBase', slot);\n}\nconst inputBaseClasses = generateUtilityClasses('MuiInputBase', ['root', 'formControl', 'focused', 'disabled', 'adornedStart', 'adornedEnd', 'error', 'sizeSmall', 'multiline', 'colorSecondary', 'fullWidth', 'hiddenLabel', 'readOnly', 'input', 'inputSizeSmall', 'inputMultiline', 'inputTypeSearch', 'inputAdornedStart', 'inputAdornedEnd', 'inputHiddenLabel']);\nexport default inputBaseClasses;","'use client';\n\nimport _formatMuiErrorMessage from \"@mui/utils/formatMuiErrorMessage\";\nvar _InputGlobalStyles;\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport elementTypeAcceptingRef from '@mui/utils/elementTypeAcceptingRef';\nimport refType from '@mui/utils/refType';\nimport composeClasses from '@mui/utils/composeClasses';\nimport TextareaAutosize from \"../TextareaAutosize/index.js\";\nimport isHostComponent from \"../utils/isHostComponent.js\";\nimport formControlState from \"../FormControl/formControlState.js\";\nimport FormControlContext from \"../FormControl/FormControlContext.js\";\nimport useFormControl from \"../FormControl/useFormControl.js\";\nimport { styled, globalCss } from \"../zero-styled/index.js\";\nimport memoTheme from \"../utils/memoTheme.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport capitalize from \"../utils/capitalize.js\";\nimport useForkRef from \"../utils/useForkRef.js\";\nimport useEnhancedEffect from \"../utils/useEnhancedEffect.js\";\nimport { isFilled } from \"./utils.js\";\nimport inputBaseClasses, { getInputBaseUtilityClass } from \"./inputBaseClasses.js\";\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nexport const rootOverridesResolver = (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.formControl && styles.formControl, ownerState.startAdornment && styles.adornedStart, ownerState.endAdornment && styles.adornedEnd, ownerState.error && styles.error, ownerState.size === 'small' && styles.sizeSmall, ownerState.multiline && styles.multiline, ownerState.color && styles[`color${capitalize(ownerState.color)}`], ownerState.fullWidth && styles.fullWidth, ownerState.hiddenLabel && styles.hiddenLabel];\n};\nexport const inputOverridesResolver = (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.input, ownerState.size === 'small' && styles.inputSizeSmall, ownerState.multiline && styles.inputMultiline, ownerState.type === 'search' && styles.inputTypeSearch, ownerState.startAdornment && styles.inputAdornedStart, ownerState.endAdornment && styles.inputAdornedEnd, ownerState.hiddenLabel && styles.inputHiddenLabel];\n};\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n color,\n disabled,\n error,\n endAdornment,\n focused,\n formControl,\n fullWidth,\n hiddenLabel,\n multiline,\n readOnly,\n size,\n startAdornment,\n type\n } = ownerState;\n const slots = {\n root: ['root', `color${capitalize(color)}`, disabled && 'disabled', error && 'error', fullWidth && 'fullWidth', focused && 'focused', formControl && 'formControl', size && size !== 'medium' && `size${capitalize(size)}`, multiline && 'multiline', startAdornment && 'adornedStart', endAdornment && 'adornedEnd', hiddenLabel && 'hiddenLabel', readOnly && 'readOnly'],\n input: ['input', disabled && 'disabled', type === 'search' && 'inputTypeSearch', multiline && 'inputMultiline', size === 'small' && 'inputSizeSmall', hiddenLabel && 'inputHiddenLabel', startAdornment && 'inputAdornedStart', endAdornment && 'inputAdornedEnd', readOnly && 'readOnly']\n };\n return composeClasses(slots, getInputBaseUtilityClass, classes);\n};\nexport const InputBaseRoot = styled('div', {\n name: 'MuiInputBase',\n slot: 'Root',\n overridesResolver: rootOverridesResolver\n})(memoTheme(({\n theme\n}) => ({\n ...theme.typography.body1,\n color: (theme.vars || theme).palette.text.primary,\n lineHeight: '1.4375em',\n // 23px\n boxSizing: 'border-box',\n // Prevent padding issue with fullWidth.\n position: 'relative',\n cursor: 'text',\n display: 'inline-flex',\n alignItems: 'center',\n [`&.${inputBaseClasses.disabled}`]: {\n color: (theme.vars || theme).palette.text.disabled,\n cursor: 'default'\n },\n variants: [{\n props: ({\n ownerState\n }) => ownerState.multiline,\n style: {\n padding: '4px 0 5px'\n }\n }, {\n props: ({\n ownerState,\n size\n }) => ownerState.multiline && size === 'small',\n style: {\n paddingTop: 1\n }\n }, {\n props: ({\n ownerState\n }) => ownerState.fullWidth,\n style: {\n width: '100%'\n }\n }]\n})));\nexport const InputBaseInput = styled('input', {\n name: 'MuiInputBase',\n slot: 'Input',\n overridesResolver: inputOverridesResolver\n})(memoTheme(({\n theme\n}) => {\n const light = theme.palette.mode === 'light';\n const placeholder = {\n color: 'currentColor',\n ...(theme.vars ? {\n opacity: theme.vars.opacity.inputPlaceholder\n } : {\n opacity: light ? 0.42 : 0.5\n }),\n transition: theme.transitions.create('opacity', {\n duration: theme.transitions.duration.shorter\n })\n };\n const placeholderHidden = {\n opacity: '0 !important'\n };\n const placeholderVisible = theme.vars ? {\n opacity: theme.vars.opacity.inputPlaceholder\n } : {\n opacity: light ? 0.42 : 0.5\n };\n return {\n font: 'inherit',\n letterSpacing: 'inherit',\n color: 'currentColor',\n padding: '4px 0 5px',\n border: 0,\n boxSizing: 'content-box',\n background: 'none',\n height: '1.4375em',\n // Reset 23pxthe native input line-height\n margin: 0,\n // Reset for Safari\n WebkitTapHighlightColor: 'transparent',\n display: 'block',\n // Make the flex item shrink with Firefox\n minWidth: 0,\n width: '100%',\n '&::-webkit-input-placeholder': placeholder,\n '&::-moz-placeholder': placeholder,\n // Firefox 19+\n '&::-ms-input-placeholder': placeholder,\n // Edge\n '&:focus': {\n outline: 0\n },\n // Reset Firefox invalid required input style\n '&:invalid': {\n boxShadow: 'none'\n },\n '&::-webkit-search-decoration': {\n // Remove the padding when type=search.\n WebkitAppearance: 'none'\n },\n // Show and hide the placeholder logic\n [`label[data-shrink=false] + .${inputBaseClasses.formControl} &`]: {\n '&::-webkit-input-placeholder': placeholderHidden,\n '&::-moz-placeholder': placeholderHidden,\n // Firefox 19+\n '&::-ms-input-placeholder': placeholderHidden,\n // Edge\n '&:focus::-webkit-input-placeholder': placeholderVisible,\n '&:focus::-moz-placeholder': placeholderVisible,\n // Firefox 19+\n '&:focus::-ms-input-placeholder': placeholderVisible // Edge\n },\n [`&.${inputBaseClasses.disabled}`]: {\n opacity: 1,\n // Reset iOS opacity\n WebkitTextFillColor: (theme.vars || theme).palette.text.disabled // Fix opacity Safari bug\n },\n variants: [{\n props: ({\n ownerState\n }) => !ownerState.disableInjectingGlobalStyles,\n style: {\n animationName: 'mui-auto-fill-cancel',\n animationDuration: '10ms',\n '&:-webkit-autofill': {\n animationDuration: '5000s',\n animationName: 'mui-auto-fill'\n }\n }\n }, {\n props: {\n size: 'small'\n },\n style: {\n paddingTop: 1\n }\n }, {\n props: ({\n ownerState\n }) => ownerState.multiline,\n style: {\n height: 'auto',\n resize: 'none',\n padding: 0,\n paddingTop: 0\n }\n }, {\n props: {\n type: 'search'\n },\n style: {\n MozAppearance: 'textfield' // Improve type search style.\n }\n }]\n };\n}));\nconst InputGlobalStyles = globalCss({\n '@keyframes mui-auto-fill': {\n from: {\n display: 'block'\n }\n },\n '@keyframes mui-auto-fill-cancel': {\n from: {\n display: 'block'\n }\n }\n});\n\n/**\n * `InputBase` contains as few styles as possible.\n * It aims to be a simple building block for creating an input.\n * It contains a load of style reset and some state logic.\n */\nconst InputBase = /*#__PURE__*/React.forwardRef(function InputBase(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiInputBase'\n });\n const {\n 'aria-describedby': ariaDescribedby,\n autoComplete,\n autoFocus,\n className,\n color,\n components = {},\n componentsProps = {},\n defaultValue,\n disabled,\n disableInjectingGlobalStyles,\n endAdornment,\n error,\n fullWidth = false,\n id,\n inputComponent = 'input',\n inputProps: inputPropsProp = {},\n inputRef: inputRefProp,\n margin,\n maxRows,\n minRows,\n multiline = false,\n name,\n onBlur,\n onChange,\n onClick,\n onFocus,\n onKeyDown,\n onKeyUp,\n placeholder,\n readOnly,\n renderSuffix,\n rows,\n size,\n slotProps = {},\n slots = {},\n startAdornment,\n type = 'text',\n value: valueProp,\n ...other\n } = props;\n const value = inputPropsProp.value != null ? inputPropsProp.value : valueProp;\n const {\n current: isControlled\n } = React.useRef(value != null);\n const inputRef = React.useRef();\n const handleInputRefWarning = React.useCallback(instance => {\n if (process.env.NODE_ENV !== 'production') {\n if (instance && instance.nodeName !== 'INPUT' && !instance.focus) {\n console.error(['MUI: You have provided a `inputComponent` to the input component', 'that does not correctly handle the `ref` prop.', 'Make sure the `ref` prop is called with a HTMLInputElement.'].join('\\n'));\n }\n }\n }, []);\n const handleInputRef = useForkRef(inputRef, inputRefProp, inputPropsProp.ref, handleInputRefWarning);\n const [focused, setFocused] = React.useState(false);\n const muiFormControl = useFormControl();\n if (process.env.NODE_ENV !== 'production') {\n // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler\n // eslint-disable-next-line react-hooks/rules-of-hooks\n React.useEffect(() => {\n if (muiFormControl) {\n return muiFormControl.registerEffect();\n }\n return undefined;\n }, [muiFormControl]);\n }\n const fcs = formControlState({\n props,\n muiFormControl,\n states: ['color', 'disabled', 'error', 'hiddenLabel', 'size', 'required', 'filled']\n });\n fcs.focused = muiFormControl ? muiFormControl.focused : focused;\n\n // The blur won't fire when the disabled state is set on a focused input.\n // We need to book keep the focused state manually.\n React.useEffect(() => {\n if (!muiFormControl && disabled && focused) {\n setFocused(false);\n if (onBlur) {\n onBlur();\n }\n }\n }, [muiFormControl, disabled, focused, onBlur]);\n const onFilled = muiFormControl && muiFormControl.onFilled;\n const onEmpty = muiFormControl && muiFormControl.onEmpty;\n const checkDirty = React.useCallback(obj => {\n if (isFilled(obj)) {\n if (onFilled) {\n onFilled();\n }\n } else if (onEmpty) {\n onEmpty();\n }\n }, [onFilled, onEmpty]);\n useEnhancedEffect(() => {\n if (isControlled) {\n checkDirty({\n value\n });\n }\n }, [value, checkDirty, isControlled]);\n const handleFocus = event => {\n if (onFocus) {\n onFocus(event);\n }\n if (inputPropsProp.onFocus) {\n inputPropsProp.onFocus(event);\n }\n if (muiFormControl && muiFormControl.onFocus) {\n muiFormControl.onFocus(event);\n } else {\n setFocused(true);\n }\n };\n const handleBlur = event => {\n if (onBlur) {\n onBlur(event);\n }\n if (inputPropsProp.onBlur) {\n inputPropsProp.onBlur(event);\n }\n if (muiFormControl && muiFormControl.onBlur) {\n muiFormControl.onBlur(event);\n } else {\n setFocused(false);\n }\n };\n const handleChange = (event, ...args) => {\n if (!isControlled) {\n const element = event.target || inputRef.current;\n if (element == null) {\n throw new Error(process.env.NODE_ENV !== \"production\" ? 'MUI: Expected valid input target. ' + 'Did you use a custom `inputComponent` and forget to forward refs? ' + 'See https://mui.com/r/input-component-ref-interface for more info.' : _formatMuiErrorMessage(1));\n }\n checkDirty({\n value: element.value\n });\n }\n if (inputPropsProp.onChange) {\n inputPropsProp.onChange(event, ...args);\n }\n\n // Perform in the willUpdate\n if (onChange) {\n onChange(event, ...args);\n }\n };\n\n // Check the input state on mount, in case it was filled by the user\n // or auto filled by the browser before the hydration (for SSR).\n React.useEffect(() => {\n checkDirty(inputRef.current);\n // TODO: uncomment once we enable eslint-plugin-react-compiler // eslint-disable-next-line react-compiler/react-compiler\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n const handleClick = event => {\n if (inputRef.current && event.currentTarget === event.target) {\n inputRef.current.focus();\n }\n if (onClick) {\n onClick(event);\n }\n };\n let InputComponent = inputComponent;\n let inputProps = inputPropsProp;\n if (multiline && InputComponent === 'input') {\n if (rows) {\n if (process.env.NODE_ENV !== 'production') {\n if (minRows || maxRows) {\n console.warn('MUI: You can not use the `minRows` or `maxRows` props when the input `rows` prop is set.');\n }\n }\n inputProps = {\n type: undefined,\n minRows: rows,\n maxRows: rows,\n ...inputProps\n };\n } else {\n inputProps = {\n type: undefined,\n maxRows,\n minRows,\n ...inputProps\n };\n }\n InputComponent = TextareaAutosize;\n }\n const handleAutoFill = event => {\n // Provide a fake value as Chrome might not let you access it for security reasons.\n checkDirty(event.animationName === 'mui-auto-fill-cancel' ? inputRef.current : {\n value: 'x'\n });\n };\n React.useEffect(() => {\n if (muiFormControl) {\n muiFormControl.setAdornedStart(Boolean(startAdornment));\n }\n }, [muiFormControl, startAdornment]);\n const ownerState = {\n ...props,\n color: fcs.color || 'primary',\n disabled: fcs.disabled,\n endAdornment,\n error: fcs.error,\n focused: fcs.focused,\n formControl: muiFormControl,\n fullWidth,\n hiddenLabel: fcs.hiddenLabel,\n multiline,\n size: fcs.size,\n startAdornment,\n type\n };\n const classes = useUtilityClasses(ownerState);\n const Root = slots.root || components.Root || InputBaseRoot;\n const rootProps = slotProps.root || componentsProps.root || {};\n const Input = slots.input || components.Input || InputBaseInput;\n inputProps = {\n ...inputProps,\n ...(slotProps.input ?? componentsProps.input)\n };\n return /*#__PURE__*/_jsxs(React.Fragment, {\n children: [!disableInjectingGlobalStyles && typeof InputGlobalStyles === 'function' && (// For Emotion/Styled-components, InputGlobalStyles will be a function\n // For Pigment CSS, this has no effect because the InputGlobalStyles will be null.\n _InputGlobalStyles || (_InputGlobalStyles = /*#__PURE__*/_jsx(InputGlobalStyles, {}))), /*#__PURE__*/_jsxs(Root, {\n ...rootProps,\n ref: ref,\n onClick: handleClick,\n ...other,\n ...(!isHostComponent(Root) && {\n ownerState: {\n ...ownerState,\n ...rootProps.ownerState\n }\n }),\n className: clsx(classes.root, rootProps.className, className, readOnly && 'MuiInputBase-readOnly'),\n children: [startAdornment, /*#__PURE__*/_jsx(FormControlContext.Provider, {\n value: null,\n children: /*#__PURE__*/_jsx(Input, {\n \"aria-invalid\": fcs.error,\n \"aria-describedby\": ariaDescribedby,\n autoComplete: autoComplete,\n autoFocus: autoFocus,\n defaultValue: defaultValue,\n disabled: fcs.disabled,\n id: id,\n onAnimationStart: handleAutoFill,\n name: name,\n placeholder: placeholder,\n readOnly: readOnly,\n required: fcs.required,\n rows: rows,\n value: value,\n onKeyDown: onKeyDown,\n onKeyUp: onKeyUp,\n type: type,\n ...inputProps,\n ...(!isHostComponent(Input) && {\n as: InputComponent,\n ownerState: {\n ...ownerState,\n ...inputProps.ownerState\n }\n }),\n ref: handleInputRef,\n className: clsx(classes.input, inputProps.className, readOnly && 'MuiInputBase-readOnly'),\n onBlur: handleBlur,\n onChange: handleChange,\n onFocus: handleFocus\n })\n }), endAdornment, renderSuffix ? renderSuffix({\n ...fcs,\n startAdornment\n }) : null]\n })]\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? InputBase.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * @ignore\n */\n 'aria-describedby': PropTypes.string,\n /**\n * This prop helps users to fill forms faster, especially on mobile devices.\n * The name can be confusing, as it's more like an autofill.\n * You can learn more about it [following the specification](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofill).\n */\n autoComplete: PropTypes.string,\n /**\n * If `true`, the `input` element is focused during the first mount.\n */\n autoFocus: PropTypes.bool,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The color of the component.\n * It supports both default and custom theme colors, which can be added as shown in the\n * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).\n * The prop defaults to the value (`'primary'`) inherited from the parent FormControl component.\n */\n color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),\n /**\n * The components used for each slot inside.\n *\n * @deprecated use the `slots` prop instead. This prop will be removed in v7. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n *\n * @default {}\n */\n components: PropTypes.shape({\n Input: PropTypes.elementType,\n Root: PropTypes.elementType\n }),\n /**\n * The extra props for the slot components.\n * You can override the existing props or add new ones.\n *\n * @deprecated use the `slotProps` prop instead. This prop will be removed in v7. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n *\n * @default {}\n */\n componentsProps: PropTypes.shape({\n input: PropTypes.object,\n root: PropTypes.object\n }),\n /**\n * The default value. Use when the component is not controlled.\n */\n defaultValue: PropTypes.any,\n /**\n * If `true`, the component is disabled.\n * The prop defaults to the value (`false`) inherited from the parent FormControl component.\n */\n disabled: PropTypes.bool,\n /**\n * If `true`, GlobalStyles for the auto-fill keyframes will not be injected/removed on mount/unmount. Make sure to inject them at the top of your application.\n * This option is intended to help with boosting the initial rendering performance if you are loading a big amount of Input components at once.\n * @default false\n */\n disableInjectingGlobalStyles: PropTypes.bool,\n /**\n * End `InputAdornment` for this component.\n */\n endAdornment: PropTypes.node,\n /**\n * If `true`, the `input` will indicate an error.\n * The prop defaults to the value (`false`) inherited from the parent FormControl component.\n */\n error: PropTypes.bool,\n /**\n * If `true`, the `input` will take up the full width of its container.\n * @default false\n */\n fullWidth: PropTypes.bool,\n /**\n * The id of the `input` element.\n */\n id: PropTypes.string,\n /**\n * The component used for the `input` element.\n * Either a string to use a HTML element or a component.\n * @default 'input'\n */\n inputComponent: elementTypeAcceptingRef,\n /**\n * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.\n * @default {}\n */\n inputProps: PropTypes.object,\n /**\n * Pass a ref to the `input` element.\n */\n inputRef: refType,\n /**\n * If `dense`, will adjust vertical spacing. This is normally obtained via context from\n * FormControl.\n * The prop defaults to the value (`'none'`) inherited from the parent FormControl component.\n */\n margin: PropTypes.oneOf(['dense', 'none']),\n /**\n * Maximum number of rows to display when multiline option is set to true.\n */\n maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n /**\n * Minimum number of rows to display when multiline option is set to true.\n */\n minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n /**\n * If `true`, a [TextareaAutosize](https://mui.com/material-ui/react-textarea-autosize/) element is rendered.\n * @default false\n */\n multiline: PropTypes.bool,\n /**\n * Name attribute of the `input` element.\n */\n name: PropTypes.string,\n /**\n * Callback fired when the `input` is blurred.\n *\n * Notice that the first argument (event) might be undefined.\n */\n onBlur: PropTypes.func,\n /**\n * Callback fired when the value is changed.\n *\n * @param {React.ChangeEvent} event The event source of the callback.\n * You can pull out the new value by accessing `event.target.value` (string).\n */\n onChange: PropTypes.func,\n /**\n * @ignore\n */\n onClick: PropTypes.func,\n /**\n * @ignore\n */\n onFocus: PropTypes.func,\n /**\n * Callback fired when the `input` doesn't satisfy its constraints.\n */\n onInvalid: PropTypes.func,\n /**\n * @ignore\n */\n onKeyDown: PropTypes.func,\n /**\n * @ignore\n */\n onKeyUp: PropTypes.func,\n /**\n * The short hint displayed in the `input` before the user enters a value.\n */\n placeholder: PropTypes.string,\n /**\n * It prevents the user from changing the value of the field\n * (not from interacting with the field).\n */\n readOnly: PropTypes.bool,\n /**\n * @ignore\n */\n renderSuffix: PropTypes.func,\n /**\n * If `true`, the `input` element is required.\n * The prop defaults to the value (`false`) inherited from the parent FormControl component.\n */\n required: PropTypes.bool,\n /**\n * Number of rows to display when multiline option is set to true.\n */\n rows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n /**\n * The size of the component.\n */\n size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),\n /**\n * The extra props for the slot components.\n * You can override the existing props or add new ones.\n *\n * This prop is an alias for the `componentsProps` prop, which will be deprecated in the future.\n *\n * @default {}\n */\n slotProps: PropTypes.shape({\n input: PropTypes.object,\n root: PropTypes.object\n }),\n /**\n * The components used for each slot inside.\n *\n * This prop is an alias for the `components` prop, which will be deprecated in the future.\n *\n * @default {}\n */\n slots: PropTypes.shape({\n input: PropTypes.elementType,\n root: PropTypes.elementType\n }),\n /**\n * Start `InputAdornment` for this component.\n */\n startAdornment: PropTypes.node,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * Type of the `input` element. It should be [a valid HTML5 input type](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Form_%3Cinput%3E_types).\n * @default 'text'\n */\n type: PropTypes.string,\n /**\n * The value of the `input` element, required for a controlled component.\n */\n value: PropTypes.any\n} : void 0;\nexport default InputBase;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nimport { inputBaseClasses } from \"../InputBase/index.js\";\nexport function getInputUtilityClass(slot) {\n return generateUtilityClass('MuiInput', slot);\n}\nconst inputClasses = {\n ...inputBaseClasses,\n ...generateUtilityClasses('MuiInput', ['root', 'underline', 'input'])\n};\nexport default inputClasses;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nimport { inputBaseClasses } from \"../InputBase/index.js\";\nexport function getOutlinedInputUtilityClass(slot) {\n return generateUtilityClass('MuiOutlinedInput', slot);\n}\nconst outlinedInputClasses = {\n ...inputBaseClasses,\n ...generateUtilityClasses('MuiOutlinedInput', ['root', 'notchedOutline', 'input'])\n};\nexport default outlinedInputClasses;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nimport { inputBaseClasses } from \"../InputBase/index.js\";\nexport function getFilledInputUtilityClass(slot) {\n return generateUtilityClass('MuiFilledInput', slot);\n}\nconst filledInputClasses = {\n ...inputBaseClasses,\n ...generateUtilityClasses('MuiFilledInput', ['root', 'underline', 'input', 'adornedStart', 'adornedEnd', 'sizeSmall', 'multiline', 'hiddenLabel'])\n};\nexport default filledInputClasses;","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from \"../../utils/createSvgIcon.js\";\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon(/*#__PURE__*/_jsx(\"path\", {\n d: \"M7 10l5 5 5-5z\"\n}), 'ArrowDropDown');","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getAutocompleteUtilityClass(slot) {\n return generateUtilityClass('MuiAutocomplete', slot);\n}\nconst autocompleteClasses = generateUtilityClasses('MuiAutocomplete', ['root', 'expanded', 'fullWidth', 'focused', 'focusVisible', 'tag', 'tagSizeSmall', 'tagSizeMedium', 'hasPopupIcon', 'hasClearIcon', 'inputRoot', 'input', 'inputFocused', 'endAdornment', 'clearIndicator', 'popupIndicator', 'popupIndicatorOpen', 'popper', 'popperDisablePortal', 'paper', 'listbox', 'loading', 'noOptions', 'option', 'groupLabel', 'groupUl']);\nexport default autocompleteClasses;","'use client';\n\nvar _ClearIcon, _ArrowDropDownIcon;\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport integerPropType from '@mui/utils/integerPropType';\nimport chainPropTypes from '@mui/utils/chainPropTypes';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { alpha } from '@mui/system/colorManipulator';\nimport useAutocomplete, { createFilterOptions } from \"../useAutocomplete/index.js\";\nimport Popper from \"../Popper/index.js\";\nimport ListSubheader from \"../ListSubheader/index.js\";\nimport Paper from \"../Paper/index.js\";\nimport IconButton from \"../IconButton/index.js\";\nimport Chip from \"../Chip/index.js\";\nimport inputClasses from \"../Input/inputClasses.js\";\nimport inputBaseClasses from \"../InputBase/inputBaseClasses.js\";\nimport outlinedInputClasses from \"../OutlinedInput/outlinedInputClasses.js\";\nimport filledInputClasses from \"../FilledInput/filledInputClasses.js\";\nimport ClearIcon from \"../internal/svg-icons/Close.js\";\nimport ArrowDropDownIcon from \"../internal/svg-icons/ArrowDropDown.js\";\nimport { styled } from \"../zero-styled/index.js\";\nimport memoTheme from \"../utils/memoTheme.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport autocompleteClasses, { getAutocompleteUtilityClass } from \"./autocompleteClasses.js\";\nimport capitalize from \"../utils/capitalize.js\";\nimport useSlot from \"../utils/useSlot.js\";\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n disablePortal,\n expanded,\n focused,\n fullWidth,\n hasClearIcon,\n hasPopupIcon,\n inputFocused,\n popupOpen,\n size\n } = ownerState;\n const slots = {\n root: ['root', expanded && 'expanded', focused && 'focused', fullWidth && 'fullWidth', hasClearIcon && 'hasClearIcon', hasPopupIcon && 'hasPopupIcon'],\n inputRoot: ['inputRoot'],\n input: ['input', inputFocused && 'inputFocused'],\n tag: ['tag', `tagSize${capitalize(size)}`],\n endAdornment: ['endAdornment'],\n clearIndicator: ['clearIndicator'],\n popupIndicator: ['popupIndicator', popupOpen && 'popupIndicatorOpen'],\n popper: ['popper', disablePortal && 'popperDisablePortal'],\n paper: ['paper'],\n listbox: ['listbox'],\n loading: ['loading'],\n noOptions: ['noOptions'],\n option: ['option'],\n groupLabel: ['groupLabel'],\n groupUl: ['groupUl']\n };\n return composeClasses(slots, getAutocompleteUtilityClass, classes);\n};\nconst AutocompleteRoot = styled('div', {\n name: 'MuiAutocomplete',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n const {\n fullWidth,\n hasClearIcon,\n hasPopupIcon,\n inputFocused,\n size\n } = ownerState;\n return [{\n [`& .${autocompleteClasses.tag}`]: styles.tag\n }, {\n [`& .${autocompleteClasses.tag}`]: styles[`tagSize${capitalize(size)}`]\n }, {\n [`& .${autocompleteClasses.inputRoot}`]: styles.inputRoot\n }, {\n [`& .${autocompleteClasses.input}`]: styles.input\n }, {\n [`& .${autocompleteClasses.input}`]: inputFocused && styles.inputFocused\n }, styles.root, fullWidth && styles.fullWidth, hasPopupIcon && styles.hasPopupIcon, hasClearIcon && styles.hasClearIcon];\n }\n})({\n [`&.${autocompleteClasses.focused} .${autocompleteClasses.clearIndicator}`]: {\n visibility: 'visible'\n },\n /* Avoid double tap issue on iOS */\n '@media (pointer: fine)': {\n [`&:hover .${autocompleteClasses.clearIndicator}`]: {\n visibility: 'visible'\n }\n },\n [`& .${autocompleteClasses.tag}`]: {\n margin: 3,\n maxWidth: 'calc(100% - 6px)'\n },\n [`& .${autocompleteClasses.inputRoot}`]: {\n [`.${autocompleteClasses.hasPopupIcon}&, .${autocompleteClasses.hasClearIcon}&`]: {\n paddingRight: 26 + 4\n },\n [`.${autocompleteClasses.hasPopupIcon}.${autocompleteClasses.hasClearIcon}&`]: {\n paddingRight: 52 + 4\n },\n [`& .${autocompleteClasses.input}`]: {\n width: 0,\n minWidth: 30\n }\n },\n [`& .${inputClasses.root}`]: {\n paddingBottom: 1,\n '& .MuiInput-input': {\n padding: '4px 4px 4px 0px'\n }\n },\n [`& .${inputClasses.root}.${inputBaseClasses.sizeSmall}`]: {\n [`& .${inputClasses.input}`]: {\n padding: '2px 4px 3px 0'\n }\n },\n [`& .${outlinedInputClasses.root}`]: {\n padding: 9,\n [`.${autocompleteClasses.hasPopupIcon}&, .${autocompleteClasses.hasClearIcon}&`]: {\n paddingRight: 26 + 4 + 9\n },\n [`.${autocompleteClasses.hasPopupIcon}.${autocompleteClasses.hasClearIcon}&`]: {\n paddingRight: 52 + 4 + 9\n },\n [`& .${autocompleteClasses.input}`]: {\n padding: '7.5px 4px 7.5px 5px'\n },\n [`& .${autocompleteClasses.endAdornment}`]: {\n right: 9\n }\n },\n [`& .${outlinedInputClasses.root}.${inputBaseClasses.sizeSmall}`]: {\n // Don't specify paddingRight, as it overrides the default value set when there is only\n // one of the popup or clear icon as the specificity is equal so the latter one wins\n paddingTop: 6,\n paddingBottom: 6,\n paddingLeft: 6,\n [`& .${autocompleteClasses.input}`]: {\n padding: '2.5px 4px 2.5px 8px'\n }\n },\n [`& .${filledInputClasses.root}`]: {\n paddingTop: 19,\n paddingLeft: 8,\n [`.${autocompleteClasses.hasPopupIcon}&, .${autocompleteClasses.hasClearIcon}&`]: {\n paddingRight: 26 + 4 + 9\n },\n [`.${autocompleteClasses.hasPopupIcon}.${autocompleteClasses.hasClearIcon}&`]: {\n paddingRight: 52 + 4 + 9\n },\n [`& .${filledInputClasses.input}`]: {\n padding: '7px 4px'\n },\n [`& .${autocompleteClasses.endAdornment}`]: {\n right: 9\n }\n },\n [`& .${filledInputClasses.root}.${inputBaseClasses.sizeSmall}`]: {\n paddingBottom: 1,\n [`& .${filledInputClasses.input}`]: {\n padding: '2.5px 4px'\n }\n },\n [`& .${inputBaseClasses.hiddenLabel}`]: {\n paddingTop: 8\n },\n [`& .${filledInputClasses.root}.${inputBaseClasses.hiddenLabel}`]: {\n paddingTop: 0,\n paddingBottom: 0,\n [`& .${autocompleteClasses.input}`]: {\n paddingTop: 16,\n paddingBottom: 17\n }\n },\n [`& .${filledInputClasses.root}.${inputBaseClasses.hiddenLabel}.${inputBaseClasses.sizeSmall}`]: {\n [`& .${autocompleteClasses.input}`]: {\n paddingTop: 8,\n paddingBottom: 9\n }\n },\n [`& .${autocompleteClasses.input}`]: {\n flexGrow: 1,\n textOverflow: 'ellipsis',\n opacity: 0\n },\n variants: [{\n props: {\n fullWidth: true\n },\n style: {\n width: '100%'\n }\n }, {\n props: {\n size: 'small'\n },\n style: {\n [`& .${autocompleteClasses.tag}`]: {\n margin: 2,\n maxWidth: 'calc(100% - 4px)'\n }\n }\n }, {\n props: {\n inputFocused: true\n },\n style: {\n [`& .${autocompleteClasses.input}`]: {\n opacity: 1\n }\n }\n }, {\n props: {\n multiple: true\n },\n style: {\n [`& .${autocompleteClasses.inputRoot}`]: {\n flexWrap: 'wrap'\n }\n }\n }]\n});\nconst AutocompleteEndAdornment = styled('div', {\n name: 'MuiAutocomplete',\n slot: 'EndAdornment',\n overridesResolver: (props, styles) => styles.endAdornment\n})({\n // We use a position absolute to support wrapping tags.\n position: 'absolute',\n right: 0,\n top: '50%',\n transform: 'translate(0, -50%)'\n});\nconst AutocompleteClearIndicator = styled(IconButton, {\n name: 'MuiAutocomplete',\n slot: 'ClearIndicator',\n overridesResolver: (props, styles) => styles.clearIndicator\n})({\n marginRight: -2,\n padding: 4,\n visibility: 'hidden'\n});\nconst AutocompletePopupIndicator = styled(IconButton, {\n name: 'MuiAutocomplete',\n slot: 'PopupIndicator',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.popupIndicator, ownerState.popupOpen && styles.popupIndicatorOpen];\n }\n})({\n padding: 2,\n marginRight: -2,\n variants: [{\n props: {\n popupOpen: true\n },\n style: {\n transform: 'rotate(180deg)'\n }\n }]\n});\nconst AutocompletePopper = styled(Popper, {\n name: 'MuiAutocomplete',\n slot: 'Popper',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [{\n [`& .${autocompleteClasses.option}`]: styles.option\n }, styles.popper, ownerState.disablePortal && styles.popperDisablePortal];\n }\n})(memoTheme(({\n theme\n}) => ({\n zIndex: (theme.vars || theme).zIndex.modal,\n variants: [{\n props: {\n disablePortal: true\n },\n style: {\n position: 'absolute'\n }\n }]\n})));\nconst AutocompletePaper = styled(Paper, {\n name: 'MuiAutocomplete',\n slot: 'Paper',\n overridesResolver: (props, styles) => styles.paper\n})(memoTheme(({\n theme\n}) => ({\n ...theme.typography.body1,\n overflow: 'auto'\n})));\nconst AutocompleteLoading = styled('div', {\n name: 'MuiAutocomplete',\n slot: 'Loading',\n overridesResolver: (props, styles) => styles.loading\n})(memoTheme(({\n theme\n}) => ({\n color: (theme.vars || theme).palette.text.secondary,\n padding: '14px 16px'\n})));\nconst AutocompleteNoOptions = styled('div', {\n name: 'MuiAutocomplete',\n slot: 'NoOptions',\n overridesResolver: (props, styles) => styles.noOptions\n})(memoTheme(({\n theme\n}) => ({\n color: (theme.vars || theme).palette.text.secondary,\n padding: '14px 16px'\n})));\nconst AutocompleteListbox = styled('ul', {\n name: 'MuiAutocomplete',\n slot: 'Listbox',\n overridesResolver: (props, styles) => styles.listbox\n})(memoTheme(({\n theme\n}) => ({\n listStyle: 'none',\n margin: 0,\n padding: '8px 0',\n maxHeight: '40vh',\n overflow: 'auto',\n position: 'relative',\n [`& .${autocompleteClasses.option}`]: {\n minHeight: 48,\n display: 'flex',\n overflow: 'hidden',\n justifyContent: 'flex-start',\n alignItems: 'center',\n cursor: 'pointer',\n paddingTop: 6,\n boxSizing: 'border-box',\n outline: '0',\n WebkitTapHighlightColor: 'transparent',\n paddingBottom: 6,\n paddingLeft: 16,\n paddingRight: 16,\n [theme.breakpoints.up('sm')]: {\n minHeight: 'auto'\n },\n [`&.${autocompleteClasses.focused}`]: {\n backgroundColor: (theme.vars || theme).palette.action.hover,\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n },\n '&[aria-disabled=\"true\"]': {\n opacity: (theme.vars || theme).palette.action.disabledOpacity,\n pointerEvents: 'none'\n },\n [`&.${autocompleteClasses.focusVisible}`]: {\n backgroundColor: (theme.vars || theme).palette.action.focus\n },\n '&[aria-selected=\"true\"]': {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / ${theme.vars.palette.action.selectedOpacity})` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity),\n [`&.${autocompleteClasses.focused}`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.hoverOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.hoverOpacity),\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n backgroundColor: (theme.vars || theme).palette.action.selected\n }\n },\n [`&.${autocompleteClasses.focusVisible}`]: {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.primary.mainChannel} / calc(${theme.vars.palette.action.selectedOpacity} + ${theme.vars.palette.action.focusOpacity}))` : alpha(theme.palette.primary.main, theme.palette.action.selectedOpacity + theme.palette.action.focusOpacity)\n }\n }\n }\n})));\nconst AutocompleteGroupLabel = styled(ListSubheader, {\n name: 'MuiAutocomplete',\n slot: 'GroupLabel',\n overridesResolver: (props, styles) => styles.groupLabel\n})(memoTheme(({\n theme\n}) => ({\n backgroundColor: (theme.vars || theme).palette.background.paper,\n top: -8\n})));\nconst AutocompleteGroupUl = styled('ul', {\n name: 'MuiAutocomplete',\n slot: 'GroupUl',\n overridesResolver: (props, styles) => styles.groupUl\n})({\n padding: 0,\n [`& .${autocompleteClasses.option}`]: {\n paddingLeft: 24\n }\n});\nexport { createFilterOptions };\nconst Autocomplete = /*#__PURE__*/React.forwardRef(function Autocomplete(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiAutocomplete'\n });\n\n /* eslint-disable @typescript-eslint/no-unused-vars */\n const {\n autoComplete = false,\n autoHighlight = false,\n autoSelect = false,\n blurOnSelect = false,\n ChipProps: ChipPropsProp,\n className,\n clearIcon = _ClearIcon || (_ClearIcon = /*#__PURE__*/_jsx(ClearIcon, {\n fontSize: \"small\"\n })),\n clearOnBlur = !props.freeSolo,\n clearOnEscape = false,\n clearText = 'Clear',\n closeText = 'Close',\n componentsProps,\n defaultValue = props.multiple ? [] : null,\n disableClearable = false,\n disableCloseOnSelect = false,\n disabled = false,\n disabledItemsFocusable = false,\n disableListWrap = false,\n disablePortal = false,\n filterOptions,\n filterSelectedOptions = false,\n forcePopupIcon = 'auto',\n freeSolo = false,\n fullWidth = false,\n getLimitTagsText = more => `+${more}`,\n getOptionDisabled,\n getOptionKey,\n getOptionLabel: getOptionLabelProp,\n isOptionEqualToValue,\n groupBy,\n handleHomeEndKeys = !props.freeSolo,\n id: idProp,\n includeInputInList = false,\n inputValue: inputValueProp,\n limitTags = -1,\n ListboxComponent: ListboxComponentProp,\n ListboxProps: ListboxPropsProp,\n loading = false,\n loadingText = 'Loading…',\n multiple = false,\n noOptionsText = 'No options',\n onChange,\n onClose,\n onHighlightChange,\n onInputChange,\n onOpen,\n open,\n openOnFocus = false,\n openText = 'Open',\n options,\n PaperComponent: PaperComponentProp,\n PopperComponent: PopperComponentProp,\n popupIcon = _ArrowDropDownIcon || (_ArrowDropDownIcon = /*#__PURE__*/_jsx(ArrowDropDownIcon, {})),\n readOnly = false,\n renderGroup: renderGroupProp,\n renderInput,\n renderOption: renderOptionProp,\n renderTags,\n selectOnFocus = !props.freeSolo,\n size = 'medium',\n slots = {},\n slotProps = {},\n value: valueProp,\n ...other\n } = props;\n /* eslint-enable @typescript-eslint/no-unused-vars */\n\n const {\n getRootProps,\n getInputProps,\n getInputLabelProps,\n getPopupIndicatorProps,\n getClearProps,\n getTagProps,\n getListboxProps,\n getOptionProps,\n value,\n dirty,\n expanded,\n id,\n popupOpen,\n focused,\n focusedTag,\n anchorEl,\n setAnchorEl,\n inputValue,\n groupedOptions\n } = useAutocomplete({\n ...props,\n componentName: 'Autocomplete'\n });\n const hasClearIcon = !disableClearable && !disabled && dirty && !readOnly;\n const hasPopupIcon = (!freeSolo || forcePopupIcon === true) && forcePopupIcon !== false;\n const {\n onMouseDown: handleInputMouseDown\n } = getInputProps();\n const {\n ref: listboxRef,\n ...otherListboxProps\n } = getListboxProps();\n const defaultGetOptionLabel = option => option.label ?? option;\n const getOptionLabel = getOptionLabelProp || defaultGetOptionLabel;\n\n // If you modify this, make sure to keep the `AutocompleteOwnerState` type in sync.\n const ownerState = {\n ...props,\n disablePortal,\n expanded,\n focused,\n fullWidth,\n getOptionLabel,\n hasClearIcon,\n hasPopupIcon,\n inputFocused: focusedTag === -1,\n popupOpen,\n size\n };\n const classes = useUtilityClasses(ownerState);\n const externalForwardedProps = {\n slots: {\n paper: PaperComponentProp,\n popper: PopperComponentProp,\n ...slots\n },\n slotProps: {\n chip: ChipPropsProp,\n listbox: ListboxPropsProp,\n ...componentsProps,\n ...slotProps\n }\n };\n const [ListboxSlot, listboxProps] = useSlot('listbox', {\n elementType: AutocompleteListbox,\n externalForwardedProps,\n ownerState,\n className: classes.listbox,\n additionalProps: otherListboxProps,\n ref: listboxRef\n });\n const [PaperSlot, paperProps] = useSlot('paper', {\n elementType: Paper,\n externalForwardedProps,\n ownerState,\n className: classes.paper\n });\n const [PopperSlot, popperProps] = useSlot('popper', {\n elementType: Popper,\n externalForwardedProps,\n ownerState,\n className: classes.popper,\n additionalProps: {\n disablePortal,\n style: {\n width: anchorEl ? anchorEl.clientWidth : null\n },\n role: 'presentation',\n anchorEl,\n open: popupOpen\n }\n });\n let startAdornment;\n if (multiple && value.length > 0) {\n const getCustomizedTagProps = params => ({\n className: classes.tag,\n disabled,\n ...getTagProps(params)\n });\n if (renderTags) {\n startAdornment = renderTags(value, getCustomizedTagProps, ownerState);\n } else {\n startAdornment = value.map((option, index) => {\n const {\n key,\n ...customTagProps\n } = getCustomizedTagProps({\n index\n });\n return /*#__PURE__*/_jsx(Chip, {\n label: getOptionLabel(option),\n size: size,\n ...customTagProps,\n ...externalForwardedProps.slotProps.chip\n }, key);\n });\n }\n }\n if (limitTags > -1 && Array.isArray(startAdornment)) {\n const more = startAdornment.length - limitTags;\n if (!focused && more > 0) {\n startAdornment = startAdornment.splice(0, limitTags);\n startAdornment.push(/*#__PURE__*/_jsx(\"span\", {\n className: classes.tag,\n children: getLimitTagsText(more)\n }, startAdornment.length));\n }\n }\n const defaultRenderGroup = params => /*#__PURE__*/_jsxs(\"li\", {\n children: [/*#__PURE__*/_jsx(AutocompleteGroupLabel, {\n className: classes.groupLabel,\n ownerState: ownerState,\n component: \"div\",\n children: params.group\n }), /*#__PURE__*/_jsx(AutocompleteGroupUl, {\n className: classes.groupUl,\n ownerState: ownerState,\n children: params.children\n })]\n }, params.key);\n const renderGroup = renderGroupProp || defaultRenderGroup;\n const defaultRenderOption = (props2, option) => {\n // Need to clearly apply key because of https://github.com/vercel/next.js/issues/55642\n const {\n key,\n ...otherProps\n } = props2;\n return /*#__PURE__*/_jsx(\"li\", {\n ...otherProps,\n children: getOptionLabel(option)\n }, key);\n };\n const renderOption = renderOptionProp || defaultRenderOption;\n const renderListOption = (option, index) => {\n const optionProps = getOptionProps({\n option,\n index\n });\n return renderOption({\n ...optionProps,\n className: classes.option\n }, option, {\n selected: optionProps['aria-selected'],\n index,\n inputValue\n }, ownerState);\n };\n const clearIndicatorSlotProps = externalForwardedProps.slotProps.clearIndicator;\n const popupIndicatorSlotProps = externalForwardedProps.slotProps.popupIndicator;\n return /*#__PURE__*/_jsxs(React.Fragment, {\n children: [/*#__PURE__*/_jsx(AutocompleteRoot, {\n ref: ref,\n className: clsx(classes.root, className),\n ownerState: ownerState,\n ...getRootProps(other),\n children: renderInput({\n id,\n disabled,\n fullWidth: true,\n size: size === 'small' ? 'small' : undefined,\n InputLabelProps: getInputLabelProps(),\n InputProps: {\n ref: setAnchorEl,\n className: classes.inputRoot,\n startAdornment,\n onMouseDown: event => {\n if (event.target === event.currentTarget) {\n handleInputMouseDown(event);\n }\n },\n ...((hasClearIcon || hasPopupIcon) && {\n endAdornment: /*#__PURE__*/_jsxs(AutocompleteEndAdornment, {\n className: classes.endAdornment,\n ownerState: ownerState,\n children: [hasClearIcon ? /*#__PURE__*/_jsx(AutocompleteClearIndicator, {\n ...getClearProps(),\n \"aria-label\": clearText,\n title: clearText,\n ownerState: ownerState,\n ...clearIndicatorSlotProps,\n className: clsx(classes.clearIndicator, clearIndicatorSlotProps?.className),\n children: clearIcon\n }) : null, hasPopupIcon ? /*#__PURE__*/_jsx(AutocompletePopupIndicator, {\n ...getPopupIndicatorProps(),\n disabled: disabled,\n \"aria-label\": popupOpen ? closeText : openText,\n title: popupOpen ? closeText : openText,\n ownerState: ownerState,\n ...popupIndicatorSlotProps,\n className: clsx(classes.popupIndicator, popupIndicatorSlotProps?.className),\n children: popupIcon\n }) : null]\n })\n })\n },\n inputProps: {\n className: classes.input,\n disabled,\n readOnly,\n ...getInputProps()\n }\n })\n }), anchorEl ? /*#__PURE__*/_jsx(AutocompletePopper, {\n as: PopperSlot,\n ...popperProps,\n children: /*#__PURE__*/_jsxs(AutocompletePaper, {\n as: PaperSlot,\n ...paperProps,\n children: [loading && groupedOptions.length === 0 ? /*#__PURE__*/_jsx(AutocompleteLoading, {\n className: classes.loading,\n ownerState: ownerState,\n children: loadingText\n }) : null, groupedOptions.length === 0 && !freeSolo && !loading ? /*#__PURE__*/_jsx(AutocompleteNoOptions, {\n className: classes.noOptions,\n ownerState: ownerState,\n role: \"presentation\",\n onMouseDown: event => {\n // Prevent input blur when interacting with the \"no options\" content\n event.preventDefault();\n },\n children: noOptionsText\n }) : null, groupedOptions.length > 0 ? /*#__PURE__*/_jsx(ListboxSlot, {\n as: ListboxComponentProp,\n ...listboxProps,\n children: groupedOptions.map((option, index) => {\n if (groupBy) {\n return renderGroup({\n key: option.key,\n group: option.group,\n children: option.options.map((option2, index2) => renderListOption(option2, option.index + index2))\n });\n }\n return renderListOption(option, index);\n })\n }) : null]\n })\n }) : null]\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Autocomplete.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * If `true`, the portion of the selected suggestion that the user hasn't typed,\n * known as the completion string, appears inline after the input cursor in the textbox.\n * The inline completion string is visually highlighted and has a selected state.\n * @default false\n */\n autoComplete: PropTypes.bool,\n /**\n * If `true`, the first option is automatically highlighted.\n * @default false\n */\n autoHighlight: PropTypes.bool,\n /**\n * If `true`, the selected option becomes the value of the input\n * when the Autocomplete loses focus unless the user chooses\n * a different option or changes the character string in the input.\n *\n * When using the `freeSolo` mode, the typed value will be the input value\n * if the Autocomplete loses focus without highlighting an option.\n * @default false\n */\n autoSelect: PropTypes.bool,\n /**\n * Control if the input should be blurred when an option is selected:\n *\n * - `false` the input is not blurred.\n * - `true` the input is always blurred.\n * - `touch` the input is blurred after a touch event.\n * - `mouse` the input is blurred after a mouse event.\n * @default false\n */\n blurOnSelect: PropTypes.oneOfType([PropTypes.oneOf(['mouse', 'touch']), PropTypes.bool]),\n /**\n * Props applied to the [`Chip`](https://mui.com/material-ui/api/chip/) element.\n * @deprecated Use `slotProps.chip` instead. This prop will be removed in v7. See [Migrating from deprecated APIs](/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n */\n ChipProps: PropTypes.object,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The icon to display in place of the default clear icon.\n * @default \n */\n clearIcon: PropTypes.node,\n /**\n * If `true`, the input's text is cleared on blur if no value is selected.\n *\n * Set it to `true` if you want to help the user enter a new value.\n * Set it to `false` if you want to help the user resume their search.\n * @default !props.freeSolo\n */\n clearOnBlur: PropTypes.bool,\n /**\n * If `true`, clear all values when the user presses escape and the popup is closed.\n * @default false\n */\n clearOnEscape: PropTypes.bool,\n /**\n * Override the default text for the *clear* icon button.\n *\n * For localization purposes, you can use the provided [translations](https://mui.com/material-ui/guides/localization/).\n * @default 'Clear'\n */\n clearText: PropTypes.string,\n /**\n * Override the default text for the *close popup* icon button.\n *\n * For localization purposes, you can use the provided [translations](https://mui.com/material-ui/guides/localization/).\n * @default 'Close'\n */\n closeText: PropTypes.string,\n /**\n * The props used for each slot inside.\n * @deprecated Use the `slotProps` prop instead. This prop will be removed in v7. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n */\n componentsProps: PropTypes.shape({\n clearIndicator: PropTypes.object,\n paper: PropTypes.object,\n popper: PropTypes.object,\n popupIndicator: PropTypes.object\n }),\n /**\n * The default value. Use when the component is not controlled.\n * @default props.multiple ? [] : null\n */\n defaultValue: chainPropTypes(PropTypes.any, props => {\n if (props.multiple && props.defaultValue !== undefined && !Array.isArray(props.defaultValue)) {\n return new Error(['MUI: The Autocomplete expects the `defaultValue` prop to be an array when `multiple={true}` or undefined.', `However, ${props.defaultValue} was provided.`].join('\\n'));\n }\n return null;\n }),\n /**\n * If `true`, the input can't be cleared.\n * @default false\n */\n disableClearable: PropTypes.bool,\n /**\n * If `true`, the popup won't close when a value is selected.\n * @default false\n */\n disableCloseOnSelect: PropTypes.bool,\n /**\n * If `true`, the component is disabled.\n * @default false\n */\n disabled: PropTypes.bool,\n /**\n * If `true`, will allow focus on disabled items.\n * @default false\n */\n disabledItemsFocusable: PropTypes.bool,\n /**\n * If `true`, the list box in the popup will not wrap focus.\n * @default false\n */\n disableListWrap: PropTypes.bool,\n /**\n * If `true`, the `Popper` content will be under the DOM hierarchy of the parent component.\n * @default false\n */\n disablePortal: PropTypes.bool,\n /**\n * A function that determines the filtered options to be rendered on search.\n *\n * @default createFilterOptions()\n * @param {Value[]} options The options to render.\n * @param {object} state The state of the component.\n * @returns {Value[]}\n */\n filterOptions: PropTypes.func,\n /**\n * If `true`, hide the selected options from the list box.\n * @default false\n */\n filterSelectedOptions: PropTypes.bool,\n /**\n * Force the visibility display of the popup icon.\n * @default 'auto'\n */\n forcePopupIcon: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.bool]),\n /**\n * If `true`, the Autocomplete is free solo, meaning that the user input is not bound to provided options.\n * @default false\n */\n freeSolo: PropTypes.bool,\n /**\n * If `true`, the input will take up the full width of its container.\n * @default false\n */\n fullWidth: PropTypes.bool,\n /**\n * The label to display when the tags are truncated (`limitTags`).\n *\n * @param {number} more The number of truncated tags.\n * @returns {ReactNode}\n * @default (more) => `+${more}`\n */\n getLimitTagsText: PropTypes.func,\n /**\n * Used to determine the disabled state for a given option.\n *\n * @param {Value} option The option to test.\n * @returns {boolean}\n */\n getOptionDisabled: PropTypes.func,\n /**\n * Used to determine the key for a given option.\n * This can be useful when the labels of options are not unique (since labels are used as keys by default).\n *\n * @param {Value} option The option to get the key for.\n * @returns {string | number}\n */\n getOptionKey: PropTypes.func,\n /**\n * Used to determine the string value for a given option.\n * It's used to fill the input (and the list box options if `renderOption` is not provided).\n *\n * If used in free solo mode, it must accept both the type of the options and a string.\n *\n * @param {Value} option\n * @returns {string}\n * @default (option) => option.label ?? option\n */\n getOptionLabel: PropTypes.func,\n /**\n * If provided, the options will be grouped under the returned string.\n * The groupBy value is also used as the text for group headings when `renderGroup` is not provided.\n *\n * @param {Value} option The Autocomplete option.\n * @returns {string}\n */\n groupBy: PropTypes.func,\n /**\n * If `true`, the component handles the \"Home\" and \"End\" keys when the popup is open.\n * It should move focus to the first option and last option, respectively.\n * @default !props.freeSolo\n */\n handleHomeEndKeys: PropTypes.bool,\n /**\n * This prop is used to help implement the accessibility logic.\n * If you don't provide an id it will fall back to a randomly generated one.\n */\n id: PropTypes.string,\n /**\n * If `true`, the highlight can move to the input.\n * @default false\n */\n includeInputInList: PropTypes.bool,\n /**\n * The input value.\n */\n inputValue: PropTypes.string,\n /**\n * Used to determine if the option represents the given value.\n * Uses strict equality by default.\n * ⚠️ Both arguments need to be handled, an option can only match with one value.\n *\n * @param {Value} option The option to test.\n * @param {Value} value The value to test against.\n * @returns {boolean}\n */\n isOptionEqualToValue: PropTypes.func,\n /**\n * The maximum number of tags that will be visible when not focused.\n * Set `-1` to disable the limit.\n * @default -1\n */\n limitTags: integerPropType,\n /**\n * The component used to render the listbox.\n * @default 'ul'\n * @deprecated Use `slotProps.listbox.component` instead. This prop will be removed in v7. See [Migrating from deprecated APIs](/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n */\n ListboxComponent: PropTypes.elementType,\n /**\n * Props applied to the Listbox element.\n * @deprecated Use `slotProps.listbox` instead. This prop will be removed in v7. See [Migrating from deprecated APIs](/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n */\n ListboxProps: PropTypes.object,\n /**\n * If `true`, the component is in a loading state.\n * This shows the `loadingText` in place of suggestions (only if there are no suggestions to show, for example `options` are empty).\n * @default false\n */\n loading: PropTypes.bool,\n /**\n * Text to display when in a loading state.\n *\n * For localization purposes, you can use the provided [translations](https://mui.com/material-ui/guides/localization/).\n * @default 'Loading…'\n */\n loadingText: PropTypes.node,\n /**\n * If `true`, `value` must be an array and the menu will support multiple selections.\n * @default false\n */\n multiple: PropTypes.bool,\n /**\n * Text to display when there are no options.\n *\n * For localization purposes, you can use the provided [translations](https://mui.com/material-ui/guides/localization/).\n * @default 'No options'\n */\n noOptionsText: PropTypes.node,\n /**\n * Callback fired when the value changes.\n *\n * @param {React.SyntheticEvent} event The event source of the callback.\n * @param {Value|Value[]} value The new value of the component.\n * @param {string} reason One of \"createOption\", \"selectOption\", \"removeOption\", \"blur\" or \"clear\".\n * @param {string} [details]\n */\n onChange: PropTypes.func,\n /**\n * Callback fired when the popup requests to be closed.\n * Use in controlled mode (see open).\n *\n * @param {React.SyntheticEvent} event The event source of the callback.\n * @param {string} reason Can be: `\"toggleInput\"`, `\"escape\"`, `\"selectOption\"`, `\"removeOption\"`, `\"blur\"`.\n */\n onClose: PropTypes.func,\n /**\n * Callback fired when the highlight option changes.\n *\n * @param {React.SyntheticEvent} event The event source of the callback.\n * @param {Value} option The highlighted option.\n * @param {string} reason Can be: `\"keyboard\"`, `\"auto\"`, `\"mouse\"`, `\"touch\"`.\n */\n onHighlightChange: PropTypes.func,\n /**\n * Callback fired when the input value changes.\n *\n * @param {React.SyntheticEvent} event The event source of the callback.\n * @param {string} value The new value of the text input.\n * @param {string} reason Can be: `\"input\"` (user input), `\"reset\"` (programmatic change), `\"clear\"`, `\"blur\"`, `\"selectOption\"`, `\"removeOption\"`\n */\n onInputChange: PropTypes.func,\n /**\n * @ignore\n */\n onKeyDown: PropTypes.func,\n /**\n * Callback fired when the popup requests to be opened.\n * Use in controlled mode (see open).\n *\n * @param {React.SyntheticEvent} event The event source of the callback.\n */\n onOpen: PropTypes.func,\n /**\n * If `true`, the component is shown.\n */\n open: PropTypes.bool,\n /**\n * If `true`, the popup will open on input focus.\n * @default false\n */\n openOnFocus: PropTypes.bool,\n /**\n * Override the default text for the *open popup* icon button.\n *\n * For localization purposes, you can use the provided [translations](https://mui.com/material-ui/guides/localization/).\n * @default 'Open'\n */\n openText: PropTypes.string,\n /**\n * A list of options that will be shown in the Autocomplete.\n */\n options: PropTypes.array.isRequired,\n /**\n * The component used to render the body of the popup.\n * @default Paper\n * @deprecated Use `slots.paper` instead. This prop will be removed in v7. See [Migrating from deprecated APIs](/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n */\n PaperComponent: PropTypes.elementType,\n /**\n * The component used to position the popup.\n * @default Popper\n * @deprecated Use `slots.popper` instead. This prop will be removed in v7. See [Migrating from deprecated APIs](/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n */\n PopperComponent: PropTypes.elementType,\n /**\n * The icon to display in place of the default popup icon.\n * @default \n */\n popupIcon: PropTypes.node,\n /**\n * If `true`, the component becomes readonly. It is also supported for multiple tags where the tag cannot be deleted.\n * @default false\n */\n readOnly: PropTypes.bool,\n /**\n * Render the group.\n *\n * @param {AutocompleteRenderGroupParams} params The group to render.\n * @returns {ReactNode}\n */\n renderGroup: PropTypes.func,\n /**\n * Render the input.\n *\n * @param {object} params\n * @returns {ReactNode}\n */\n renderInput: PropTypes.func.isRequired,\n /**\n * Render the option, use `getOptionLabel` by default.\n *\n * @param {object} props The props to apply on the li element.\n * @param {Value} option The option to render.\n * @param {object} state The state of each option.\n * @param {object} ownerState The state of the Autocomplete component.\n * @returns {ReactNode}\n */\n renderOption: PropTypes.func,\n /**\n * Render the selected value.\n *\n * @param {Value[]} value The `value` provided to the component.\n * @param {function} getTagProps A tag props getter.\n * @param {object} ownerState The state of the Autocomplete component.\n * @returns {ReactNode}\n */\n renderTags: PropTypes.func,\n /**\n * If `true`, the input's text is selected on focus.\n * It helps the user clear the selected value.\n * @default !props.freeSolo\n */\n selectOnFocus: PropTypes.bool,\n /**\n * The size of the component.\n * @default 'medium'\n */\n size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['small', 'medium']), PropTypes.string]),\n /**\n * The props used for each slot inside.\n * @default {}\n */\n slotProps: PropTypes /* @typescript-to-proptypes-ignore */.shape({\n chip: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n clearIndicator: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n listbox: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n paper: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n popper: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n popupIndicator: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside.\n * @default {}\n */\n slots: PropTypes.shape({\n listbox: PropTypes.elementType,\n paper: PropTypes.elementType,\n popper: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The value of the autocomplete.\n *\n * The value must have reference equality with the option in order to be selected.\n * You can customize the equality behavior with the `isOptionEqualToValue` prop.\n */\n value: chainPropTypes(PropTypes.any, props => {\n if (props.multiple && props.value !== undefined && !Array.isArray(props.value)) {\n return new Error(['MUI: The Autocomplete expects the `value` prop to be an array when `multiple={true}` or undefined.', `However, ${props.value} was provided.`].join('\\n'));\n }\n return null;\n })\n} : void 0;\nexport default Autocomplete;","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from \"../../utils/createSvgIcon.js\";\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon(/*#__PURE__*/_jsx(\"path\", {\n d: \"M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z\"\n}), 'Person');","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getAvatarUtilityClass(slot) {\n return generateUtilityClass('MuiAvatar', slot);\n}\nconst avatarClasses = generateUtilityClasses('MuiAvatar', ['root', 'colorDefault', 'circular', 'rounded', 'square', 'img', 'fallback']);\nexport default avatarClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { styled } from \"../zero-styled/index.js\";\nimport memoTheme from \"../utils/memoTheme.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport Person from \"../internal/svg-icons/Person.js\";\nimport { getAvatarUtilityClass } from \"./avatarClasses.js\";\nimport useSlot from \"../utils/useSlot.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n variant,\n colorDefault\n } = ownerState;\n const slots = {\n root: ['root', variant, colorDefault && 'colorDefault'],\n img: ['img'],\n fallback: ['fallback']\n };\n return composeClasses(slots, getAvatarUtilityClass, classes);\n};\nconst AvatarRoot = styled('div', {\n name: 'MuiAvatar',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, styles[ownerState.variant], ownerState.colorDefault && styles.colorDefault];\n }\n})(memoTheme(({\n theme\n}) => ({\n position: 'relative',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n flexShrink: 0,\n width: 40,\n height: 40,\n fontFamily: theme.typography.fontFamily,\n fontSize: theme.typography.pxToRem(20),\n lineHeight: 1,\n borderRadius: '50%',\n overflow: 'hidden',\n userSelect: 'none',\n variants: [{\n props: {\n variant: 'rounded'\n },\n style: {\n borderRadius: (theme.vars || theme).shape.borderRadius\n }\n }, {\n props: {\n variant: 'square'\n },\n style: {\n borderRadius: 0\n }\n }, {\n props: {\n colorDefault: true\n },\n style: {\n color: (theme.vars || theme).palette.background.default,\n ...(theme.vars ? {\n backgroundColor: theme.vars.palette.Avatar.defaultBg\n } : {\n backgroundColor: theme.palette.grey[400],\n ...theme.applyStyles('dark', {\n backgroundColor: theme.palette.grey[600]\n })\n })\n }\n }]\n})));\nconst AvatarImg = styled('img', {\n name: 'MuiAvatar',\n slot: 'Img',\n overridesResolver: (props, styles) => styles.img\n})({\n width: '100%',\n height: '100%',\n textAlign: 'center',\n // Handle non-square image.\n objectFit: 'cover',\n // Hide alt text.\n color: 'transparent',\n // Hide the image broken icon, only works on Chrome.\n textIndent: 10000\n});\nconst AvatarFallback = styled(Person, {\n name: 'MuiAvatar',\n slot: 'Fallback',\n overridesResolver: (props, styles) => styles.fallback\n})({\n width: '75%',\n height: '75%'\n});\nfunction useLoaded({\n crossOrigin,\n referrerPolicy,\n src,\n srcSet\n}) {\n const [loaded, setLoaded] = React.useState(false);\n React.useEffect(() => {\n if (!src && !srcSet) {\n return undefined;\n }\n setLoaded(false);\n let active = true;\n const image = new Image();\n image.onload = () => {\n if (!active) {\n return;\n }\n setLoaded('loaded');\n };\n image.onerror = () => {\n if (!active) {\n return;\n }\n setLoaded('error');\n };\n image.crossOrigin = crossOrigin;\n image.referrerPolicy = referrerPolicy;\n image.src = src;\n if (srcSet) {\n image.srcset = srcSet;\n }\n return () => {\n active = false;\n };\n }, [crossOrigin, referrerPolicy, src, srcSet]);\n return loaded;\n}\nconst Avatar = /*#__PURE__*/React.forwardRef(function Avatar(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiAvatar'\n });\n const {\n alt,\n children: childrenProp,\n className,\n component = 'div',\n slots = {},\n slotProps = {},\n imgProps,\n sizes,\n src,\n srcSet,\n variant = 'circular',\n ...other\n } = props;\n let children = null;\n const ownerState = {\n ...props,\n component,\n variant\n };\n\n // Use a hook instead of onError on the img element to support server-side rendering.\n const loaded = useLoaded({\n ...imgProps,\n ...(typeof slotProps.img === 'function' ? slotProps.img(ownerState) : slotProps.img),\n src,\n srcSet\n });\n const hasImg = src || srcSet;\n const hasImgNotFailing = hasImg && loaded !== 'error';\n ownerState.colorDefault = !hasImgNotFailing;\n // This issue explains why this is required: https://github.com/mui/material-ui/issues/42184\n delete ownerState.ownerState;\n const classes = useUtilityClasses(ownerState);\n const [ImgSlot, imgSlotProps] = useSlot('img', {\n className: classes.img,\n elementType: AvatarImg,\n externalForwardedProps: {\n slots,\n slotProps: {\n img: {\n ...imgProps,\n ...slotProps.img\n }\n }\n },\n additionalProps: {\n alt,\n src,\n srcSet,\n sizes\n },\n ownerState\n });\n if (hasImgNotFailing) {\n children = /*#__PURE__*/_jsx(ImgSlot, {\n ...imgSlotProps\n });\n // We only render valid children, non valid children are rendered with a fallback\n // We consider that invalid children are all falsy values, except 0, which is valid.\n } else if (!!childrenProp || childrenProp === 0) {\n children = childrenProp;\n } else if (hasImg && alt) {\n children = alt[0];\n } else {\n children = /*#__PURE__*/_jsx(AvatarFallback, {\n ownerState: ownerState,\n className: classes.fallback\n });\n }\n return /*#__PURE__*/_jsx(AvatarRoot, {\n as: component,\n className: clsx(classes.root, className),\n ref: ref,\n ...other,\n ownerState: ownerState,\n children: children\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Avatar.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Used in combination with `src` or `srcSet` to\n * provide an alt attribute for the rendered `img` element.\n */\n alt: PropTypes.string,\n /**\n * Used to render icon or text elements inside the Avatar if `src` is not set.\n * This can be an element, or just a string.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attributes) applied to the `img` element if the component is used to display an image.\n * It can be used to listen for the loading error event.\n * @deprecated Use `slotProps.img` instead. This prop will be removed in v7. See [Migrating from deprecated APIs](/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n */\n imgProps: PropTypes.object,\n /**\n * The `sizes` attribute for the `img` element.\n */\n sizes: PropTypes.string,\n /**\n * The props used for each slot inside.\n * @default {}\n */\n slotProps: PropTypes.shape({\n img: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside.\n * @default {}\n */\n slots: PropTypes.shape({\n img: PropTypes.elementType\n }),\n /**\n * The `src` attribute for the `img` element.\n */\n src: PropTypes.string,\n /**\n * The `srcSet` attribute for the `img` element.\n * Use this attribute for responsive image display.\n */\n srcSet: PropTypes.string,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The shape of the avatar.\n * @default 'circular'\n */\n variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['circular', 'rounded', 'square']), PropTypes.string])\n} : void 0;\nexport default Avatar;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { Transition } from 'react-transition-group';\nimport elementAcceptingRef from '@mui/utils/elementAcceptingRef';\nimport getReactElementRef from '@mui/utils/getReactElementRef';\nimport { useTheme } from \"../zero-styled/index.js\";\nimport { reflow, getTransitionProps } from \"../transitions/utils.js\";\nimport useForkRef from \"../utils/useForkRef.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst styles = {\n entering: {\n opacity: 1\n },\n entered: {\n opacity: 1\n }\n};\n\n/**\n * The Fade transition is used by the [Modal](/material-ui/react-modal/) component.\n * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.\n */\nconst Fade = /*#__PURE__*/React.forwardRef(function Fade(props, ref) {\n const theme = useTheme();\n const defaultTimeout = {\n enter: theme.transitions.duration.enteringScreen,\n exit: theme.transitions.duration.leavingScreen\n };\n const {\n addEndListener,\n appear = true,\n children,\n easing,\n in: inProp,\n onEnter,\n onEntered,\n onEntering,\n onExit,\n onExited,\n onExiting,\n style,\n timeout = defaultTimeout,\n // eslint-disable-next-line react/prop-types\n TransitionComponent = Transition,\n ...other\n } = props;\n const enableStrictModeCompat = true;\n const nodeRef = React.useRef(null);\n const handleRef = useForkRef(nodeRef, getReactElementRef(children), ref);\n const normalizedTransitionCallback = callback => maybeIsAppearing => {\n if (callback) {\n const node = nodeRef.current;\n\n // onEnterXxx and onExitXxx callbacks have a different arguments.length value.\n if (maybeIsAppearing === undefined) {\n callback(node);\n } else {\n callback(node, maybeIsAppearing);\n }\n }\n };\n const handleEntering = normalizedTransitionCallback(onEntering);\n const handleEnter = normalizedTransitionCallback((node, isAppearing) => {\n reflow(node); // So the animation always start from the start.\n\n const transitionProps = getTransitionProps({\n style,\n timeout,\n easing\n }, {\n mode: 'enter'\n });\n node.style.webkitTransition = theme.transitions.create('opacity', transitionProps);\n node.style.transition = theme.transitions.create('opacity', transitionProps);\n if (onEnter) {\n onEnter(node, isAppearing);\n }\n });\n const handleEntered = normalizedTransitionCallback(onEntered);\n const handleExiting = normalizedTransitionCallback(onExiting);\n const handleExit = normalizedTransitionCallback(node => {\n const transitionProps = getTransitionProps({\n style,\n timeout,\n easing\n }, {\n mode: 'exit'\n });\n node.style.webkitTransition = theme.transitions.create('opacity', transitionProps);\n node.style.transition = theme.transitions.create('opacity', transitionProps);\n if (onExit) {\n onExit(node);\n }\n });\n const handleExited = normalizedTransitionCallback(onExited);\n const handleAddEndListener = next => {\n if (addEndListener) {\n // Old call signature before `react-transition-group` implemented `nodeRef`\n addEndListener(nodeRef.current, next);\n }\n };\n return /*#__PURE__*/_jsx(TransitionComponent, {\n appear: appear,\n in: inProp,\n nodeRef: enableStrictModeCompat ? nodeRef : undefined,\n onEnter: handleEnter,\n onEntered: handleEntered,\n onEntering: handleEntering,\n onExit: handleExit,\n onExited: handleExited,\n onExiting: handleExiting,\n addEndListener: handleAddEndListener,\n timeout: timeout,\n ...other,\n children: (state, {\n ownerState,\n ...restChildProps\n }) => {\n return /*#__PURE__*/React.cloneElement(children, {\n style: {\n opacity: 0,\n visibility: state === 'exited' && !inProp ? 'hidden' : undefined,\n ...styles[state],\n ...style,\n ...children.props.style\n },\n ref: handleRef,\n ...restChildProps\n });\n }\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Fade.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * Add a custom transition end trigger. Called with the transitioning DOM\n * node and a done callback. Allows for more fine grained transition end\n * logic. Note: Timeouts are still used as a fallback if provided.\n */\n addEndListener: PropTypes.func,\n /**\n * Perform the enter transition when it first mounts if `in` is also `true`.\n * Set this to `false` to disable this behavior.\n * @default true\n */\n appear: PropTypes.bool,\n /**\n * A single child content element.\n */\n children: elementAcceptingRef.isRequired,\n /**\n * The transition timing function.\n * You may specify a single easing or a object containing enter and exit values.\n */\n easing: PropTypes.oneOfType([PropTypes.shape({\n enter: PropTypes.string,\n exit: PropTypes.string\n }), PropTypes.string]),\n /**\n * If `true`, the component will transition in.\n */\n in: PropTypes.bool,\n /**\n * @ignore\n */\n onEnter: PropTypes.func,\n /**\n * @ignore\n */\n onEntered: PropTypes.func,\n /**\n * @ignore\n */\n onEntering: PropTypes.func,\n /**\n * @ignore\n */\n onExit: PropTypes.func,\n /**\n * @ignore\n */\n onExited: PropTypes.func,\n /**\n * @ignore\n */\n onExiting: PropTypes.func,\n /**\n * @ignore\n */\n style: PropTypes.object,\n /**\n * The duration for the transition, in milliseconds.\n * You may specify a single timeout for all transitions, or individually with an object.\n * @default {\n * enter: theme.transitions.duration.enteringScreen,\n * exit: theme.transitions.duration.leavingScreen,\n * }\n */\n timeout: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })])\n} : void 0;\nexport default Fade;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getBackdropUtilityClass(slot) {\n return generateUtilityClass('MuiBackdrop', slot);\n}\nconst backdropClasses = generateUtilityClasses('MuiBackdrop', ['root', 'invisible']);\nexport default backdropClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { styled } from \"../zero-styled/index.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport useSlot from \"../utils/useSlot.js\";\nimport Fade from \"../Fade/index.js\";\nimport { getBackdropUtilityClass } from \"./backdropClasses.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n invisible\n } = ownerState;\n const slots = {\n root: ['root', invisible && 'invisible']\n };\n return composeClasses(slots, getBackdropUtilityClass, classes);\n};\nconst BackdropRoot = styled('div', {\n name: 'MuiBackdrop',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.invisible && styles.invisible];\n }\n})({\n position: 'fixed',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n right: 0,\n bottom: 0,\n top: 0,\n left: 0,\n backgroundColor: 'rgba(0, 0, 0, 0.5)',\n WebkitTapHighlightColor: 'transparent',\n variants: [{\n props: {\n invisible: true\n },\n style: {\n backgroundColor: 'transparent'\n }\n }]\n});\nconst Backdrop = /*#__PURE__*/React.forwardRef(function Backdrop(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiBackdrop'\n });\n const {\n children,\n className,\n component = 'div',\n invisible = false,\n open,\n components = {},\n componentsProps = {},\n slotProps = {},\n slots = {},\n TransitionComponent: TransitionComponentProp,\n transitionDuration,\n ...other\n } = props;\n const ownerState = {\n ...props,\n component,\n invisible\n };\n const classes = useUtilityClasses(ownerState);\n const backwardCompatibleSlots = {\n transition: TransitionComponentProp,\n root: components.Root,\n ...slots\n };\n const backwardCompatibleSlotProps = {\n ...componentsProps,\n ...slotProps\n };\n const externalForwardedProps = {\n slots: backwardCompatibleSlots,\n slotProps: backwardCompatibleSlotProps\n };\n const [RootSlot, rootProps] = useSlot('root', {\n elementType: BackdropRoot,\n externalForwardedProps,\n className: clsx(classes.root, className),\n ownerState\n });\n const [TransitionSlot, transitionProps] = useSlot('transition', {\n elementType: Fade,\n externalForwardedProps,\n ownerState\n });\n return /*#__PURE__*/_jsx(TransitionSlot, {\n in: open,\n timeout: transitionDuration,\n ...other,\n ...transitionProps,\n children: /*#__PURE__*/_jsx(RootSlot, {\n \"aria-hidden\": true,\n ...rootProps,\n classes: classes,\n ref: ref,\n children: children\n })\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Backdrop.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * The components used for each slot inside.\n *\n * @deprecated Use the `slots` prop instead. This prop will be removed in v7. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n *\n * @default {}\n */\n components: PropTypes.shape({\n Root: PropTypes.elementType\n }),\n /**\n * The extra props for the slot components.\n * You can override the existing props or add new ones.\n *\n * @deprecated Use the `slotProps` prop instead. This prop will be removed in v7. See [Migrating from deprecated APIs](https://mui.com/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n *\n * @default {}\n */\n componentsProps: PropTypes.shape({\n root: PropTypes.object\n }),\n /**\n * If `true`, the backdrop is invisible.\n * It can be used when rendering a popover or a custom select component.\n * @default false\n */\n invisible: PropTypes.bool,\n /**\n * If `true`, the component is shown.\n */\n open: PropTypes.bool.isRequired,\n /**\n * The props used for each slot inside.\n * @default {}\n */\n slotProps: PropTypes.shape({\n root: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n transition: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside.\n * @default {}\n */\n slots: PropTypes.shape({\n root: PropTypes.elementType,\n transition: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The component used for the transition.\n * [Follow this guide](https://mui.com/material-ui/transitions/#transitioncomponent-prop) to learn more about the requirements for this component.\n * @default Fade\n * @deprecated Use `slots.transition` instead. This prop will be removed in v7. See [Migrating from deprecated APIs](/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n */\n TransitionComponent: PropTypes.elementType,\n /**\n * The duration for the transition, in milliseconds.\n * You may specify a single timeout for all transitions, or individually with an object.\n */\n transitionDuration: PropTypes.oneOfType([PropTypes.number, PropTypes.shape({\n appear: PropTypes.number,\n enter: PropTypes.number,\n exit: PropTypes.number\n })])\n} : void 0;\nexport default Backdrop;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nconst boxClasses = generateUtilityClasses('MuiBox', ['root']);\nexport default boxClasses;","'use client';\n\nimport { createBox } from '@mui/system';\nimport PropTypes from 'prop-types';\nimport { unstable_ClassNameGenerator as ClassNameGenerator } from \"../className/index.js\";\nimport { createTheme } from \"../styles/index.js\";\nimport THEME_ID from \"../styles/identifier.js\";\nimport boxClasses from \"./boxClasses.js\";\nconst defaultTheme = createTheme();\nconst Box = createBox({\n themeId: THEME_ID,\n defaultTheme,\n defaultClassName: boxClasses.root,\n generateClassName: ClassNameGenerator.generate\n});\nprocess.env.NODE_ENV !== \"production\" ? Box.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * @ignore\n */\n children: PropTypes.node,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default Box;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getButtonUtilityClass(slot) {\n return generateUtilityClass('MuiButton', slot);\n}\nconst buttonClasses = generateUtilityClasses('MuiButton', ['root', 'text', 'textInherit', 'textPrimary', 'textSecondary', 'textSuccess', 'textError', 'textInfo', 'textWarning', 'outlined', 'outlinedInherit', 'outlinedPrimary', 'outlinedSecondary', 'outlinedSuccess', 'outlinedError', 'outlinedInfo', 'outlinedWarning', 'contained', 'containedInherit', 'containedPrimary', 'containedSecondary', 'containedSuccess', 'containedError', 'containedInfo', 'containedWarning', 'disableElevation', 'focusVisible', 'disabled', 'colorInherit', 'colorPrimary', 'colorSecondary', 'colorSuccess', 'colorError', 'colorInfo', 'colorWarning', 'textSizeSmall', 'textSizeMedium', 'textSizeLarge', 'outlinedSizeSmall', 'outlinedSizeMedium', 'outlinedSizeLarge', 'containedSizeSmall', 'containedSizeMedium', 'containedSizeLarge', 'sizeMedium', 'sizeSmall', 'sizeLarge', 'fullWidth', 'startIcon', 'endIcon', 'icon', 'iconSizeSmall', 'iconSizeMedium', 'iconSizeLarge', 'loading', 'loadingWrapper', 'loadingIconPlaceholder', 'loadingIndicator', 'loadingPositionCenter', 'loadingPositionStart', 'loadingPositionEnd']);\nexport default buttonClasses;","'use client';\n\nimport * as React from 'react';\n/**\n * @ignore - internal component.\n */\nconst ButtonGroupContext = /*#__PURE__*/React.createContext({});\nif (process.env.NODE_ENV !== 'production') {\n ButtonGroupContext.displayName = 'ButtonGroupContext';\n}\nexport default ButtonGroupContext;","'use client';\n\nimport * as React from 'react';\n/**\n * @ignore - internal component.\n */\nconst ButtonGroupButtonContext = /*#__PURE__*/React.createContext(undefined);\nif (process.env.NODE_ENV !== 'production') {\n ButtonGroupButtonContext.displayName = 'ButtonGroupButtonContext';\n}\nexport default ButtonGroupButtonContext;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport resolveProps from '@mui/utils/resolveProps';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { alpha } from '@mui/system/colorManipulator';\nimport { unstable_useId as useId } from '@mui/material/utils';\nimport rootShouldForwardProp from \"../styles/rootShouldForwardProp.js\";\nimport { styled } from \"../zero-styled/index.js\";\nimport memoTheme from \"../utils/memoTheme.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport ButtonBase from \"../ButtonBase/index.js\";\nimport CircularProgress from \"../CircularProgress/index.js\";\nimport capitalize from \"../utils/capitalize.js\";\nimport createSimplePaletteValueFilter from \"../utils/createSimplePaletteValueFilter.js\";\nimport buttonClasses, { getButtonUtilityClass } from \"./buttonClasses.js\";\nimport ButtonGroupContext from \"../ButtonGroup/ButtonGroupContext.js\";\nimport ButtonGroupButtonContext from \"../ButtonGroup/ButtonGroupButtonContext.js\";\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n color,\n disableElevation,\n fullWidth,\n size,\n variant,\n loading,\n loadingPosition,\n classes\n } = ownerState;\n const slots = {\n root: ['root', loading && 'loading', variant, `${variant}${capitalize(color)}`, `size${capitalize(size)}`, `${variant}Size${capitalize(size)}`, `color${capitalize(color)}`, disableElevation && 'disableElevation', fullWidth && 'fullWidth', loading && `loadingPosition${capitalize(loadingPosition)}`],\n startIcon: ['icon', 'startIcon', `iconSize${capitalize(size)}`],\n endIcon: ['icon', 'endIcon', `iconSize${capitalize(size)}`],\n loadingIndicator: ['loadingIndicator'],\n loadingWrapper: ['loadingWrapper']\n };\n const composedClasses = composeClasses(slots, getButtonUtilityClass, classes);\n return {\n ...classes,\n // forward the focused, disabled, etc. classes to the ButtonBase\n ...composedClasses\n };\n};\nconst commonIconStyles = [{\n props: {\n size: 'small'\n },\n style: {\n '& > *:nth-of-type(1)': {\n fontSize: 18\n }\n }\n}, {\n props: {\n size: 'medium'\n },\n style: {\n '& > *:nth-of-type(1)': {\n fontSize: 20\n }\n }\n}, {\n props: {\n size: 'large'\n },\n style: {\n '& > *:nth-of-type(1)': {\n fontSize: 22\n }\n }\n}];\nconst ButtonRoot = styled(ButtonBase, {\n shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',\n name: 'MuiButton',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, styles[ownerState.variant], styles[`${ownerState.variant}${capitalize(ownerState.color)}`], styles[`size${capitalize(ownerState.size)}`], styles[`${ownerState.variant}Size${capitalize(ownerState.size)}`], ownerState.color === 'inherit' && styles.colorInherit, ownerState.disableElevation && styles.disableElevation, ownerState.fullWidth && styles.fullWidth, ownerState.loading && styles.loading];\n }\n})(memoTheme(({\n theme\n}) => {\n const inheritContainedBackgroundColor = theme.palette.mode === 'light' ? theme.palette.grey[300] : theme.palette.grey[800];\n const inheritContainedHoverBackgroundColor = theme.palette.mode === 'light' ? theme.palette.grey.A100 : theme.palette.grey[700];\n return {\n ...theme.typography.button,\n minWidth: 64,\n padding: '6px 16px',\n border: 0,\n borderRadius: (theme.vars || theme).shape.borderRadius,\n transition: theme.transitions.create(['background-color', 'box-shadow', 'border-color', 'color'], {\n duration: theme.transitions.duration.short\n }),\n '&:hover': {\n textDecoration: 'none'\n },\n [`&.${buttonClasses.disabled}`]: {\n color: (theme.vars || theme).palette.action.disabled\n },\n variants: [{\n props: {\n variant: 'contained'\n },\n style: {\n color: `var(--variant-containedColor)`,\n backgroundColor: `var(--variant-containedBg)`,\n boxShadow: (theme.vars || theme).shadows[2],\n '&:hover': {\n boxShadow: (theme.vars || theme).shadows[4],\n // Reset on touch devices, it doesn't add specificity\n '@media (hover: none)': {\n boxShadow: (theme.vars || theme).shadows[2]\n }\n },\n '&:active': {\n boxShadow: (theme.vars || theme).shadows[8]\n },\n [`&.${buttonClasses.focusVisible}`]: {\n boxShadow: (theme.vars || theme).shadows[6]\n },\n [`&.${buttonClasses.disabled}`]: {\n color: (theme.vars || theme).palette.action.disabled,\n boxShadow: (theme.vars || theme).shadows[0],\n backgroundColor: (theme.vars || theme).palette.action.disabledBackground\n }\n }\n }, {\n props: {\n variant: 'outlined'\n },\n style: {\n padding: '5px 15px',\n border: '1px solid currentColor',\n borderColor: `var(--variant-outlinedBorder, currentColor)`,\n backgroundColor: `var(--variant-outlinedBg)`,\n color: `var(--variant-outlinedColor)`,\n [`&.${buttonClasses.disabled}`]: {\n border: `1px solid ${(theme.vars || theme).palette.action.disabledBackground}`\n }\n }\n }, {\n props: {\n variant: 'text'\n },\n style: {\n padding: '6px 8px',\n color: `var(--variant-textColor)`,\n backgroundColor: `var(--variant-textBg)`\n }\n }, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()).map(([color]) => ({\n props: {\n color\n },\n style: {\n '--variant-textColor': (theme.vars || theme).palette[color].main,\n '--variant-outlinedColor': (theme.vars || theme).palette[color].main,\n '--variant-outlinedBorder': theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / 0.5)` : alpha(theme.palette[color].main, 0.5),\n '--variant-containedColor': (theme.vars || theme).palette[color].contrastText,\n '--variant-containedBg': (theme.vars || theme).palette[color].main,\n '@media (hover: hover)': {\n '&:hover': {\n '--variant-containedBg': (theme.vars || theme).palette[color].dark,\n '--variant-textBg': theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette[color].main, theme.palette.action.hoverOpacity),\n '--variant-outlinedBorder': (theme.vars || theme).palette[color].main,\n '--variant-outlinedBg': theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette[color].main, theme.palette.action.hoverOpacity)\n }\n }\n }\n })), {\n props: {\n color: 'inherit'\n },\n style: {\n color: 'inherit',\n borderColor: 'currentColor',\n '--variant-containedBg': theme.vars ? theme.vars.palette.Button.inheritContainedBg : inheritContainedBackgroundColor,\n '@media (hover: hover)': {\n '&:hover': {\n '--variant-containedBg': theme.vars ? theme.vars.palette.Button.inheritContainedHoverBg : inheritContainedHoverBackgroundColor,\n '--variant-textBg': theme.vars ? `rgba(${theme.vars.palette.text.primaryChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette.text.primary, theme.palette.action.hoverOpacity),\n '--variant-outlinedBg': theme.vars ? `rgba(${theme.vars.palette.text.primaryChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette.text.primary, theme.palette.action.hoverOpacity)\n }\n }\n }\n }, {\n props: {\n size: 'small',\n variant: 'text'\n },\n style: {\n padding: '4px 5px',\n fontSize: theme.typography.pxToRem(13)\n }\n }, {\n props: {\n size: 'large',\n variant: 'text'\n },\n style: {\n padding: '8px 11px',\n fontSize: theme.typography.pxToRem(15)\n }\n }, {\n props: {\n size: 'small',\n variant: 'outlined'\n },\n style: {\n padding: '3px 9px',\n fontSize: theme.typography.pxToRem(13)\n }\n }, {\n props: {\n size: 'large',\n variant: 'outlined'\n },\n style: {\n padding: '7px 21px',\n fontSize: theme.typography.pxToRem(15)\n }\n }, {\n props: {\n size: 'small',\n variant: 'contained'\n },\n style: {\n padding: '4px 10px',\n fontSize: theme.typography.pxToRem(13)\n }\n }, {\n props: {\n size: 'large',\n variant: 'contained'\n },\n style: {\n padding: '8px 22px',\n fontSize: theme.typography.pxToRem(15)\n }\n }, {\n props: {\n disableElevation: true\n },\n style: {\n boxShadow: 'none',\n '&:hover': {\n boxShadow: 'none'\n },\n [`&.${buttonClasses.focusVisible}`]: {\n boxShadow: 'none'\n },\n '&:active': {\n boxShadow: 'none'\n },\n [`&.${buttonClasses.disabled}`]: {\n boxShadow: 'none'\n }\n }\n }, {\n props: {\n fullWidth: true\n },\n style: {\n width: '100%'\n }\n }, {\n props: {\n loadingPosition: 'center'\n },\n style: {\n transition: theme.transitions.create(['background-color', 'box-shadow', 'border-color'], {\n duration: theme.transitions.duration.short\n }),\n [`&.${buttonClasses.loading}`]: {\n color: 'transparent'\n }\n }\n }]\n };\n}));\nconst ButtonStartIcon = styled('span', {\n name: 'MuiButton',\n slot: 'StartIcon',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.startIcon, ownerState.loading && styles.startIconLoadingStart, styles[`iconSize${capitalize(ownerState.size)}`]];\n }\n})(({\n theme\n}) => ({\n display: 'inherit',\n marginRight: 8,\n marginLeft: -4,\n variants: [{\n props: {\n size: 'small'\n },\n style: {\n marginLeft: -2\n }\n }, {\n props: {\n loadingPosition: 'start',\n loading: true\n },\n style: {\n transition: theme.transitions.create(['opacity'], {\n duration: theme.transitions.duration.short\n }),\n opacity: 0\n }\n }, {\n props: {\n loadingPosition: 'start',\n loading: true,\n fullWidth: true\n },\n style: {\n marginRight: -8\n }\n }, ...commonIconStyles]\n}));\nconst ButtonEndIcon = styled('span', {\n name: 'MuiButton',\n slot: 'EndIcon',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.endIcon, ownerState.loading && styles.endIconLoadingEnd, styles[`iconSize${capitalize(ownerState.size)}`]];\n }\n})(({\n theme\n}) => ({\n display: 'inherit',\n marginRight: -4,\n marginLeft: 8,\n variants: [{\n props: {\n size: 'small'\n },\n style: {\n marginRight: -2\n }\n }, {\n props: {\n loadingPosition: 'end',\n loading: true\n },\n style: {\n transition: theme.transitions.create(['opacity'], {\n duration: theme.transitions.duration.short\n }),\n opacity: 0\n }\n }, {\n props: {\n loadingPosition: 'end',\n loading: true,\n fullWidth: true\n },\n style: {\n marginLeft: -8\n }\n }, ...commonIconStyles]\n}));\nconst ButtonLoadingIndicator = styled('span', {\n name: 'MuiButton',\n slot: 'LoadingIndicator',\n overridesResolver: (props, styles) => styles.loadingIndicator\n})(({\n theme\n}) => ({\n display: 'none',\n position: 'absolute',\n visibility: 'visible',\n variants: [{\n props: {\n loading: true\n },\n style: {\n display: 'flex'\n }\n }, {\n props: {\n loadingPosition: 'start'\n },\n style: {\n left: 14\n }\n }, {\n props: {\n loadingPosition: 'start',\n size: 'small'\n },\n style: {\n left: 10\n }\n }, {\n props: {\n variant: 'text',\n loadingPosition: 'start'\n },\n style: {\n left: 6\n }\n }, {\n props: {\n loadingPosition: 'center'\n },\n style: {\n left: '50%',\n transform: 'translate(-50%)',\n color: (theme.vars || theme).palette.action.disabled\n }\n }, {\n props: {\n loadingPosition: 'end'\n },\n style: {\n right: 14\n }\n }, {\n props: {\n loadingPosition: 'end',\n size: 'small'\n },\n style: {\n right: 10\n }\n }, {\n props: {\n variant: 'text',\n loadingPosition: 'end'\n },\n style: {\n right: 6\n }\n }, {\n props: {\n loadingPosition: 'start',\n fullWidth: true\n },\n style: {\n position: 'relative',\n left: -10\n }\n }, {\n props: {\n loadingPosition: 'end',\n fullWidth: true\n },\n style: {\n position: 'relative',\n right: -10\n }\n }]\n}));\nconst ButtonLoadingIconPlaceholder = styled('span', {\n name: 'MuiButton',\n slot: 'LoadingIconPlaceholder',\n overridesResolver: (props, styles) => styles.loadingIconPlaceholder\n})({\n display: 'inline-block',\n width: '1em',\n height: '1em'\n});\nconst Button = /*#__PURE__*/React.forwardRef(function Button(inProps, ref) {\n // props priority: `inProps` > `contextProps` > `themeDefaultProps`\n const contextProps = React.useContext(ButtonGroupContext);\n const buttonGroupButtonContextPositionClassName = React.useContext(ButtonGroupButtonContext);\n const resolvedProps = resolveProps(contextProps, inProps);\n const props = useDefaultProps({\n props: resolvedProps,\n name: 'MuiButton'\n });\n const {\n children,\n color = 'primary',\n component = 'button',\n className,\n disabled = false,\n disableElevation = false,\n disableFocusRipple = false,\n endIcon: endIconProp,\n focusVisibleClassName,\n fullWidth = false,\n id: idProp,\n loading = null,\n loadingIndicator: loadingIndicatorProp,\n loadingPosition = 'center',\n size = 'medium',\n startIcon: startIconProp,\n type,\n variant = 'text',\n ...other\n } = props;\n const loadingId = useId(idProp);\n const loadingIndicator = loadingIndicatorProp ?? /*#__PURE__*/_jsx(CircularProgress, {\n \"aria-labelledby\": loadingId,\n color: \"inherit\",\n size: 16\n });\n const ownerState = {\n ...props,\n color,\n component,\n disabled,\n disableElevation,\n disableFocusRipple,\n fullWidth,\n loading,\n loadingIndicator,\n loadingPosition,\n size,\n type,\n variant\n };\n const classes = useUtilityClasses(ownerState);\n const startIcon = (startIconProp || loading && loadingPosition === 'start') && /*#__PURE__*/_jsx(ButtonStartIcon, {\n className: classes.startIcon,\n ownerState: ownerState,\n children: startIconProp || /*#__PURE__*/_jsx(ButtonLoadingIconPlaceholder, {\n className: classes.loadingIconPlaceholder,\n ownerState: ownerState\n })\n });\n const endIcon = (endIconProp || loading && loadingPosition === 'end') && /*#__PURE__*/_jsx(ButtonEndIcon, {\n className: classes.endIcon,\n ownerState: ownerState,\n children: endIconProp || /*#__PURE__*/_jsx(ButtonLoadingIconPlaceholder, {\n className: classes.loadingIconPlaceholder,\n ownerState: ownerState\n })\n });\n const positionClassName = buttonGroupButtonContextPositionClassName || '';\n const loader = typeof loading === 'boolean' ?\n /*#__PURE__*/\n // use plain HTML span to minimize the runtime overhead\n _jsx(\"span\", {\n className: classes.loadingWrapper,\n style: {\n display: 'contents'\n },\n children: loading && /*#__PURE__*/_jsx(ButtonLoadingIndicator, {\n className: classes.loadingIndicator,\n ownerState: ownerState,\n children: loadingIndicator\n })\n }) : null;\n return /*#__PURE__*/_jsxs(ButtonRoot, {\n ownerState: ownerState,\n className: clsx(contextProps.className, classes.root, className, positionClassName),\n component: component,\n disabled: disabled || loading,\n focusRipple: !disableFocusRipple,\n focusVisibleClassName: clsx(classes.focusVisible, focusVisibleClassName),\n ref: ref,\n type: type,\n id: loading ? loadingId : idProp,\n ...other,\n classes: classes,\n children: [startIcon, loadingPosition !== 'end' && loader, children, loadingPosition === 'end' && loader, endIcon]\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Button.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The color of the component.\n * It supports both default and custom theme colors, which can be added as shown in the\n * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).\n * @default 'primary'\n */\n color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['inherit', 'primary', 'secondary', 'success', 'error', 'info', 'warning']), PropTypes.string]),\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * If `true`, the component is disabled.\n * @default false\n */\n disabled: PropTypes.bool,\n /**\n * If `true`, no elevation is used.\n * @default false\n */\n disableElevation: PropTypes.bool,\n /**\n * If `true`, the keyboard focus ripple is disabled.\n * @default false\n */\n disableFocusRipple: PropTypes.bool,\n /**\n * If `true`, the ripple effect is disabled.\n *\n * ⚠️ Without a ripple there is no styling for :focus-visible by default. Be sure\n * to highlight the element by applying separate styles with the `.Mui-focusVisible` class.\n * @default false\n */\n disableRipple: PropTypes.bool,\n /**\n * Element placed after the children.\n */\n endIcon: PropTypes.node,\n /**\n * @ignore\n */\n focusVisibleClassName: PropTypes.string,\n /**\n * If `true`, the button will take up the full width of its container.\n * @default false\n */\n fullWidth: PropTypes.bool,\n /**\n * The URL to link to when the button is clicked.\n * If defined, an `a` element will be used as the root node.\n */\n href: PropTypes.string,\n /**\n * @ignore\n */\n id: PropTypes.string,\n /**\n * If `true`, the loading indicator is visible and the button is disabled.\n * If `true | false`, the loading wrapper is always rendered before the children to prevent [Google Translation Crash](https://github.com/mui/material-ui/issues/27853).\n * @default null\n */\n loading: PropTypes.bool,\n /**\n * Element placed before the children if the button is in loading state.\n * The node should contain an element with `role=\"progressbar\"` with an accessible name.\n * By default, it renders a `CircularProgress` that is labeled by the button itself.\n * @default \n */\n loadingIndicator: PropTypes.node,\n /**\n * The loading indicator can be positioned on the start, end, or the center of the button.\n * @default 'center'\n */\n loadingPosition: PropTypes.oneOf(['center', 'end', 'start']),\n /**\n * The size of the component.\n * `small` is equivalent to the dense button styling.\n * @default 'medium'\n */\n size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['small', 'medium', 'large']), PropTypes.string]),\n /**\n * Element placed before the children.\n */\n startIcon: PropTypes.node,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * @ignore\n */\n type: PropTypes.oneOfType([PropTypes.oneOf(['button', 'reset', 'submit']), PropTypes.string]),\n /**\n * The variant to use.\n * @default 'text'\n */\n variant: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['contained', 'outlined', 'text']), PropTypes.string])\n} : void 0;\nexport default Button;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getCardUtilityClass(slot) {\n return generateUtilityClass('MuiCard', slot);\n}\nconst cardClasses = generateUtilityClasses('MuiCard', ['root']);\nexport default cardClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport chainPropTypes from '@mui/utils/chainPropTypes';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { styled } from \"../zero-styled/index.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport Paper from \"../Paper/index.js\";\nimport { getCardUtilityClass } from \"./cardClasses.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes\n } = ownerState;\n const slots = {\n root: ['root']\n };\n return composeClasses(slots, getCardUtilityClass, classes);\n};\nconst CardRoot = styled(Paper, {\n name: 'MuiCard',\n slot: 'Root',\n overridesResolver: (props, styles) => styles.root\n})({\n overflow: 'hidden'\n});\nconst Card = /*#__PURE__*/React.forwardRef(function Card(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiCard'\n });\n const {\n className,\n raised = false,\n ...other\n } = props;\n const ownerState = {\n ...props,\n raised\n };\n const classes = useUtilityClasses(ownerState);\n return /*#__PURE__*/_jsx(CardRoot, {\n className: clsx(classes.root, className),\n elevation: raised ? 8 : undefined,\n ref: ref,\n ownerState: ownerState,\n ...other\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Card.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * If `true`, the card will use raised styling.\n * @default false\n */\n raised: chainPropTypes(PropTypes.bool, props => {\n if (props.raised && props.variant === 'outlined') {\n return new Error('MUI: Combining `raised={true}` with `variant=\"outlined\"` has no effect.');\n }\n return null;\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default Card;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getCardContentUtilityClass(slot) {\n return generateUtilityClass('MuiCardContent', slot);\n}\nconst cardContentClasses = generateUtilityClasses('MuiCardContent', ['root']);\nexport default cardContentClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { styled } from \"../zero-styled/index.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport { getCardContentUtilityClass } from \"./cardContentClasses.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes\n } = ownerState;\n const slots = {\n root: ['root']\n };\n return composeClasses(slots, getCardContentUtilityClass, classes);\n};\nconst CardContentRoot = styled('div', {\n name: 'MuiCardContent',\n slot: 'Root',\n overridesResolver: (props, styles) => styles.root\n})({\n padding: 16,\n '&:last-child': {\n paddingBottom: 24\n }\n});\nconst CardContent = /*#__PURE__*/React.forwardRef(function CardContent(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiCardContent'\n });\n const {\n className,\n component = 'div',\n ...other\n } = props;\n const ownerState = {\n ...props,\n component\n };\n const classes = useUtilityClasses(ownerState);\n return /*#__PURE__*/_jsx(CardContentRoot, {\n as: component,\n className: clsx(classes.root, className),\n ownerState: ownerState,\n ref: ref,\n ...other\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? CardContent.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The content of the component.\n */\n children: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The component used for the root node.\n * Either a string to use a HTML element or a component.\n */\n component: PropTypes.elementType,\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object])\n} : void 0;\nexport default CardContent;","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getSwitchBaseUtilityClass(slot) {\n return generateUtilityClass('PrivateSwitchBase', slot);\n}\nconst switchBaseClasses = generateUtilityClasses('PrivateSwitchBase', ['root', 'checked', 'disabled', 'input', 'edgeStart', 'edgeEnd']);\nexport default switchBaseClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport refType from '@mui/utils/refType';\nimport composeClasses from '@mui/utils/composeClasses';\nimport capitalize from \"../utils/capitalize.js\";\nimport rootShouldForwardProp from \"../styles/rootShouldForwardProp.js\";\nimport { styled } from \"../zero-styled/index.js\";\nimport useControlled from \"../utils/useControlled.js\";\nimport useFormControl from \"../FormControl/useFormControl.js\";\nimport ButtonBase from \"../ButtonBase/index.js\";\nimport { getSwitchBaseUtilityClass } from \"./switchBaseClasses.js\";\nimport useSlot from \"../utils/useSlot.js\";\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n checked,\n disabled,\n edge\n } = ownerState;\n const slots = {\n root: ['root', checked && 'checked', disabled && 'disabled', edge && `edge${capitalize(edge)}`],\n input: ['input']\n };\n return composeClasses(slots, getSwitchBaseUtilityClass, classes);\n};\nconst SwitchBaseRoot = styled(ButtonBase)({\n padding: 9,\n borderRadius: '50%',\n variants: [{\n props: {\n edge: 'start',\n size: 'small'\n },\n style: {\n marginLeft: -3\n }\n }, {\n props: ({\n edge,\n ownerState\n }) => edge === 'start' && ownerState.size !== 'small',\n style: {\n marginLeft: -12\n }\n }, {\n props: {\n edge: 'end',\n size: 'small'\n },\n style: {\n marginRight: -3\n }\n }, {\n props: ({\n edge,\n ownerState\n }) => edge === 'end' && ownerState.size !== 'small',\n style: {\n marginRight: -12\n }\n }]\n});\nconst SwitchBaseInput = styled('input', {\n shouldForwardProp: rootShouldForwardProp\n})({\n cursor: 'inherit',\n position: 'absolute',\n opacity: 0,\n width: '100%',\n height: '100%',\n top: 0,\n left: 0,\n margin: 0,\n padding: 0,\n zIndex: 1\n});\n\n/**\n * @ignore - internal component.\n */\nconst SwitchBase = /*#__PURE__*/React.forwardRef(function SwitchBase(props, ref) {\n const {\n autoFocus,\n checked: checkedProp,\n checkedIcon,\n defaultChecked,\n disabled: disabledProp,\n disableFocusRipple = false,\n edge = false,\n icon,\n id,\n inputProps,\n inputRef,\n name,\n onBlur,\n onChange,\n onFocus,\n readOnly,\n required = false,\n tabIndex,\n type,\n value,\n slots = {},\n slotProps = {},\n ...other\n } = props;\n const [checked, setCheckedState] = useControlled({\n controlled: checkedProp,\n default: Boolean(defaultChecked),\n name: 'SwitchBase',\n state: 'checked'\n });\n const muiFormControl = useFormControl();\n const handleFocus = event => {\n if (onFocus) {\n onFocus(event);\n }\n if (muiFormControl && muiFormControl.onFocus) {\n muiFormControl.onFocus(event);\n }\n };\n const handleBlur = event => {\n if (onBlur) {\n onBlur(event);\n }\n if (muiFormControl && muiFormControl.onBlur) {\n muiFormControl.onBlur(event);\n }\n };\n const handleInputChange = event => {\n // Workaround for https://github.com/facebook/react/issues/9023\n if (event.nativeEvent.defaultPrevented) {\n return;\n }\n const newChecked = event.target.checked;\n setCheckedState(newChecked);\n if (onChange) {\n // TODO v6: remove the second argument.\n onChange(event, newChecked);\n }\n };\n let disabled = disabledProp;\n if (muiFormControl) {\n if (typeof disabled === 'undefined') {\n disabled = muiFormControl.disabled;\n }\n }\n const hasLabelFor = type === 'checkbox' || type === 'radio';\n const ownerState = {\n ...props,\n checked,\n disabled,\n disableFocusRipple,\n edge\n };\n const classes = useUtilityClasses(ownerState);\n const externalForwardedProps = {\n slots,\n slotProps: {\n input: inputProps,\n ...slotProps\n }\n };\n const [RootSlot, rootSlotProps] = useSlot('root', {\n ref,\n elementType: SwitchBaseRoot,\n className: classes.root,\n shouldForwardComponentProp: true,\n externalForwardedProps: {\n ...externalForwardedProps,\n component: 'span',\n ...other\n },\n getSlotProps: handlers => ({\n ...handlers,\n onFocus: event => {\n handlers.onFocus?.(event);\n handleFocus(event);\n },\n onBlur: event => {\n handlers.onBlur?.(event);\n handleBlur(event);\n }\n }),\n ownerState,\n additionalProps: {\n centerRipple: true,\n focusRipple: !disableFocusRipple,\n disabled,\n role: undefined,\n tabIndex: null\n }\n });\n const [InputSlot, inputSlotProps] = useSlot('input', {\n ref: inputRef,\n elementType: SwitchBaseInput,\n className: classes.input,\n externalForwardedProps,\n getSlotProps: handlers => ({\n onChange: event => {\n handlers.onChange?.(event);\n handleInputChange(event);\n }\n }),\n ownerState,\n additionalProps: {\n autoFocus,\n checked: checkedProp,\n defaultChecked,\n disabled,\n id: hasLabelFor ? id : undefined,\n name,\n readOnly,\n required,\n tabIndex,\n type,\n ...(type === 'checkbox' && value === undefined ? {} : {\n value\n })\n }\n });\n return /*#__PURE__*/_jsxs(RootSlot, {\n ...rootSlotProps,\n children: [/*#__PURE__*/_jsx(InputSlot, {\n ...inputSlotProps\n }), checked ? checkedIcon : icon]\n });\n});\n\n// NB: If changed, please update Checkbox, Switch and Radio\n// so that the API documentation is updated.\nprocess.env.NODE_ENV !== \"production\" ? SwitchBase.propTypes = {\n /**\n * If `true`, the `input` element is focused during the first mount.\n */\n autoFocus: PropTypes.bool,\n /**\n * If `true`, the component is checked.\n */\n checked: PropTypes.bool,\n /**\n * The icon to display when the component is checked.\n */\n checkedIcon: PropTypes.node.isRequired,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * @ignore\n */\n defaultChecked: PropTypes.bool,\n /**\n * If `true`, the component is disabled.\n */\n disabled: PropTypes.bool,\n /**\n * If `true`, the keyboard focus ripple is disabled.\n * @default false\n */\n disableFocusRipple: PropTypes.bool,\n /**\n * If given, uses a negative margin to counteract the padding on one\n * side (this is often helpful for aligning the left or right\n * side of the icon with content above or below, without ruining the border\n * size and shape).\n * @default false\n */\n edge: PropTypes.oneOf(['end', 'start', false]),\n /**\n * The icon to display when the component is unchecked.\n */\n icon: PropTypes.node.isRequired,\n /**\n * The id of the `input` element.\n */\n id: PropTypes.string,\n /**\n * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.\n */\n inputProps: PropTypes.object,\n /**\n * Pass a ref to the `input` element.\n */\n inputRef: refType,\n /*\n * @ignore\n */\n name: PropTypes.string,\n /**\n * @ignore\n */\n onBlur: PropTypes.func,\n /**\n * Callback fired when the state is changed.\n *\n * @param {object} event The event source of the callback.\n * You can pull out the new checked state by accessing `event.target.checked` (boolean).\n */\n onChange: PropTypes.func,\n /**\n * @ignore\n */\n onFocus: PropTypes.func,\n /**\n * It prevents the user from changing the value of the field\n * (not from interacting with the field).\n */\n readOnly: PropTypes.bool,\n /**\n * If `true`, the `input` element is required.\n */\n required: PropTypes.bool,\n /**\n * The props used for each slot inside.\n * @default {}\n */\n slotProps: PropTypes.shape({\n input: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside.\n * @default {}\n */\n slots: PropTypes.shape({\n input: PropTypes.elementType,\n root: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.object,\n /**\n * @ignore\n */\n tabIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),\n /**\n * The input component prop `type`.\n */\n type: PropTypes.string.isRequired,\n /**\n * The value of the component.\n */\n value: PropTypes.any\n} : void 0;\nexport default SwitchBase;","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from \"../../utils/createSvgIcon.js\";\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon(/*#__PURE__*/_jsx(\"path\", {\n d: \"M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z\"\n}), 'CheckBoxOutlineBlank');","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from \"../../utils/createSvgIcon.js\";\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon(/*#__PURE__*/_jsx(\"path\", {\n d: \"M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z\"\n}), 'CheckBox');","'use client';\n\nimport * as React from 'react';\nimport createSvgIcon from \"../../utils/createSvgIcon.js\";\n\n/**\n * @ignore - internal component.\n */\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nexport default createSvgIcon(/*#__PURE__*/_jsx(\"path\", {\n d: \"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 10H7v-2h10v2z\"\n}), 'IndeterminateCheckBox');","import generateUtilityClasses from '@mui/utils/generateUtilityClasses';\nimport generateUtilityClass from '@mui/utils/generateUtilityClass';\nexport function getCheckboxUtilityClass(slot) {\n return generateUtilityClass('MuiCheckbox', slot);\n}\nconst checkboxClasses = generateUtilityClasses('MuiCheckbox', ['root', 'checked', 'disabled', 'indeterminate', 'colorPrimary', 'colorSecondary', 'sizeSmall', 'sizeMedium']);\nexport default checkboxClasses;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport clsx from 'clsx';\nimport composeClasses from '@mui/utils/composeClasses';\nimport { alpha } from '@mui/system/colorManipulator';\nimport SwitchBase from \"../internal/SwitchBase.js\";\nimport CheckBoxOutlineBlankIcon from \"../internal/svg-icons/CheckBoxOutlineBlank.js\";\nimport CheckBoxIcon from \"../internal/svg-icons/CheckBox.js\";\nimport IndeterminateCheckBoxIcon from \"../internal/svg-icons/IndeterminateCheckBox.js\";\nimport capitalize from \"../utils/capitalize.js\";\nimport rootShouldForwardProp from \"../styles/rootShouldForwardProp.js\";\nimport checkboxClasses, { getCheckboxUtilityClass } from \"./checkboxClasses.js\";\nimport { styled } from \"../zero-styled/index.js\";\nimport memoTheme from \"../utils/memoTheme.js\";\nimport createSimplePaletteValueFilter from \"../utils/createSimplePaletteValueFilter.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\nimport { mergeSlotProps } from \"../utils/index.js\";\nimport useSlot from \"../utils/useSlot.js\";\nimport { jsx as _jsx } from \"react/jsx-runtime\";\nconst useUtilityClasses = ownerState => {\n const {\n classes,\n indeterminate,\n color,\n size\n } = ownerState;\n const slots = {\n root: ['root', indeterminate && 'indeterminate', `color${capitalize(color)}`, `size${capitalize(size)}`]\n };\n const composedClasses = composeClasses(slots, getCheckboxUtilityClass, classes);\n return {\n ...classes,\n // forward the disabled and checked classes to the SwitchBase\n ...composedClasses\n };\n};\nconst CheckboxRoot = styled(SwitchBase, {\n shouldForwardProp: prop => rootShouldForwardProp(prop) || prop === 'classes',\n name: 'MuiCheckbox',\n slot: 'Root',\n overridesResolver: (props, styles) => {\n const {\n ownerState\n } = props;\n return [styles.root, ownerState.indeterminate && styles.indeterminate, styles[`size${capitalize(ownerState.size)}`], ownerState.color !== 'default' && styles[`color${capitalize(ownerState.color)}`]];\n }\n})(memoTheme(({\n theme\n}) => ({\n color: (theme.vars || theme).palette.text.secondary,\n variants: [{\n props: {\n color: 'default',\n disableRipple: false\n },\n style: {\n '&:hover': {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette.action.activeChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette.action.active, theme.palette.action.hoverOpacity)\n }\n }\n }, ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()).map(([color]) => ({\n props: {\n color,\n disableRipple: false\n },\n style: {\n '&:hover': {\n backgroundColor: theme.vars ? `rgba(${theme.vars.palette[color].mainChannel} / ${theme.vars.palette.action.hoverOpacity})` : alpha(theme.palette[color].main, theme.palette.action.hoverOpacity)\n }\n }\n })), ...Object.entries(theme.palette).filter(createSimplePaletteValueFilter()).map(([color]) => ({\n props: {\n color\n },\n style: {\n [`&.${checkboxClasses.checked}, &.${checkboxClasses.indeterminate}`]: {\n color: (theme.vars || theme).palette[color].main\n },\n [`&.${checkboxClasses.disabled}`]: {\n color: (theme.vars || theme).palette.action.disabled\n }\n }\n })), {\n // Should be last to override other colors\n props: {\n disableRipple: false\n },\n style: {\n // Reset on touch devices, it doesn't add specificity\n '&:hover': {\n '@media (hover: none)': {\n backgroundColor: 'transparent'\n }\n }\n }\n }]\n})));\nconst defaultCheckedIcon = /*#__PURE__*/_jsx(CheckBoxIcon, {});\nconst defaultIcon = /*#__PURE__*/_jsx(CheckBoxOutlineBlankIcon, {});\nconst defaultIndeterminateIcon = /*#__PURE__*/_jsx(IndeterminateCheckBoxIcon, {});\nconst Checkbox = /*#__PURE__*/React.forwardRef(function Checkbox(inProps, ref) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiCheckbox'\n });\n const {\n checkedIcon = defaultCheckedIcon,\n color = 'primary',\n icon: iconProp = defaultIcon,\n indeterminate = false,\n indeterminateIcon: indeterminateIconProp = defaultIndeterminateIcon,\n inputProps,\n size = 'medium',\n disableRipple = false,\n className,\n slots = {},\n slotProps = {},\n ...other\n } = props;\n const icon = indeterminate ? indeterminateIconProp : iconProp;\n const indeterminateIcon = indeterminate ? indeterminateIconProp : checkedIcon;\n const ownerState = {\n ...props,\n disableRipple,\n color,\n indeterminate,\n size\n };\n const classes = useUtilityClasses(ownerState);\n const externalInputProps = slotProps.input ?? inputProps;\n const [RootSlot, rootSlotProps] = useSlot('root', {\n ref,\n elementType: CheckboxRoot,\n className: clsx(classes.root, className),\n shouldForwardComponentProp: true,\n externalForwardedProps: {\n slots,\n slotProps,\n ...other\n },\n ownerState,\n additionalProps: {\n type: 'checkbox',\n icon: /*#__PURE__*/React.cloneElement(icon, {\n fontSize: icon.props.fontSize ?? size\n }),\n checkedIcon: /*#__PURE__*/React.cloneElement(indeterminateIcon, {\n fontSize: indeterminateIcon.props.fontSize ?? size\n }),\n disableRipple,\n slots,\n slotProps: {\n input: mergeSlotProps(typeof externalInputProps === 'function' ? externalInputProps(ownerState) : externalInputProps, {\n 'data-indeterminate': indeterminate\n })\n }\n }\n });\n return /*#__PURE__*/_jsx(RootSlot, {\n ...rootSlotProps,\n classes: classes\n });\n});\nprocess.env.NODE_ENV !== \"production\" ? Checkbox.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * If `true`, the component is checked.\n */\n checked: PropTypes.bool,\n /**\n * The icon to display when the component is checked.\n * @default \n */\n checkedIcon: PropTypes.node,\n /**\n * Override or extend the styles applied to the component.\n */\n classes: PropTypes.object,\n /**\n * @ignore\n */\n className: PropTypes.string,\n /**\n * The color of the component.\n * It supports both default and custom theme colors, which can be added as shown in the\n * [palette customization guide](https://mui.com/material-ui/customization/palette/#custom-colors).\n * @default 'primary'\n */\n color: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['default', 'primary', 'secondary', 'error', 'info', 'success', 'warning']), PropTypes.string]),\n /**\n * The default checked state. Use when the component is not controlled.\n */\n defaultChecked: PropTypes.bool,\n /**\n * If `true`, the component is disabled.\n * @default false\n */\n disabled: PropTypes.bool,\n /**\n * If `true`, the ripple effect is disabled.\n * @default false\n */\n disableRipple: PropTypes.bool,\n /**\n * The icon to display when the component is unchecked.\n * @default \n */\n icon: PropTypes.node,\n /**\n * The id of the `input` element.\n */\n id: PropTypes.string,\n /**\n * If `true`, the component appears indeterminate.\n * This does not set the native input element to indeterminate due\n * to inconsistent behavior across browsers.\n * However, we set a `data-indeterminate` attribute on the `input`.\n * @default false\n */\n indeterminate: PropTypes.bool,\n /**\n * The icon to display when the component is indeterminate.\n * @default \n */\n indeterminateIcon: PropTypes.node,\n /**\n * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element.\n * @deprecated Use `slotProps.input` instead. This prop will be removed in v7. See [Migrating from deprecated APIs](/material-ui/migration/migrating-from-deprecated-apis/) for more details.\n */\n inputProps: PropTypes.object,\n /**\n * Callback fired when the state is changed.\n *\n * @param {React.ChangeEvent} event The event source of the callback.\n * You can pull out the new checked state by accessing `event.target.checked` (boolean).\n */\n onChange: PropTypes.func,\n /**\n * If `true`, the `input` element is required.\n * @default false\n */\n required: PropTypes.bool,\n /**\n * The size of the component.\n * `small` is equivalent to the dense checkbox styling.\n * @default 'medium'\n */\n size: PropTypes /* @typescript-to-proptypes-ignore */.oneOfType([PropTypes.oneOf(['medium', 'small']), PropTypes.string]),\n /**\n * The props used for each slot inside.\n * @default {}\n */\n slotProps: PropTypes.shape({\n input: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),\n root: PropTypes.oneOfType([PropTypes.func, PropTypes.object])\n }),\n /**\n * The components used for each slot inside.\n * @default {}\n */\n slots: PropTypes.shape({\n input: PropTypes.elementType,\n root: PropTypes.elementType\n }),\n /**\n * The system prop that allows defining system overrides as well as additional CSS styles.\n */\n sx: PropTypes.oneOfType([PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object, PropTypes.bool])), PropTypes.func, PropTypes.object]),\n /**\n * The value of the component. The DOM API casts this to a string.\n * The browser uses \"on\" as the default value.\n */\n value: PropTypes.any\n} : void 0;\nexport default Checkbox;","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { elementAcceptingRef, exactProp, unstable_ownerDocument as ownerDocument, unstable_useForkRef as useForkRef, unstable_useEventCallback as useEventCallback } from '@mui/utils';\nimport getReactElementRef from '@mui/utils/getReactElementRef';\n\n// TODO: return `EventHandlerName extends `on${infer EventName}` ? Lowercase : never` once generatePropTypes runs with TS 4.1\nfunction mapEventPropToEvent(eventProp) {\n return eventProp.substring(2).toLowerCase();\n}\nfunction clickedRootScrollbar(event, doc) {\n return doc.documentElement.clientWidth < event.clientX || doc.documentElement.clientHeight < event.clientY;\n}\n/**\n * Listen for click events that occur somewhere in the document, outside of the element itself.\n * For instance, if you need to hide a menu when people click anywhere else on your page.\n *\n * Demos:\n *\n * - [Click-Away Listener](https://mui.com/material-ui/react-click-away-listener/)\n * - [Menu](https://mui.com/material-ui/react-menu/)\n *\n * API:\n *\n * - [ClickAwayListener API](https://mui.com/material-ui/api/click-away-listener/)\n */\nfunction ClickAwayListener(props) {\n const {\n children,\n disableReactTree = false,\n mouseEvent = 'onClick',\n onClickAway,\n touchEvent = 'onTouchEnd'\n } = props;\n const movedRef = React.useRef(false);\n const nodeRef = React.useRef(null);\n const activatedRef = React.useRef(false);\n const syntheticEventRef = React.useRef(false);\n React.useEffect(() => {\n // Ensure that this component is not \"activated\" synchronously.\n // https://github.com/facebook/react/issues/20074\n setTimeout(() => {\n activatedRef.current = true;\n }, 0);\n return () => {\n activatedRef.current = false;\n };\n }, []);\n const handleRef = useForkRef(getReactElementRef(children), nodeRef);\n\n // The handler doesn't take event.defaultPrevented into account:\n //\n // event.preventDefault() is meant to stop default behaviors like\n // clicking a checkbox to check it, hitting a button to submit a form,\n // and hitting left arrow to move the cursor in a text input etc.\n // Only special HTML elements have these default behaviors.\n const handleClickAway = useEventCallback(event => {\n // Given developers can stop the propagation of the synthetic event,\n // we can only be confident with a positive value.\n const insideReactTree = syntheticEventRef.current;\n syntheticEventRef.current = false;\n const doc = ownerDocument(nodeRef.current);\n\n // 1. IE11 support, which trigger the handleClickAway even after the unbind\n // 2. The child might render null.\n // 3. Behave like a blur listener.\n if (!activatedRef.current || !nodeRef.current || 'clientX' in event && clickedRootScrollbar(event, doc)) {\n return;\n }\n\n // Do not act if user performed touchmove\n if (movedRef.current) {\n movedRef.current = false;\n return;\n }\n let insideDOM;\n\n // If not enough, can use https://github.com/DieterHolvoet/event-propagation-path/blob/master/propagationPath.js\n if (event.composedPath) {\n insideDOM = event.composedPath().includes(nodeRef.current);\n } else {\n insideDOM = !doc.documentElement.contains(\n // @ts-expect-error returns `false` as intended when not dispatched from a Node\n event.target) || nodeRef.current.contains(\n // @ts-expect-error returns `false` as intended when not dispatched from a Node\n event.target);\n }\n if (!insideDOM && (disableReactTree || !insideReactTree)) {\n onClickAway(event);\n }\n });\n\n // Keep track of mouse/touch events that bubbled up through the portal.\n const createHandleSynthetic = handlerName => event => {\n syntheticEventRef.current = true;\n const childrenPropsHandler = children.props[handlerName];\n if (childrenPropsHandler) {\n childrenPropsHandler(event);\n }\n };\n const childrenProps = {\n ref: handleRef\n };\n if (touchEvent !== false) {\n childrenProps[touchEvent] = createHandleSynthetic(touchEvent);\n }\n React.useEffect(() => {\n if (touchEvent !== false) {\n const mappedTouchEvent = mapEventPropToEvent(touchEvent);\n const doc = ownerDocument(nodeRef.current);\n const handleTouchMove = () => {\n movedRef.current = true;\n };\n doc.addEventListener(mappedTouchEvent, handleClickAway);\n doc.addEventListener('touchmove', handleTouchMove);\n return () => {\n doc.removeEventListener(mappedTouchEvent, handleClickAway);\n doc.removeEventListener('touchmove', handleTouchMove);\n };\n }\n return undefined;\n }, [handleClickAway, touchEvent]);\n if (mouseEvent !== false) {\n childrenProps[mouseEvent] = createHandleSynthetic(mouseEvent);\n }\n React.useEffect(() => {\n if (mouseEvent !== false) {\n const mappedMouseEvent = mapEventPropToEvent(mouseEvent);\n const doc = ownerDocument(nodeRef.current);\n doc.addEventListener(mappedMouseEvent, handleClickAway);\n return () => {\n doc.removeEventListener(mappedMouseEvent, handleClickAway);\n };\n }\n return undefined;\n }, [handleClickAway, mouseEvent]);\n return /*#__PURE__*/React.cloneElement(children, childrenProps);\n}\nprocess.env.NODE_ENV !== \"production\" ? ClickAwayListener.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the TypeScript types and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * The wrapped element.\n */\n children: elementAcceptingRef.isRequired,\n /**\n * If `true`, the React tree is ignored and only the DOM tree is considered.\n * This prop changes how portaled elements are handled.\n * @default false\n */\n disableReactTree: PropTypes.bool,\n /**\n * The mouse event to listen to. You can disable the listener by providing `false`.\n * @default 'onClick'\n */\n mouseEvent: PropTypes.oneOf(['onClick', 'onMouseDown', 'onMouseUp', 'onPointerDown', 'onPointerUp', false]),\n /**\n * Callback fired when a \"click away\" event is detected.\n */\n onClickAway: PropTypes.func.isRequired,\n /**\n * The touch event to listen to. You can disable the listener by providing `false`.\n * @default 'onTouchEnd'\n */\n touchEvent: PropTypes.oneOf(['onTouchEnd', 'onTouchStart', false])\n} : void 0;\nif (process.env.NODE_ENV !== 'production') {\n // eslint-disable-next-line\n ClickAwayListener['propTypes' + ''] = exactProp(ClickAwayListener.propTypes);\n}\nexport { ClickAwayListener };","'use client';\n\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { globalCss } from \"../zero-styled/index.js\";\nimport { useDefaultProps } from \"../DefaultPropsProvider/index.js\";\n\n// to determine if the global styles are static or dynamic\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\nconst isDynamicSupport = typeof globalCss({}) === 'function';\nexport const html = (theme, enableColorScheme) => ({\n WebkitFontSmoothing: 'antialiased',\n // Antialiasing.\n MozOsxFontSmoothing: 'grayscale',\n // Antialiasing.\n // Change from `box-sizing: content-box` so that `width`\n // is not affected by `padding` or `border`.\n boxSizing: 'border-box',\n // Fix font resize problem in iOS\n WebkitTextSizeAdjust: '100%',\n // When used under CssVarsProvider, colorScheme should not be applied dynamically because it will generate the stylesheet twice for server-rendered applications.\n ...(enableColorScheme && !theme.vars && {\n colorScheme: theme.palette.mode\n })\n});\nexport const body = theme => ({\n color: (theme.vars || theme).palette.text.primary,\n ...theme.typography.body1,\n backgroundColor: (theme.vars || theme).palette.background.default,\n '@media print': {\n // Save printer ink.\n backgroundColor: (theme.vars || theme).palette.common.white\n }\n});\nexport const styles = (theme, enableColorScheme = false) => {\n const colorSchemeStyles = {};\n if (enableColorScheme && theme.colorSchemes && typeof theme.getColorSchemeSelector === 'function') {\n Object.entries(theme.colorSchemes).forEach(([key, scheme]) => {\n const selector = theme.getColorSchemeSelector(key);\n if (selector.startsWith('@')) {\n // for @media (prefers-color-scheme), we need to target :root\n colorSchemeStyles[selector] = {\n ':root': {\n colorScheme: scheme.palette?.mode\n }\n };\n } else {\n // else, it's likely that the selector already target an element with a class or data attribute\n colorSchemeStyles[selector.replace(/\\s*&/, '')] = {\n colorScheme: scheme.palette?.mode\n };\n }\n });\n }\n let defaultStyles = {\n html: html(theme, enableColorScheme),\n '*, *::before, *::after': {\n boxSizing: 'inherit'\n },\n 'strong, b': {\n fontWeight: theme.typography.fontWeightBold\n },\n body: {\n margin: 0,\n // Remove the margin in all browsers.\n ...body(theme),\n // Add support for document.body.requestFullScreen().\n // Other elements, if background transparent, are not supported.\n '&::backdrop': {\n backgroundColor: (theme.vars || theme).palette.background.default\n }\n },\n ...colorSchemeStyles\n };\n const themeOverrides = theme.components?.MuiCssBaseline?.styleOverrides;\n if (themeOverrides) {\n defaultStyles = [defaultStyles, themeOverrides];\n }\n return defaultStyles;\n};\n\n// `ecs` stands for enableColorScheme. This is internal logic to make it work with Pigment CSS, so shorter is better.\nconst SELECTOR = 'mui-ecs';\nconst staticStyles = theme => {\n const result = styles(theme, false);\n const baseStyles = Array.isArray(result) ? result[0] : result;\n if (!theme.vars && baseStyles) {\n baseStyles.html[`:root:has(${SELECTOR})`] = {\n colorScheme: theme.palette.mode\n };\n }\n if (theme.colorSchemes) {\n Object.entries(theme.colorSchemes).forEach(([key, scheme]) => {\n const selector = theme.getColorSchemeSelector(key);\n if (selector.startsWith('@')) {\n // for @media (prefers-color-scheme), we need to target :root\n baseStyles[selector] = {\n [`:root:not(:has(.${SELECTOR}))`]: {\n colorScheme: scheme.palette?.mode\n }\n };\n } else {\n // else, it's likely that the selector already target an element with a class or data attribute\n baseStyles[selector.replace(/\\s*&/, '')] = {\n [`&:not(:has(.${SELECTOR}))`]: {\n colorScheme: scheme.palette?.mode\n }\n };\n }\n });\n }\n return result;\n};\nconst GlobalStyles = globalCss(isDynamicSupport ? ({\n theme,\n enableColorScheme\n}) => styles(theme, enableColorScheme) : ({\n theme\n}) => staticStyles(theme));\n\n/**\n * Kickstart an elegant, consistent, and simple baseline to build upon.\n */\nfunction CssBaseline(inProps) {\n const props = useDefaultProps({\n props: inProps,\n name: 'MuiCssBaseline'\n });\n const {\n children,\n enableColorScheme = false\n } = props;\n return /*#__PURE__*/_jsxs(React.Fragment, {\n children: [isDynamicSupport && /*#__PURE__*/_jsx(GlobalStyles, {\n enableColorScheme: enableColorScheme\n }), !isDynamicSupport && !enableColorScheme && /*#__PURE__*/_jsx(\"span\", {\n className: SELECTOR,\n style: {\n display: 'none'\n }\n }), children]\n });\n}\nprocess.env.NODE_ENV !== \"production\" ? CssBaseline.propTypes /* remove-proptypes */ = {\n // ┌────────────────────────────── Warning ──────────────────────────────┐\n // │ These PropTypes are generated from the TypeScript type definitions. │\n // │ To update them, edit the d.ts file and run `pnpm proptypes`. │\n // └─────────────────────────────────────────────────────────────────────┘\n /**\n * You can wrap a node.\n */\n children: PropTypes.node,\n /**\n * Enable `color-scheme` CSS property to use `theme.palette.mode`.\n * For more details, check out https://developer.mozilla.org/en-US/docs/Web/CSS/color-scheme\n * For browser support, check out https://caniuse.com/?search=color-scheme\n * @default false\n */\n enableColorScheme: PropTypes.bool\n} : void 0;\nexport default CssBaseline;","import { unstable_ownerWindow as ownerWindow, unstable_ownerDocument as ownerDocument, unstable_getScrollbarSize as getScrollbarSize } from '@mui/utils';\n// Is a vertical scrollbar displayed?\nfunction isOverflowing(container) {\n const doc = ownerDocument(container);\n if (doc.body === container) {\n return ownerWindow(container).innerWidth > doc.documentElement.clientWidth;\n }\n return container.scrollHeight > container.clientHeight;\n}\nexport function ariaHidden(element, hide) {\n if (hide) {\n element.setAttribute('aria-hidden', 'true');\n } else {\n element.removeAttribute('aria-hidden');\n }\n}\nfunction getPaddingRight(element) {\n return parseInt(ownerWindow(element).getComputedStyle(element).paddingRight, 10) || 0;\n}\nfunction isAriaHiddenForbiddenOnElement(element) {\n // The forbidden HTML tags are the ones from ARIA specification that\n // can be children of body and can't have aria-hidden attribute.\n // cf. https://www.w3.org/TR/html-aria/#docconformance\n const forbiddenTagNames = ['TEMPLATE', 'SCRIPT', 'STYLE', 'LINK', 'MAP', 'META', 'NOSCRIPT', 'PICTURE', 'COL', 'COLGROUP', 'PARAM', 'SLOT', 'SOURCE', 'TRACK'];\n const isForbiddenTagName = forbiddenTagNames.includes(element.tagName);\n const isInputHidden = element.tagName === 'INPUT' && element.getAttribute('type') === 'hidden';\n return isForbiddenTagName || isInputHidden;\n}\nfunction ariaHiddenSiblings(container, mountElement, currentElement, elementsToExclude, hide) {\n const blacklist = [mountElement, currentElement, ...elementsToExclude];\n [].forEach.call(container.children, element => {\n const isNotExcludedElement = !blacklist.includes(element);\n const isNotForbiddenElement = !isAriaHiddenForbiddenOnElement(element);\n if (isNotExcludedElement && isNotForbiddenElement) {\n ariaHidden(element, hide);\n }\n });\n}\nfunction findIndexOf(items, callback) {\n let idx = -1;\n items.some((item, index) => {\n if (callback(item)) {\n idx = index;\n return true;\n }\n return false;\n });\n return idx;\n}\nfunction handleContainer(containerInfo, props) {\n const restoreStyle = [];\n const container = containerInfo.container;\n if (!props.disableScrollLock) {\n if (isOverflowing(container)) {\n // Compute the size before applying overflow hidden to avoid any scroll jumps.\n const scrollbarSize = getScrollbarSize(ownerWindow(container));\n restoreStyle.push({\n value: container.style.paddingRight,\n property: 'padding-right',\n el: container\n });\n // Use computed style, here to get the real padding to add our scrollbar width.\n container.style.paddingRight = `${getPaddingRight(container) + scrollbarSize}px`;\n\n // .mui-fixed is a global helper.\n const fixedElements = ownerDocument(container).querySelectorAll('.mui-fixed');\n [].forEach.call(fixedElements, element => {\n restoreStyle.push({\n value: element.style.paddingRight,\n property: 'padding-right',\n el: element\n });\n element.style.paddingRight = `${getPaddingRight(element) + scrollbarSize}px`;\n });\n }\n let scrollContainer;\n if (container.parentNode instanceof DocumentFragment) {\n scrollContainer = ownerDocument(container).body;\n } else {\n // Support html overflow-y: auto for scroll stability between pages\n // https://css-tricks.com/snippets/css/force-vertical-scrollbar/\n const parent = container.parentElement;\n const containerWindow = ownerWindow(container);\n scrollContainer = parent?.nodeName === 'HTML' && containerWindow.getComputedStyle(parent).overflowY === 'scroll' ? parent : container;\n }\n\n // Block the scroll even if no scrollbar is visible to account for mobile keyboard\n // screensize shrink.\n restoreStyle.push({\n value: scrollContainer.style.overflow,\n property: 'overflow',\n el: scrollContainer\n }, {\n value: scrollContainer.style.overflowX,\n property: 'overflow-x',\n el: scrollContainer\n }, {\n value: scrollContainer.style.overflowY,\n property: 'overflow-y',\n el: scrollContainer\n });\n scrollContainer.style.overflow = 'hidden';\n }\n const restore = () => {\n restoreStyle.forEach(({\n value,\n el,\n property\n }) => {\n if (value) {\n el.style.setProperty(property, value);\n } else {\n el.style.removeProperty(property);\n }\n });\n };\n return restore;\n}\nfunction getHiddenSiblings(container) {\n const hiddenSiblings = [];\n [].forEach.call(container.children, element => {\n if (element.getAttribute('aria-hidden') === 'true') {\n hiddenSiblings.push(element);\n }\n });\n return hiddenSiblings;\n}\n/**\n * @ignore - do not document.\n *\n * Proper state management for containers and the modals in those containers.\n * Simplified, but inspired by react-overlay's ModalManager class.\n * Used by the Modal to ensure proper styling of containers.\n */\nexport class ModalManager {\n constructor() {\n this.modals = [];\n this.containers = [];\n }\n add(modal, container) {\n let modalIndex = this.modals.indexOf(modal);\n if (modalIndex !== -1) {\n return modalIndex;\n }\n modalIndex = this.modals.length;\n this.modals.push(modal);\n\n // If the modal we are adding is already in the DOM.\n if (modal.modalRef) {\n ariaHidden(modal.modalRef, false);\n }\n const hiddenSiblings = getHiddenSiblings(container);\n ariaHiddenSiblings(container, modal.mount, modal.modalRef, hiddenSiblings, true);\n const containerIndex = findIndexOf(this.containers, item => item.container === container);\n if (containerIndex !== -1) {\n this.containers[containerIndex].modals.push(modal);\n return modalIndex;\n }\n this.containers.push({\n modals: [modal],\n container,\n restore: null,\n hiddenSiblings\n });\n return modalIndex;\n }\n mount(modal, props) {\n const containerIndex = findIndexOf(this.containers, item => item.modals.includes(modal));\n const containerInfo = this.containers[containerIndex];\n if (!containerInfo.restore) {\n containerInfo.restore = handleContainer(containerInfo, props);\n }\n }\n remove(modal, ariaHiddenState = true) {\n const modalIndex = this.modals.indexOf(modal);\n if (modalIndex === -1) {\n return modalIndex;\n }\n const containerIndex = findIndexOf(this.containers, item => item.modals.includes(modal));\n const containerInfo = this.containers[containerIndex];\n containerInfo.modals.splice(containerInfo.modals.indexOf(modal), 1);\n this.modals.splice(modalIndex, 1);\n\n // If that was the last modal in a container, clean up the container.\n if (containerInfo.modals.length === 0) {\n // The modal might be closed before it had the chance to be mounted in the DOM.\n if (containerInfo.restore) {\n containerInfo.restore();\n }\n if (modal.modalRef) {\n // In case the modal wasn't in the DOM yet.\n ariaHidden(modal.modalRef, ariaHiddenState);\n }\n ariaHiddenSiblings(containerInfo.container, modal.mount, modal.modalRef, containerInfo.hiddenSiblings, false);\n this.containers.splice(containerIndex, 1);\n } else {\n // Otherwise make sure the next top modal is visible to a screen reader.\n const nextTop = containerInfo.modals[containerInfo.modals.length - 1];\n // as soon as a modal is adding its modalRef is undefined. it can't set\n // aria-hidden because the dom element doesn't exist either\n // when modal was unmounted before modalRef gets null\n if (nextTop.modalRef) {\n ariaHidden(nextTop.modalRef, false);\n }\n }\n return modalIndex;\n }\n isTopModal(modal) {\n return this.modals.length > 0 && this.modals[this.modals.length - 1] === modal;\n }\n}","'use client';\n\n/* eslint-disable consistent-return, jsx-a11y/no-noninteractive-tabindex */\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { exactProp, elementAcceptingRef, unstable_useForkRef as useForkRef, unstable_ownerDocument as ownerDocument, unstable_getReactElementRef as getReactElementRef } from '@mui/utils';\nimport { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\n// Inspired by https://github.com/focus-trap/tabbable\nconst candidatesSelector = ['input', 'select', 'textarea', 'a[href]', 'button', '[tabindex]', 'audio[controls]', 'video[controls]', '[contenteditable]:not([contenteditable=\"false\"])'].join(',');\nfunction getTabIndex(node) {\n const tabindexAttr = parseInt(node.getAttribute('tabindex') || '', 10);\n if (!Number.isNaN(tabindexAttr)) {\n return tabindexAttr;\n }\n\n // Browsers do not return `tabIndex` correctly for contentEditable nodes;\n // https://issues.chromium.org/issues/41283952\n // so if they don't have a tabindex attribute specifically set, assume it's 0.\n // in Chrome,
,