{"version":3,"file":"main.22d1ed8389cf9c62.js","sources":["./apps/snowylive-app/src/app/alert/alert.service.ts","./apps/snowylive-app/src/app/cache/data-config.ts","./apps/snowylive-app/src/app/cache/db-config.ts","./node_modules/compare-versions/lib/esm/compare.js","./apps/snowylive-app/src/app/cache/db.service.ts","./node_modules/rxjs/dist/esm/internal/firstValueFrom.js","./apps/snowylive-app/src/app/contentful/contentful.actions.ts","./apps/snowylive-app/src/app/contentful/contentful.reducer.ts","./apps/snowylive-app/src/app/contentful/contentful.selectors.ts","./node_modules/@capacitor-community/keep-awake/dist/esm/index.js","./apps/snowylive-app/src/app/contentful/contentful.service.ts","./apps/snowylive-app/src/app/contentful/contentful.ts","./apps/snowylive-app/src/app/favourites/favourites.actions.ts","./apps/snowylive-app/src/app/favourites/favourites.models.ts","./node_modules/@ngrx/entity/fesm2022/ngrx-entity.mjs","./apps/snowylive-app/src/app/favourites/favourites.reducer.ts","./apps/snowylive-app/src/app/favourites/favourites.selectors.ts","./apps/snowylive-app/src/app/favourites/favourites.service.ts","./apps/snowylive-app/src/app/home/home.service.ts","./apps/snowylive-app/src/app/lake-levels/lake-levels.service.ts","./apps/snowylive-app/src/app/models/Description.ts","./apps/snowylive-app/src/app/models/Item.ts","./apps/snowylive-app/src/app/models/LakeLevel.ts","./apps/snowylive-app/src/app/models/PublicAccess.ts","./apps/snowylive-app/src/app/models/Scheme.ts","./apps/snowylive-app/src/app/models/SnowDepth.ts","./apps/snowylive-app/src/app/models/WaterRelease.ts","./apps/snowylive-app/src/app/public-access/public-access.service.ts","./node_modules/rambda/src/_internals/cloneList.js","./node_modules/rambda/src/curry.js","./node_modules/rambda/src/adjust.js","./node_modules/rambda/src/any.js","./node_modules/rambda/src/assoc.js","./node_modules/rambda/src/both.js","./node_modules/rambda/src/complement.js","./node_modules/rambda/src/concat.js","./node_modules/rambda/src/defaultTo.js","./node_modules/rambda/src/dissoc.js","./node_modules/rambda/src/either.js","./node_modules/rambda/src/_internals/isArray.js","./node_modules/rambda/src/type.js","./node_modules/rambda/src/equals.js","./node_modules/rambda/src/filter.js","./node_modules/rambda/src/find.js","./node_modules/rambda/src/flatten.js","./node_modules/rambda/src/flip.js","./node_modules/rambda/src/groupBy.js","./node_modules/rambda/src/has.js","./node_modules/rambda/src/includes.js","./node_modules/rambda/src/is.js","./node_modules/rambda/src/isEmpty.js","./node_modules/rambda/src/match.js","./node_modules/rambda/src/mergeRight.js","./node_modules/rambda/src/_internals/constants.js","./node_modules/rambda/src/_internals/keys.js","./node_modules/rambda/src/map.js","./node_modules/rambda/src/mergeAll.js","./node_modules/rambda/src/multiply.js","./node_modules/rambda/src/negate.js","./node_modules/rambda/src/_internals/createPath.js","./node_modules/rambda/src/omit.js","./node_modules/rambda/src/path.js","./node_modules/rambda/src/pathOr.js","./node_modules/rambda/src/pick.js","./node_modules/rambda/src/pluck.js","./node_modules/rambda/src/prop.js","./node_modules/rambda/src/range.js","./node_modules/rambda/src/reduce.js","./node_modules/rambda/src/replace.js","./node_modules/rambda/src/sortBy.js","./node_modules/rambda/src/sum.js","./node_modules/rambda/src/toLower.js","./node_modules/rambda/src/toPairs.js","./node_modules/rambda/src/values.js","./node_modules/ramda/es/internal/_isPlaceholder.js","./node_modules/ramda/es/internal/_curry1.js","./node_modules/ramda/es/internal/_curry2.js","./node_modules/ramda/es/add.js","./node_modules/ramda/es/internal/_isArray.js","./node_modules/ramda/es/internal/_dispatchable.js","./node_modules/ramda/es/internal/_isTransformer.js","./node_modules/ramda/es/internal/_reduced.js","./node_modules/ramda/es/internal/_xfBase.js","./node_modules/ramda/es/internal/_xall.js","./node_modules/ramda/es/all.js","./node_modules/ramda/es/internal/_arrayFromIterator.js","./node_modules/ramda/es/internal/_includesWith.js","./node_modules/ramda/es/internal/_has.js","./node_modules/ramda/es/internal/_objectIs.js","./node_modules/ramda/es/internal/_isArguments.js","./node_modules/ramda/es/keys.js","./node_modules/ramda/es/type.js","./node_modules/ramda/es/internal/_equals.js","./node_modules/ramda/es/internal/_functionName.js","./node_modules/ramda/es/equals.js","./node_modules/ramda/es/internal/_includes.js","./node_modules/ramda/es/internal/_indexOf.js","./node_modules/ramda/es/internal/_map.js","./node_modules/ramda/es/internal/_quote.js","./node_modules/ramda/es/internal/_toISOString.js","./node_modules/ramda/es/internal/_arrayReduce.js","./node_modules/ramda/es/internal/_filter.js","./node_modules/ramda/es/internal/_isObject.js","./node_modules/ramda/es/internal/_xfilter.js","./node_modules/ramda/es/filter.js","./node_modules/ramda/es/reject.js","./node_modules/ramda/es/internal/_complement.js","./node_modules/ramda/es/internal/_toString.js","./node_modules/ramda/es/toString.js","./node_modules/ramda/es/max.js","./node_modules/ramda/es/internal/_xmap.js","./node_modules/ramda/es/internal/_arity.js","./node_modules/ramda/es/internal/_curryN.js","./node_modules/ramda/es/curryN.js","./node_modules/ramda/es/map.js","./node_modules/ramda/es/internal/_isInteger.js","./node_modules/ramda/es/internal/_isString.js","./node_modules/ramda/es/nth.js","./node_modules/ramda/es/prop.js","./node_modules/ramda/es/pluck.js","./node_modules/ramda/es/internal/_curry3.js","./node_modules/ramda/es/internal/_isArrayLike.js","./node_modules/ramda/es/internal/_createReduce.js","./node_modules/ramda/es/internal/_xArrayReduce.js","./node_modules/ramda/es/bind.js","./node_modules/ramda/es/internal/_xReduce.js","./node_modules/ramda/es/internal/_xwrap.js","./node_modules/ramda/es/reduce.js","./node_modules/ramda/es/and.js","./node_modules/ramda/es/anyPass.js","./node_modules/ramda/es/apply.js","./node_modules/ramda/es/values.js","./node_modules/ramda/es/applySpec.js","./node_modules/ramda/es/ascend.js","./node_modules/ramda/es/isNil.js","./node_modules/ramda/es/assocPath.js","./node_modules/ramda/es/internal/_assoc.js","./node_modules/ramda/es/assoc.js","./node_modules/ramda/es/internal/_flatCat.js","./node_modules/ramda/es/internal/_forceReduced.js","./node_modules/ramda/es/internal/_xchain.js","./node_modules/ramda/es/chain.js","./node_modules/ramda/es/internal/_makeFlat.js","./node_modules/ramda/es/internal/_clone.js","./node_modules/ramda/es/internal/_cloneRegExp.js","./node_modules/ramda/es/clone.js","./node_modules/ramda/es/comparator.js","./node_modules/ramda/es/internal/_pipe.js","./node_modules/ramda/es/internal/_checkForMethod.js","./node_modules/ramda/es/slice.js","./node_modules/ramda/es/tail.js","./node_modules/ramda/es/pipe.js","./node_modules/ramda/es/reverse.js","./node_modules/ramda/es/compose.js","./node_modules/ramda/es/converge.js","./node_modules/ramda/es/internal/_xreduceBy.js","./node_modules/ramda/es/reduceBy.js","./node_modules/ramda/es/curry.js","./node_modules/ramda/es/descend.js","./node_modules/ramda/es/internal/_Set.js","./node_modules/ramda/es/difference.js","./node_modules/ramda/es/differenceWith.js","./node_modules/ramda/es/internal/_xtake.js","./node_modules/ramda/es/take.js","./node_modules/ramda/es/eqProps.js","./node_modules/ramda/es/forEach.js","./node_modules/ramda/es/groupWith.js","./node_modules/ramda/es/gt.js","./node_modules/ramda/es/internal/_identity.js","./node_modules/ramda/es/identity.js","./node_modules/ramda/es/ifElse.js","./node_modules/ramda/es/indexBy.js","./node_modules/ramda/es/internal/_xuniqBy.js","./node_modules/ramda/es/uniqBy.js","./node_modules/ramda/es/uniq.js","./node_modules/ramda/es/intersection.js","./node_modules/ramda/es/internal/_objectAssign.js","./node_modules/ramda/es/invoker.js","./node_modules/ramda/es/internal/_isFunction.js","./node_modules/ramda/es/isNotNil.js","./node_modules/ramda/es/join.js","./node_modules/ramda/es/juxt.js","./node_modules/ramda/es/length.js","./node_modules/ramda/es/internal/_isNumber.js","./node_modules/ramda/es/lens.js","./node_modules/ramda/es/paths.js","./node_modules/ramda/es/path.js","./node_modules/ramda/es/lensPath.js","./node_modules/ramda/es/lensProp.js","./node_modules/ramda/es/lt.js","./node_modules/ramda/es/mergeWithKey.js","./node_modules/ramda/es/mergeDeepWithKey.js","./node_modules/ramda/es/mergeDeepLeft.js","./node_modules/ramda/es/mergeDeepRight.js","./node_modules/ramda/es/mergeRight.js","./node_modules/ramda/es/mergeWith.js","./node_modules/ramda/es/not.js","./node_modules/ramda/es/or.js","./node_modules/ramda/es/over.js","./node_modules/ramda/es/partition.js","./node_modules/ramda/es/pickBy.js","./node_modules/ramda/es/propEq.js","./node_modules/ramda/es/defaultTo.js","./node_modules/ramda/es/propOr.js","./node_modules/ramda/es/props.js","./node_modules/ramda/es/remove.js","./node_modules/ramda/es/always.js","./node_modules/ramda/es/set.js","./node_modules/ramda/es/sort.js","./node_modules/ramda/es/sortWith.js","./node_modules/ramda/es/startsWith.js","./node_modules/ramda/es/view.js","./node_modules/ramda/es/when.js","./node_modules/ramda/es/without.js","./apps/snowylive-app/src/app/ramda-functions.ts","./apps/snowylive-app/src/app/shared/services/platform.service.ts","./apps/snowylive-app/src/app/shared/services/toast.service.ts","./apps/snowylive-app/src/app/shared/ui/header/header.component.html","./apps/snowylive-app/src/app/shared/ui/header/header.component.ts","./apps/snowylive-app/src/app/snow-depths/snow-depths.service.ts","./apps/snowylive-app/src/app/update/mobile/mobile-update.service.ts","./apps/snowylive-app/src/app/update/update.utils.ts","./apps/snowylive-app/src/app/visit-the-scheme/visit-the-scheme.service.ts","./apps/snowylive-app/src/app/water-releases/water-releases.service.ts","./apps/snowylive-app/src/environments/environment.prod.ts","./apps/snowylive-app/src/app/contentful/contentful.effects.ts","./apps/snowylive-app/src/app/info/info.component.ts","./apps/snowylive-app/src/app/info/info.component.html","./apps/snowylive-app/src/app/contact-us/contact-us.component.ts","./apps/snowylive-app/src/app/contact-us/contact-us.component.html","./apps/snowylive-app/src/app/favourites/favourites.effects.ts","./apps/snowylive-app/src/app/app.routes.ts","./node_modules/rxjs/dist/esm/internal/observable/never.js","./node_modules/rxjs/dist/esm/internal/operators/connect.js","./node_modules/rxjs/dist/esm/internal/observable/fromSubscribable.js","./node_modules/rxjs/dist/esm/internal/operators/delayWhen.js","./node_modules/rxjs/dist/esm/internal/observable/timer.js","./node_modules/rxjs/dist/esm/internal/operators/delay.js","./node_modules/@angular/service-worker/fesm2022/service-worker.mjs","./node_modules/rxjs/dist/esm/internal/operators/publish.js","./node_modules/rxjs/dist/esm/internal/operators/multicast.js","./node_modules/@ionic/storage-angular/fesm2020/ionic-storage-angular.mjs","./node_modules/ngrx-store-localstorage/fesm2022/ngrx-store-localstorage.mjs","./apps/snowylive-app/src/app/reducers/persistence-keys.ts","./apps/snowylive-app/src/app/reducers/index.ts","./node_modules/@sentry/utils/esm/is.js","./node_modules/@sentry/utils/esm/browser.js","./node_modules/@sentry/utils/esm/logger.js","./node_modules/@sentry/utils/esm/string.js","./node_modules/@sentry/utils/esm/object.js","./node_modules/@sentry/utils/esm/misc.js","./node_modules/@sentry/core/esm/constants.js","./node_modules/@sentry/utils/esm/syncpromise.js","./node_modules/@sentry/core/esm/eventProcessors.js","./node_modules/@sentry/core/esm/session.js","./node_modules/@sentry/core/esm/scope.js","./node_modules/@sentry/core/esm/hub.js","./node_modules/@sentry/core/esm/exports.js","./node_modules/@sentry/core/esm/integrations/inboundfilters.js","./node_modules/@sentry/core/esm/integrations/functiontostring.js","./node_modules/@sentry/core/esm/integration.js","./node_modules/@sentry/utils/esm/dsn.js","./node_modules/@sentry/core/esm/api.js","./node_modules/@sentry/utils/esm/stacktrace.js","./node_modules/@sentry/utils/esm/supports.js","./node_modules/@sentry/utils/esm/vendor/supportsHistory.js","./node_modules/@sentry/utils/esm/instrument.js","./node_modules/@sentry/utils/esm/normalize.js","./node_modules/@sentry/utils/esm/memo.js","./node_modules/@sentry/utils/esm/envelope.js","./node_modules/@sentry/utils/esm/error.js","./node_modules/@sentry/core/esm/tracing/dynamicSamplingContext.js","./node_modules/@sentry/core/esm/utils/prepareEvent.js","./node_modules/@sentry/core/esm/baseclient.js","./node_modules/@sentry/core/esm/envelope.js","./node_modules/@sentry/core/esm/version.js","./node_modules/@sentry/browser/esm/eventbuilder.js","./node_modules/@sentry/browser/esm/helpers.js","./node_modules/@sentry/browser/esm/client.js","./node_modules/@sentry/browser/esm/userfeedback.js","./node_modules/@sentry/utils/esm/clientreport.js","./node_modules/@sentry/browser/esm/integrations/globalhandlers.js","./node_modules/@sentry/browser/esm/integrations/trycatch.js","./node_modules/@sentry/utils/esm/severity.js","./node_modules/@sentry/utils/esm/url.js","./node_modules/@sentry/browser/esm/integrations/breadcrumbs.js","./node_modules/@sentry/utils/esm/aggregate-errors.js","./node_modules/@sentry/browser/esm/integrations/linkederrors.js","./node_modules/@sentry/browser/esm/integrations/httpcontext.js","./node_modules/@sentry/browser/esm/integrations/dedupe.js","./node_modules/@sentry/browser/esm/stack-parsers.js","./node_modules/@sentry/utils/esm/promisebuffer.js","./node_modules/@sentry/utils/esm/ratelimit.js","./node_modules/@sentry/core/esm/transports/base.js","./node_modules/@sentry/browser/esm/transports/utils.js","./node_modules/@sentry/browser/esm/transports/fetch.js","./node_modules/@sentry/browser/esm/transports/xhr.js","./node_modules/@sentry/browser/esm/sdk.js","./node_modules/@sentry/core/esm/sdk.js","./node_modules/@sentry/angular-ivy/fesm2015/sentry-angular-ivy.js","./apps/snowylive-app/src/app/app.config.ts","./apps/snowylive-app/src/app/update/pwa/check-update.service.ts","./node_modules/rxjs/dist/esm/internal/observable/interval.js","./apps/snowylive-app/src/app/update/pwa/log-update.service.ts","./apps/snowylive-app/src/app/update/pwa/prompt-update.service.ts","./apps/snowylive-app/src/app/update/pwa/unrecoverable-state.service.ts","./apps/snowylive-app/src/app/app.component.ts","./apps/snowylive-app/src/app/app.component.html","./node_modules/@sentry/capacitor/dist/esm/integrations/eventorigin.js","./node_modules/@sentry/capacitor/dist/esm/plugin.js","./node_modules/@sentry/capacitor/dist/esm/utils/normalize.js","./node_modules/@sentry/capacitor/dist/esm/vendor/buffer/utf8ToBytes.js","./node_modules/@sentry/capacitor/dist/esm/wrapper.js","./node_modules/@sentry/capacitor/dist/esm/nativeOptions.js","./node_modules/@sentry/capacitor/dist/esm/integrations/sdkinfo.js","./node_modules/@sentry/capacitor/dist/esm/version.js","./node_modules/@sentry/capacitor/dist/esm/integrations/release.js","./node_modules/@sentry/capacitor/dist/esm/integrations/devicecontext.js","./node_modules/@sentry/utils/esm/path.js","./node_modules/@sentry/integrations/esm/rewriteframes.js","./node_modules/@sentry/capacitor/dist/esm/integrations/rewriteframes.js","./node_modules/@sentry/capacitor/dist/esm/utils/webViewUrl.js","./node_modules/@sentry/capacitor/dist/esm/scope.js","./node_modules/@sentry/capacitor/dist/esm/transports/native.js","./node_modules/@sentry/utils/esm/baggage.js","./node_modules/@sentry/utils/esm/tracing.js","./node_modules/@sentry/core/esm/tracing/span.js","./node_modules/@sentry/core/esm/tracing/transaction.js","./node_modules/@sentry/core/esm/tracing/idletransaction.js","./node_modules/@sentry/core/esm/tracing/utils.js","./node_modules/@sentry/core/esm/tracing/errors.js","./node_modules/@sentry/core/esm/utils/hasTracingEnabled.js","./node_modules/@sentry/core/esm/tracing/sampling.js","./node_modules/@sentry/core/esm/tracing/hubextensions.js","./node_modules/@sentry-internal/tracing/esm/browser/types.js","./node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/bindReporter.js","./node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/getNavigationEntry.js","./node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/getActivationStart.js","./node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/initMetric.js","./node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/generateUniqueID.js","./node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/observe.js","./node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/onHidden.js","./node_modules/@sentry-internal/tracing/esm/browser/web-vitals/getCLS.js","./node_modules/@sentry-internal/tracing/esm/browser/web-vitals/lib/getVisibilityWatcher.js","./node_modules/@sentry-internal/tracing/esm/browser/web-vitals/getFID.js","./node_modules/@sentry-internal/tracing/esm/browser/web-vitals/getLCP.js","./node_modules/@sentry-internal/tracing/esm/browser/instrument.js","./node_modules/@sentry-internal/tracing/esm/browser/metrics/utils.js","./node_modules/@sentry-internal/tracing/esm/browser/metrics/index.js","./node_modules/@sentry-internal/tracing/esm/browser/request.js","./node_modules/@sentry-internal/tracing/esm/common/fetch.js","./node_modules/@sentry-internal/tracing/esm/browser/browsertracing.js","./node_modules/@sentry-internal/tracing/esm/browser/router.js","./node_modules/@sentry/capacitor/dist/esm/sdk.js","./node_modules/@sentry/capacitor/dist/esm/transports/TextEncoder.js","./apps/snowylive-app/src/main.ts","./node_modules/@sentry-internal/tracing/esm/browser/backgroundtab.js","./node_modules/@capacitor/core/dist/index.js","./node_modules/@contentful/rich-text-html-renderer/dist/rich-text-html-renderer.es5.js","./node_modules/@ionic/core/components/helpers.js","./node_modules/@ionic/core/components/index2.js","./node_modules/@ionic/core/dist/esm/animation-8aa13916.js","./node_modules/@ionic/core/dist/esm/config-96c9ace3.js","./node_modules/@ionic/core/dist/esm/framework-delegate-aa433dea.js","./node_modules/@ionic/core/dist/esm/gesture-controller-0fa396c4.js","./node_modules/@ionic/core/dist/esm/hardware-back-button-39299f84.js","./node_modules/@ionic/core/dist/esm/helpers-3379ba19.js","./node_modules/@ionic/core/dist/esm/index-0aa6e61f.js","./node_modules/@ionic/core/dist/esm/index-595d62c9.js","./node_modules/@ionic/core/dist/esm/index-6a0ccabb.js","./node_modules/@ionic/core/dist/esm/index-7a14ecec.js","./node_modules/@ionic/core/dist/esm/index-7c9b1bca.js","./node_modules/@ionic/core/dist/esm/index-ff313b19.js","./node_modules/@ionic/core/dist/esm/ionic-global-40e42e7f.js","./node_modules/@ionic/core/dist/esm/ios.transition-1651c430.js","./node_modules/@ionic/core/dist/esm/md.transition-66f18369.js","./node_modules/@ionic/core/dist/esm/overlays-6c9feb7e.js","./node_modules/@ionic/storage/dist/esm/index.js","./node_modules/@sentry/utils/esm/env.js","./node_modules/@sentry/utils/esm/node.js","./node_modules/@sentry/utils/esm/time.js","./node_modules/@sentry/utils/esm/worldwide.js","./node_modules/base64-js/index.js","./node_modules/buffer/index.js","./node_modules/call-bind/callBound.js","./node_modules/call-bind/index.js","./node_modules/compare-versions/lib/esm/utils.js","./node_modules/compare-versions/lib/esm/compareVersions.js","./node_modules/contentful-sdk-core/dist/index.es-modules.js","./node_modules/contentful/dist/es-modules/entities/space.js","./node_modules/contentful/dist/es-modules/mixins/stringify-safe.js","./node_modules/contentful-resolve-response/dist/esm/index.js","./node_modules/contentful/dist/es-modules/entities/entry.js","./node_modules/contentful/dist/es-modules/entities/asset.js","./node_modules/contentful/dist/es-modules/entities/asset-key.js","./node_modules/contentful/dist/es-modules/entities/content-type.js","./node_modules/contentful/dist/es-modules/entities/locale.js","./node_modules/contentful/dist/es-modules/entities/tag.js","./node_modules/contentful/dist/es-modules/entities/index.js","./node_modules/contentful/dist/es-modules/paged-sync.js","./node_modules/contentful/dist/es-modules/utils/normalize-select.js","./node_modules/contentful/dist/es-modules/utils/validate-timestamp.js","./node_modules/contentful/dist/es-modules/create-contentful-api.js","./node_modules/contentful/dist/es-modules/contentful.js","./node_modules/contentful/dist/es-modules/create-global-options.js","./node_modules/contentful/node_modules/axios/index.js","./node_modules/contentful/node_modules/axios/lib/adapters/xhr.js","./node_modules/contentful/node_modules/axios/lib/axios.js","./node_modules/contentful/node_modules/axios/lib/cancel/CancelToken.js","./node_modules/contentful/node_modules/axios/lib/cancel/CanceledError.js","./node_modules/contentful/node_modules/axios/lib/cancel/isCancel.js","./node_modules/contentful/node_modules/axios/lib/core/Axios.js","./node_modules/contentful/node_modules/axios/lib/core/AxiosError.js","./node_modules/contentful/node_modules/axios/lib/core/InterceptorManager.js","./node_modules/contentful/node_modules/axios/lib/core/buildFullPath.js","./node_modules/contentful/node_modules/axios/lib/core/dispatchRequest.js","./node_modules/contentful/node_modules/axios/lib/core/mergeConfig.js","./node_modules/contentful/node_modules/axios/lib/core/settle.js","./node_modules/contentful/node_modules/axios/lib/core/transformData.js","./node_modules/contentful/node_modules/axios/lib/defaults/index.js","./node_modules/contentful/node_modules/axios/lib/defaults/transitional.js","./node_modules/contentful/node_modules/axios/lib/env/data.js","./node_modules/contentful/node_modules/axios/lib/helpers/bind.js","./node_modules/contentful/node_modules/axios/lib/helpers/buildURL.js","./node_modules/contentful/node_modules/axios/lib/helpers/combineURLs.js","./node_modules/contentful/node_modules/axios/lib/helpers/cookies.js","./node_modules/contentful/node_modules/axios/lib/helpers/isAbsoluteURL.js","./node_modules/contentful/node_modules/axios/lib/helpers/isAxiosError.js","./node_modules/contentful/node_modules/axios/lib/helpers/isURLSameOrigin.js","./node_modules/contentful/node_modules/axios/lib/helpers/normalizeHeaderName.js","./node_modules/contentful/node_modules/axios/lib/helpers/null.js","./node_modules/contentful/node_modules/axios/lib/helpers/parseHeaders.js","./node_modules/contentful/node_modules/axios/lib/helpers/parseProtocol.js","./node_modules/contentful/node_modules/axios/lib/helpers/spread.js","./node_modules/contentful/node_modules/axios/lib/helpers/toFormData.js","./node_modules/contentful/node_modules/axios/lib/helpers/validator.js","./node_modules/contentful/node_modules/axios/lib/utils.js","./node_modules/deepmerge/dist/cjs.js","./node_modules/emitter-component/index.js","./node_modules/events/events.js","./node_modules/fast-copy/dist/fast-copy.js","./node_modules/function-bind/implementation.js","./node_modules/function-bind/index.js","./node_modules/get-intrinsic/index.js","./node_modules/has-proto/index.js","./node_modules/has-symbols/index.js","./node_modules/has-symbols/shams.js","./node_modules/has/src/index.js","./node_modules/ieee754/index.js","./node_modules/json-stringify-safe/stringify.js","./node_modules/localforage/dist/localforage.js","./node_modules/lodash.isplainobject/index.js","./node_modules/lodash.isstring/index.js","./node_modules/object-inspect/index.js","./node_modules/p-throttle/index.js","./node_modules/qs/lib/formats.js","./node_modules/qs/lib/index.js","./node_modules/qs/lib/parse.js","./node_modules/qs/lib/stringify.js","./node_modules/qs/lib/utils.js","./node_modules/rambda/src/isNil.js","./node_modules/rxjs/dist/esm/internal/BehaviorSubject.js","./node_modules/rxjs/dist/esm/internal/Observable.js","./node_modules/rxjs/dist/esm/internal/ReplaySubject.js","./node_modules/rxjs/dist/esm/internal/util/ObjectUnsubscribedError.js","./node_modules/rxjs/dist/esm/internal/Subject.js","./node_modules/rxjs/dist/esm/internal/NotificationFactories.js","./node_modules/rxjs/dist/esm/internal/Subscriber.js","./node_modules/rxjs/dist/esm/internal/util/UnsubscriptionError.js","./node_modules/rxjs/dist/esm/internal/Subscription.js","./node_modules/rxjs/dist/esm/internal/config.js","./node_modules/rxjs/dist/esm/internal/observable/ConnectableObservable.js","./node_modules/rxjs/dist/esm/internal/observable/combineLatest.js","./node_modules/rxjs/dist/esm/internal/observable/concat.js","./node_modules/rxjs/dist/esm/internal/operators/concatAll.js","./node_modules/rxjs/dist/esm/internal/observable/defer.js","./node_modules/rxjs/dist/esm/internal/observable/empty.js","./node_modules/rxjs/dist/esm/internal/operators/subscribeOn.js","./node_modules/rxjs/dist/esm/internal/scheduled/scheduleAsyncIterable.js","./node_modules/rxjs/dist/esm/internal/observable/from.js","./node_modules/rxjs/dist/esm/internal/scheduled/scheduled.js","./node_modules/rxjs/dist/esm/internal/scheduled/scheduleObservable.js","./node_modules/rxjs/dist/esm/internal/scheduled/scheduleArray.js","./node_modules/rxjs/dist/esm/internal/scheduled/schedulePromise.js","./node_modules/rxjs/dist/esm/internal/scheduled/scheduleIterable.js","./node_modules/rxjs/dist/esm/internal/scheduled/scheduleReadableStreamLike.js","./node_modules/rxjs/dist/esm/internal/observable/fromEvent.js","./node_modules/rxjs/dist/esm/internal/observable/innerFrom.js","./node_modules/rxjs/dist/esm/internal/observable/merge.js","./node_modules/rxjs/dist/esm/internal/observable/of.js","./node_modules/rxjs/dist/esm/internal/observable/throwError.js","./node_modules/rxjs/dist/esm/internal/operators/OperatorSubscriber.js","./node_modules/rxjs/dist/esm/internal/operators/catchError.js","./node_modules/rxjs/dist/esm/internal/operators/concatMap.js","./node_modules/rxjs/dist/esm/internal/operators/debounceTime.js","./node_modules/rxjs/dist/esm/internal/operators/defaultIfEmpty.js","./node_modules/rxjs/dist/esm/internal/operators/distinctUntilChanged.js","./node_modules/rxjs/dist/esm/internal/operators/filter.js","./node_modules/rxjs/dist/esm/internal/operators/finalize.js","./node_modules/rxjs/dist/esm/internal/operators/first.js","./node_modules/rxjs/dist/esm/internal/operators/ignoreElements.js","./node_modules/rxjs/dist/esm/internal/operators/map.js","./node_modules/rxjs/dist/esm/internal/operators/mapTo.js","./node_modules/rxjs/dist/esm/internal/operators/mergeAll.js","./node_modules/rxjs/dist/esm/internal/operators/mergeMap.js","./node_modules/rxjs/dist/esm/internal/operators/mergeInternals.js","./node_modules/rxjs/dist/esm/internal/operators/observeOn.js","./node_modules/rxjs/dist/esm/internal/operators/refCount.js","./node_modules/rxjs/dist/esm/internal/operators/scan.js","./node_modules/rxjs/dist/esm/internal/operators/scanInternals.js","./node_modules/rxjs/dist/esm/internal/operators/share.js","./node_modules/rxjs/dist/esm/internal/operators/skip.js","./node_modules/rxjs/dist/esm/internal/operators/startWith.js","./node_modules/rxjs/dist/esm/internal/operators/switchMap.js","./node_modules/rxjs/dist/esm/internal/operators/take.js","./node_modules/rxjs/dist/esm/internal/operators/takeUntil.js","./node_modules/rxjs/dist/esm/internal/operators/tap.js","./node_modules/rxjs/dist/esm/internal/operators/throwIfEmpty.js","./node_modules/rxjs/dist/esm/internal/operators/timeout.js","./node_modules/rxjs/dist/esm/internal/operators/withLatestFrom.js","./node_modules/rxjs/dist/esm/internal/scheduler/Action.js","./node_modules/rxjs/dist/esm/internal/scheduler/intervalProvider.js","./node_modules/rxjs/dist/esm/internal/scheduler/AsyncAction.js","./node_modules/rxjs/dist/esm/internal/Scheduler.js","./node_modules/rxjs/dist/esm/internal/scheduler/AsyncScheduler.js","./node_modules/rxjs/dist/esm/internal/scheduler/async.js","./node_modules/rxjs/dist/esm/internal/scheduler/dateTimestampProvider.js","./node_modules/rxjs/dist/esm/internal/scheduler/queue.js","./node_modules/rxjs/dist/esm/internal/scheduler/QueueScheduler.js","./node_modules/rxjs/dist/esm/internal/scheduler/QueueAction.js","./node_modules/rxjs/dist/esm/internal/scheduler/timeoutProvider.js","./node_modules/rxjs/dist/esm/internal/symbol/iterator.js","./node_modules/rxjs/dist/esm/internal/symbol/observable.js","./node_modules/rxjs/dist/esm/internal/util/EmptyError.js","./node_modules/rxjs/dist/esm/internal/util/args.js","./node_modules/rxjs/dist/esm/internal/util/argsArgArrayOrObject.js","./node_modules/rxjs/dist/esm/internal/util/arrRemove.js","./node_modules/rxjs/dist/esm/internal/util/createErrorClass.js","./node_modules/rxjs/dist/esm/internal/util/createObject.js","./node_modules/rxjs/dist/esm/internal/util/errorContext.js","./node_modules/rxjs/dist/esm/internal/util/executeSchedule.js","./node_modules/rxjs/dist/esm/internal/util/identity.js","./node_modules/rxjs/dist/esm/internal/util/isArrayLike.js","./node_modules/rxjs/dist/esm/internal/util/isAsyncIterable.js","./node_modules/rxjs/dist/esm/internal/util/isDate.js","./node_modules/rxjs/dist/esm/internal/util/isFunction.js","./node_modules/rxjs/dist/esm/internal/util/isInteropObservable.js","./node_modules/rxjs/dist/esm/internal/util/isIterable.js","./node_modules/rxjs/dist/esm/internal/util/isPromise.js","./node_modules/rxjs/dist/esm/internal/util/isReadableStreamLike.js","./node_modules/rxjs/dist/esm/internal/util/isScheduler.js","./node_modules/rxjs/dist/esm/internal/util/lift.js","./node_modules/rxjs/dist/esm/internal/util/mapOneOrManyArgs.js","./node_modules/rxjs/dist/esm/internal/util/noop.js","./node_modules/rxjs/dist/esm/internal/util/pipe.js","./node_modules/rxjs/dist/esm/internal/util/reportUnhandledError.js","./node_modules/rxjs/dist/esm/internal/util/throwUnobservableError.js","./node_modules/safe-buffer/index.js","./node_modules/sax/lib/sax.js","./node_modules/side-channel/index.js","./node_modules/stream/index.js","./node_modules/string_decoder/lib/string_decoder.js","./node_modules/timers/index.js","./node_modules/xml2js/lib/bom.js","./node_modules/xml2js/lib/builder.js","./node_modules/xml2js/lib/defaults.js","./node_modules/xml2js/lib/parser.js","./node_modules/xml2js/lib/processors.js","./node_modules/xml2js/lib/xml2js.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/DocumentPosition.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/NodeType.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/Utility.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/WriterState.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLAttribute.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLCData.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLCharacterData.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLComment.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDOMConfiguration.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDOMErrorHandler.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDOMImplementation.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDOMStringList.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDTDAttList.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDTDElement.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDTDEntity.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDTDNotation.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDeclaration.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDocType.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDocument.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDocumentCB.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLDummy.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLElement.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLNamedNodeMap.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLNode.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLNodeList.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLProcessingInstruction.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLRaw.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLStreamWriter.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLStringWriter.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLStringifier.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLText.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/XMLWriterBase.js","./node_modules/xml2js/node_modules/xmlbuilder/lib/index.js","./node_modules/@ionic/core/dist/esm/ lazy ^\\.\\/.*\\.entry\\.js$ include: \\.entry\\.js$ exclude: \\.system\\.entry\\.js$ namespace object","./node_modules/@babel/runtime/helpers/asyncToGenerator.js","./node_modules/@angular/common/fesm2022/common.mjs","./node_modules/@angular/common/fesm2022/http.mjs","./node_modules/@angular/core/fesm2022/core.mjs","./node_modules/@angular/core/fesm2022/rxjs-interop.mjs","./node_modules/@angular/forms/fesm2022/forms.mjs","./node_modules/rxjs/dist/esm/internal/observable/forkJoin.js","./node_modules/@angular/platform-browser/fesm2022/platform-browser.mjs","./node_modules/rxjs/dist/esm/internal/operators/takeLast.js","./node_modules/@angular/router/fesm2022/router.mjs","./node_modules/rxjs/dist/esm/internal/util/isObservable.js","./node_modules/rxjs/dist/esm/internal/operators/last.js","./node_modules/@ionic/core/components/ionic-global.js","./node_modules/@ionic/angular/fesm2020/ionic-angular-common.mjs","./node_modules/@ionic/core/dist/esm/app-globals-2398e405.js","./node_modules/@ionic/angular/fesm2020/ionic-angular.mjs","./node_modules/@ionic/core/dist/esm/polyfills/index.js","./node_modules/@ionic/core/dist/esm/loader.js","./node_modules/rxjs/dist/esm/internal/Notification.js","./node_modules/rxjs/dist/esm/internal/operators/groupBy.js","./node_modules/rxjs/dist/esm/internal/operators/exhaustMap.js","./node_modules/@ngrx/effects/fesm2022/ngrx-effects.mjs","./node_modules/rxjs/dist/esm/internal/operators/materialize.js","./node_modules/rxjs/dist/esm/internal/operators/dematerialize.js","./node_modules/@ngrx/store-devtools/fesm2022/ngrx-store-devtools.mjs","./node_modules/@ngrx/store/fesm2022/ngrx-store.mjs","./node_modules/rxjs/dist/esm/internal/operators/pluck.js","./node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js","./node_modules/tslib/tslib.es6.mjs"],"sourceRoot":"webpack:///","sourcesContent":["import { inject, Injectable } from '@angular/core';\nimport { complement, isNil, isNilOrEmpty } from '../ramda-functions';\nimport { AlertController } from '@ionic/angular';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class AlertService {\n private alertController = inject(AlertController);\n\n public async presentDoubleActionAlert(\n header: string,\n message: string,\n yesHandler: () => void,\n yesText = 'Ok',\n noHandler?: () => void,\n runNoHandlerOnDismiss = false\n ) {\n const alert = await this.alertController.create({\n header,\n message,\n buttons: [\n {\n text: yesText,\n handler: yesHandler,\n },\n {\n text: 'Cancel',\n ...(isNil(noHandler) ? { role: 'cancel' } : { handler: noHandler }),\n cssClass: 'danger-alert-button',\n },\n ],\n });\n\n if (runNoHandlerOnDismiss && complement(isNilOrEmpty(noHandler))) {\n alert.onWillDismiss().then(() => {\n noHandler?.();\n });\n }\n\n return alert.present();\n }\n\n public async presentSingleActionAlert(\n header: string,\n message: string,\n yesHandler: () => void,\n yesText = 'Ok'\n ) {\n const alert = await this.alertController.create({\n header,\n message,\n buttons: [\n {\n text: yesText,\n handler: yesHandler,\n },\n ],\n });\n\n return alert.present();\n }\n}\n","export enum DBTableName {\n LakeLevels = 'lakeLevels',\n SnowDepths = 'snowDepths',\n WaterReleases = 'waterReleases',\n Cache = 'cache',\n Version = 'version',\n}\n\nexport interface IValidationPeriod {\n [key: string]: DataValidationPeriod;\n}\nexport enum DataValidationPeriod {\n Daily = 1,\n HalfDaily = 0.5,\n realtime = 0,\n}\n\nexport const DataValidationPeriods: IValidationPeriod = {\n [DBTableName.LakeLevels]: DataValidationPeriod.Daily,\n [DBTableName.SnowDepths]: DataValidationPeriod.Daily,\n [DBTableName.WaterReleases]: DataValidationPeriod.HalfDaily,\n};\n\nexport enum DataFetchType {\n LakeLevels = 'LakeLevels',\n SnowyDepths = 'SnowyDepths',\n CaravanCampingParks = 'CaravanCampingParks',\n SHLFacilities = 'SHLFacilities',\n Jindabyne = 'WaterReleasesJindabyne',\n Tantangara = 'WaterReleasesTantangara',\n Khancoban = 'DamCurrentReleases',\n}\n","import { DBTableName } from './data-config';\nimport { environment } from '../../environments/environment';\n\nexport const DB_TABLES = [\n {\n name: DBTableName.Version,\n data: environment.version,\n },\n {\n name: DBTableName.Cache,\n data: {\n lakeLevels: null,\n snowDepths: null,\n visitTheScheme: null,\n publicAccess: null,\n waterReleases: null,\n favourites: null,\n },\n },\n {\n name: DBTableName.LakeLevels,\n data: {},\n },\n {\n name: DBTableName.SnowDepths,\n data: {},\n },\n {\n name: DBTableName.WaterReleases,\n data: {},\n },\n];\n","import { compareVersions } from './compareVersions';\n/**\n * Compare [semver](https://semver.org/) version strings using the specified operator.\n *\n * @param v1 First version to compare\n * @param v2 Second version to compare\n * @param operator Allowed arithmetic operator to use\n * @returns `true` if the comparison between the firstVersion and the secondVersion satisfies the operator, `false` otherwise.\n *\n * @example\n * ```\n * compare('10.1.8', '10.0.4', '>'); // return true\n * compare('10.0.1', '10.0.1', '='); // return true\n * compare('10.1.1', '10.2.2', '<'); // return true\n * compare('10.1.1', '10.2.2', '<='); // return true\n * compare('10.1.1', '10.2.2', '>='); // return false\n * ```\n */\nexport const compare = (v1, v2, operator) => {\n // validate input operator\n assertValidOperator(operator);\n // since result of compareVersions can only be -1 or 0 or 1\n // a simple map can be used to replace switch\n const res = compareVersions(v1, v2);\n return operatorResMap[operator].includes(res);\n};\nconst operatorResMap = {\n '>': [1],\n '>=': [0, 1],\n '=': [0],\n '<=': [-1, 0],\n '<': [-1],\n '!=': [-1, 1],\n};\nconst allowedOperators = Object.keys(operatorResMap);\nconst assertValidOperator = (op) => {\n if (typeof op !== 'string') {\n throw new TypeError(`Invalid operator type, expected string but got ${typeof op}`);\n }\n if (allowedOperators.indexOf(op) === -1) {\n throw new Error(`Invalid operator, expected one of ${allowedOperators.join('|')}`);\n }\n};\n","import { Injectable, inject } from '@angular/core';\nimport { Storage } from '@ionic/storage-angular';\nimport { DB_TABLES } from './db-config';\nimport { equals, isNil, isNilOrEmpty } from '../ramda-functions';\nimport { environment } from '../../environments/environment';\nimport { DBTableName } from './data-config';\nimport { HttpClient } from '@angular/common/http';\nimport { firstValueFrom } from 'rxjs';\nimport { parseString } from 'xml2js';\nimport { compare } from 'compare-versions';\nimport { IItemJson } from '../models/Item';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class DBService {\n private storage = inject(Storage);\n private http = inject(HttpClient);\n\n get = async (key: string) => await this.storage.get(key);\n set = async (key: string, value: any) => await this.storage.set(key, value);\n getValue = async (key: string, value: any) => {\n const data = await this.get(key);\n return data ? data[value] : null;\n };\n create = async () => await this.storage.create();\n clear = async () => await this.storage.clear();\n\n async initDB() {\n await this.create();\n await this.compareAppVersion();\n await this.initialiseTables();\n }\n\n compareAppVersion = async () => {\n const appVersion = await this.get(DBTableName.Version);\n if (this.isAppVersionUpdated(appVersion)) {\n await this.clear();\n }\n };\n\n isAppVersionUpdated = (savedVersion: string) => {\n if (isNil(savedVersion)) {\n return true;\n }\n return compare(environment.version, savedVersion, '>');\n };\n\n isDataExpired = async (dbTableName: DBTableName) => {\n const cache = await this.get(DBTableName.Cache);\n\n if (isNil(cache)) {\n return true;\n }\n\n const lastModified = cache[dbTableName];\n\n if (isNil(lastModified)) {\n return true;\n }\n\n const now = new Date();\n const diff = now.getTime() - lastModified.getTime();\n const diffInHours = diff / (1000 * 60); // minutes\n return diffInHours > 5;\n };\n\n isDataExisted = async (dbTableName: DBTableName) =>\n !isNilOrEmpty(await this.storage.get(dbTableName));\n\n isDataValid = async (dbTableName: DBTableName) => {\n const isOffline = !navigator.onLine;\n const isDataExisted = await this.isDataExisted(dbTableName);\n const isDataExpired = await this.isDataExpired(dbTableName);\n return isDataExisted && (isOffline || !isDataExpired);\n };\n\n initialiseTables = async () => {\n for (const table of DB_TABLES) {\n const tableData = await this.get(table.name);\n if (isNilOrEmpty(tableData)) {\n await this.set(table.name, table.data);\n }\n }\n };\n\n updateCacheLastModified = async (dbTableName: DBTableName) => {\n const cache = await this.get(DBTableName.Cache);\n const updatedCache = {\n ...cache,\n [dbTableName]: new Date(),\n };\n await this.set(DBTableName.Cache, updatedCache);\n };\n\n fetchData = async (url: string): Promise => {\n try {\n const response = await firstValueFrom(\n this.http.get(url, { responseType: 'text' })\n );\n return await this.parseXml(response);\n } catch (error: any) {\n const err = new Error('Failed to fetch data: ' + error);\n if (equals(error.status, 404)) {\n err.name = 'DataNotFoundError';\n }\n throw err;\n }\n };\n\n private parseXml = (xmlData: string): Promise => {\n return new Promise((resolve, reject) => {\n parseString(xmlData, (err, result) => {\n if (err) {\n reject(err);\n } else {\n resolve(result);\n }\n });\n });\n };\n\n generateUrl = (text: string) => {\n return `${environment.dataUrl}/${text}.xml`;\n };\n}\n","import { EmptyError } from './util/EmptyError';\nimport { SafeSubscriber } from './Subscriber';\nexport function firstValueFrom(source, config) {\n const hasConfig = typeof config === 'object';\n return new Promise((resolve, reject) => {\n const subscriber = new SafeSubscriber({\n next: (value) => {\n resolve(value);\n subscriber.unsubscribe();\n },\n error: reject,\n complete: () => {\n if (hasConfig) {\n resolve(config.defaultValue);\n }\n else {\n reject(new EmptyError());\n }\n },\n });\n source.subscribe(subscriber);\n });\n}\n","import { createAction, props } from '@ngrx/store';\nimport { ContentfulContext, ISyncCollection } from './contentful';\n\nexport const retry = createAction('[Contentful] Retry');\n\nexport const checkUpdateFailure = createAction(\n '[Contentful] Check Update Failure',\n props<{ error: any }>()\n);\n\nexport const syncEntries = createAction(\n '[Contentful] Sync Entries',\n props<{ syncCollection: ISyncCollection }>()\n);\n\nexport const syncEntriesSuccess = createAction(\n '[Contentful] Sync Entries Success',\n props<{ syncCollection: ISyncCollection }>()\n);\n\nexport const syncSkipped = createAction('[Contentful] Sync Skipped');\n\nexport const syncEntriesFailure = createAction(\n '[Contentful] Sync Entries Failure',\n props<{ error: any }>()\n);\n\nexport const syncAssets = createAction(\n '[Contentful] Sync Assets',\n props<{ syncCollection: ISyncCollection }>()\n);\n\nexport const assetsDownloaded = createAction('[Contentful] Assets Downloaded');\n\nexport const syncAssetsSuccess = createAction(\n '[Contentful] Sync Assets Success',\n props<{ nextSyncToken: string }>()\n);\n\nexport const syncAssetsFailure = createAction(\n '[Contentful] Sync Assets Failure',\n props<{ error: any }>()\n);\n\nexport const clearCache = createAction('[Contentful] Clear Cache');\n\nexport const updateEntriesToCache = createAction(\n '[Contentful] Update Entries To Download',\n props<{ entriesToCache: number }>()\n);\n\nexport const updateEntriesCached = createAction(\n '[Contentful] Update Entries Downloaded'\n);\n\nexport const updateAssetsToCache = createAction(\n '[Contentful] Update Assets To Download',\n props<{ assetsToCache: number }>()\n);\n\nexport const updateAssetsDownloaded = createAction(\n '[Contentful] Update Assets Downloaded'\n);\n\nexport const updateAssetsCached = createAction(\n '[Contentful] Update Assets Cached'\n);\n\nexport const nextSyncTokenUpdate = createAction(\n '[Contentful] Next Sync Token Update',\n props<{ nextSyncToken: string }>()\n);\n\nexport const clearNextSyncToken = createAction(\n '[Contentful] Clear Next Sync Token'\n);\n\nexport const switchContentfulContext = createAction(\n '[Contentful] Switch Contentful Context',\n props<{ contentfulContext: ContentfulContext }>()\n);\n","import { createReducer, on, Action } from '@ngrx/store';\nimport { ContentfulContext, ContentfulSyncStatus } from './contentful';\nimport {\n assetsDownloaded,\n checkUpdateFailure,\n clearNextSyncToken,\n nextSyncTokenUpdate,\n retry,\n switchContentfulContext,\n syncAssetsFailure,\n syncAssetsSuccess,\n syncEntries,\n syncEntriesFailure,\n syncEntriesSuccess,\n syncSkipped,\n updateAssetsCached,\n updateAssetsDownloaded,\n updateAssetsToCache,\n updateEntriesCached,\n updateEntriesToCache,\n} from './contentful.actions';\nimport { environment } from '../../environments/environment';\n\nexport const CONTENTFUL_FEATURE_KEY = 'contentful';\n\nexport interface IContentfulState {\n error: string;\n nextSyncToken: string;\n contentfulContext: ContentfulContext;\n viewStatus: ContentfulSyncStatus;\n entriesToCache: number;\n entriesCached: number;\n assetsToCache: number;\n assetsDownloaded: number;\n assetsCached: number;\n}\n\nexport const initialState: IContentfulState = {\n error: '',\n nextSyncToken: '',\n contentfulContext: environment.contentful.context as ContentfulContext,\n viewStatus: ContentfulSyncStatus.Initial,\n entriesToCache: 0,\n entriesCached: 0,\n assetsToCache: 0,\n assetsDownloaded: 0,\n assetsCached: 0,\n};\n\nexport const reducer = createReducer(\n initialState,\n on(retry, (state) => ({\n ...state,\n viewStatus: ContentfulSyncStatus.Initial,\n entriesToCache: 0,\n entriesCached: 0,\n assetsToCache: 0,\n assetsDownloaded: 0,\n assetsCached: 0,\n })),\n on(syncEntries, (state) => ({\n ...state,\n viewStatus: ContentfulSyncStatus.UpdateChecked,\n })),\n on(syncEntriesSuccess, (state) => ({\n ...state,\n viewStatus: ContentfulSyncStatus.EntriesSynced,\n })),\n on(assetsDownloaded, (state) => ({\n ...state,\n viewStatus: ContentfulSyncStatus.AssetsDownloaded,\n })),\n on(syncAssetsSuccess, (state) => ({\n ...state,\n viewStatus: ContentfulSyncStatus.AssetsSynced,\n })),\n on(syncSkipped, (state) => ({\n ...state,\n viewStatus: ContentfulSyncStatus.AssetsSynced,\n })),\n on(\n syncAssetsFailure,\n syncEntriesFailure,\n checkUpdateFailure,\n (state, action) => ({\n ...state,\n error: action.error,\n viewStatus: ContentfulSyncStatus.Failure,\n })\n ),\n on(updateEntriesToCache, (state, action) => ({\n ...state,\n entriesToCache: action.entriesToCache,\n })),\n on(updateEntriesCached, (state) => ({\n ...state,\n entriesCached: state.entriesCached + 1,\n })),\n on(updateAssetsToCache, (state, action) => ({\n ...state,\n assetsToCache: action.assetsToCache,\n })),\n on(updateAssetsDownloaded, (state) => ({\n ...state,\n assetsDownloaded: state.assetsDownloaded + 1,\n })),\n on(updateAssetsCached, (state) => ({\n ...state,\n assetsCached: state.assetsCached + 1,\n })),\n on(nextSyncTokenUpdate, (state, action) => ({\n ...state,\n nextSyncToken: action.nextSyncToken,\n })),\n on(clearNextSyncToken, () => initialState),\n on(switchContentfulContext, (state, action) => ({\n ...state,\n contentfulContext: action.contentfulContext,\n }))\n);\n\nexport function contentfulReducer(\n state: IContentfulState | undefined,\n action: Action\n) {\n return reducer(state, action);\n}\n","import { createFeatureSelector, createSelector } from '@ngrx/store';\nimport { CONTENTFUL_FEATURE_KEY, IContentfulState } from './contentful.reducer';\nimport { ContentfulSyncStatus } from './contentful';\nimport { includes, not } from '../ramda-functions';\n\nexport const selectContentfulState = createFeatureSelector(\n CONTENTFUL_FEATURE_KEY\n);\n\nexport const selectError = createSelector(\n selectContentfulState,\n (state: IContentfulState) => state.error\n);\n\nexport const selectViewStatus = createSelector(\n selectContentfulState,\n (state: IContentfulState) => state.viewStatus\n);\n\nexport const selectIsSyncing = createSelector(\n selectViewStatus,\n (viewStatus: ContentfulSyncStatus) =>\n not(\n includes(viewStatus, [\n ContentfulSyncStatus.Initial,\n ContentfulSyncStatus.AssetsSynced,\n ContentfulSyncStatus.Failure,\n ])\n )\n);\n\nexport const selectEntriesToDownload = createSelector(\n selectContentfulState,\n (state: IContentfulState) => state.entriesToCache\n);\n\nexport const selectEntriesDownloaded = createSelector(\n selectContentfulState,\n (state: IContentfulState) => state.entriesCached\n);\n\nexport const selectAssetsToDownload = createSelector(\n selectContentfulState,\n (state: IContentfulState) => state.assetsToCache\n);\n\nexport const selectAssetsDownloaded = createSelector(\n selectContentfulState,\n (state: IContentfulState) => state.assetsDownloaded\n);\n\nexport const selectAssetsCached = createSelector(\n selectContentfulState,\n (state: IContentfulState) => state.assetsCached\n);\n\nexport const selectNextSyncToken = createSelector(\n selectContentfulState,\n (state: IContentfulState) => state.nextSyncToken\n);\n\nexport const selectContentfulContext = createSelector(\n selectContentfulState,\n (state: IContentfulState) => state.contentfulContext\n);\n","import { registerPlugin } from '@capacitor/core';\nconst KeepAwake = registerPlugin('KeepAwake', {\n web: () => import('./web').then(m => new m.KeepAwakeWeb()),\n});\nexport * from './definitions';\nexport { KeepAwake };\n","import { inject, Injectable } from '@angular/core';\nimport {\n combineLatest,\n from,\n map,\n Observable,\n of,\n switchMap,\n take,\n tap,\n} from 'rxjs';\nimport {\n createClient,\n Entry,\n Asset,\n ContentfulClientApi,\n SyncCollection,\n} from 'contentful';\nimport { HttpClient } from '@angular/common/http';\nimport { Store } from '@ngrx/store';\nimport { IContentfulState } from './contentful.reducer';\nimport { KeepAwake } from '@capacitor-community/keep-awake';\nimport {\n contentfulApis,\n contentUpdateMessage,\n getAssetFile,\n getId,\n ICacheAsset,\n ISyncCollection,\n} from './contentful';\nimport { isEmpty, isNil, isNilOrEmpty } from '../ramda-functions';\nimport {\n assetsDownloaded,\n clearNextSyncToken,\n nextSyncTokenUpdate,\n updateAssetsCached,\n updateAssetsDownloaded,\n updateAssetsToCache,\n updateEntriesCached,\n updateEntriesToCache,\n} from './contentful.actions';\nimport { Storage } from '@ionic/storage-angular';\nimport { AlertService } from '../alert/alert.service';\nimport {\n selectContentfulContext,\n selectNextSyncToken,\n} from './contentful.selectors';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class ContentfulService {\n private http = inject(HttpClient);\n private contentfulStore = inject(Store);\n private storage = inject(Storage);\n private alertService = inject(AlertService);\n\n private initClient = (): Observable =>\n this.contentfulStore.select(selectContentfulContext).pipe(\n map((contentfulContext) => {\n return contentfulApis[contentfulContext];\n }),\n map(({ accessToken, host, space, environment }) =>\n createClient({\n accessToken: accessToken,\n host: host,\n space: space,\n environment: environment,\n })\n )\n );\n\n preventScreenSleep = async () => {\n await KeepAwake.keepAwake();\n };\n\n allowScreenSleep = async () => {\n await KeepAwake.allowSleep();\n };\n\n presentNotificationIfHasChanges = async (\n syncCollection: ISyncCollection,\n firstLaunch: boolean\n ) => {\n if (\n firstLaunch ||\n (isNilOrEmpty(syncCollection.assets) &&\n isNilOrEmpty(syncCollection.entries))\n ) {\n return Promise.resolve(undefined);\n }\n\n return new Promise((resolve, reject) => {\n this.alertService.presentDoubleActionAlert(\n 'New content!',\n contentUpdateMessage,\n () => {\n this.contentfulStore.dispatch(clearNextSyncToken());\n },\n 'Yes',\n reject,\n true\n );\n });\n };\n\n checkRemoteUpdate = (): Observable => {\n const fetchAllEntriesIfNeedToUpdate = (\n client: ContentfulClientApi,\n syncCollection: SyncCollection\n ) => {\n return !isEmpty(syncCollection.entries)\n ? from(client.getEntries({ limit: 1000 })).pipe(\n map((entries) => ({\n ...syncCollection,\n entries: JSON.parse(entries.stringifySafe()).items,\n }))\n )\n : of(syncCollection);\n };\n\n const updateEntriesAssetsToDownload = (syncCollection: ISyncCollection) => {\n const entriesToCache = syncCollection.entries.length;\n const assetsToCache = syncCollection.assets.length;\n this.contentfulStore.dispatch(updateEntriesToCache({ entriesToCache }));\n this.contentfulStore.dispatch(updateAssetsToCache({ assetsToCache }));\n };\n\n const sync = (\n client: ContentfulClientApi,\n nextSyncToken: string\n ): Observable =>\n from(\n client.sync({\n ...(isNilOrEmpty(nextSyncToken)\n ? { initial: true }\n : { nextSyncToken }),\n resolveLinks: false,\n })\n ).pipe(\n map((syncCollection) => ({\n ...JSON.parse(syncCollection.stringifySafe()),\n })),\n switchMap((syncCollection) =>\n fetchAllEntriesIfNeedToUpdate(client, syncCollection)\n ),\n tap(updateEntriesAssetsToDownload)\n );\n\n return combineLatest([\n this.initClient(),\n this.contentfulStore.select(selectNextSyncToken).pipe(take(1)),\n ]).pipe(\n switchMap(([client, nextSyncToken]) => sync(client, nextSyncToken))\n );\n };\n\n public syncEntries(\n syncCollection: ISyncCollection\n ): Observable {\n const store = (entries: Array>): Observable> =>\n combineLatest(\n entries.map((entry) =>\n this.storage\n .set(getId(entry), JSON.stringify(entry))\n .then(() => this.contentfulStore.dispatch(updateEntriesCached()))\n )\n );\n\n const sync = (): Observable => {\n const { entries, deletedEntries } = syncCollection;\n if (isEmpty(entries) && isEmpty(deletedEntries)) {\n return of(syncCollection);\n }\n const updateEntries = store(entries);\n const deleteEntries = deletedEntries.map((entry) =>\n this.storage.remove(getId(entry))\n );\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return combineLatest([].concat(updateEntries).concat(deleteEntries)).pipe(\n map(() => syncCollection)\n );\n };\n\n return sync();\n }\n\n public syncAssets(syncCollection: ISyncCollection): Observable {\n const { assets, deletedAssets } = syncCollection;\n if (isEmpty(assets) && isEmpty(deletedAssets)) {\n return of(syncCollection.nextSyncToken);\n }\n const updateAssets = this.fetchAssets(assets).pipe(\n tap(() => this.contentfulStore.dispatch(assetsDownloaded())),\n switchMap((assetsToCache) => this.cacheAssets(assetsToCache))\n );\n const deleteAssets = deletedAssets.map((asset) =>\n from(this.storage.remove(getId(asset)))\n );\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return combineLatest([].concat(updateAssets).concat(deleteAssets)).pipe(\n map(() => syncCollection.nextSyncToken)\n );\n }\n\n private fetchAssets(assets: Array): Observable> {\n const assetsToFetch = assets\n .filter((asset) => !isNil(getAssetFile(asset)?.url))\n .map((asset) => this.constructAssetUrl(asset));\n return combineLatest(\n assetsToFetch.map((asset) =>\n this.http.get(asset.url, { responseType: 'blob' }).pipe(\n map((blob) => ({ blob, type: asset.type, id: asset.id })),\n tap(() => this.contentfulStore.dispatch(updateAssetsDownloaded()))\n )\n )\n ) as Observable>;\n }\n\n private cacheAssets(assets: Array) {\n const fileReaderPromise = (blob: Blob, type: string) =>\n new Promise((resolve) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result);\n type.includes('image')\n ? reader.readAsDataURL(blob)\n : reader.readAsText(blob);\n });\n return combineLatest(\n assets.map(async (asset) => {\n const result = await fileReaderPromise(asset.blob, asset.type);\n return this.storage\n .set(asset.id, result as string)\n .then(() => this.contentfulStore.dispatch(updateAssetsCached()));\n })\n );\n }\n\n getEntryById = (entryId: string): Promise> =>\n this.storage.get(entryId).then((value) => JSON.parse(value));\n\n getImageAssetById = (assetId: string): Promise =>\n this.storage.get(assetId);\n\n private constructAssetUrl(asset: Asset): {\n id: string;\n url: string;\n type: string;\n } {\n return {\n id: getId(asset),\n type: getAssetFile(asset)?.contentType as string,\n url: `https:${getAssetFile(asset)?.url}?w=${window.innerWidth * 2}`,\n };\n }\n\n clearCache = (): Observable =>\n this.initClient().pipe(\n switchMap(() => this.storage.clear()),\n tap(() => this.contentfulStore.dispatch(clearNextSyncToken()))\n );\n\n updateNextToken = (nextSyncToken: string) => {\n this.contentfulStore.dispatch(nextSyncTokenUpdate({ nextSyncToken }));\n };\n}\n","import { Asset, Entry } from 'contentful';\nimport { Document } from '@contentful/rich-text-types';\nimport { environment } from '../../environments/environment';\n\nexport enum ContentfulContext {\n STAGING = 'staging',\n PRODUCTION = 'production',\n}\n\nexport interface ContentfulApi {\n name: string;\n space: string;\n host: string;\n accessToken: string;\n environment: string;\n}\n\nexport const contentfulApis: {\n [name: string]: ContentfulApi;\n} = {\n [ContentfulContext.PRODUCTION]: {\n name: ContentfulContext.PRODUCTION,\n environment: ContentfulContext.PRODUCTION,\n space: environment.contentful.spaceId,\n accessToken: environment.contentful.productAccessToken,\n host: environment.contentful.productHost,\n },\n [ContentfulContext.STAGING]: {\n name: ContentfulContext.STAGING,\n environment: ContentfulContext.STAGING,\n space: environment.contentful.spaceId,\n accessToken: environment.contentful.stagingAccessToken,\n host: environment.contentful.stagingHost,\n },\n};\n\nexport enum ContentfulContentType {\n species = 'speciesPage',\n}\n\nexport enum InfoEntries {\n infoPage = '2TD5lcQUv8nUAtBrQO8wHo',\n contactUs = '72JuknrN6UdRtNBVuA44kN',\n}\n\nexport enum PublicAccessEntries {\n SafetyAroundTheScheme = '3A6y0Tt2L8XHwpkgbHZIl3',\n PublicAccess = '1cFbuOao5AUfdNfxzHqGQm',\n LitteringAndForeshoreUse = '6BeBBoF0Ewy4IMvGEHuTqE',\n OvernightCamping = 'OJCa83y4TRwqBeVoaWTgp',\n Snowy20 = '7uf4d6V2PSQdgfPCUjBNYz',\n}\n\nexport enum SchemeEntries {\n Cabramurra = '67OF3oZ0nzSACMZphbl98q',\n SnowyHydro = '6Fb8OJTRNltz1gx3F0VNfr',\n Talbingo = '1LYmqpmjsAGL3gX4N2jPKW',\n Khancoban = '54TVoxUe3zTXP52GC7QTJ5',\n}\n\nexport enum DescriptionEntries {\n Favourites = '6WJAnMUAKrSdgj0VlCfEw0',\n VisitTheScheme = '3SNMrpFtSHT6esfQihD8Io',\n PublicAccess = 'CJ7kplgkaw9IBXuIs4po8',\n}\n\nexport enum BackgroundAssets {\n Home = '7qVHdfSqXfx558vEsRQmJp',\n Blank = '7g9nQZ3ygcz4RsnhMzBWxl',\n WaterReleases = '206oyBBFjLPTSDcqKJvb5b',\n LakeLevels = '18mwwdDGjOEAOEURrWiiCa',\n PublicAccess = 'zLhcsWNKKVWAOGGkCpS7C',\n Others = '5Yl7Ub8Mh2alF0KUDb4Cl4',\n Backup = '4mmY62AgoyQsLEa3iJ9NoT',\n}\n\nexport interface ISyncCollection {\n entries: Array>;\n deletedEntries: Array>;\n assets: Array;\n deletedAssets: Array;\n nextSyncToken: string;\n}\n\nexport interface IPublicAccessContent {\n title: string;\n content: Document;\n}\n\nexport interface IInfoContent {\n content: Document;\n}\n\nexport interface IDescriptionContent {\n title: string;\n content: Document;\n}\n\nexport const getAssetFile = (asset: Asset) => {\n const file = asset?.fields?.file;\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n // eslint-disable-next-line no-prototype-builtins\n return file?.hasOwnProperty('en-US') ? file['en-US'] : file;\n};\n\nexport const getId = (content: Asset | Entry) => content?.sys.id;\n\nexport enum ContentfulSyncStatus {\n Initial = 'Initial',\n UpdateChecked = 'UpdateChecked',\n EntriesSynced = 'EntriesSynced',\n AssetsDownloaded = 'AssetsDownloaded',\n AssetsSynced = 'AssetsSynced',\n Failure = 'Failure',\n}\n\nexport interface ICacheAsset {\n blob: Blob;\n type: string;\n id: string;\n}\n\nexport const contentUpdateMessage = `There have been content updates since you last used the app.\n Would you like to download the latest contents now?`;\n\nexport enum AppMetadataEntries {\n LatestVersion = '5H0DzpZvzGqZUyXGJufWR9',\n}\n\nexport interface IAppMetadata {\n metadataName: string;\n value: any;\n}\n","import { createAction, props } from '@ngrx/store';\nimport { IFavouritesEntity } from './favourites.models';\n\nexport const addFavourite = createAction(\n '[Favourites/API] Add Favourite',\n props<{ favourite: IFavouritesEntity }>()\n);\n\nexport const removeFavourite = createAction(\n '[Favourites/API] Remove Favourite',\n props<{ id: string }>()\n);\n\nexport const clearFavourites = createAction(\n '[Favourites/API] Clear Favourites'\n);\n\nexport const updateFavourites = createAction(\n '[Favourites/API] Refresh Favourites',\n props<{ favourites: IFavouritesEntity[] }>()\n);\n\nexport const updateFavouritesSuccess = createAction(\n '[Favourites/API] Refresh Favourites Success',\n props<{ favourites: IFavouritesEntity[] }>()\n);\n\nexport const updateFavouritesFailure = createAction(\n '[Favourites/API] Refresh Favourites Failure',\n props<{ error: any }>()\n);\n","import { TileType } from '../models/Item';\n\n/**\n * Interface for the 'Favourites' data\n */\nexport interface IFavouritesEntity {\n id: string;\n icon: string;\n href: string;\n value?: number;\n unit?: string;\n growthStatus?: string;\n type?: TileType;\n}\n\nexport enum FavouriteHref {\n LakeLevel = '/lake-levels/lake-level-history/',\n publicAccess = '/public-access/details/',\n snowDepth = '/snow-depths/snow-depth-history/',\n visitTheScheme = '/visit-the-scheme/details/',\n waterRelease = '/water-releases',\n}\n\nexport enum FavouriteTileIcon {\n lakeLevel = 'water',\n snowDepth = 'snow',\n waterRelease = 'custom-water-release',\n pubicAccess = 'boat',\n visitTheScheme = 'car',\n}\n","import { createSelector } from '@ngrx/store';\nimport { isDevMode } from '@angular/core';\n\nfunction getInitialEntityState() {\n return {\n ids: [],\n entities: {},\n };\n}\nfunction createInitialStateFactory() {\n function getInitialState(additionalState = {}) {\n return Object.assign(getInitialEntityState(), additionalState);\n }\n return { getInitialState };\n}\n\nfunction createSelectorsFactory() {\n function getSelectors(selectState) {\n const selectIds = (state) => state.ids;\n const selectEntities = (state) => state.entities;\n const selectAll = createSelector(selectIds, selectEntities, (ids, entities) => ids.map((id) => entities[id]));\n const selectTotal = createSelector(selectIds, (ids) => ids.length);\n if (!selectState) {\n return {\n selectIds,\n selectEntities,\n selectAll,\n selectTotal,\n };\n }\n return {\n selectIds: createSelector(selectState, selectIds),\n selectEntities: createSelector(selectState, selectEntities),\n selectAll: createSelector(selectState, selectAll),\n selectTotal: createSelector(selectState, selectTotal),\n };\n }\n return { getSelectors };\n}\n\nvar DidMutate;\n(function (DidMutate) {\n DidMutate[DidMutate[\"EntitiesOnly\"] = 0] = \"EntitiesOnly\";\n DidMutate[DidMutate[\"Both\"] = 1] = \"Both\";\n DidMutate[DidMutate[\"None\"] = 2] = \"None\";\n})(DidMutate || (DidMutate = {}));\nfunction createStateOperator(mutator) {\n return function operation(arg, state) {\n const clonedEntityState = {\n ids: [...state.ids],\n entities: { ...state.entities },\n };\n const didMutate = mutator(arg, clonedEntityState);\n if (didMutate === DidMutate.Both) {\n return Object.assign({}, state, clonedEntityState);\n }\n if (didMutate === DidMutate.EntitiesOnly) {\n return {\n ...state,\n entities: clonedEntityState.entities,\n };\n }\n return state;\n };\n}\n\nfunction selectIdValue(entity, selectId) {\n const key = selectId(entity);\n if (isDevMode() && key === undefined) {\n console.warn('@ngrx/entity: The entity passed to the `selectId` implementation returned undefined.', 'You should probably provide your own `selectId` implementation.', 'The entity that was passed:', entity, 'The `selectId` implementation:', selectId.toString());\n }\n return key;\n}\n\nfunction createUnsortedStateAdapter(selectId) {\n function addOneMutably(entity, state) {\n const key = selectIdValue(entity, selectId);\n if (key in state.entities) {\n return DidMutate.None;\n }\n state.ids.push(key);\n state.entities[key] = entity;\n return DidMutate.Both;\n }\n function addManyMutably(entities, state) {\n let didMutate = false;\n for (const entity of entities) {\n didMutate = addOneMutably(entity, state) !== DidMutate.None || didMutate;\n }\n return didMutate ? DidMutate.Both : DidMutate.None;\n }\n function setAllMutably(entities, state) {\n state.ids = [];\n state.entities = {};\n addManyMutably(entities, state);\n return DidMutate.Both;\n }\n function setOneMutably(entity, state) {\n const key = selectIdValue(entity, selectId);\n if (key in state.entities) {\n state.entities[key] = entity;\n return DidMutate.EntitiesOnly;\n }\n state.ids.push(key);\n state.entities[key] = entity;\n return DidMutate.Both;\n }\n function setManyMutably(entities, state) {\n const didMutateSetOne = entities.map((entity) => setOneMutably(entity, state));\n switch (true) {\n case didMutateSetOne.some((didMutate) => didMutate === DidMutate.Both):\n return DidMutate.Both;\n case didMutateSetOne.some((didMutate) => didMutate === DidMutate.EntitiesOnly):\n return DidMutate.EntitiesOnly;\n default:\n return DidMutate.None;\n }\n }\n function removeOneMutably(key, state) {\n return removeManyMutably([key], state);\n }\n function removeManyMutably(keysOrPredicate, state) {\n const keys = keysOrPredicate instanceof Array\n ? keysOrPredicate\n : state.ids.filter((key) => keysOrPredicate(state.entities[key]));\n const didMutate = keys\n .filter((key) => key in state.entities)\n .map((key) => delete state.entities[key]).length > 0;\n if (didMutate) {\n state.ids = state.ids.filter((id) => id in state.entities);\n }\n return didMutate ? DidMutate.Both : DidMutate.None;\n }\n function removeAll(state) {\n return Object.assign({}, state, {\n ids: [],\n entities: {},\n });\n }\n function takeNewKey(keys, update, state) {\n const original = state.entities[update.id];\n const updated = Object.assign({}, original, update.changes);\n const newKey = selectIdValue(updated, selectId);\n const hasNewKey = newKey !== update.id;\n if (hasNewKey) {\n keys[update.id] = newKey;\n delete state.entities[update.id];\n }\n state.entities[newKey] = updated;\n return hasNewKey;\n }\n function updateOneMutably(update, state) {\n return updateManyMutably([update], state);\n }\n function updateManyMutably(updates, state) {\n const newKeys = {};\n updates = updates.filter((update) => update.id in state.entities);\n const didMutateEntities = updates.length > 0;\n if (didMutateEntities) {\n const didMutateIds = updates.filter((update) => takeNewKey(newKeys, update, state)).length >\n 0;\n if (didMutateIds) {\n state.ids = state.ids.map((id) => newKeys[id] || id);\n return DidMutate.Both;\n }\n else {\n return DidMutate.EntitiesOnly;\n }\n }\n return DidMutate.None;\n }\n function mapMutably(map, state) {\n const changes = state.ids.reduce((changes, id) => {\n const change = map(state.entities[id]);\n if (change !== state.entities[id]) {\n changes.push({ id, changes: change });\n }\n return changes;\n }, []);\n const updates = changes.filter(({ id }) => id in state.entities);\n return updateManyMutably(updates, state);\n }\n function mapOneMutably({ map, id }, state) {\n const entity = state.entities[id];\n if (!entity) {\n return DidMutate.None;\n }\n const updatedEntity = map(entity);\n return updateOneMutably({\n id: id,\n changes: updatedEntity,\n }, state);\n }\n function upsertOneMutably(entity, state) {\n return upsertManyMutably([entity], state);\n }\n function upsertManyMutably(entities, state) {\n const added = [];\n const updated = [];\n for (const entity of entities) {\n const id = selectIdValue(entity, selectId);\n if (id in state.entities) {\n updated.push({ id, changes: entity });\n }\n else {\n added.push(entity);\n }\n }\n const didMutateByUpdated = updateManyMutably(updated, state);\n const didMutateByAdded = addManyMutably(added, state);\n switch (true) {\n case didMutateByAdded === DidMutate.None &&\n didMutateByUpdated === DidMutate.None:\n return DidMutate.None;\n case didMutateByAdded === DidMutate.Both ||\n didMutateByUpdated === DidMutate.Both:\n return DidMutate.Both;\n default:\n return DidMutate.EntitiesOnly;\n }\n }\n return {\n removeAll,\n addOne: createStateOperator(addOneMutably),\n addMany: createStateOperator(addManyMutably),\n setAll: createStateOperator(setAllMutably),\n setOne: createStateOperator(setOneMutably),\n setMany: createStateOperator(setManyMutably),\n updateOne: createStateOperator(updateOneMutably),\n updateMany: createStateOperator(updateManyMutably),\n upsertOne: createStateOperator(upsertOneMutably),\n upsertMany: createStateOperator(upsertManyMutably),\n removeOne: createStateOperator(removeOneMutably),\n removeMany: createStateOperator(removeManyMutably),\n map: createStateOperator(mapMutably),\n mapOne: createStateOperator(mapOneMutably),\n };\n}\n\nfunction createSortedStateAdapter(selectId, sort) {\n const { removeOne, removeMany, removeAll } = createUnsortedStateAdapter(selectId);\n function addOneMutably(entity, state) {\n return addManyMutably([entity], state);\n }\n function addManyMutably(newModels, state) {\n const models = newModels.filter((model) => !(selectIdValue(model, selectId) in state.entities));\n if (models.length === 0) {\n return DidMutate.None;\n }\n else {\n merge(models, state);\n return DidMutate.Both;\n }\n }\n function setAllMutably(models, state) {\n state.entities = {};\n state.ids = [];\n addManyMutably(models, state);\n return DidMutate.Both;\n }\n function setOneMutably(entity, state) {\n const id = selectIdValue(entity, selectId);\n if (id in state.entities) {\n state.ids = state.ids.filter((val) => val !== id);\n merge([entity], state);\n return DidMutate.Both;\n }\n else {\n return addOneMutably(entity, state);\n }\n }\n function setManyMutably(entities, state) {\n const didMutateSetOne = entities.map((entity) => setOneMutably(entity, state));\n switch (true) {\n case didMutateSetOne.some((didMutate) => didMutate === DidMutate.Both):\n return DidMutate.Both;\n case didMutateSetOne.some((didMutate) => didMutate === DidMutate.EntitiesOnly):\n return DidMutate.EntitiesOnly;\n default:\n return DidMutate.None;\n }\n }\n function updateOneMutably(update, state) {\n return updateManyMutably([update], state);\n }\n function takeUpdatedModel(models, update, state) {\n if (!(update.id in state.entities)) {\n return false;\n }\n const original = state.entities[update.id];\n const updated = Object.assign({}, original, update.changes);\n const newKey = selectIdValue(updated, selectId);\n delete state.entities[update.id];\n models.push(updated);\n return newKey !== update.id;\n }\n function updateManyMutably(updates, state) {\n const models = [];\n const didMutateIds = updates.filter((update) => takeUpdatedModel(models, update, state))\n .length > 0;\n if (models.length === 0) {\n return DidMutate.None;\n }\n else {\n const originalIds = state.ids;\n const updatedIndexes = [];\n state.ids = state.ids.filter((id, index) => {\n if (id in state.entities) {\n return true;\n }\n else {\n updatedIndexes.push(index);\n return false;\n }\n });\n merge(models, state);\n if (!didMutateIds &&\n updatedIndexes.every((i) => state.ids[i] === originalIds[i])) {\n return DidMutate.EntitiesOnly;\n }\n else {\n return DidMutate.Both;\n }\n }\n }\n function mapMutably(updatesOrMap, state) {\n const updates = state.ids.reduce((changes, id) => {\n const change = updatesOrMap(state.entities[id]);\n if (change !== state.entities[id]) {\n changes.push({ id, changes: change });\n }\n return changes;\n }, []);\n return updateManyMutably(updates, state);\n }\n function mapOneMutably({ map, id }, state) {\n const entity = state.entities[id];\n if (!entity) {\n return DidMutate.None;\n }\n const updatedEntity = map(entity);\n return updateOneMutably({\n id: id,\n changes: updatedEntity,\n }, state);\n }\n function upsertOneMutably(entity, state) {\n return upsertManyMutably([entity], state);\n }\n function upsertManyMutably(entities, state) {\n const added = [];\n const updated = [];\n for (const entity of entities) {\n const id = selectIdValue(entity, selectId);\n if (id in state.entities) {\n updated.push({ id, changes: entity });\n }\n else {\n added.push(entity);\n }\n }\n const didMutateByUpdated = updateManyMutably(updated, state);\n const didMutateByAdded = addManyMutably(added, state);\n switch (true) {\n case didMutateByAdded === DidMutate.None &&\n didMutateByUpdated === DidMutate.None:\n return DidMutate.None;\n case didMutateByAdded === DidMutate.Both ||\n didMutateByUpdated === DidMutate.Both:\n return DidMutate.Both;\n default:\n return DidMutate.EntitiesOnly;\n }\n }\n function merge(models, state) {\n models.sort(sort);\n const ids = [];\n let i = 0;\n let j = 0;\n while (i < models.length && j < state.ids.length) {\n const model = models[i];\n const modelId = selectIdValue(model, selectId);\n const entityId = state.ids[j];\n const entity = state.entities[entityId];\n if (sort(model, entity) <= 0) {\n ids.push(modelId);\n i++;\n }\n else {\n ids.push(entityId);\n j++;\n }\n }\n if (i < models.length) {\n state.ids = ids.concat(models.slice(i).map(selectId));\n }\n else {\n state.ids = ids.concat(state.ids.slice(j));\n }\n models.forEach((model, i) => {\n state.entities[selectId(model)] = model;\n });\n }\n return {\n removeOne,\n removeMany,\n removeAll,\n addOne: createStateOperator(addOneMutably),\n updateOne: createStateOperator(updateOneMutably),\n upsertOne: createStateOperator(upsertOneMutably),\n setAll: createStateOperator(setAllMutably),\n setOne: createStateOperator(setOneMutably),\n setMany: createStateOperator(setManyMutably),\n addMany: createStateOperator(addManyMutably),\n updateMany: createStateOperator(updateManyMutably),\n upsertMany: createStateOperator(upsertManyMutably),\n map: createStateOperator(mapMutably),\n mapOne: createStateOperator(mapOneMutably),\n };\n}\n\nfunction createEntityAdapter(options = {}) {\n const { selectId, sortComparer } = {\n selectId: options.selectId ?? ((entity) => entity.id),\n sortComparer: options.sortComparer ?? false,\n };\n const stateFactory = createInitialStateFactory();\n const selectorsFactory = createSelectorsFactory();\n const stateAdapter = sortComparer\n ? createSortedStateAdapter(selectId, sortComparer)\n : createUnsortedStateAdapter(selectId);\n return {\n selectId,\n sortComparer,\n ...stateFactory,\n ...selectorsFactory,\n ...stateAdapter,\n };\n}\n\nclass Dictionary {\n}\n\n/**\n * DO NOT EDIT\n *\n * This file is automatically generated at build\n */\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { Dictionary, createEntityAdapter };\n","import { EntityState, EntityAdapter, createEntityAdapter } from '@ngrx/entity';\nimport { createReducer, on, Action } from '@ngrx/store';\n\nimport * as FavouritesActions from './favourites.actions';\nimport { IFavouritesEntity } from './favourites.models';\n\nexport const FAVOURITES_FEATURE_KEY = 'favourites';\n\nexport interface FavouritesState extends EntityState {\n selectedId?: string | number; // which Favourites record has been selected\n error?: string | null; // last known error (if any)\n}\n\nexport interface FavouritesPartialState {\n readonly [FAVOURITES_FEATURE_KEY]: FavouritesState;\n}\n\nexport const favouritesAdapter: EntityAdapter =\n createEntityAdapter();\n\nexport const initialFavouritesState: FavouritesState =\n favouritesAdapter.getInitialState({});\n\nconst reducer = createReducer(\n initialFavouritesState,\n on(FavouritesActions.addFavourite, (state, { favourite }) =>\n favouritesAdapter.addOne(favourite, state)\n ),\n on(FavouritesActions.removeFavourite, (state, { id }) =>\n favouritesAdapter.removeOne(id, state)\n ),\n on(FavouritesActions.clearFavourites, (state) =>\n favouritesAdapter.removeAll(state)\n ),\n on(FavouritesActions.updateFavouritesSuccess, (state, { favourites }) =>\n favouritesAdapter.upsertMany(favourites, state)\n ),\n on(FavouritesActions.updateFavouritesFailure, (state, { error }) => ({\n ...state,\n error,\n }))\n);\n\nexport function favouritesReducer(\n state: FavouritesState | undefined,\n action: Action\n) {\n return reducer(state, action);\n}\n","import { createFeatureSelector, createSelector } from '@ngrx/store';\nimport {\n FAVOURITES_FEATURE_KEY,\n FavouritesState,\n favouritesAdapter,\n} from './favourites.reducer';\n\n// Lookup the 'Favourites' feature state managed by NgRx\nexport const selectFavouritesState = createFeatureSelector(\n FAVOURITES_FEATURE_KEY\n);\n\nconst { selectAll, selectEntities } = favouritesAdapter.getSelectors();\n\nexport const selectFavouritesError = createSelector(\n selectFavouritesState,\n (state: FavouritesState) => state.error\n);\n\nexport const selectAllFavourites = createSelector(\n selectFavouritesState,\n (state: FavouritesState) => selectAll(state)\n);\n\nexport const selectFavouriteById = (id: string) =>\n createSelector(selectAllFavourites, (allFavourites) =>\n allFavourites.find((favourite) => favourite.id === id)\n );\n\nexport const selectFavouriteAdded = (id: string) =>\n createSelector(selectFavouriteById(id), (favourite) => !!favourite);\n\nexport const selectFavouritesEntities = createSelector(\n selectFavouritesState,\n (state: FavouritesState) => selectEntities(state)\n);\n\nexport const selectSelectedId = createSelector(\n selectFavouritesState,\n (state: FavouritesState) => state.selectedId\n);\n\nexport const selectEntity = createSelector(\n selectFavouritesEntities,\n selectSelectedId,\n (entities, selectedId) => (selectedId ? entities[selectedId] : undefined)\n);\n","import { inject, Injectable } from '@angular/core';\nimport { Store } from '@ngrx/store';\nimport { FavouritesState } from './favourites.reducer';\nimport { IFavouritesEntity } from './favourites.models';\nimport {\n addFavourite,\n clearFavourites,\n removeFavourite,\n} from './favourites.actions';\nimport { DBService } from '../cache/db.service';\nimport { ITileItem, TileType } from '../models/Item';\nimport { LakeLevelsService } from '../lake-levels/lake-levels.service';\nimport { WaterReleasesService } from '../water-releases/water-releases.service';\nimport { SnowDepthsService } from '../snow-depths/snow-depths.service';\nimport { mergeMap, Observable, of } from 'rxjs';\nimport { concatLatestFrom } from '@ngrx/effects';\nimport { selectAllFavourites } from './favourites.selectors';\nimport { equals, not } from '../ramda-functions';\n\n@Injectable({ providedIn: 'root' })\nexport class FavouritesService {\n private favouriteStore = inject(Store);\n private dbService = inject(DBService);\n private lakeLevelsService = inject(LakeLevelsService);\n private waterReleasesService = inject(WaterReleasesService);\n private snowDepthsService = inject(SnowDepthsService);\n\n addFavourite = (favourite: IFavouritesEntity) => {\n this.favouriteStore.dispatch(addFavourite({ favourite }));\n };\n\n removeFavourite = (id: string) => {\n this.favouriteStore.dispatch(removeFavourite({ id }));\n };\n\n clearFavourites = () => {\n this.favouriteStore.dispatch(clearFavourites());\n };\n\n addOrRemoveFavorites = (item: IFavouritesEntity, isFavorite: boolean) => {\n if (isFavorite) {\n this.removeFavourite(item.id);\n } else {\n this.addFavourite(item);\n }\n };\n\n updateFavourites(\n favourites: IFavouritesEntity[]\n ): Observable {\n return of(favourites).pipe(\n concatLatestFrom(() => this.favouriteStore.select(selectAllFavourites)),\n mergeMap(([updatedFavourites, existingFavourites]) => {\n // Create a set of existing favorite ids\n const existingFavoritesIdSet = new Set(\n existingFavourites.map((item) => item.id)\n );\n\n const displayedFavourites = updatedFavourites\n .map((updatedItem) =>\n // reconstruct the href for items that have the details view\n not(\n equals(updatedItem.type, TileType.WaterRelease) ||\n equals(updatedItem.type, TileType.CurrentRelease)\n )\n ? {\n ...updatedItem,\n href: updatedItem.href + '/' + updatedItem.id,\n }\n : updatedItem\n )\n // Filter out the items that are not previously existed\n .filter((updatedItem) => existingFavoritesIdSet.has(updatedItem.id));\n\n // return the filtered values that need to be updated\n return of(displayedFavourites);\n })\n );\n }\n\n generateFavouriteItemValue = (\n item: ITileItem\n ): Partial => {\n if ('currentValue' in item) {\n return {\n value: item.currentValue.value,\n unit: item.currentValue.unit,\n growthStatus:\n 'growthStatus' in item.currentValue\n ? item.currentValue.growthStatus\n : undefined,\n };\n }\n\n return {\n value: item.value,\n unit: item.unit,\n growthStatus: item.growthStatus,\n };\n };\n}\n","import { ElementRef, inject, Injectable } from '@angular/core';\nimport { LakeLevelsService } from '../lake-levels/lake-levels.service';\nimport { SnowDepthsService } from '../snow-depths/snow-depths.service';\nimport { WaterReleasesService } from '../water-releases/water-releases.service';\nimport { ICurrentReleaseItem, WaterReleaseDam } from '../models/WaterRelease';\nimport { ContentfulService } from '../contentful/contentful.service';\nimport {\n Descriptions,\n DescriptionTitle,\n IDescription,\n} from '../models/Description';\nimport { Document } from '@contentful/rich-text-types';\nimport { PlatformService } from '../shared/services/platform.service';\nimport { VisitTheSchemeService } from '../visit-the-scheme/visit-the-scheme.service';\nimport { PublicAccessService } from '../public-access/public-access.service';\nimport { publicAccess } from '../models/PublicAccess';\nimport { schemes } from '../models/Scheme';\nimport { SwiperOptions } from 'swiper/types';\nimport { SwiperContainer } from 'swiper/swiper-element';\nimport { AlertService } from '../alert/alert.service';\nimport { MobileUpdateService } from '../update/mobile/mobile-update.service';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class HomeService {\n private lakeLevelsService = inject(LakeLevelsService);\n private snowDepthsService = inject(SnowDepthsService);\n private waterReleasesService = inject(WaterReleasesService);\n private contentfulService = inject(ContentfulService);\n private platformService = inject(PlatformService);\n private visitTheSchemeService = inject(VisitTheSchemeService);\n private publicAccessService = inject(PublicAccessService);\n private alertService = inject(AlertService);\n private mobileUpdateService = inject(MobileUpdateService);\n\n private descriptions = Descriptions;\n promptEvent: any;\n isAppInstalled = true;\n\n getIsAppInstalled = () => this.isAppInstalled;\n\n setIsAppInstalled = (isAppInstalled: boolean) => {\n this.isAppInstalled = isAppInstalled;\n };\n\n isIOS = () => this.platformService.isIOS();\n isStandAlone = () => this.platformService.isIosPwa();\n\n setDescriptions = (descriptions: IDescription[]) => {\n this.descriptions = descriptions;\n };\n\n getDescription = (title: DescriptionTitle) =>\n this.descriptions.find((description) => description.title === title);\n\n initDescriptions = async (descriptions: IDescription[]) => {\n try {\n const descriptionsWithContent: IDescription[] =\n await this.loadDescriptions(descriptions);\n this.setDescriptions(descriptionsWithContent);\n } catch (error) {\n throw new Error(`Error loading descriptions: ${error}`);\n }\n };\n\n private loadDescriptions = async (\n descriptions: IDescription[]\n ): Promise =>\n Promise.all(\n descriptions.map(async (description) => {\n const descriptionContent = (\n await this.contentfulService.getEntryById(description.entryId)\n ).fields;\n return {\n ...description,\n content: descriptionContent.content as Document,\n };\n })\n );\n\n loadData = async () => {\n const [lakeLevels, snowDepths, waterReleases] = await Promise.all([\n this.lakeLevelsService.loadLakeLevelsData(),\n this.snowDepthsService.loadSnowDepthData(),\n this.waterReleasesService.loadWaterReleasesData(),\n ]);\n\n this.lakeLevelsService.setLakeLevels(lakeLevels);\n this.snowDepthsService.setSnowDepths(snowDepths);\n this.waterReleasesService.setWaterReleases(waterReleases);\n };\n\n loadContentfulData = async () => {\n await this.visitTheSchemeService.initSchemeContents(schemes);\n await this.publicAccessService.initPublicAccessContents(publicAccess);\n };\n\n getCurrentReleaseLoadedTime = () => {\n const waterReleases = this.waterReleasesService.getWaterReleases();\n const currentRelease = waterReleases[\n WaterReleaseDam.Khancoban\n ] as ICurrentReleaseItem;\n return currentRelease.date;\n };\n\n initPwaPrompt() {\n if (this.isIOS() && !this.isStandAlone()) {\n this.setIsAppInstalled(false);\n }\n\n window.addEventListener('beforeinstallprompt', (event: any) => {\n event.preventDefault();\n this.promptEvent = event;\n // Check if the app is already installed\n this.setIsAppInstalled(false);\n });\n }\n\n installPwa() {\n if (this.promptEvent && !this.isAppInstalled) {\n this.promptEvent.prompt();\n this.promptEvent.userChoice.then((choiceResult: any) => {\n if (choiceResult.outcome === 'accepted') {\n // The app was installed\n this.setIsAppInstalled(true);\n }\n this.promptEvent = null;\n });\n }\n }\n\n initSwiper = (swiperRef: ElementRef | undefined) => {\n if (swiperRef) {\n const swiperEl = swiperRef.nativeElement;\n const swiper = swiperEl.swiper;\n const config: SwiperOptions = {\n slidesPerView: 1,\n init: true,\n enabled: true,\n pagination: {\n enabled: true,\n renderBullet: (index, className) => {\n // hide rendering the first and the last dummy slide\n if (index === 0 || index === swiper.slides.length - 1) {\n return (\n ''\n );\n }\n return '';\n },\n },\n autoplay: true,\n loop: false,\n speed: 400,\n };\n\n Object.assign(swiperEl, config);\n swiperEl.initialize();\n\n // if slides is more than 1, then jump to the real slide\n if (swiper.slides.length > 1) {\n swiper.slideTo(1, 0);\n }\n\n swiper.on('slideChange', () => {\n // Logic to jump to the other side or handle the boundary condition\n if (swiper.isBeginning) {\n swiper.slideTo(swiper.slides.length - 2, 300);\n } else if (swiper.isEnd) {\n swiper.slideTo(1, 300);\n }\n });\n\n return swiperEl;\n }\n\n return undefined;\n };\n}\n","import { inject, Injectable } from '@angular/core';\nimport { DataFetchType, DBTableName } from '../cache/data-config';\nimport { DBService } from '../cache/db.service';\nimport {\n IConvertedLakeLevel,\n IGroupedLakeLevel,\n ILakeLevel,\n ILakeLevelJson,\n ILakeLevelJsonItem,\n ILakeLevelValue,\n LakeLevelBoundary,\n} from '../models/LakeLevel';\nimport { GrowthStatus, ItemDescription, TileType } from '../models/Item';\nimport { Store } from '@ngrx/store';\nimport { FavouritesState } from '../favourites/favourites.reducer';\nimport { updateFavourites } from '../favourites/favourites.actions';\nimport {\n FavouriteHref,\n FavouriteTileIcon,\n} from '../favourites/favourites.models';\nimport { equals } from '../ramda-functions';\nimport { ToastService } from '../shared/services/toast.service';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class LakeLevelsService {\n private dbService = inject(DBService);\n private favouriteStore = inject(Store);\n private toastService = inject(ToastService);\n\n private lakeLevels!: ILakeLevel;\n\n setLakeLevels = (lakeLevels: ILakeLevel) => {\n this.lakeLevels = lakeLevels;\n };\n\n getLakeLevels = () => this.lakeLevels;\n\n private generateLakeLevelsUrl = () =>\n this.dbService.generateUrl(DataFetchType.LakeLevels);\n\n fetchLakeLevelsData = async () => {\n const url = this.generateLakeLevelsUrl();\n try {\n return await this.dbService.fetchData(url);\n } catch (e) {\n const error = e as Error;\n if (equals(error.name, 'DataNotFoundError')) {\n await this.toastService.presentToast(`No lake levels data found.`);\n return {};\n } else {\n throw error;\n }\n }\n };\n\n loadLakeLevelsData = async () => {\n if (await this.dbService.isDataValid(DBTableName.LakeLevels)) {\n return this.dbService.get(DBTableName.LakeLevels);\n }\n return this.initLakeLevelsData();\n };\n\n initLakeLevelsData = async () => {\n try {\n const lakeLevelsData =\n (await this.fetchLakeLevelsData()) as ILakeLevelJson;\n const formattedLakeLevels = this.convertLakeLevelData(lakeLevelsData);\n await this.updateLakeLevelsData(formattedLakeLevels);\n return formattedLakeLevels;\n } catch (error) {\n if (await this.dbService.isDataExisted(DBTableName.LakeLevels)) {\n return this.dbService.get(DBTableName.LakeLevels);\n }\n throw error;\n }\n };\n\n private updateLakeLevelsData = async (data: ILakeLevel) => {\n await this.dbService.set(DBTableName.LakeLevels, data);\n await this.dbService.updateCacheLastModified(DBTableName.LakeLevels);\n this.updateFavourite(data);\n };\n\n private updateFavourite = (data: ILakeLevel) => {\n const favourites = Object.entries(data).map(([id, lakeLevel]) => ({\n id,\n icon: FavouriteTileIcon.lakeLevel,\n type: TileType.LakeLevel,\n href: FavouriteHref.LakeLevel,\n value: lakeLevel.currentValue.value,\n unit: lakeLevel.currentValue.unit,\n growthStatus: lakeLevel.currentValue.growthStatus,\n }));\n this.favouriteStore.dispatch(updateFavourites({ favourites }));\n };\n\n convertLakeLevelData = (rawJsonData: ILakeLevelJson) => {\n const lakeLevels = rawJsonData.snowyhydro.level;\n const formattedLakeLevels = lakeLevels.flatMap(\n (lakeLevel: ILakeLevelJsonItem) => {\n return lakeLevel.lake.map((lake) => ({\n name: lake.$.name,\n date: new Date(lake.$.dataTimeStamp),\n level: parseFloat(lake._),\n }));\n }\n );\n\n const structuredLakeLevels = this.groupLakeLevels(formattedLakeLevels);\n return this.addCurrentLakeLevel(structuredLakeLevels);\n };\n\n private groupLakeLevels = (lakeLevels: IConvertedLakeLevel[]) => {\n return lakeLevels.reduce((acc, lakeLevel) => {\n if (!acc[lakeLevel.name]) {\n acc[lakeLevel.name] = [];\n }\n acc[lakeLevel.name].push({\n date: lakeLevel.date,\n value: lakeLevel.level,\n });\n return acc;\n }, {} as IGroupedLakeLevel);\n };\n\n addCurrentLakeLevel = (lakeLevels: IGroupedLakeLevel): ILakeLevel => {\n return Object.keys(lakeLevels).reduce(\n (result: ILakeLevel, lakeLevelName) => {\n const lakeLevel = lakeLevels[lakeLevelName];\n const currentLakeLevel = this.calculateCurrentLakeLevel(\n lakeLevel,\n lakeLevelName\n );\n result[lakeLevelName] = {\n currentValue: currentLakeLevel,\n values: lakeLevel,\n };\n return result;\n },\n {}\n );\n };\n\n calculateCurrentLakeLevel = (\n lakeLevel: ILakeLevelValue[],\n lakeLevelName: string\n ) => {\n const currentLakeLevel = lakeLevel[lakeLevel.length - 1];\n const previousLakeLevel = lakeLevel[lakeLevel.length - 2];\n const growthStatus = this.calculateGrowthStatus(\n currentLakeLevel,\n previousLakeLevel,\n LakeLevelBoundary[lakeLevelName]\n );\n return {\n date: currentLakeLevel.date,\n value: currentLakeLevel.value,\n unit: '%',\n growthStatus,\n description: ItemDescription.CurrentStorage,\n };\n };\n\n calculateGrowthStatus = (\n currentLakeLevel: ILakeLevelValue,\n previousLakeLevel: ILakeLevelValue,\n boundary: number\n ) => {\n const changeValue = currentLakeLevel.value - previousLakeLevel.value;\n const compareToRange = Math.abs(changeValue) > boundary;\n\n if (changeValue > 0 && compareToRange) {\n return GrowthStatus.GROWING;\n }\n if (changeValue < 0 && compareToRange) {\n return GrowthStatus.FALLING;\n }\n return GrowthStatus.STABLE;\n };\n}\n","import {\n DescriptionEntries,\n IDescriptionContent,\n} from '../contentful/contentful';\nimport { Document } from '@contentful/rich-text-types';\n\nexport enum DescriptionTitle {\n Favourites = 'favourites',\n VisitTheScheme = 'visitTheScheme',\n PublicAccess = 'publicAccess',\n}\n\nexport interface IDescription {\n title: DescriptionTitle;\n entryId: string;\n content?: Document;\n}\n\nexport const Descriptions: IDescription[] = [\n {\n title: DescriptionTitle.Favourites,\n entryId: DescriptionEntries.Favourites,\n },\n {\n title: DescriptionTitle.VisitTheScheme,\n entryId: DescriptionEntries.VisitTheScheme,\n },\n {\n title: DescriptionTitle.PublicAccess,\n entryId: DescriptionEntries.PublicAccess,\n },\n];\n","import {\n ICurrentLakeLevel,\n ILakeLevel,\n ILakeLevelItem,\n ILakeLevelJson,\n} from './LakeLevel';\nimport {\n ILatestSnowDepth,\n ISnowDepth,\n ISnowDepthJson,\n ISnowDepthObject,\n} from './SnowDepth';\nimport {\n ICurrentReleaseItem,\n IWaterRelease,\n IWaterReleaseItem,\n IWaterReleaseJson,\n IWaterReleaseValue,\n} from './WaterRelease';\nimport { Document } from '@contentful/rich-text-types';\n\nexport interface IMenuItem {\n name: string;\n href: string;\n icon?: string;\n image?: string;\n}\n\nexport enum GrowthStatus {\n 'GROWING' = 'trending-up-outline',\n 'FALLING' = 'trending-down-outline',\n 'STABLE' = 'custom-stable',\n}\n\nexport enum ItemDescription {\n CurrentStorage = 'Current Storage',\n LatestDepth = 'Latest Depth',\n}\n\nexport enum TileType {\n LakeLevel = 'lakeLevel',\n SnowDepth = 'snowDepth',\n WaterRelease = 'waterRelease',\n CurrentRelease = 'currentRelease',\n}\n\nexport type IItem = IWaterRelease | ILakeLevel | ISnowDepth;\n\nexport type ITileItem =\n | ILakeLevelItem\n | ISnowDepthObject\n | IWaterReleaseItem\n | ICurrentReleaseItem;\n\nexport type IDisplayedItem =\n | ICurrentLakeLevel\n | ILatestSnowDepth\n | IWaterReleaseValue\n | ICurrentReleaseItem;\n\nexport type IItemJson = ILakeLevelJson | ISnowDepthJson | IWaterReleaseJson;\n\nexport interface ITile {\n name: string;\n value: ITileItem;\n}\n","import { GrowthStatus, ItemDescription } from './Item';\nimport { ChartOptions } from 'chart.js';\n\nexport const LakeLevelBoundary: IBoundary = {\n 'Lake Eucumbene': 0.1,\n 'Lake Jindabyne': 0.1,\n 'Tantangara Reservoir': 0.1,\n};\n\nexport enum LakeLevelLake {\n Eucumbene = 'Lake Eucumbene',\n Jindabyne = 'Lake Jindabyne',\n Tantangara = 'Tantangara Reservoir',\n}\n\nexport interface IBoundary {\n [key: string]: number;\n}\n\nexport interface ILakeLevel {\n [key: string]: ILakeLevelItem;\n}\n\nexport interface ILakeLevelItem {\n currentValue: ICurrentLakeLevel;\n values: ILakeLevelValue[];\n}\n\nexport interface ILakeLevelValue {\n date: Date;\n value: number;\n}\n\nexport interface ICurrentLakeLevel {\n date: Date;\n value: number;\n unit: string;\n growthStatus: GrowthStatus;\n description: ItemDescription;\n}\n\nexport interface ILakeLevelJson {\n snowyhydro: {\n level: ILakeLevelJsonItem[];\n };\n}\n\nexport interface ILakeLevelJsonItem {\n $: {\n date: string;\n };\n lake: ILakeLevelJsonItemLake[];\n}\n\nexport interface ILakeLevelJsonItemLake {\n $: {\n name: string;\n dataTimeStamp: string;\n };\n _: string;\n}\n\nexport interface IConvertedLakeLevel {\n name: string;\n date: Date;\n level: number;\n}\n\nexport interface IGroupedLakeLevel {\n [key: string]: ILakeLevelValue[];\n}\n\nexport const lakeLevelHistoryChartOptions: ChartOptions = {\n parsing: {\n xAxisKey: 'date',\n yAxisKey: 'value',\n },\n scales: {\n y: {\n beginAtZero: true,\n suggestedMax: 100,\n ticks: {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n callback: (value: number) => `${value}%`,\n },\n },\n x: {\n type: 'timeseries',\n time: {\n unit: 'month',\n displayFormats: {\n month: 'dd MMM yy',\n },\n },\n ticks: {\n autoSkip: true,\n maxTicksLimit: 4,\n },\n },\n },\n responsive: true,\n maintainAspectRatio: false,\n};\n\nexport const lakeLevelsChartDataConfig = {\n label: 'Lake Level',\n borderWidth: 1,\n borderColor: 'rgba(51, 150, 197, 1)',\n backgroundColor: 'rgba(51, 150, 197, 0.2)',\n};\n","import { Document } from '@contentful/rich-text-types';\nimport { PublicAccessEntries } from '../contentful/contentful';\n\nexport enum PublicAccessTitle {\n SafetyAroundTheScheme = 'Safety Around the Scheme',\n PublicAccess = 'Public Access',\n LitteringAndForeshoreUse = 'Littering and Foreshore Use',\n OvernightCamping = 'Overnight Camping',\n Snowy20 = 'Snowy 2.0',\n}\n\nexport interface IPublicAccess {\n name: PublicAccessTitle;\n href: string;\n icon: string;\n entryId: string;\n content?: Document;\n}\n\nexport const publicAccess: IPublicAccess[] = [\n {\n name: PublicAccessTitle.SafetyAroundTheScheme,\n href: '/safety-around-the-visit-the-scheme',\n icon: 'warning',\n entryId: PublicAccessEntries.SafetyAroundTheScheme,\n },\n {\n name: PublicAccessTitle.PublicAccess,\n href: '/public-access',\n icon: 'people',\n entryId: PublicAccessEntries.PublicAccess,\n },\n {\n name: PublicAccessTitle.LitteringAndForeshoreUse,\n href: '/littering-and-foreshore-use',\n icon: 'trash',\n entryId: PublicAccessEntries.LitteringAndForeshoreUse,\n },\n {\n name: PublicAccessTitle.OvernightCamping,\n href: '/overnight-camping',\n icon: 'moon',\n entryId: PublicAccessEntries.OvernightCamping,\n },\n {\n name: PublicAccessTitle.Snowy20,\n href: '/snowy-2-0',\n icon: 'snow',\n entryId: PublicAccessEntries.Snowy20,\n },\n];\n\nexport const noContentString = 'No content';\n","import { Document } from '@contentful/rich-text-types';\nimport { SchemeEntries } from '../contentful/contentful';\nimport { Asset } from 'contentful';\n\nexport interface IScheme {\n name: SchemeTitle;\n icon: string;\n href: string;\n entryId: SchemeEntries;\n title?: string;\n content?: Document;\n coverImage?: string;\n detailImages?: string[];\n}\n\nexport interface ISchemeContent {\n title: string;\n description: Document;\n coverImage: Asset;\n detailImages: Asset[];\n}\n\nexport enum SchemeTitle {\n Cabramurra = 'Cabramurra Visitor Centre and General Store',\n SnowyHydro = 'Snowy Hydro Discovery Centre',\n Talbingo = 'Talbingo Visitor Display',\n Khancoban = 'Khancoban Visitor Information Centre',\n}\n\nexport enum SchemeHref {\n Cabramurra = '/cabramurra',\n SnowyHydro = '/snowy-hydro',\n Talbingo = '/talbingo',\n Khancoban = '/khancoban',\n}\n\nexport const schemes: IScheme[] = [\n {\n name: SchemeTitle.Cabramurra,\n entryId: SchemeEntries.Cabramurra,\n href: SchemeHref.Cabramurra,\n icon: 'car',\n },\n {\n name: SchemeTitle.SnowyHydro,\n entryId: SchemeEntries.SnowyHydro,\n href: SchemeHref.SnowyHydro,\n icon: 'car',\n },\n {\n name: SchemeTitle.Talbingo,\n entryId: SchemeEntries.Talbingo,\n href: SchemeHref.Talbingo,\n icon: 'car',\n },\n {\n name: SchemeTitle.Khancoban,\n entryId: SchemeEntries.Khancoban,\n href: SchemeHref.Khancoban,\n icon: 'car',\n },\n];\n","import { ItemDescription } from './Item';\nimport { ChartOptions } from 'chart.js';\n\nexport interface ISnowDepth {\n [key: string]: ISnowDepthObject;\n}\n\nexport interface ISnowDepthObject {\n snowDepthThisYear: ISnowDepthValue[];\n snowDepthLastYear: ISnowDepthValue[];\n currentValue: ILatestSnowDepth;\n}\n\nexport interface ISnowDepthValue {\n date: Date;\n value: number;\n quality: string;\n}\n\nexport interface ILatestSnowDepth {\n date: Date;\n value: number;\n unit: string;\n description: ItemDescription;\n}\n\nexport enum SnowDepthObject {\n SpencersCreek = 'Spencers Creek',\n DeepCreek = 'Deep Creek',\n ThreeMileDam = 'Three Mile Dam',\n}\n\nexport const SnowDepthObjectOrder = [\n SnowDepthObject.SpencersCreek,\n SnowDepthObject.DeepCreek,\n SnowDepthObject.ThreeMileDam,\n];\n\nexport interface ISnowDepthJson {\n snowyhydro: {\n level: ISnowDepthJsonItem[];\n };\n}\n\nexport interface ISnowDepthJsonItem {\n $: {\n date: string;\n };\n snow: ISnowDepthJsonItemSnow[];\n}\n\nexport interface ISnowDepthJsonItemSnow {\n $: {\n name: string;\n dataTimestamp: string;\n quality: string;\n };\n _: string;\n}\n\nexport interface IConvertedSnowDepth {\n name: string;\n date: Date;\n quality: string;\n value: number;\n}\n\nexport interface IGroupedSnowDepths {\n [key: string]: ISnowDepthValue[];\n}\n\nexport const snowDepthHistoryChartOptions: ChartOptions = {\n parsing: {\n xAxisKey: 'date',\n yAxisKey: 'value',\n },\n scales: {\n y: {\n beginAtZero: true,\n suggestedMax: 200,\n ticks: {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n callback: (value: number) => `${value}cm`,\n },\n },\n x: {\n min: new Date(new Date().getFullYear(), 0, 1).getTime(),\n max: new Date(new Date().getFullYear(), 10, 31).getTime(),\n type: 'time',\n time: {\n unit: 'month',\n displayFormats: {\n month: 'MMM',\n },\n tooltipFormat: 'MMM dd',\n },\n ticks: {},\n },\n },\n responsive: true,\n maintainAspectRatio: false,\n};\n\nexport const SnowDepthThisYearChartDataConfig = (year: number) => ({\n borderColor: 'rgba(80, 169, 99, 1)',\n backgroundColor: 'rgba(80, 169, 99, 0.2)',\n fill: true,\n label: year.toString(),\n});\n\nexport const SnowDepthLastYearChartDataConfig = (year: number) => ({\n borderColor: 'rgba(51, 150, 197, 1)',\n backgroundColor: 'rgba(51, 150, 197, 0.2)',\n fill: true,\n label: year.toString(),\n});\n","export enum WaterReleaseDam {\n Jindabyne = 'Jindabyne Dam',\n Tantangara = 'Tantangara Dam',\n Khancoban = 'Khancoban Dam',\n}\n\nexport interface IWaterRelease {\n [key: string]: IWaterReleaseItem | ICurrentReleaseItem;\n}\n\nexport interface IWaterReleaseItem {\n currentValue: IWaterReleaseValue;\n values: IWaterReleaseValue[];\n}\n\nexport interface ICurrentReleaseItem {\n value: number;\n date: Date;\n growthStatus: string;\n unit: string;\n}\n\nexport interface IWaterReleaseValue {\n date: Date;\n value: number;\n unit: string;\n}\n\nexport interface IWaterReleaseJson {\n snowyhydro: IWaterReleaseJsonItem | ICurrentWaterReleaseJsonItem;\n}\n\nexport interface IWaterReleaseJsonItem {\n releases: IWaterReleaseJsonItemRelease[];\n}\n\nexport interface ICurrentWaterReleaseJsonItem {\n dam: ICurrentWaterReleaseJsonItemDam[];\n}\n\nexport interface IWaterReleaseJsonItemRelease {\n $: {\n dam: string;\n date: string;\n };\n release: IReleaseValue[];\n}\n\nexport interface IReleaseValue {\n $: {\n date: string;\n };\n _: string;\n}\n\nexport interface ICurrentWaterReleaseJsonItemDam {\n $: {\n name: string;\n flowRateChange: string;\n dataTimeStamp: string;\n };\n _: string;\n}\n","import { inject, Injectable } from '@angular/core';\nimport { ContentfulService } from '../contentful/contentful.service';\nimport { IPublicAccess, publicAccess } from '../models/PublicAccess';\nimport { IMenuItem } from '../models/Item';\nimport { Document } from '@contentful/rich-text-types';\nimport { equals } from '../ramda-functions';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class PublicAccessService {\n private contentfulService = inject(ContentfulService);\n\n private publicAccessContents = publicAccess;\n\n getPublicAccessContents = () => this.publicAccessContents;\n\n setPublicAccessContents = (publicAccessContents: IPublicAccess[]) => {\n this.publicAccessContents = publicAccessContents;\n };\n\n getPublicAccessContent = (name: string) =>\n this.publicAccessContents.find((publicAccessContent) =>\n equals(publicAccessContent.name, name)\n );\n\n initPublicAccessContents = async (publicAccessContents: IPublicAccess[]) => {\n try {\n const publicAccessContentsWithContent =\n await this.loadPublicAccessContents(publicAccessContents);\n this.setPublicAccessContents(publicAccessContentsWithContent);\n } catch (error) {\n throw new Error(`Error loading public access contents: ${error}`);\n }\n };\n\n private loadPublicAccessContents = async (contents: IPublicAccess[]) => {\n return Promise.all(\n contents.map(async (content) => {\n const publicAccessContent = (\n await this.contentfulService.getEntryById(content.entryId)\n ).fields;\n return {\n ...content,\n content: publicAccessContent.content as Document,\n };\n })\n );\n };\n\n generateMenuItems = (publicAccessContents: IPublicAccess[]): IMenuItem[] =>\n publicAccessContents.map(({ name, href, icon }) => ({\n name,\n href,\n icon,\n }));\n}\n","export const cloneList = list => Array.prototype.slice.call(list)\n","export function curry(fn, args = []){\n return (..._args) =>\n (rest => rest.length >= fn.length ? fn(...rest) : curry(fn, rest))([\n ...args,\n ..._args,\n ])\n}\n","import { cloneList } from './_internals/cloneList.js'\nimport { curry } from './curry.js'\n\nfunction adjustFn(\n index, replaceFn, list\n){\n const actualIndex = index < 0 ? list.length + index : index\n if (index >= list.length || actualIndex < 0) return list\n\n const clone = cloneList(list)\n clone[ actualIndex ] = replaceFn(clone[ actualIndex ])\n\n return clone\n}\n\nexport const adjust = curry(adjustFn)\n","export function any(predicate, list){\n if (arguments.length === 1) return _list => any(predicate, _list)\n\n let counter = 0\n while (counter < list.length){\n if (predicate(list[ counter ], counter)){\n return true\n }\n counter++\n }\n\n return false\n}\n","import { curry } from './curry.js'\n\nfunction assocFn(\n prop, newValue, obj\n){\n return Object.assign(\n {}, obj, { [ prop ] : newValue }\n )\n}\n\nexport const assoc = curry(assocFn)\n","export function both(f, g){\n if (arguments.length === 1) return _g => both(f, _g)\n\n return (...input) => f(...input) && g(...input)\n}\n","export function complement(fn){\n return (...input) => !fn(...input)\n}\n","export function concat(x, y){\n if (arguments.length === 1) return _y => concat(x, _y)\n\n return typeof x === 'string' ? `${ x }${ y }` : [ ...x, ...y ]\n}\n","function isFalsy(input){\n return (\n input === undefined || input === null || Number.isNaN(input) === true\n )\n}\n\nexport function defaultTo(defaultArgument, input){\n if (arguments.length === 1){\n return _input => defaultTo(defaultArgument, _input)\n }\n\n return isFalsy(input) ? defaultArgument : input\n}\n","export function dissoc(prop, obj){\n if (arguments.length === 1) return _obj => dissoc(prop, _obj)\n\n if (obj === null || obj === undefined) return {}\n\n const willReturn = {}\n for (const p in obj){\n willReturn[ p ] = obj[ p ]\n }\n delete willReturn[ prop ]\n\n return willReturn\n}\n","export function either(firstPredicate, secondPredicate){\n if (arguments.length === 1){\n return _secondPredicate => either(firstPredicate, _secondPredicate)\n }\n\n return (...input) =>\n Boolean(firstPredicate(...input) || secondPredicate(...input))\n}\n","export const { isArray } = Array\n","export function type(input){\n if (input === null){\n return 'Null'\n } else if (input === undefined){\n return 'Undefined'\n } else if (Number.isNaN(input)){\n return 'NaN'\n }\n const typeResult = Object.prototype.toString.call(input).slice(8, -1)\n\n return typeResult === 'AsyncFunction' ? 'Promise' : typeResult\n}\n","import { isArray } from './_internals/isArray.js'\nimport { type } from './type.js'\n\nexport function _lastIndexOf(valueToFind, list){\n if (!isArray(list)){\n throw new Error(`Cannot read property 'indexOf' of ${ list }`)\n }\n const typeOfValue = type(valueToFind)\n if (![ 'Object', 'Array', 'NaN', 'RegExp' ].includes(typeOfValue))\n return list.lastIndexOf(valueToFind)\n\n const { length } = list\n let index = length\n let foundIndex = -1\n\n while (--index > -1 && foundIndex === -1){\n if (equals(list[ index ], valueToFind)){\n foundIndex = index\n }\n }\n\n return foundIndex\n}\n\nexport function _indexOf(valueToFind, list){\n if (!isArray(list)){\n throw new Error(`Cannot read property 'indexOf' of ${ list }`)\n }\n const typeOfValue = type(valueToFind)\n if (![ 'Object', 'Array', 'NaN', 'RegExp' ].includes(typeOfValue))\n return list.indexOf(valueToFind)\n\n let index = -1\n let foundIndex = -1\n const { length } = list\n\n while (++index < length && foundIndex === -1){\n if (equals(list[ index ], valueToFind)){\n foundIndex = index\n }\n }\n\n return foundIndex\n}\n\nfunction _arrayFromIterator(iter){\n const list = []\n let next\n while (!(next = iter.next()).done){\n list.push(next.value)\n }\n\n return list\n}\n\nfunction _equalsSets(a, b){\n if (a.size !== b.size){\n return false\n }\n const aList = _arrayFromIterator(a.values())\n const bList = _arrayFromIterator(b.values())\n\n const filtered = aList.filter(aInstance => _indexOf(aInstance, bList) === -1)\n\n return filtered.length === 0\n}\n\nfunction parseError(maybeError){\n const typeofError = maybeError.__proto__.toString()\n if (![ 'Error', 'TypeError' ].includes(typeofError)) return []\n\n return [ typeofError, maybeError.message ]\n}\n\nfunction parseDate(maybeDate){\n if (!maybeDate.toDateString) return [ false ]\n\n return [ true, maybeDate.getTime() ]\n}\n\nfunction parseRegex(maybeRegex){\n if (maybeRegex.constructor !== RegExp) return [ false ]\n\n return [ true, maybeRegex.toString() ]\n}\n\nexport function equals(a, b){\n if (arguments.length === 1) return _b => equals(a, _b)\n\n const aType = type(a)\n\n if (aType !== type(b)) return false\n if (aType === 'Function'){\n return a.name === undefined ? false : a.name === b.name\n }\n\n if ([ 'NaN', 'Undefined', 'Null' ].includes(aType)) return true\n\n if (aType === 'Number'){\n if (Object.is(-0, a) !== Object.is(-0, b)) return false\n\n return a.toString() === b.toString()\n }\n\n if ([ 'String', 'Boolean' ].includes(aType)){\n return a.toString() === b.toString()\n }\n\n if (aType === 'Array'){\n const aClone = Array.from(a)\n const bClone = Array.from(b)\n\n if (aClone.toString() !== bClone.toString()){\n return false\n }\n\n let loopArrayFlag = true\n aClone.forEach((aCloneInstance, aCloneIndex) => {\n if (loopArrayFlag){\n if (\n aCloneInstance !== bClone[ aCloneIndex ] &&\n !equals(aCloneInstance, bClone[ aCloneIndex ])\n ){\n loopArrayFlag = false\n }\n }\n })\n\n return loopArrayFlag\n }\n\n const aRegex = parseRegex(a)\n const bRegex = parseRegex(b)\n\n if (aRegex[ 0 ]){\n return bRegex[ 0 ] ? aRegex[ 1 ] === bRegex[ 1 ] : false\n } else if (bRegex[ 0 ]) return false\n\n const aDate = parseDate(a)\n const bDate = parseDate(b)\n\n if (aDate[ 0 ]){\n return bDate[ 0 ] ? aDate[ 1 ] === bDate[ 1 ] : false\n } else if (bDate[ 0 ]) return false\n\n const aError = parseError(a)\n const bError = parseError(b)\n\n if (aError[ 0 ]){\n return bError[ 0 ] ?\n aError[ 0 ] === bError[ 0 ] && aError[ 1 ] === bError[ 1 ] :\n false\n }\n if (aType === 'Set'){\n return _equalsSets(a, b)\n }\n if (aType === 'Object'){\n const aKeys = Object.keys(a)\n\n if (aKeys.length !== Object.keys(b).length){\n return false\n }\n\n let loopObjectFlag = true\n aKeys.forEach(aKeyInstance => {\n if (loopObjectFlag){\n const aValue = a[ aKeyInstance ]\n const bValue = b[ aKeyInstance ]\n\n if (aValue !== bValue && !equals(aValue, bValue)){\n loopObjectFlag = false\n }\n }\n })\n\n return loopObjectFlag\n }\n\n return false\n}\n","import { isArray } from './_internals/isArray.js'\n\nexport function filterObject(predicate, obj){\n const willReturn = {}\n\n for (const prop in obj){\n if (predicate(\n obj[ prop ], prop, obj\n )){\n willReturn[ prop ] = obj[ prop ]\n }\n }\n\n return willReturn\n}\n\nexport function filterArray(\n predicate, list, indexed = false\n){\n let index = 0\n const len = list.length\n const willReturn = []\n\n while (index < len){\n const predicateResult = indexed ?\n predicate(list[ index ], index) :\n predicate(list[ index ])\n if (predicateResult){\n willReturn.push(list[ index ])\n }\n\n index++\n }\n\n return willReturn\n}\n\nexport function filter(predicate, iterable){\n if (arguments.length === 1)\n return _iterable => filter(predicate, _iterable)\n if (!iterable){\n throw new Error('Incorrect iterable input')\n }\n\n if (isArray(iterable)) return filterArray(\n predicate, iterable, false\n )\n\n return filterObject(predicate, iterable)\n}\n","export function find(predicate, list){\n if (arguments.length === 1) return _list => find(predicate, _list)\n\n let index = 0\n const len = list.length\n\n while (index < len){\n const x = list[ index ]\n if (predicate(x)){\n return x\n }\n\n index++\n }\n}\n","import { isArray } from './_internals/isArray.js'\n\nexport function flatten(list, input){\n const willReturn = input === undefined ? [] : input\n\n for (let i = 0; i < list.length; i++){\n if (isArray(list[ i ])){\n flatten(list[ i ], willReturn)\n } else {\n willReturn.push(list[ i ])\n }\n }\n\n return willReturn\n}\n","function flipFn(fn){\n return (...input) => {\n if (input.length === 1){\n return holder => fn(holder, input[ 0 ])\n } else if (input.length === 2){\n return fn(input[ 1 ], input[ 0 ])\n } else if (input.length === 3){\n return fn(\n input[ 1 ], input[ 0 ], input[ 2 ]\n )\n } else if (input.length === 4){\n return fn(\n input[ 1 ], input[ 0 ], input[ 2 ], input[ 3 ]\n )\n }\n\n throw new Error('R.flip doesn\\'t work with arity > 4')\n }\n}\n\nexport function flip(fn){\n return flipFn(fn)\n}\n","export function groupBy(groupFn, list){\n if (arguments.length === 1) return _list => groupBy(groupFn, _list)\n\n const result = {}\n for (let i = 0; i < list.length; i++){\n const item = list[ i ]\n const key = groupFn(item)\n\n if (!result[ key ]){\n result[ key ] = []\n }\n\n result[ key ].push(item)\n }\n\n return result\n}\n","export function has(prop, obj){\n if (arguments.length === 1) return _obj => has(prop, _obj)\n\n if (!obj) return false\n\n return obj.hasOwnProperty(prop)\n}\n","import { isArray } from './_internals/isArray.js'\nimport { _indexOf } from './equals.js'\n\nexport function includes(valueToFind, iterable){\n if (arguments.length === 1)\n return _iterable => includes(valueToFind, _iterable)\n if (typeof iterable === 'string'){\n return iterable.includes(valueToFind)\n }\n if (!iterable){\n throw new TypeError(`Cannot read property \\'indexOf\\' of ${ iterable }`)\n }\n if (!isArray(iterable)) return false\n\n return _indexOf(valueToFind, iterable) > -1\n}\n","export function is(targetPrototype, x){\n if (arguments.length === 1) return _x => is(targetPrototype, _x)\n\n return (\n x != null && x.constructor === targetPrototype ||\n x instanceof targetPrototype\n )\n}\n","import { type } from './type.js'\n\nexport function isEmpty(input){\n const inputType = type(input)\n if ([ 'Undefined', 'NaN', 'Number', 'Null' ].includes(inputType))\n return false\n if (!input) return true\n\n if (inputType === 'Object'){\n return Object.keys(input).length === 0\n }\n\n if (inputType === 'Array'){\n return input.length === 0\n }\n\n return false\n}\n","export function match(pattern, input){\n if (arguments.length === 1) return _input => match(pattern, _input)\n\n const willReturn = input.match(pattern)\n\n return willReturn === null ? [] : willReturn\n}\n","export function mergeRight(target, newProps){\n if (arguments.length === 1)\n return _newProps => mergeRight(target, _newProps)\n\n return Object.assign(\n {}, target || {}, newProps || {}\n )\n}\n","export const INCORRECT_ITERABLE_INPUT = 'Incorrect iterable input'\n","export const { keys } = Object\n","import { INCORRECT_ITERABLE_INPUT } from './_internals/constants.js'\nimport { isArray } from './_internals/isArray.js'\nimport { keys } from './_internals/keys.js'\n\nexport function mapArray(\n fn, list, isIndexed = false\n){\n let index = 0\n const willReturn = Array(list.length)\n\n while (index < list.length){\n willReturn[ index ] = isIndexed ? fn(list[ index ], index) : fn(list[ index ])\n\n index++\n }\n\n return willReturn\n}\n\nexport function mapObject(fn, obj){\n if (arguments.length === 1){\n return _obj => mapObject(fn, _obj)\n }\n let index = 0\n const objKeys = keys(obj)\n const len = objKeys.length\n const willReturn = {}\n\n while (index < len){\n const key = objKeys[ index ]\n willReturn[ key ] = fn(\n obj[ key ], key, obj\n )\n index++\n }\n\n return willReturn\n}\n\nexport const mapObjIndexed = mapObject\n\nexport function map(fn, iterable){\n if (arguments.length === 1) return _iterable => map(fn, _iterable)\n if (!iterable){\n throw new Error(INCORRECT_ITERABLE_INPUT)\n }\n\n if (isArray(iterable)) return mapArray(fn, iterable)\n\n return mapObject(fn, iterable)\n}\n","import { map } from './map.js'\nimport { mergeRight } from './mergeRight.js'\n\nexport function mergeAll(arr){\n let willReturn = {}\n map(val => {\n willReturn = mergeRight(willReturn, val)\n }, arr)\n\n return willReturn\n}\n","export function multiply(x, y){\n if (arguments.length === 1) return _y => multiply(x, _y)\n\n return x * y\n}\n","export function negate(x){\n return -x\n}\n","export function createPath(path, delimiter = '.'){\n return typeof path === 'string' ? path.split(delimiter) : path\n}\n","import { createPath } from './_internals/createPath.js'\n\nexport function omit(propsToOmit, obj){\n if (arguments.length === 1) return _obj => omit(propsToOmit, _obj)\n\n if (obj === null || obj === undefined){\n return undefined\n }\n\n const propsToOmitValue = createPath(propsToOmit, ',')\n const willReturn = {}\n\n for (const key in obj){\n if (!propsToOmitValue.includes(key)){\n willReturn[ key ] = obj[ key ]\n }\n }\n\n return willReturn\n}\n","import { createPath } from './_internals/createPath.js'\n\nexport function pathFn(pathInput, obj){\n let willReturn = obj\n let counter = 0\n\n const pathArrValue = createPath(pathInput)\n\n while (counter < pathArrValue.length){\n if (willReturn === null || willReturn === undefined){\n return undefined\n }\n if (willReturn[ pathArrValue[ counter ] ] === null) return undefined\n\n willReturn = willReturn[ pathArrValue[ counter ] ]\n counter++\n }\n\n return willReturn\n}\n\nexport function path(pathInput, obj){\n if (arguments.length === 1) return _obj => path(pathInput, _obj)\n\n if (obj === null || obj === undefined){\n return undefined\n }\n\n return pathFn(pathInput, obj)\n}\n","import { curry } from './curry.js'\nimport { defaultTo } from './defaultTo.js'\nimport { path } from './path.js'\n\nfunction pathOrFn(\n defaultValue, pathInput, obj\n){\n return defaultTo(defaultValue, path(pathInput, obj))\n}\n\nexport const pathOr = curry(pathOrFn)\n","import { createPath } from './_internals/createPath.js'\n\nexport function pick(propsToPick, input){\n if (arguments.length === 1) return _input => pick(propsToPick, _input)\n\n if (input === null || input === undefined){\n return undefined\n }\n const keys = createPath(propsToPick, ',')\n const willReturn = {}\n let counter = 0\n\n while (counter < keys.length){\n if (keys[ counter ] in input){\n willReturn[ keys[ counter ] ] = input[ keys[ counter ] ]\n }\n counter++\n }\n\n return willReturn\n}\n","import { map } from './map.js'\n\nexport function pluck(property, list){\n if (arguments.length === 1) return _list => pluck(property, _list)\n\n const willReturn = []\n\n map(x => {\n if (x[ property ] !== undefined){\n willReturn.push(x[ property ])\n }\n }, list)\n\n return willReturn\n}\n","export function prop(propToFind, obj){\n if (arguments.length === 1) return _obj => prop(propToFind, _obj)\n\n if (!obj) return undefined\n\n return obj[ propToFind ]\n}\n","export function range(start, end){\n if (arguments.length === 1) return _end => range(start, _end)\n\n if (Number.isNaN(Number(start)) || Number.isNaN(Number(end))){\n throw new TypeError('Both arguments to range must be numbers')\n }\n\n if (end < start) return []\n\n const len = end - start\n const willReturn = Array(len)\n\n for (let i = 0; i < len; i++){\n willReturn[ i ] = start + i\n }\n\n return willReturn\n}\n","import { isArray } from './_internals/isArray.js'\nimport { curry } from './curry.js'\n\nclass ReduceStopper{\n constructor(value){\n this.value = value\n }\n}\n\nexport function reduceFn(\n reducer, acc, list\n){\n if (list == null){\n return acc\n }\n if (!isArray(list)){\n throw new TypeError('reduce: list must be array or iterable')\n }\n let index = 0\n const len = list.length\n\n while (index < len){\n acc = reducer(\n acc, list[ index ], index, list\n )\n if (acc instanceof ReduceStopper){\n return acc.value\n }\n index++\n }\n\n return acc\n}\n\nexport const reduce = curry(reduceFn)\nexport const reduceStopper = value => new ReduceStopper(value)\n","import { curry } from './curry.js'\n\nfunction replaceFn(\n pattern, replacer, str\n){\n return str.replace(pattern, replacer)\n}\n\nexport const replace = curry(replaceFn)\n","import { cloneList } from './_internals/cloneList.js'\n\nexport function sortBy(sortFn, list){\n if (arguments.length === 1) return _list => sortBy(sortFn, _list)\n\n const clone = cloneList(list)\n\n return clone.sort((a, b) => {\n const aSortResult = sortFn(a)\n const bSortResult = sortFn(b)\n\n if (aSortResult === bSortResult) return 0\n\n return aSortResult < bSortResult ? -1 : 1\n })\n}\n","export function sum(list){\n return list.reduce((prev, current) => prev + current, 0)\n}\n","export function toLower(str){\n return str.toLowerCase()\n}\n","export function toPairs(obj){\n return Object.entries(obj)\n}\n","import { type } from './type.js'\n\nexport function values(obj){\n if (type(obj) !== 'Object') return []\n\n return Object.values(obj)\n}\n","export default function _isPlaceholder(a) {\n return a != null && typeof a === 'object' && a['@@functional/placeholder'] === true;\n}","import _isPlaceholder from \"./_isPlaceholder.js\";\n/**\n * Optimized internal one-arity curry function.\n *\n * @private\n * @category Function\n * @param {Function} fn The function to curry.\n * @return {Function} The curried function.\n */\n\nexport default function _curry1(fn) {\n return function f1(a) {\n if (arguments.length === 0 || _isPlaceholder(a)) {\n return f1;\n } else {\n return fn.apply(this, arguments);\n }\n };\n}","import _curry1 from \"./_curry1.js\";\nimport _isPlaceholder from \"./_isPlaceholder.js\";\n/**\n * Optimized internal two-arity curry function.\n *\n * @private\n * @category Function\n * @param {Function} fn The function to curry.\n * @return {Function} The curried function.\n */\n\nexport default function _curry2(fn) {\n return function f2(a, b) {\n switch (arguments.length) {\n case 0:\n return f2;\n\n case 1:\n return _isPlaceholder(a) ? f2 : _curry1(function (_b) {\n return fn(a, _b);\n });\n\n default:\n return _isPlaceholder(a) && _isPlaceholder(b) ? f2 : _isPlaceholder(a) ? _curry1(function (_a) {\n return fn(_a, b);\n }) : _isPlaceholder(b) ? _curry1(function (_b) {\n return fn(a, _b);\n }) : fn(a, b);\n }\n };\n}","import _curry2 from \"./internal/_curry2.js\";\n/**\n * Adds two values.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Math\n * @sig Number -> Number -> Number\n * @param {Number} a\n * @param {Number} b\n * @return {Number}\n * @see R.subtract\n * @example\n *\n * R.add(2, 3); //=> 5\n * R.add(7)(10); //=> 17\n */\n\nvar add =\n/*#__PURE__*/\n_curry2(function add(a, b) {\n return Number(a) + Number(b);\n});\n\nexport default add;","/**\n * Tests whether or not an object is an array.\n *\n * @private\n * @param {*} val The object to test.\n * @return {Boolean} `true` if `val` is an array, `false` otherwise.\n * @example\n *\n * _isArray([]); //=> true\n * _isArray(null); //=> false\n * _isArray({}); //=> false\n */\nexport default Array.isArray || function _isArray(val) {\n return val != null && val.length >= 0 && Object.prototype.toString.call(val) === '[object Array]';\n};","import _isArray from \"./_isArray.js\";\nimport _isTransformer from \"./_isTransformer.js\";\n/**\n * Returns a function that dispatches with different strategies based on the\n * object in list position (last argument). If it is an array, executes [fn].\n * Otherwise, if it has a function with one of the given method names, it will\n * execute that function (functor case). Otherwise, if it is a transformer,\n * uses transducer created by [transducerCreator] to return a new transformer\n * (transducer case).\n * Otherwise, it will default to executing [fn].\n *\n * @private\n * @param {Array} methodNames properties to check for a custom implementation\n * @param {Function} transducerCreator transducer factory if object is transformer\n * @param {Function} fn default ramda implementation\n * @return {Function} A function that dispatches on object in list position\n */\n\nexport default function _dispatchable(methodNames, transducerCreator, fn) {\n return function () {\n if (arguments.length === 0) {\n return fn();\n }\n\n var obj = arguments[arguments.length - 1];\n\n if (!_isArray(obj)) {\n var idx = 0;\n\n while (idx < methodNames.length) {\n if (typeof obj[methodNames[idx]] === 'function') {\n return obj[methodNames[idx]].apply(obj, Array.prototype.slice.call(arguments, 0, -1));\n }\n\n idx += 1;\n }\n\n if (_isTransformer(obj)) {\n var transducer = transducerCreator.apply(null, Array.prototype.slice.call(arguments, 0, -1));\n return transducer(obj);\n }\n }\n\n return fn.apply(this, arguments);\n };\n}","export default function _isTransformer(obj) {\n return obj != null && typeof obj['@@transducer/step'] === 'function';\n}","export default function _reduced(x) {\n return x && x['@@transducer/reduced'] ? x : {\n '@@transducer/value': x,\n '@@transducer/reduced': true\n };\n}","export default {\n init: function () {\n return this.xf['@@transducer/init']();\n },\n result: function (result) {\n return this.xf['@@transducer/result'](result);\n }\n};","import _reduced from \"./_reduced.js\";\nimport _xfBase from \"./_xfBase.js\";\n\nvar XAll =\n/*#__PURE__*/\nfunction () {\n function XAll(f, xf) {\n this.xf = xf;\n this.f = f;\n this.all = true;\n }\n\n XAll.prototype['@@transducer/init'] = _xfBase.init;\n\n XAll.prototype['@@transducer/result'] = function (result) {\n if (this.all) {\n result = this.xf['@@transducer/step'](result, true);\n }\n\n return this.xf['@@transducer/result'](result);\n };\n\n XAll.prototype['@@transducer/step'] = function (result, input) {\n if (!this.f(input)) {\n this.all = false;\n result = _reduced(this.xf['@@transducer/step'](result, false));\n }\n\n return result;\n };\n\n return XAll;\n}();\n\nexport default function _xall(f) {\n return function (xf) {\n return new XAll(f, xf);\n };\n}","import _curry2 from \"./internal/_curry2.js\";\nimport _dispatchable from \"./internal/_dispatchable.js\";\nimport _xall from \"./internal/_xall.js\";\n/**\n * Returns `true` if all elements of the list match the predicate, `false` if\n * there are any that don't.\n *\n * Dispatches to the `all` method of the second argument, if present.\n *\n * Acts as a transducer if a transformer is given in list position.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @sig (a -> Boolean) -> [a] -> Boolean\n * @param {Function} fn The predicate function.\n * @param {Array} list The array to consider.\n * @return {Boolean} `true` if the predicate is satisfied by every element, `false`\n * otherwise.\n * @see R.any, R.none, R.transduce\n * @example\n *\n * const equals3 = R.equals(3);\n * R.all(equals3)([3, 3, 3, 3]); //=> true\n * R.all(equals3)([3, 3, 1, 3]); //=> false\n */\n\nvar all =\n/*#__PURE__*/\n_curry2(\n/*#__PURE__*/\n_dispatchable(['all'], _xall, function all(fn, list) {\n var idx = 0;\n\n while (idx < list.length) {\n if (!fn(list[idx])) {\n return false;\n }\n\n idx += 1;\n }\n\n return true;\n}));\n\nexport default all;","export default function _arrayFromIterator(iter) {\n var list = [];\n var next;\n\n while (!(next = iter.next()).done) {\n list.push(next.value);\n }\n\n return list;\n}","export default function _includesWith(pred, x, list) {\n var idx = 0;\n var len = list.length;\n\n while (idx < len) {\n if (pred(x, list[idx])) {\n return true;\n }\n\n idx += 1;\n }\n\n return false;\n}","export default function _has(prop, obj) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}","// Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\nfunction _objectIs(a, b) {\n // SameValue algorithm\n if (a === b) {\n // Steps 1-5, 7-10\n // Steps 6.b-6.e: +0 != -0\n return a !== 0 || 1 / a === 1 / b;\n } else {\n // Step 6.a: NaN == NaN\n return a !== a && b !== b;\n }\n}\n\nexport default typeof Object.is === 'function' ? Object.is : _objectIs;","import _has from \"./_has.js\";\nvar toString = Object.prototype.toString;\n\nvar _isArguments =\n/*#__PURE__*/\nfunction () {\n return toString.call(arguments) === '[object Arguments]' ? function _isArguments(x) {\n return toString.call(x) === '[object Arguments]';\n } : function _isArguments(x) {\n return _has('callee', x);\n };\n}();\n\nexport default _isArguments;","import _curry1 from \"./internal/_curry1.js\";\nimport _has from \"./internal/_has.js\";\nimport _isArguments from \"./internal/_isArguments.js\"; // cover IE < 9 keys issues\n\nvar hasEnumBug = !\n/*#__PURE__*/\n{\n toString: null\n}.propertyIsEnumerable('toString');\nvar nonEnumerableProps = ['constructor', 'valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; // Safari bug\n\nvar hasArgsEnumBug =\n/*#__PURE__*/\nfunction () {\n 'use strict';\n\n return arguments.propertyIsEnumerable('length');\n}();\n\nvar contains = function contains(list, item) {\n var idx = 0;\n\n while (idx < list.length) {\n if (list[idx] === item) {\n return true;\n }\n\n idx += 1;\n }\n\n return false;\n};\n/**\n * Returns a list containing the names of all the enumerable own properties of\n * the supplied object.\n * Note that the order of the output array is not guaranteed to be consistent\n * across different JS platforms.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Object\n * @sig {k: v} -> [k]\n * @param {Object} obj The object to extract properties from\n * @return {Array} An array of the object's own properties.\n * @see R.keysIn, R.values, R.toPairs\n * @example\n *\n * R.keys({a: 1, b: 2, c: 3}); //=> ['a', 'b', 'c']\n */\n\n\nvar keys = typeof Object.keys === 'function' && !hasArgsEnumBug ?\n/*#__PURE__*/\n_curry1(function keys(obj) {\n return Object(obj) !== obj ? [] : Object.keys(obj);\n}) :\n/*#__PURE__*/\n_curry1(function keys(obj) {\n if (Object(obj) !== obj) {\n return [];\n }\n\n var prop, nIdx;\n var ks = [];\n\n var checkArgsLength = hasArgsEnumBug && _isArguments(obj);\n\n for (prop in obj) {\n if (_has(prop, obj) && (!checkArgsLength || prop !== 'length')) {\n ks[ks.length] = prop;\n }\n }\n\n if (hasEnumBug) {\n nIdx = nonEnumerableProps.length - 1;\n\n while (nIdx >= 0) {\n prop = nonEnumerableProps[nIdx];\n\n if (_has(prop, obj) && !contains(ks, prop)) {\n ks[ks.length] = prop;\n }\n\n nIdx -= 1;\n }\n }\n\n return ks;\n});\nexport default keys;","import _curry1 from \"./internal/_curry1.js\";\n/**\n * Gives a single-word string description of the (native) type of a value,\n * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not\n * attempt to distinguish user Object types any further, reporting them all as\n * 'Object'.\n *\n * @func\n * @memberOf R\n * @since v0.8.0\n * @category Type\n * @sig * -> String\n * @param {*} val The value to test\n * @return {String}\n * @example\n *\n * R.type({}); //=> \"Object\"\n * R.type(1); //=> \"Number\"\n * R.type(false); //=> \"Boolean\"\n * R.type('s'); //=> \"String\"\n * R.type(null); //=> \"Null\"\n * R.type([]); //=> \"Array\"\n * R.type(/[A-z]/); //=> \"RegExp\"\n * R.type(() => {}); //=> \"Function\"\n * R.type(undefined); //=> \"Undefined\"\n */\n\nvar type =\n/*#__PURE__*/\n_curry1(function type(val) {\n return val === null ? 'Null' : val === undefined ? 'Undefined' : Object.prototype.toString.call(val).slice(8, -1);\n});\n\nexport default type;","import _arrayFromIterator from \"./_arrayFromIterator.js\";\nimport _includesWith from \"./_includesWith.js\";\nimport _functionName from \"./_functionName.js\";\nimport _has from \"./_has.js\";\nimport _objectIs from \"./_objectIs.js\";\nimport keys from \"../keys.js\";\nimport type from \"../type.js\";\n/**\n * private _uniqContentEquals function.\n * That function is checking equality of 2 iterator contents with 2 assumptions\n * - iterators lengths are the same\n * - iterators values are unique\n *\n * false-positive result will be returned for comparison of, e.g.\n * - [1,2,3] and [1,2,3,4]\n * - [1,1,1] and [1,2,3]\n * */\n\nfunction _uniqContentEquals(aIterator, bIterator, stackA, stackB) {\n var a = _arrayFromIterator(aIterator);\n\n var b = _arrayFromIterator(bIterator);\n\n function eq(_a, _b) {\n return _equals(_a, _b, stackA.slice(), stackB.slice());\n } // if *a* array contains any element that is not included in *b*\n\n\n return !_includesWith(function (b, aItem) {\n return !_includesWith(eq, aItem, b);\n }, b, a);\n}\n\nexport default function _equals(a, b, stackA, stackB) {\n if (_objectIs(a, b)) {\n return true;\n }\n\n var typeA = type(a);\n\n if (typeA !== type(b)) {\n return false;\n }\n\n if (typeof a['fantasy-land/equals'] === 'function' || typeof b['fantasy-land/equals'] === 'function') {\n return typeof a['fantasy-land/equals'] === 'function' && a['fantasy-land/equals'](b) && typeof b['fantasy-land/equals'] === 'function' && b['fantasy-land/equals'](a);\n }\n\n if (typeof a.equals === 'function' || typeof b.equals === 'function') {\n return typeof a.equals === 'function' && a.equals(b) && typeof b.equals === 'function' && b.equals(a);\n }\n\n switch (typeA) {\n case 'Arguments':\n case 'Array':\n case 'Object':\n if (typeof a.constructor === 'function' && _functionName(a.constructor) === 'Promise') {\n return a === b;\n }\n\n break;\n\n case 'Boolean':\n case 'Number':\n case 'String':\n if (!(typeof a === typeof b && _objectIs(a.valueOf(), b.valueOf()))) {\n return false;\n }\n\n break;\n\n case 'Date':\n if (!_objectIs(a.valueOf(), b.valueOf())) {\n return false;\n }\n\n break;\n\n case 'Error':\n return a.name === b.name && a.message === b.message;\n\n case 'RegExp':\n if (!(a.source === b.source && a.global === b.global && a.ignoreCase === b.ignoreCase && a.multiline === b.multiline && a.sticky === b.sticky && a.unicode === b.unicode)) {\n return false;\n }\n\n break;\n }\n\n var idx = stackA.length - 1;\n\n while (idx >= 0) {\n if (stackA[idx] === a) {\n return stackB[idx] === b;\n }\n\n idx -= 1;\n }\n\n switch (typeA) {\n case 'Map':\n if (a.size !== b.size) {\n return false;\n }\n\n return _uniqContentEquals(a.entries(), b.entries(), stackA.concat([a]), stackB.concat([b]));\n\n case 'Set':\n if (a.size !== b.size) {\n return false;\n }\n\n return _uniqContentEquals(a.values(), b.values(), stackA.concat([a]), stackB.concat([b]));\n\n case 'Arguments':\n case 'Array':\n case 'Object':\n case 'Boolean':\n case 'Number':\n case 'String':\n case 'Date':\n case 'Error':\n case 'RegExp':\n case 'Int8Array':\n case 'Uint8Array':\n case 'Uint8ClampedArray':\n case 'Int16Array':\n case 'Uint16Array':\n case 'Int32Array':\n case 'Uint32Array':\n case 'Float32Array':\n case 'Float64Array':\n case 'ArrayBuffer':\n break;\n\n default:\n // Values of other types are only equal if identical.\n return false;\n }\n\n var keysA = keys(a);\n\n if (keysA.length !== keys(b).length) {\n return false;\n }\n\n var extendedStackA = stackA.concat([a]);\n var extendedStackB = stackB.concat([b]);\n idx = keysA.length - 1;\n\n while (idx >= 0) {\n var key = keysA[idx];\n\n if (!(_has(key, b) && _equals(b[key], a[key], extendedStackA, extendedStackB))) {\n return false;\n }\n\n idx -= 1;\n }\n\n return true;\n}","export default function _functionName(f) {\n // String(x => x) evaluates to \"x => x\", so the pattern may not match.\n var match = String(f).match(/^function (\\w*)/);\n return match == null ? '' : match[1];\n}","import _curry2 from \"./internal/_curry2.js\";\nimport _equals from \"./internal/_equals.js\";\n/**\n * Returns `true` if its arguments are equivalent, `false` otherwise. Handles\n * cyclical data structures.\n *\n * Dispatches symmetrically to the `equals` methods of both arguments, if\n * present.\n *\n * @func\n * @memberOf R\n * @since v0.15.0\n * @category Relation\n * @sig a -> b -> Boolean\n * @param {*} a\n * @param {*} b\n * @return {Boolean}\n * @example\n *\n * R.equals(1, 1); //=> true\n * R.equals(1, '1'); //=> false\n * R.equals([1, 2, 3], [1, 2, 3]); //=> true\n *\n * const a = {}; a.v = a;\n * const b = {}; b.v = b;\n * R.equals(a, b); //=> true\n */\n\nvar equals =\n/*#__PURE__*/\n_curry2(function equals(a, b) {\n return _equals(a, b, [], []);\n});\n\nexport default equals;","import _indexOf from \"./_indexOf.js\";\nexport default function _includes(a, list) {\n return _indexOf(list, a, 0) >= 0;\n}","import equals from \"../equals.js\";\nexport default function _indexOf(list, a, idx) {\n var inf, item; // Array.prototype.indexOf doesn't exist below IE9\n\n if (typeof list.indexOf === 'function') {\n switch (typeof a) {\n case 'number':\n if (a === 0) {\n // manually crawl the list to distinguish between +0 and -0\n inf = 1 / a;\n\n while (idx < list.length) {\n item = list[idx];\n\n if (item === 0 && 1 / item === inf) {\n return idx;\n }\n\n idx += 1;\n }\n\n return -1;\n } else if (a !== a) {\n // NaN\n while (idx < list.length) {\n item = list[idx];\n\n if (typeof item === 'number' && item !== item) {\n return idx;\n }\n\n idx += 1;\n }\n\n return -1;\n } // non-zero numbers can utilise Set\n\n\n return list.indexOf(a, idx);\n // all these types can utilise Set\n\n case 'string':\n case 'boolean':\n case 'function':\n case 'undefined':\n return list.indexOf(a, idx);\n\n case 'object':\n if (a === null) {\n // null can utilise Set\n return list.indexOf(a, idx);\n }\n\n }\n } // anything else not covered above, defer to R.equals\n\n\n while (idx < list.length) {\n if (equals(list[idx], a)) {\n return idx;\n }\n\n idx += 1;\n }\n\n return -1;\n}","export default function _map(fn, functor) {\n var idx = 0;\n var len = functor.length;\n var result = Array(len);\n\n while (idx < len) {\n result[idx] = fn(functor[idx]);\n idx += 1;\n }\n\n return result;\n}","export default function _quote(s) {\n var escaped = s.replace(/\\\\/g, '\\\\\\\\').replace(/[\\b]/g, '\\\\b') // \\b matches word boundary; [\\b] matches backspace\n .replace(/\\f/g, '\\\\f').replace(/\\n/g, '\\\\n').replace(/\\r/g, '\\\\r').replace(/\\t/g, '\\\\t').replace(/\\v/g, '\\\\v').replace(/\\0/g, '\\\\0');\n return '\"' + escaped.replace(/\"/g, '\\\\\"') + '\"';\n}","/**\n * Polyfill from .\n */\nvar pad = function pad(n) {\n return (n < 10 ? '0' : '') + n;\n};\n\nvar _toISOString = typeof Date.prototype.toISOString === 'function' ? function _toISOString(d) {\n return d.toISOString();\n} : function _toISOString(d) {\n return d.getUTCFullYear() + '-' + pad(d.getUTCMonth() + 1) + '-' + pad(d.getUTCDate()) + 'T' + pad(d.getUTCHours()) + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds()) + '.' + (d.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z';\n};\n\nexport default _toISOString;","export default function _arrayReduce(reducer, acc, list) {\n var index = 0;\n var length = list.length;\n\n while (index < length) {\n acc = reducer(acc, list[index]);\n index += 1;\n }\n\n return acc;\n}","export default function _filter(fn, list) {\n var idx = 0;\n var len = list.length;\n var result = [];\n\n while (idx < len) {\n if (fn(list[idx])) {\n result[result.length] = list[idx];\n }\n\n idx += 1;\n }\n\n return result;\n}","export default function _isObject(x) {\n return Object.prototype.toString.call(x) === '[object Object]';\n}","import _xfBase from \"./_xfBase.js\";\n\nvar XFilter =\n/*#__PURE__*/\nfunction () {\n function XFilter(f, xf) {\n this.xf = xf;\n this.f = f;\n }\n\n XFilter.prototype['@@transducer/init'] = _xfBase.init;\n XFilter.prototype['@@transducer/result'] = _xfBase.result;\n\n XFilter.prototype['@@transducer/step'] = function (result, input) {\n return this.f(input) ? this.xf['@@transducer/step'](result, input) : result;\n };\n\n return XFilter;\n}();\n\nexport default function _xfilter(f) {\n return function (xf) {\n return new XFilter(f, xf);\n };\n}","import _arrayReduce from \"./internal/_arrayReduce.js\";\nimport _curry2 from \"./internal/_curry2.js\";\nimport _dispatchable from \"./internal/_dispatchable.js\";\nimport _filter from \"./internal/_filter.js\";\nimport _isObject from \"./internal/_isObject.js\";\nimport _xfilter from \"./internal/_xfilter.js\";\nimport keys from \"./keys.js\";\n/**\n * Takes a predicate and a `Filterable`, and returns a new filterable of the\n * same type containing the members of the given filterable which satisfy the\n * given predicate. Filterable objects include plain objects or any object\n * that has a filter method such as `Array`.\n *\n * Dispatches to the `filter` method of the second argument, if present.\n *\n * Acts as a transducer if a transformer is given in list position.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @category Object\n * @sig Filterable f => (a -> Boolean) -> f a -> f a\n * @param {Function} pred\n * @param {Array} filterable\n * @return {Array} Filterable\n * @see R.reject, R.transduce, R.addIndex\n * @example\n *\n * const isEven = n => n % 2 === 0;\n *\n * R.filter(isEven, [1, 2, 3, 4]); //=> [2, 4]\n *\n * R.filter(isEven, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4}\n */\n\nvar filter =\n/*#__PURE__*/\n_curry2(\n/*#__PURE__*/\n_dispatchable(['fantasy-land/filter', 'filter'], _xfilter, function (pred, filterable) {\n return _isObject(filterable) ? _arrayReduce(function (acc, key) {\n if (pred(filterable[key])) {\n acc[key] = filterable[key];\n }\n\n return acc;\n }, {}, keys(filterable)) : // else\n _filter(pred, filterable);\n}));\n\nexport default filter;","import _complement from \"./internal/_complement.js\";\nimport _curry2 from \"./internal/_curry2.js\";\nimport filter from \"./filter.js\";\n/**\n * The complement of [`filter`](#filter).\n *\n * Acts as a transducer if a transformer is given in list position. Filterable\n * objects include plain objects or any object that has a filter method such\n * as `Array`.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @sig Filterable f => (a -> Boolean) -> f a -> f a\n * @param {Function} pred\n * @param {Array} filterable\n * @return {Array}\n * @see R.filter, R.transduce, R.addIndex\n * @example\n *\n * const isOdd = (n) => n % 2 !== 0;\n *\n * R.reject(isOdd, [1, 2, 3, 4]); //=> [2, 4]\n *\n * R.reject(isOdd, {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, d: 4}\n */\n\nvar reject =\n/*#__PURE__*/\n_curry2(function reject(pred, filterable) {\n return filter(_complement(pred), filterable);\n});\n\nexport default reject;","export default function _complement(f) {\n return function () {\n return !f.apply(this, arguments);\n };\n}","import _includes from \"./_includes.js\";\nimport _map from \"./_map.js\";\nimport _quote from \"./_quote.js\";\nimport _toISOString from \"./_toISOString.js\";\nimport keys from \"../keys.js\";\nimport reject from \"../reject.js\";\nexport default function _toString(x, seen) {\n var recur = function recur(y) {\n var xs = seen.concat([x]);\n return _includes(y, xs) ? '' : _toString(y, xs);\n }; // mapPairs :: (Object, [String]) -> [String]\n\n\n var mapPairs = function (obj, keys) {\n return _map(function (k) {\n return _quote(k) + ': ' + recur(obj[k]);\n }, keys.slice().sort());\n };\n\n switch (Object.prototype.toString.call(x)) {\n case '[object Arguments]':\n return '(function() { return arguments; }(' + _map(recur, x).join(', ') + '))';\n\n case '[object Array]':\n return '[' + _map(recur, x).concat(mapPairs(x, reject(function (k) {\n return /^\\d+$/.test(k);\n }, keys(x)))).join(', ') + ']';\n\n case '[object Boolean]':\n return typeof x === 'object' ? 'new Boolean(' + recur(x.valueOf()) + ')' : x.toString();\n\n case '[object Date]':\n return 'new Date(' + (isNaN(x.valueOf()) ? recur(NaN) : _quote(_toISOString(x))) + ')';\n\n case '[object Map]':\n return 'new Map(' + recur(Array.from(x)) + ')';\n\n case '[object Null]':\n return 'null';\n\n case '[object Number]':\n return typeof x === 'object' ? 'new Number(' + recur(x.valueOf()) + ')' : 1 / x === -Infinity ? '-0' : x.toString(10);\n\n case '[object Set]':\n return 'new Set(' + recur(Array.from(x).sort()) + ')';\n\n case '[object String]':\n return typeof x === 'object' ? 'new String(' + recur(x.valueOf()) + ')' : _quote(x);\n\n case '[object Undefined]':\n return 'undefined';\n\n default:\n if (typeof x.toString === 'function') {\n var repr = x.toString();\n\n if (repr !== '[object Object]') {\n return repr;\n }\n }\n\n return '{' + mapPairs(x, keys(x)).join(', ') + '}';\n }\n}","import _curry1 from \"./internal/_curry1.js\";\nimport _toString from \"./internal/_toString.js\";\n/**\n * Returns the string representation of the given value. `eval`'ing the output\n * should result in a value equivalent to the input value. Many of the built-in\n * `toString` methods do not satisfy this requirement.\n *\n * If the given value is an `[object Object]` with a `toString` method other\n * than `Object.prototype.toString`, this method is invoked with no arguments\n * to produce the return value. This means user-defined constructor functions\n * can provide a suitable `toString` method. For example:\n *\n * function Point(x, y) {\n * this.x = x;\n * this.y = y;\n * }\n *\n * Point.prototype.toString = function() {\n * return 'new Point(' + this.x + ', ' + this.y + ')';\n * };\n *\n * R.toString(new Point(1, 2)); //=> 'new Point(1, 2)'\n *\n * @func\n * @memberOf R\n * @since v0.14.0\n * @category String\n * @sig * -> String\n * @param {*} val\n * @return {String}\n * @example\n *\n * R.toString(42); //=> '42'\n * R.toString('abc'); //=> '\"abc\"'\n * R.toString([1, 2, 3]); //=> '[1, 2, 3]'\n * R.toString({foo: 1, bar: 2, baz: 3}); //=> '{\"bar\": 2, \"baz\": 3, \"foo\": 1}'\n * R.toString(new Date('2001-02-03T04:05:06Z')); //=> 'new Date(\"2001-02-03T04:05:06.000Z\")'\n */\n\nvar toString =\n/*#__PURE__*/\n_curry1(function toString(val) {\n return _toString(val, []);\n});\n\nexport default toString;","import _curry2 from \"./internal/_curry2.js\";\nimport toString from \"./toString.js\";\n/**\n * Returns the larger of its two arguments.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Relation\n * @sig Ord a => a -> a -> a\n * @param {*} a\n * @param {*} b\n * @return {*}\n * @see R.maxBy, R.min\n * @example\n *\n * R.max(789, 123); //=> 789\n * R.max('a', 'b'); //=> 'b'\n */\n\nvar max =\n/*#__PURE__*/\n_curry2(function max(a, b) {\n if (a === b) {\n return b;\n }\n\n function safeMax(x, y) {\n if (x > y !== y > x) {\n return y > x ? y : x;\n }\n\n return undefined;\n }\n\n var maxByValue = safeMax(a, b);\n\n if (maxByValue !== undefined) {\n return maxByValue;\n }\n\n var maxByType = safeMax(typeof a, typeof b);\n\n if (maxByType !== undefined) {\n return maxByType === typeof a ? a : b;\n }\n\n var stringA = toString(a);\n var maxByStringValue = safeMax(stringA, toString(b));\n\n if (maxByStringValue !== undefined) {\n return maxByStringValue === stringA ? a : b;\n }\n\n return b;\n});\n\nexport default max;","import _xfBase from \"./_xfBase.js\";\n\nvar XMap =\n/*#__PURE__*/\nfunction () {\n function XMap(f, xf) {\n this.xf = xf;\n this.f = f;\n }\n\n XMap.prototype['@@transducer/init'] = _xfBase.init;\n XMap.prototype['@@transducer/result'] = _xfBase.result;\n\n XMap.prototype['@@transducer/step'] = function (result, input) {\n return this.xf['@@transducer/step'](result, this.f(input));\n };\n\n return XMap;\n}();\n\nvar _xmap = function _xmap(f) {\n return function (xf) {\n return new XMap(f, xf);\n };\n};\n\nexport default _xmap;","export default function _arity(n, fn) {\n /* eslint-disable no-unused-vars */\n switch (n) {\n case 0:\n return function () {\n return fn.apply(this, arguments);\n };\n\n case 1:\n return function (a0) {\n return fn.apply(this, arguments);\n };\n\n case 2:\n return function (a0, a1) {\n return fn.apply(this, arguments);\n };\n\n case 3:\n return function (a0, a1, a2) {\n return fn.apply(this, arguments);\n };\n\n case 4:\n return function (a0, a1, a2, a3) {\n return fn.apply(this, arguments);\n };\n\n case 5:\n return function (a0, a1, a2, a3, a4) {\n return fn.apply(this, arguments);\n };\n\n case 6:\n return function (a0, a1, a2, a3, a4, a5) {\n return fn.apply(this, arguments);\n };\n\n case 7:\n return function (a0, a1, a2, a3, a4, a5, a6) {\n return fn.apply(this, arguments);\n };\n\n case 8:\n return function (a0, a1, a2, a3, a4, a5, a6, a7) {\n return fn.apply(this, arguments);\n };\n\n case 9:\n return function (a0, a1, a2, a3, a4, a5, a6, a7, a8) {\n return fn.apply(this, arguments);\n };\n\n case 10:\n return function (a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) {\n return fn.apply(this, arguments);\n };\n\n default:\n throw new Error('First argument to _arity must be a non-negative integer no greater than ten');\n }\n}","import _arity from \"./_arity.js\";\nimport _isPlaceholder from \"./_isPlaceholder.js\";\n/**\n * Internal curryN function.\n *\n * @private\n * @category Function\n * @param {Number} length The arity of the curried function.\n * @param {Array} received An array of arguments received thus far.\n * @param {Function} fn The function to curry.\n * @return {Function} The curried function.\n */\n\nexport default function _curryN(length, received, fn) {\n return function () {\n var combined = [];\n var argsIdx = 0;\n var left = length;\n var combinedIdx = 0;\n\n while (combinedIdx < received.length || argsIdx < arguments.length) {\n var result;\n\n if (combinedIdx < received.length && (!_isPlaceholder(received[combinedIdx]) || argsIdx >= arguments.length)) {\n result = received[combinedIdx];\n } else {\n result = arguments[argsIdx];\n argsIdx += 1;\n }\n\n combined[combinedIdx] = result;\n\n if (!_isPlaceholder(result)) {\n left -= 1;\n }\n\n combinedIdx += 1;\n }\n\n return left <= 0 ? fn.apply(this, combined) : _arity(left, _curryN(length, combined, fn));\n };\n}","import _arity from \"./internal/_arity.js\";\nimport _curry1 from \"./internal/_curry1.js\";\nimport _curry2 from \"./internal/_curry2.js\";\nimport _curryN from \"./internal/_curryN.js\";\n/**\n * Returns a curried equivalent of the provided function, with the specified\n * arity. The curried function has two unusual capabilities. First, its\n * arguments needn't be provided one at a time. If `g` is `R.curryN(3, f)`, the\n * following are equivalent:\n *\n * - `g(1)(2)(3)`\n * - `g(1)(2, 3)`\n * - `g(1, 2)(3)`\n * - `g(1, 2, 3)`\n *\n * Secondly, the special placeholder value [`R.__`](#__) may be used to specify\n * \"gaps\", allowing partial application of any combination of arguments,\n * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__),\n * the following are equivalent:\n *\n * - `g(1, 2, 3)`\n * - `g(_, 2, 3)(1)`\n * - `g(_, _, 3)(1)(2)`\n * - `g(_, _, 3)(1, 2)`\n * - `g(_, 2)(1)(3)`\n * - `g(_, 2)(1, 3)`\n * - `g(_, 2)(_, 3)(1)`\n *\n * @func\n * @memberOf R\n * @since v0.5.0\n * @category Function\n * @sig Number -> (* -> a) -> (* -> a)\n * @param {Number} length The arity for the returned function.\n * @param {Function} fn The function to curry.\n * @return {Function} A new, curried function.\n * @see R.curry\n * @example\n *\n * const sumArgs = (...args) => R.sum(args);\n *\n * const curriedAddFourNumbers = R.curryN(4, sumArgs);\n * const f = curriedAddFourNumbers(1, 2);\n * const g = f(3);\n * g(4); //=> 10\n */\n\nvar curryN =\n/*#__PURE__*/\n_curry2(function curryN(length, fn) {\n if (length === 1) {\n return _curry1(fn);\n }\n\n return _arity(length, _curryN(length, [], fn));\n});\n\nexport default curryN;","import _arrayReduce from \"./internal/_arrayReduce.js\";\nimport _curry2 from \"./internal/_curry2.js\";\nimport _dispatchable from \"./internal/_dispatchable.js\";\nimport _map from \"./internal/_map.js\";\nimport _xmap from \"./internal/_xmap.js\";\nimport curryN from \"./curryN.js\";\nimport keys from \"./keys.js\";\n/**\n * Takes a function and\n * a [functor](https://github.com/fantasyland/fantasy-land#functor),\n * applies the function to each of the functor's values, and returns\n * a functor of the same shape.\n *\n * Ramda provides suitable `map` implementations for `Array` and `Object`,\n * so this function may be applied to `[1, 2, 3]` or `{x: 1, y: 2, z: 3}`.\n *\n * Dispatches to the `map` method of the second argument, if present.\n *\n * Acts as a transducer if a transformer is given in list position.\n *\n * Also treats functions as functors and will compose them together.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @sig Functor f => (a -> b) -> f a -> f b\n * @param {Function} fn The function to be called on every element of the input `list`.\n * @param {Array} list The list to be iterated over.\n * @return {Array} The new list.\n * @see R.transduce, R.addIndex, R.pluck, R.project\n * @example\n *\n * const double = x => x * 2;\n *\n * R.map(double, [1, 2, 3]); //=> [2, 4, 6]\n *\n * R.map(double, {x: 1, y: 2, z: 3}); //=> {x: 2, y: 4, z: 6}\n * @symb R.map(f, [a, b]) = [f(a), f(b)]\n * @symb R.map(f, { x: a, y: b }) = { x: f(a), y: f(b) }\n * @symb R.map(f, functor_o) = functor_o.map(f)\n */\n\nvar map =\n/*#__PURE__*/\n_curry2(\n/*#__PURE__*/\n_dispatchable(['fantasy-land/map', 'map'], _xmap, function map(fn, functor) {\n switch (Object.prototype.toString.call(functor)) {\n case '[object Function]':\n return curryN(functor.length, function () {\n return fn.call(this, functor.apply(this, arguments));\n });\n\n case '[object Object]':\n return _arrayReduce(function (acc, key) {\n acc[key] = fn(functor[key]);\n return acc;\n }, {}, keys(functor));\n\n default:\n return _map(fn, functor);\n }\n}));\n\nexport default map;","/**\n * Determine if the passed argument is an integer.\n *\n * @private\n * @param {*} n\n * @category Type\n * @return {Boolean}\n */\nexport default Number.isInteger || function _isInteger(n) {\n return n << 0 === n;\n};","export default function _isString(x) {\n return Object.prototype.toString.call(x) === '[object String]';\n}","import _curry2 from \"./internal/_curry2.js\";\nimport _isString from \"./internal/_isString.js\";\n/**\n * Returns the nth element of the given list or string. If n is negative the\n * element at index length + n is returned.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @sig Number -> [a] -> a | Undefined\n * @sig Number -> String -> String\n * @param {Number} offset\n * @param {*} list\n * @return {*}\n * @example\n *\n * const list = ['foo', 'bar', 'baz', 'quux'];\n * R.nth(1, list); //=> 'bar'\n * R.nth(-1, list); //=> 'quux'\n * R.nth(-99, list); //=> undefined\n *\n * R.nth(2, 'abc'); //=> 'c'\n * R.nth(3, 'abc'); //=> ''\n * @symb R.nth(-1, [a, b, c]) = c\n * @symb R.nth(0, [a, b, c]) = a\n * @symb R.nth(1, [a, b, c]) = b\n */\n\nvar nth =\n/*#__PURE__*/\n_curry2(function nth(offset, list) {\n var idx = offset < 0 ? list.length + offset : offset;\n return _isString(list) ? list.charAt(idx) : list[idx];\n});\n\nexport default nth;","import _curry2 from \"./internal/_curry2.js\";\nimport _isInteger from \"./internal/_isInteger.js\";\nimport nth from \"./nth.js\";\n/**\n * Returns a function that when supplied an object returns the indicated\n * property of that object, if it exists.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Object\n * @typedefn Idx = String | Int | Symbol\n * @sig Idx -> {s: a} -> a | Undefined\n * @param {String|Number} p The property name or array index\n * @param {Object} obj The object to query\n * @return {*} The value at `obj.p`.\n * @see R.path, R.props, R.pluck, R.project, R.nth\n * @example\n *\n * R.prop('x', {x: 100}); //=> 100\n * R.prop('x', {}); //=> undefined\n * R.prop(0, [100]); //=> 100\n * R.compose(R.inc, R.prop('x'))({ x: 3 }) //=> 4\n */\n\nvar prop =\n/*#__PURE__*/\n_curry2(function prop(p, obj) {\n if (obj == null) {\n return;\n }\n\n return _isInteger(p) ? nth(p, obj) : obj[p];\n});\n\nexport default prop;","import _curry2 from \"./internal/_curry2.js\";\nimport map from \"./map.js\";\nimport prop from \"./prop.js\";\n/**\n * Returns a new list by plucking the same named property off all objects in\n * the list supplied.\n *\n * `pluck` will work on\n * any [functor](https://github.com/fantasyland/fantasy-land#functor) in\n * addition to arrays, as it is equivalent to `R.map(R.prop(k), f)`.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @sig Functor f => k -> f {k: v} -> f v\n * @param {Number|String} key The key name to pluck off of each object.\n * @param {Array} f The array or functor to consider.\n * @return {Array} The list of values for the given key.\n * @see R.project, R.prop, R.props\n * @example\n *\n * var getAges = R.pluck('age');\n * getAges([{name: 'fred', age: 29}, {name: 'wilma', age: 27}]); //=> [29, 27]\n *\n * R.pluck(0, [[1, 2], [3, 4]]); //=> [1, 3]\n * R.pluck('val', {a: {val: 3}, b: {val: 5}}); //=> {a: 3, b: 5}\n * @symb R.pluck('x', [{x: 1, y: 2}, {x: 3, y: 4}, {x: 5, y: 6}]) = [1, 3, 5]\n * @symb R.pluck(0, [[1, 2], [3, 4], [5, 6]]) = [1, 3, 5]\n */\n\nvar pluck =\n/*#__PURE__*/\n_curry2(function pluck(p, list) {\n return map(prop(p), list);\n});\n\nexport default pluck;","import _curry1 from \"./_curry1.js\";\nimport _curry2 from \"./_curry2.js\";\nimport _isPlaceholder from \"./_isPlaceholder.js\";\n/**\n * Optimized internal three-arity curry function.\n *\n * @private\n * @category Function\n * @param {Function} fn The function to curry.\n * @return {Function} The curried function.\n */\n\nexport default function _curry3(fn) {\n return function f3(a, b, c) {\n switch (arguments.length) {\n case 0:\n return f3;\n\n case 1:\n return _isPlaceholder(a) ? f3 : _curry2(function (_b, _c) {\n return fn(a, _b, _c);\n });\n\n case 2:\n return _isPlaceholder(a) && _isPlaceholder(b) ? f3 : _isPlaceholder(a) ? _curry2(function (_a, _c) {\n return fn(_a, b, _c);\n }) : _isPlaceholder(b) ? _curry2(function (_b, _c) {\n return fn(a, _b, _c);\n }) : _curry1(function (_c) {\n return fn(a, b, _c);\n });\n\n default:\n return _isPlaceholder(a) && _isPlaceholder(b) && _isPlaceholder(c) ? f3 : _isPlaceholder(a) && _isPlaceholder(b) ? _curry2(function (_a, _b) {\n return fn(_a, _b, c);\n }) : _isPlaceholder(a) && _isPlaceholder(c) ? _curry2(function (_a, _c) {\n return fn(_a, b, _c);\n }) : _isPlaceholder(b) && _isPlaceholder(c) ? _curry2(function (_b, _c) {\n return fn(a, _b, _c);\n }) : _isPlaceholder(a) ? _curry1(function (_a) {\n return fn(_a, b, c);\n }) : _isPlaceholder(b) ? _curry1(function (_b) {\n return fn(a, _b, c);\n }) : _isPlaceholder(c) ? _curry1(function (_c) {\n return fn(a, b, _c);\n }) : fn(a, b, c);\n }\n };\n}","import _curry1 from \"./_curry1.js\";\nimport _isArray from \"./_isArray.js\";\nimport _isString from \"./_isString.js\";\n/**\n * Tests whether or not an object is similar to an array.\n *\n * @private\n * @category Type\n * @category List\n * @sig * -> Boolean\n * @param {*} x The object to test.\n * @return {Boolean} `true` if `x` has a numeric length property and extreme indices defined; `false` otherwise.\n * @example\n *\n * _isArrayLike([]); //=> true\n * _isArrayLike(true); //=> false\n * _isArrayLike({}); //=> false\n * _isArrayLike({length: 10}); //=> false\n * _isArrayLike({0: 'zero', 9: 'nine', length: 10}); //=> true\n * _isArrayLike({nodeType: 1, length: 1}) // => false\n */\n\nvar _isArrayLike =\n/*#__PURE__*/\n_curry1(function isArrayLike(x) {\n if (_isArray(x)) {\n return true;\n }\n\n if (!x) {\n return false;\n }\n\n if (typeof x !== 'object') {\n return false;\n }\n\n if (_isString(x)) {\n return false;\n }\n\n if (x.length === 0) {\n return true;\n }\n\n if (x.length > 0) {\n return x.hasOwnProperty(0) && x.hasOwnProperty(x.length - 1);\n }\n\n return false;\n});\n\nexport default _isArrayLike;","import _isArrayLike from \"./_isArrayLike.js\";\nvar symIterator = typeof Symbol !== 'undefined' ? Symbol.iterator : '@@iterator';\nexport default function _createReduce(arrayReduce, methodReduce, iterableReduce) {\n return function _reduce(xf, acc, list) {\n if (_isArrayLike(list)) {\n return arrayReduce(xf, acc, list);\n }\n\n if (list == null) {\n return acc;\n }\n\n if (typeof list['fantasy-land/reduce'] === 'function') {\n return methodReduce(xf, acc, list, 'fantasy-land/reduce');\n }\n\n if (list[symIterator] != null) {\n return iterableReduce(xf, acc, list[symIterator]());\n }\n\n if (typeof list.next === 'function') {\n return iterableReduce(xf, acc, list);\n }\n\n if (typeof list.reduce === 'function') {\n return methodReduce(xf, acc, list, 'reduce');\n }\n\n throw new TypeError('reduce: list must be array or iterable');\n };\n}","export default function _xArrayReduce(xf, acc, list) {\n var idx = 0;\n var len = list.length;\n\n while (idx < len) {\n acc = xf['@@transducer/step'](acc, list[idx]);\n\n if (acc && acc['@@transducer/reduced']) {\n acc = acc['@@transducer/value'];\n break;\n }\n\n idx += 1;\n }\n\n return xf['@@transducer/result'](acc);\n}","import _arity from \"./internal/_arity.js\";\nimport _curry2 from \"./internal/_curry2.js\";\n/**\n * Creates a function that is bound to a context.\n * Note: `R.bind` does not provide the additional argument-binding capabilities of\n * [Function.prototype.bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind).\n *\n * @func\n * @memberOf R\n * @since v0.6.0\n * @category Function\n * @category Object\n * @sig (* -> *) -> {*} -> (* -> *)\n * @param {Function} fn The function to bind to context\n * @param {Object} thisObj The context to bind `fn` to\n * @return {Function} A function that will execute in the context of `thisObj`.\n * @see R.partial\n * @example\n *\n * const log = R.bind(console.log, console);\n * R.pipe(R.assoc('a', 2), R.tap(log), R.assoc('a', 3))({a: 1}); //=> {a: 3}\n * // logs {a: 2}\n * @symb R.bind(f, o)(a, b) = f.call(o, a, b)\n */\n\nvar bind =\n/*#__PURE__*/\n_curry2(function bind(fn, thisObj) {\n return _arity(fn.length, function () {\n return fn.apply(thisObj, arguments);\n });\n});\n\nexport default bind;","import _createReduce from \"./_createReduce.js\";\nimport _xArrayReduce from \"./_xArrayReduce.js\";\nimport bind from \"../bind.js\";\n\nfunction _xIterableReduce(xf, acc, iter) {\n var step = iter.next();\n\n while (!step.done) {\n acc = xf['@@transducer/step'](acc, step.value);\n\n if (acc && acc['@@transducer/reduced']) {\n acc = acc['@@transducer/value'];\n break;\n }\n\n step = iter.next();\n }\n\n return xf['@@transducer/result'](acc);\n}\n\nfunction _xMethodReduce(xf, acc, obj, methodName) {\n return xf['@@transducer/result'](obj[methodName](bind(xf['@@transducer/step'], xf), acc));\n}\n\nvar _xReduce =\n/*#__PURE__*/\n_createReduce(_xArrayReduce, _xMethodReduce, _xIterableReduce);\n\nexport default _xReduce;","var XWrap =\n/*#__PURE__*/\nfunction () {\n function XWrap(fn) {\n this.f = fn;\n }\n\n XWrap.prototype['@@transducer/init'] = function () {\n throw new Error('init not implemented on XWrap');\n };\n\n XWrap.prototype['@@transducer/result'] = function (acc) {\n return acc;\n };\n\n XWrap.prototype['@@transducer/step'] = function (acc, x) {\n return this.f(acc, x);\n };\n\n return XWrap;\n}();\n\nexport default function _xwrap(fn) {\n return new XWrap(fn);\n}","import _curry3 from \"./internal/_curry3.js\";\nimport _xReduce from \"./internal/_xReduce.js\";\nimport _xwrap from \"./internal/_xwrap.js\";\n/**\n * Returns a single item by iterating through the list, successively calling\n * the iterator function and passing it an accumulator value and the current\n * value from the array, and then passing the result to the next call.\n *\n * The iterator function receives two values: *(acc, value)*. It may use\n * [`R.reduced`](#reduced) to shortcut the iteration.\n *\n * The arguments' order of [`reduceRight`](#reduceRight)'s iterator function\n * is *(value, acc)*.\n *\n * Note: `R.reduce` does not skip deleted or unassigned indices (sparse\n * arrays), unlike the native `Array.prototype.reduce` method. For more details\n * on this behavior, see:\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Description\n *\n * Be cautious of mutating and returning the accumulator. If you reuse it across\n * invocations, it will continue to accumulate onto the same value. The general\n * recommendation is to always return a new value. If you can't do so for\n * performance reasons, then be sure to reinitialize the accumulator on each\n * invocation.\n *\n * Dispatches to the `reduce` method of the third argument, if present. When\n * doing so, it is up to the user to handle the [`R.reduced`](#reduced)\n * shortcuting, as this is not implemented by `reduce`.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @sig ((a, b) -> a) -> a -> [b] -> a\n * @param {Function} fn The iterator function. Receives two values, the accumulator and the\n * current element from the array.\n * @param {*} acc The accumulator value.\n * @param {Array} list The list to iterate over.\n * @return {*} The final, accumulated value.\n * @see R.reduced, R.addIndex, R.reduceRight\n * @example\n *\n * R.reduce(R.subtract, 0, [1, 2, 3, 4]) // => ((((0 - 1) - 2) - 3) - 4) = -10\n * // - -10\n * // / \\ / \\\n * // - 4 -6 4\n * // / \\ / \\\n * // - 3 ==> -3 3\n * // / \\ / \\\n * // - 2 -1 2\n * // / \\ / \\\n * // 0 1 0 1\n *\n * @symb R.reduce(f, a, [b, c, d]) = f(f(f(a, b), c), d)\n */\n\nvar reduce =\n/*#__PURE__*/\n_curry3(function (xf, acc, list) {\n return _xReduce(typeof xf === 'function' ? _xwrap(xf) : xf, acc, list);\n});\n\nexport default reduce;","import _curry2 from \"./internal/_curry2.js\";\n/**\n * Returns the first argument if it is falsy, otherwise the second argument.\n * Acts as the boolean `and` statement if both inputs are `Boolean`s.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Logic\n * @sig a -> b -> a | b\n * @param {Any} a\n * @param {Any} b\n * @return {Any}\n * @see R.both, R.or\n * @example\n *\n * R.and(true, true); //=> true\n * R.and(true, false); //=> false\n * R.and(false, true); //=> false\n * R.and(false, false); //=> false\n */\n\nvar and =\n/*#__PURE__*/\n_curry2(function and(a, b) {\n return a && b;\n});\n\nexport default and;","import _curry1 from \"./internal/_curry1.js\";\nimport curryN from \"./curryN.js\";\nimport max from \"./max.js\";\nimport pluck from \"./pluck.js\";\nimport reduce from \"./reduce.js\";\n/**\n * Takes a list of predicates and returns a predicate that returns true for a\n * given list of arguments if at least one of the provided predicates is\n * satisfied by those arguments.\n *\n * The function returned is a curried function whose arity matches that of the\n * highest-arity predicate.\n *\n * @func\n * @memberOf R\n * @since v0.9.0\n * @category Logic\n * @sig [(*... -> Boolean)] -> (*... -> Boolean)\n * @param {Array} predicates An array of predicates to check\n * @return {Function} The combined predicate\n * @see R.allPass, R.either\n * @example\n *\n * const isClub = R.propEq('suit', '♣');\n * const isSpade = R.propEq('suit', '♠');\n * const isBlackCard = R.anyPass([isClub, isSpade]);\n *\n * isBlackCard({rank: '10', suit: '♣'}); //=> true\n * isBlackCard({rank: 'Q', suit: '♠'}); //=> true\n * isBlackCard({rank: 'Q', suit: '♦'}); //=> false\n */\n\nvar anyPass =\n/*#__PURE__*/\n_curry1(function anyPass(preds) {\n return curryN(reduce(max, 0, pluck('length', preds)), function () {\n var idx = 0;\n var len = preds.length;\n\n while (idx < len) {\n if (preds[idx].apply(this, arguments)) {\n return true;\n }\n\n idx += 1;\n }\n\n return false;\n });\n});\n\nexport default anyPass;","import _curry2 from \"./internal/_curry2.js\";\n/**\n * Applies function `fn` to the argument list `args`. This is useful for\n * creating a fixed-arity function from a variadic function. `fn` should be a\n * bound function if context is significant.\n *\n * @func\n * @memberOf R\n * @since v0.7.0\n * @category Function\n * @sig (*... -> a) -> [*] -> a\n * @param {Function} fn The function which will be called with `args`\n * @param {Array} args The arguments to call `fn` with\n * @return {*} result The result, equivalent to `fn(...args)`\n * @see R.call, R.unapply\n * @example\n *\n * const nums = [1, 2, 3, -99, 42, 6, 7];\n * R.apply(Math.max, nums); //=> 42\n * @symb R.apply(f, [a, b, c]) = f(a, b, c)\n */\n\nvar apply =\n/*#__PURE__*/\n_curry2(function apply(fn, args) {\n return fn.apply(this, args);\n});\n\nexport default apply;","import _curry1 from \"./internal/_curry1.js\";\nimport keys from \"./keys.js\";\n/**\n * Returns a list of all the enumerable own properties of the supplied object.\n * Note that the order of the output array is not guaranteed across different\n * JS platforms.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Object\n * @sig {k: v} -> [v]\n * @param {Object} obj The object to extract values from\n * @return {Array} An array of the values of the object's own properties.\n * @see R.valuesIn, R.keys, R.toPairs\n * @example\n *\n * R.values({a: 1, b: 2, c: 3}); //=> [1, 2, 3]\n */\n\nvar values =\n/*#__PURE__*/\n_curry1(function values(obj) {\n var props = keys(obj);\n var len = props.length;\n var vals = [];\n var idx = 0;\n\n while (idx < len) {\n vals[idx] = obj[props[idx]];\n idx += 1;\n }\n\n return vals;\n});\n\nexport default values;","import _curry1 from \"./internal/_curry1.js\";\nimport _isArray from \"./internal/_isArray.js\";\nimport apply from \"./apply.js\";\nimport curryN from \"./curryN.js\";\nimport max from \"./max.js\";\nimport pluck from \"./pluck.js\";\nimport reduce from \"./reduce.js\";\nimport keys from \"./keys.js\";\nimport values from \"./values.js\"; // Use custom mapValues function to avoid issues with specs that include a \"map\" key and R.map\n// delegating calls to .map\n\nfunction mapValues(fn, obj) {\n return _isArray(obj) ? obj.map(fn) : keys(obj).reduce(function (acc, key) {\n acc[key] = fn(obj[key]);\n return acc;\n }, {});\n}\n/**\n * Given a spec object recursively mapping properties to functions, creates a\n * function producing an object of the same structure, by mapping each property\n * to the result of calling its associated function with the supplied arguments.\n *\n * @func\n * @memberOf R\n * @since v0.20.0\n * @category Function\n * @sig {k: ((a, b, ..., m) -> v)} -> ((a, b, ..., m) -> {k: v})\n * @param {Object} spec an object recursively mapping properties to functions for\n * producing the values for these properties.\n * @return {Function} A function that returns an object of the same structure\n * as `spec', with each property set to the value returned by calling its\n * associated function with the supplied arguments.\n * @see R.converge, R.juxt\n * @example\n *\n * const getMetrics = R.applySpec({\n * sum: R.add,\n * nested: { mul: R.multiply }\n * });\n * getMetrics(2, 4); // => { sum: 6, nested: { mul: 8 } }\n * @symb R.applySpec({ x: f, y: { z: g } })(a, b) = { x: f(a, b), y: { z: g(a, b) } }\n */\n\n\nvar applySpec =\n/*#__PURE__*/\n_curry1(function applySpec(spec) {\n spec = mapValues(function (v) {\n return typeof v == 'function' ? v : applySpec(v);\n }, spec);\n return curryN(reduce(max, 0, pluck('length', values(spec))), function () {\n var args = arguments;\n return mapValues(function (f) {\n return apply(f, args);\n }, spec);\n });\n});\n\nexport default applySpec;","import _curry3 from \"./internal/_curry3.js\";\n/**\n * Makes an ascending comparator function out of a function that returns a value\n * that can be compared with `<` and `>`.\n *\n * @func\n * @memberOf R\n * @since v0.23.0\n * @category Function\n * @sig Ord b => (a -> b) -> a -> a -> Number\n * @param {Function} fn A function of arity one that returns a value that can be compared\n * @param {*} a The first item to be compared.\n * @param {*} b The second item to be compared.\n * @return {Number} `-1` if fn(a) < fn(b), `1` if fn(b) < fn(a), otherwise `0`\n * @see R.descend\n * @example\n *\n * const byAge = R.ascend(R.prop('age'));\n * const people = [\n * { name: 'Emma', age: 70 },\n * { name: 'Peter', age: 78 },\n * { name: 'Mikhail', age: 62 },\n * ];\n * const peopleByYoungestFirst = R.sort(byAge, people);\n * //=> [{ name: 'Mikhail', age: 62 },{ name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }]\n */\n\nvar ascend =\n/*#__PURE__*/\n_curry3(function ascend(fn, a, b) {\n var aa = fn(a);\n var bb = fn(b);\n return aa < bb ? -1 : aa > bb ? 1 : 0;\n});\n\nexport default ascend;","import _curry1 from \"./internal/_curry1.js\";\n/**\n * Checks if the input value is `null` or `undefined`.\n *\n * @func\n * @memberOf R\n * @since v0.9.0\n * @category Type\n * @sig * -> Boolean\n * @param {*} x The value to test.\n * @return {Boolean} `true` if `x` is `undefined` or `null`, otherwise `false`.\n * @example\n *\n * R.isNil(null); //=> true\n * R.isNil(undefined); //=> true\n * R.isNil(0); //=> false\n * R.isNil([]); //=> false\n */\n\nvar isNil =\n/*#__PURE__*/\n_curry1(function isNil(x) {\n return x == null;\n});\n\nexport default isNil;","import _curry3 from \"./internal/_curry3.js\";\nimport _has from \"./internal/_has.js\";\nimport _isInteger from \"./internal/_isInteger.js\";\nimport _assoc from \"./internal/_assoc.js\";\nimport isNil from \"./isNil.js\";\n/**\n * Makes a shallow clone of an object, setting or overriding the nodes required\n * to create the given path, and placing the specific value at the tail end of\n * that path. Note that this copies and flattens prototype properties onto the\n * new object as well. All non-primitive properties are copied by reference.\n *\n * @func\n * @memberOf R\n * @since v0.8.0\n * @category Object\n * @typedefn Idx = String | Int | Symbol\n * @sig [Idx] -> a -> {a} -> {a}\n * @param {Array} path the path to set\n * @param {*} val The new value\n * @param {Object} obj The object to clone\n * @return {Object} A new object equivalent to the original except along the specified path.\n * @see R.dissocPath\n * @example\n *\n * R.assocPath(['a', 'b', 'c'], 42, {a: {b: {c: 0}}}); //=> {a: {b: {c: 42}}}\n *\n * // Any missing or non-object keys in path will be overridden\n * R.assocPath(['a', 'b', 'c'], 42, {a: 5}); //=> {a: {b: {c: 42}}}\n */\n\nvar assocPath =\n/*#__PURE__*/\n_curry3(function assocPath(path, val, obj) {\n if (path.length === 0) {\n return val;\n }\n\n var idx = path[0];\n\n if (path.length > 1) {\n var nextObj = !isNil(obj) && _has(idx, obj) && typeof obj[idx] === 'object' ? obj[idx] : _isInteger(path[1]) ? [] : {};\n val = assocPath(Array.prototype.slice.call(path, 1), val, nextObj);\n }\n\n return _assoc(idx, val, obj);\n});\n\nexport default assocPath;","import _isArray from \"./_isArray.js\";\nimport _isInteger from \"./_isInteger.js\";\n/**\n * Makes a shallow clone of an object, setting or overriding the specified\n * property with the given value. Note that this copies and flattens prototype\n * properties onto the new object as well. All non-primitive properties are\n * copied by reference.\n *\n * @private\n * @param {String|Number} prop The property name to set\n * @param {*} val The new value\n * @param {Object|Array} obj The object to clone\n * @return {Object|Array} A new object equivalent to the original except for the changed property.\n */\n\nexport default function _assoc(prop, val, obj) {\n if (_isInteger(prop) && _isArray(obj)) {\n var arr = [].concat(obj);\n arr[prop] = val;\n return arr;\n }\n\n var result = {};\n\n for (var p in obj) {\n result[p] = obj[p];\n }\n\n result[prop] = val;\n return result;\n}","import _curry3 from \"./internal/_curry3.js\";\nimport assocPath from \"./assocPath.js\";\n/**\n * Makes a shallow clone of an object, setting or overriding the specified\n * property with the given value. Note that this copies and flattens prototype\n * properties onto the new object as well. All non-primitive properties are\n * copied by reference.\n *\n * @func\n * @memberOf R\n * @since v0.8.0\n * @category Object\n * @typedefn Idx = String | Int\n * @sig Idx -> a -> {k: v} -> {k: v}\n * @param {String|Number} prop The property name to set\n * @param {*} val The new value\n * @param {Object} obj The object to clone\n * @return {Object} A new object equivalent to the original except for the changed property.\n * @see R.dissoc, R.pick\n * @example\n *\n * R.assoc('c', 3, {a: 1, b: 2}); //=> {a: 1, b: 2, c: 3}\n */\n\nvar assoc =\n/*#__PURE__*/\n_curry3(function assoc(prop, val, obj) {\n return assocPath([prop], val, obj);\n});\n\nexport default assoc;","import _forceReduced from \"./_forceReduced.js\";\nimport _isArrayLike from \"./_isArrayLike.js\";\nimport _xArrayReduce from \"./_xArrayReduce.js\";\nimport _xReduce from \"./_xReduce.js\";\nimport _xfBase from \"./_xfBase.js\";\nvar tInit = '@@transducer/init';\nvar tStep = '@@transducer/step';\nvar tResult = '@@transducer/result';\n\nvar XPreservingReduced =\n/*#__PURE__*/\nfunction () {\n function XPreservingReduced(xf) {\n this.xf = xf;\n }\n\n XPreservingReduced.prototype[tInit] = _xfBase.init;\n XPreservingReduced.prototype[tResult] = _xfBase.result;\n\n XPreservingReduced.prototype[tStep] = function (result, input) {\n var ret = this.xf[tStep](result, input);\n return ret['@@transducer/reduced'] ? _forceReduced(ret) : ret;\n };\n\n return XPreservingReduced;\n}();\n\nvar XFlatCat =\n/*#__PURE__*/\nfunction () {\n function XFlatCat(xf) {\n this.xf = new XPreservingReduced(xf);\n }\n\n XFlatCat.prototype[tInit] = _xfBase.init;\n XFlatCat.prototype[tResult] = _xfBase.result;\n\n XFlatCat.prototype[tStep] = function (result, input) {\n return !_isArrayLike(input) ? _xArrayReduce(this.xf, result, [input]) : _xReduce(this.xf, result, input);\n };\n\n return XFlatCat;\n}();\n\nvar _flatCat = function _xcat(xf) {\n return new XFlatCat(xf);\n};\n\nexport default _flatCat;","export default function _forceReduced(x) {\n return {\n '@@transducer/value': x,\n '@@transducer/reduced': true\n };\n}","import _flatCat from \"./_flatCat.js\";\nimport _xmap from \"./_xmap.js\";\nexport default function _xchain(f) {\n return function (xf) {\n return _xmap(f)(_flatCat(xf));\n };\n}","import _curry2 from \"./internal/_curry2.js\";\nimport _dispatchable from \"./internal/_dispatchable.js\";\nimport _makeFlat from \"./internal/_makeFlat.js\";\nimport _xchain from \"./internal/_xchain.js\";\nimport map from \"./map.js\";\n/**\n * `chain` maps a function over a list and concatenates the results. `chain`\n * is also known as `flatMap` in some libraries.\n *\n * Dispatches to the `chain` method of the second argument, if present,\n * according to the [FantasyLand Chain spec](https://github.com/fantasyland/fantasy-land#chain).\n *\n * If second argument is a function, `chain(f, g)(x)` is equivalent to `f(g(x), x)`.\n *\n * Acts as a transducer if a transformer is given in list position.\n *\n * @func\n * @memberOf R\n * @since v0.3.0\n * @category List\n * @sig Chain m => (a -> m b) -> m a -> m b\n * @param {Function} fn The function to map with\n * @param {Array} list The list to map over\n * @return {Array} The result of flat-mapping `list` with `fn`\n * @example\n *\n * const duplicate = n => [n, n];\n * R.chain(duplicate, [1, 2, 3]); //=> [1, 1, 2, 2, 3, 3]\n *\n * R.chain(R.append, R.head)([1, 2, 3]); //=> [1, 2, 3, 1]\n */\n\nvar chain =\n/*#__PURE__*/\n_curry2(\n/*#__PURE__*/\n_dispatchable(['fantasy-land/chain', 'chain'], _xchain, function chain(fn, monad) {\n if (typeof monad === 'function') {\n return function (x) {\n return fn(monad(x))(x);\n };\n }\n\n return _makeFlat(false)(map(fn, monad));\n}));\n\nexport default chain;","import _isArrayLike from \"./_isArrayLike.js\";\n/**\n * `_makeFlat` is a helper function that returns a one-level or fully recursive\n * function based on the flag passed in.\n *\n * @private\n */\n\nexport default function _makeFlat(recursive) {\n return function flatt(list) {\n var value, jlen, j;\n var result = [];\n var idx = 0;\n var ilen = list.length;\n\n while (idx < ilen) {\n if (_isArrayLike(list[idx])) {\n value = recursive ? flatt(list[idx]) : list[idx];\n j = 0;\n jlen = value.length;\n\n while (j < jlen) {\n result[result.length] = value[j];\n j += 1;\n }\n } else {\n result[result.length] = list[idx];\n }\n\n idx += 1;\n }\n\n return result;\n };\n}","import _cloneRegExp from \"./_cloneRegExp.js\";\nimport type from \"../type.js\";\n/**\n * Copies an object.\n *\n * @private\n * @param {*} value The value to be copied\n * @param {Boolean} deep Whether or not to perform deep cloning.\n * @return {*} The copied value.\n */\n\nexport default function _clone(value, deep, map) {\n map || (map = new _ObjectMap()); // this avoids the slower switch with a quick if decision removing some milliseconds in each run.\n\n if (_isPrimitive(value)) {\n return value;\n }\n\n var copy = function copy(copiedValue) {\n // Check for circular and same references on the object graph and return its corresponding clone.\n var cachedCopy = map.get(value);\n\n if (cachedCopy) {\n return cachedCopy;\n }\n\n map.set(value, copiedValue);\n\n for (var key in value) {\n if (Object.prototype.hasOwnProperty.call(value, key)) {\n copiedValue[key] = deep ? _clone(value[key], true, map) : value[key];\n }\n }\n\n return copiedValue;\n };\n\n switch (type(value)) {\n case 'Object':\n return copy(Object.create(Object.getPrototypeOf(value)));\n\n case 'Array':\n return copy([]);\n\n case 'Date':\n return new Date(value.valueOf());\n\n case 'RegExp':\n return _cloneRegExp(value);\n\n case 'Int8Array':\n case 'Uint8Array':\n case 'Uint8ClampedArray':\n case 'Int16Array':\n case 'Uint16Array':\n case 'Int32Array':\n case 'Uint32Array':\n case 'Float32Array':\n case 'Float64Array':\n case 'BigInt64Array':\n case 'BigUint64Array':\n return value.slice();\n\n default:\n return value;\n }\n}\n\nfunction _isPrimitive(param) {\n var type = typeof param;\n return param == null || type != 'object' && type != 'function';\n}\n\nvar _ObjectMap =\n/*#__PURE__*/\nfunction () {\n function _ObjectMap() {\n this.map = {};\n this.length = 0;\n }\n\n _ObjectMap.prototype.set = function (key, value) {\n const hashedKey = this.hash(key);\n let bucket = this.map[hashedKey];\n\n if (!bucket) {\n this.map[hashedKey] = bucket = [];\n }\n\n bucket.push([key, value]);\n this.length += 1;\n };\n\n _ObjectMap.prototype.hash = function (key) {\n let hashedKey = [];\n\n for (var value in key) {\n hashedKey.push(Object.prototype.toString.call(key[value]));\n }\n\n return hashedKey.join();\n };\n\n _ObjectMap.prototype.get = function (key) {\n /**\n * depending on the number of objects to be cloned is faster to just iterate over the items in the map just because the hash function is so costly,\n * on my tests this number is 180, anything above that using the hash function is faster.\n */\n if (this.length <= 180) {\n for (const p in this.map) {\n const bucket = this.map[p];\n\n for (let i = 0; i < bucket.length; i += 1) {\n const element = bucket[i];\n\n if (element[0] === key) {\n return element[1];\n }\n }\n }\n\n return;\n }\n\n const hashedKey = this.hash(key);\n const bucket = this.map[hashedKey];\n\n if (!bucket) {\n return;\n }\n\n for (let i = 0; i < bucket.length; i += 1) {\n const element = bucket[i];\n\n if (element[0] === key) {\n return element[1];\n }\n }\n };\n\n return _ObjectMap;\n}();","export default function _cloneRegExp(pattern) {\n return new RegExp(pattern.source, pattern.flags ? pattern.flags : (pattern.global ? 'g' : '') + (pattern.ignoreCase ? 'i' : '') + (pattern.multiline ? 'm' : '') + (pattern.sticky ? 'y' : '') + (pattern.unicode ? 'u' : '') + (pattern.dotAll ? 's' : ''));\n}","import _clone from \"./internal/_clone.js\";\nimport _curry1 from \"./internal/_curry1.js\";\n/**\n * Creates a deep copy of the source that can be used in place of the source\n * object without retaining any references to it.\n * The source object may contain (nested) `Array`s and `Object`s,\n * `Number`s, `String`s, `Boolean`s and `Date`s.\n * `Function`s are assigned by reference rather than copied.\n *\n * Dispatches to a `clone` method if present.\n *\n * Note that if the source object has multiple nodes that share a reference,\n * the returned object will have the same structure, but the references will\n * be pointed to the location within the cloned value.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Object\n * @sig {*} -> {*}\n * @param {*} value The object or array to clone\n * @return {*} A deeply cloned copy of `val`\n * @example\n *\n * const objects = [{}, {}, {}];\n * const objectsClone = R.clone(objects);\n * objects === objectsClone; //=> false\n * objects[0] === objectsClone[0]; //=> false\n */\n\nvar clone =\n/*#__PURE__*/\n_curry1(function clone(value) {\n return value != null && typeof value.clone === 'function' ? value.clone() : _clone(value, true);\n});\n\nexport default clone;","import _curry1 from \"./internal/_curry1.js\";\n/**\n * Makes a comparator function out of a function that reports whether the first\n * element is less than the second.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Function\n * @sig ((a, b) -> Boolean) -> ((a, b) -> Number)\n * @param {Function} pred A predicate function of arity two which will return `true` if the first argument\n * is less than the second, `false` otherwise\n * @return {Function} A Function :: a -> b -> Int that returns `-1` if a < b, `1` if b < a, otherwise `0`\n * @example\n *\n * const byAge = R.comparator((a, b) => a.age < b.age);\n * const people = [\n * { name: 'Emma', age: 70 },\n * { name: 'Peter', age: 78 },\n * { name: 'Mikhail', age: 62 },\n * ];\n * const peopleByIncreasingAge = R.sort(byAge, people);\n * //=> [{ name: 'Mikhail', age: 62 },{ name: 'Emma', age: 70 }, { name: 'Peter', age: 78 }]\n */\n\nvar comparator =\n/*#__PURE__*/\n_curry1(function comparator(pred) {\n return function (a, b) {\n return pred(a, b) ? -1 : pred(b, a) ? 1 : 0;\n };\n});\n\nexport default comparator;","export default function _pipe(f, g) {\n return function () {\n return g.call(this, f.apply(this, arguments));\n };\n}","import _isArray from \"./_isArray.js\";\n/**\n * This checks whether a function has a [methodname] function. If it isn't an\n * array it will execute that function otherwise it will default to the ramda\n * implementation.\n *\n * @private\n * @param {Function} fn ramda implementation\n * @param {String} methodname property to check for a custom implementation\n * @return {Object} Whatever the return value of the method is.\n */\n\nexport default function _checkForMethod(methodname, fn) {\n return function () {\n var length = arguments.length;\n\n if (length === 0) {\n return fn();\n }\n\n var obj = arguments[length - 1];\n return _isArray(obj) || typeof obj[methodname] !== 'function' ? fn.apply(this, arguments) : obj[methodname].apply(obj, Array.prototype.slice.call(arguments, 0, length - 1));\n };\n}","import _checkForMethod from \"./internal/_checkForMethod.js\";\nimport _curry3 from \"./internal/_curry3.js\";\n/**\n * Returns the elements of the given list or string (or object with a `slice`\n * method) from `fromIndex` (inclusive) to `toIndex` (exclusive).\n *\n * Dispatches to the `slice` method of the third argument, if present.\n *\n * @func\n * @memberOf R\n * @since v0.1.4\n * @category List\n * @sig Number -> Number -> [a] -> [a]\n * @sig Number -> Number -> String -> String\n * @param {Number} fromIndex The start index (inclusive).\n * @param {Number} toIndex The end index (exclusive).\n * @param {*} list\n * @return {*}\n * @example\n *\n * R.slice(1, 3, ['a', 'b', 'c', 'd']); //=> ['b', 'c']\n * R.slice(1, Infinity, ['a', 'b', 'c', 'd']); //=> ['b', 'c', 'd']\n * R.slice(0, -1, ['a', 'b', 'c', 'd']); //=> ['a', 'b', 'c']\n * R.slice(-3, -1, ['a', 'b', 'c', 'd']); //=> ['b', 'c']\n * R.slice(0, 3, 'ramda'); //=> 'ram'\n */\n\nvar slice =\n/*#__PURE__*/\n_curry3(\n/*#__PURE__*/\n_checkForMethod('slice', function slice(fromIndex, toIndex, list) {\n return Array.prototype.slice.call(list, fromIndex, toIndex);\n}));\n\nexport default slice;","import _checkForMethod from \"./internal/_checkForMethod.js\";\nimport _curry1 from \"./internal/_curry1.js\";\nimport slice from \"./slice.js\";\n/**\n * Returns all but the first element of the given list or string (or object\n * with a `tail` method).\n *\n * Dispatches to the `slice` method of the first argument, if present.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @sig [a] -> [a]\n * @sig String -> String\n * @param {*} list\n * @return {*}\n * @see R.head, R.init, R.last\n * @example\n *\n * R.tail([1, 2, 3]); //=> [2, 3]\n * R.tail([1, 2]); //=> [2]\n * R.tail([1]); //=> []\n * R.tail([]); //=> []\n *\n * R.tail('abc'); //=> 'bc'\n * R.tail('ab'); //=> 'b'\n * R.tail('a'); //=> ''\n * R.tail(''); //=> ''\n */\n\nvar tail =\n/*#__PURE__*/\n_curry1(\n/*#__PURE__*/\n_checkForMethod('tail',\n/*#__PURE__*/\nslice(1, Infinity)));\n\nexport default tail;","import _arity from \"./internal/_arity.js\";\nimport _pipe from \"./internal/_pipe.js\";\nimport reduce from \"./reduce.js\";\nimport tail from \"./tail.js\";\n/**\n * Performs left-to-right function composition. The first argument may have\n * any arity; the remaining arguments must be unary.\n *\n * In some libraries this function is named `sequence`.\n *\n * **Note:** The result of pipe is not automatically curried.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Function\n * @sig (((a, b, ..., n) -> o), (o -> p), ..., (x -> y), (y -> z)) -> ((a, b, ..., n) -> z)\n * @param {...Function} functions\n * @return {Function}\n * @see R.compose\n * @example\n *\n * const f = R.pipe(Math.pow, R.negate, R.inc);\n *\n * f(3, 4); // -(3^4) + 1\n * @symb R.pipe(f, g, h)(a, b) = h(g(f(a, b)))\n * @symb R.pipe(f, g, h)(a)(b) = h(g(f(a)))(b)\n */\n\nexport default function pipe() {\n if (arguments.length === 0) {\n throw new Error('pipe requires at least one argument');\n }\n\n return _arity(arguments[0].length, reduce(_pipe, arguments[0], tail(arguments)));\n}","import _curry1 from \"./internal/_curry1.js\";\nimport _isString from \"./internal/_isString.js\";\n/**\n * Returns a new list or string with the elements or characters in reverse\n * order.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @sig [a] -> [a]\n * @sig String -> String\n * @param {Array|String} list\n * @return {Array|String}\n * @example\n *\n * R.reverse([1, 2, 3]); //=> [3, 2, 1]\n * R.reverse([1, 2]); //=> [2, 1]\n * R.reverse([1]); //=> [1]\n * R.reverse([]); //=> []\n *\n * R.reverse('abc'); //=> 'cba'\n * R.reverse('ab'); //=> 'ba'\n * R.reverse('a'); //=> 'a'\n * R.reverse(''); //=> ''\n */\n\nvar reverse =\n/*#__PURE__*/\n_curry1(function reverse(list) {\n return _isString(list) ? list.split('').reverse().join('') : Array.prototype.slice.call(list, 0).reverse();\n});\n\nexport default reverse;","import pipe from \"./pipe.js\";\nimport reverse from \"./reverse.js\";\n/**\n * Performs right-to-left function composition. The last argument may have\n * any arity; the remaining arguments must be unary.\n *\n * **Note:** The result of compose is not automatically curried.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Function\n * @sig ((y -> z), (x -> y), ..., (o -> p), ((a, b, ..., n) -> o)) -> ((a, b, ..., n) -> z)\n * @param {...Function} ...functions The functions to compose\n * @return {Function}\n * @see R.pipe\n * @example\n *\n * const classyGreeting = (firstName, lastName) => \"The name's \" + lastName + \", \" + firstName + \" \" + lastName\n * const yellGreeting = R.compose(R.toUpper, classyGreeting);\n * yellGreeting('James', 'Bond'); //=> \"THE NAME'S BOND, JAMES BOND\"\n *\n * R.compose(Math.abs, R.add(1), R.multiply(2))(-4) //=> 7\n *\n * @symb R.compose(f, g, h)(a, b) = f(g(h(a, b)))\n * @symb R.compose(f, g, h)(a)(b) = f(g(h(a)))(b)\n */\n\nexport default function compose() {\n if (arguments.length === 0) {\n throw new Error('compose requires at least one argument');\n }\n\n return pipe.apply(this, reverse(arguments));\n}","import _curry2 from \"./internal/_curry2.js\";\nimport _map from \"./internal/_map.js\";\nimport curryN from \"./curryN.js\";\nimport max from \"./max.js\";\nimport pluck from \"./pluck.js\";\nimport reduce from \"./reduce.js\";\n/**\n * Accepts a converging function and a list of branching functions and returns\n * a new function. The arity of the new function is the same as the arity of\n * the longest branching function. When invoked, this new function is applied\n * to some arguments, and each branching function is applied to those same\n * arguments. The results of each branching function are passed as arguments\n * to the converging function to produce the return value.\n *\n * @func\n * @memberOf R\n * @since v0.4.2\n * @category Function\n * @sig ((x1, x2, ...) -> z) -> [((a, b, ...) -> x1), ((a, b, ...) -> x2), ...] -> (a -> b -> ... -> z)\n * @param {Function} after A function. `after` will be invoked with the return values of\n * `fn1` and `fn2` as its arguments.\n * @param {Array} functions A list of functions.\n * @return {Function} A new function.\n * @see R.useWith\n * @example\n *\n * const average = R.converge(R.divide, [R.sum, R.length])\n * average([1, 2, 3, 4, 5, 6, 7]) //=> 4\n *\n * const strangeConcat = R.converge(R.concat, [R.toUpper, R.toLower])\n * strangeConcat(\"Yodel\") //=> \"YODELyodel\"\n *\n * @symb R.converge(f, [g, h])(a, b) = f(g(a, b), h(a, b))\n */\n\nvar converge =\n/*#__PURE__*/\n_curry2(function converge(after, fns) {\n return curryN(reduce(max, 0, pluck('length', fns)), function () {\n var args = arguments;\n var context = this;\n return after.apply(context, _map(function (fn) {\n return fn.apply(context, args);\n }, fns));\n });\n});\n\nexport default converge;","import _clone from \"./_clone.js\";\nimport _has from \"./_has.js\";\nimport _xfBase from \"./_xfBase.js\";\n\nvar XReduceBy =\n/*#__PURE__*/\nfunction () {\n function XReduceBy(valueFn, valueAcc, keyFn, xf) {\n this.valueFn = valueFn;\n this.valueAcc = valueAcc;\n this.keyFn = keyFn;\n this.xf = xf;\n this.inputs = {};\n }\n\n XReduceBy.prototype['@@transducer/init'] = _xfBase.init;\n\n XReduceBy.prototype['@@transducer/result'] = function (result) {\n var key;\n\n for (key in this.inputs) {\n if (_has(key, this.inputs)) {\n result = this.xf['@@transducer/step'](result, this.inputs[key]);\n\n if (result['@@transducer/reduced']) {\n result = result['@@transducer/value'];\n break;\n }\n }\n }\n\n this.inputs = null;\n return this.xf['@@transducer/result'](result);\n };\n\n XReduceBy.prototype['@@transducer/step'] = function (result, input) {\n var key = this.keyFn(input);\n this.inputs[key] = this.inputs[key] || [key, _clone(this.valueAcc, false)];\n this.inputs[key][1] = this.valueFn(this.inputs[key][1], input);\n return result;\n };\n\n return XReduceBy;\n}();\n\nexport default function _xreduceBy(valueFn, valueAcc, keyFn) {\n return function (xf) {\n return new XReduceBy(valueFn, valueAcc, keyFn, xf);\n };\n}","import _clone from \"./internal/_clone.js\";\nimport _curryN from \"./internal/_curryN.js\";\nimport _dispatchable from \"./internal/_dispatchable.js\";\nimport _has from \"./internal/_has.js\";\nimport _reduced from \"./internal/_reduced.js\";\nimport _xReduce from \"./internal/_xReduce.js\";\nimport _xreduceBy from \"./internal/_xreduceBy.js\";\nimport _xwrap from \"./internal/_xwrap.js\";\n/**\n * Groups the elements of the list according to the result of calling\n * the String-returning function `keyFn` on each element and reduces the elements\n * of each group to a single value via the reducer function `valueFn`.\n *\n * The value function receives two values: *(acc, value)*. It may use\n * [`R.reduced`](#reduced) to short circuit the iteration.\n *\n * This function is basically a more general [`groupBy`](#groupBy) function.\n *\n * Acts as a transducer if a transformer is given in list position.\n *\n * @func\n * @memberOf R\n * @since v0.20.0\n * @category List\n * @sig ((a, b) -> a) -> a -> (b -> String) -> [b] -> {String: a}\n * @param {Function} valueFn The function that reduces the elements of each group to a single\n * value. Receives two values, accumulator for a particular group and the current element.\n * @param {*} acc The (initial) accumulator value for each group.\n * @param {Function} keyFn The function that maps the list's element into a key.\n * @param {Array} list The array to group.\n * @return {Object} An object with the output of `keyFn` for keys, mapped to the output of\n * `valueFn` for elements which produced that key when passed to `keyFn`.\n * @see R.groupBy, R.reduce, R.reduced\n * @example\n *\n * const groupNames = (acc, {name}) => acc.concat(name)\n * const toGrade = ({score}) =>\n * score < 65 ? 'F' :\n * score < 70 ? 'D' :\n * score < 80 ? 'C' :\n * score < 90 ? 'B' : 'A'\n *\n * var students = [\n * {name: 'Abby', score: 83},\n * {name: 'Bart', score: 62},\n * {name: 'Curt', score: 88},\n * {name: 'Dora', score: 92},\n * ]\n *\n * reduceBy(groupNames, [], toGrade, students)\n * //=> {\"A\": [\"Dora\"], \"B\": [\"Abby\", \"Curt\"], \"F\": [\"Bart\"]}\n */\n\nvar reduceBy =\n/*#__PURE__*/\n_curryN(4, [],\n/*#__PURE__*/\n_dispatchable([], _xreduceBy, function reduceBy(valueFn, valueAcc, keyFn, list) {\n var xf = _xwrap(function (acc, elt) {\n var key = keyFn(elt);\n var value = valueFn(_has(key, acc) ? acc[key] : _clone(valueAcc, false), elt);\n\n if (value && value['@@transducer/reduced']) {\n return _reduced(acc);\n }\n\n acc[key] = value;\n return acc;\n });\n\n return _xReduce(xf, {}, list);\n}));\n\nexport default reduceBy;","import _curry1 from \"./internal/_curry1.js\";\nimport curryN from \"./curryN.js\";\n/**\n * Returns a curried equivalent of the provided function. The curried function\n * has two unusual capabilities. First, its arguments needn't be provided one\n * at a time. If `f` is a ternary function and `g` is `R.curry(f)`, the\n * following are equivalent:\n *\n * - `g(1)(2)(3)`\n * - `g(1)(2, 3)`\n * - `g(1, 2)(3)`\n * - `g(1, 2, 3)`\n *\n * Secondly, the special placeholder value [`R.__`](#__) may be used to specify\n * \"gaps\", allowing partial application of any combination of arguments,\n * regardless of their positions. If `g` is as above and `_` is [`R.__`](#__),\n * the following are equivalent:\n *\n * - `g(1, 2, 3)`\n * - `g(_, 2, 3)(1)`\n * - `g(_, _, 3)(1)(2)`\n * - `g(_, _, 3)(1, 2)`\n * - `g(_, 2)(1)(3)`\n * - `g(_, 2)(1, 3)`\n * - `g(_, 2)(_, 3)(1)`\n *\n * Please note that default parameters don't count towards a [function arity](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length)\n * and therefore `curry` won't work well with those:\n *\n * ```\n * const h = R.curry((a, b, c = 2) => a + b + c);\n *\n * h(40);\n * //=> function (waits for `b`)\n *\n * h(39)(1);\n * //=> 42\n *\n * h(1)(2, 3);\n * //=> 6\n *\n * h(1)(2)(7);\n * //=> Error! (`3` is not a function!)\n * ```\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Function\n * @sig (* -> a) -> (* -> a)\n * @param {Function} fn The function to curry.\n * @return {Function} A new, curried function.\n * @see R.curryN, R.partial\n * @example\n *\n * const addFourNumbers = (a, b, c, d) => a + b + c + d;\n *\n * const curriedAddFourNumbers = R.curry(addFourNumbers);\n * const f = curriedAddFourNumbers(1, 2);\n * const g = f(3);\n * g(4); //=> 10\n */\n\nvar curry =\n/*#__PURE__*/\n_curry1(function curry(fn) {\n return curryN(fn.length, fn);\n});\n\nexport default curry;","import _curry3 from \"./internal/_curry3.js\";\n/**\n * Makes a descending comparator function out of a function that returns a value\n * that can be compared with `<` and `>`.\n *\n * @func\n * @memberOf R\n * @since v0.23.0\n * @category Function\n * @sig Ord b => (a -> b) -> a -> a -> Number\n * @param {Function} fn A function of arity one that returns a value that can be compared\n * @param {*} a The first item to be compared.\n * @param {*} b The second item to be compared.\n * @return {Number} `-1` if fn(a) > fn(b), `1` if fn(b) > fn(a), otherwise `0`\n * @see R.ascend\n * @example\n *\n * const byAge = R.descend(R.prop('age'));\n * const people = [\n * { name: 'Emma', age: 70 },\n * { name: 'Peter', age: 78 },\n * { name: 'Mikhail', age: 62 },\n * ];\n * const peopleByOldestFirst = R.sort(byAge, people);\n * //=> [{ name: 'Peter', age: 78 }, { name: 'Emma', age: 70 }, { name: 'Mikhail', age: 62 }]\n */\n\nvar descend =\n/*#__PURE__*/\n_curry3(function descend(fn, a, b) {\n var aa = fn(a);\n var bb = fn(b);\n return aa > bb ? -1 : aa < bb ? 1 : 0;\n});\n\nexport default descend;","import _includes from \"./_includes.js\";\n\nvar _Set =\n/*#__PURE__*/\nfunction () {\n function _Set() {\n /* globals Set */\n this._nativeSet = typeof Set === 'function' ? new Set() : null;\n this._items = {};\n }\n\n // until we figure out why jsdoc chokes on this\n // @param item The item to add to the Set\n // @returns {boolean} true if the item did not exist prior, otherwise false\n //\n _Set.prototype.add = function (item) {\n return !hasOrAdd(item, true, this);\n }; //\n // @param item The item to check for existence in the Set\n // @returns {boolean} true if the item exists in the Set, otherwise false\n //\n\n\n _Set.prototype.has = function (item) {\n return hasOrAdd(item, false, this);\n }; //\n // Combines the logic for checking whether an item is a member of the set and\n // for adding a new item to the set.\n //\n // @param item The item to check or add to the Set instance.\n // @param shouldAdd If true, the item will be added to the set if it doesn't\n // already exist.\n // @param set The set instance to check or add to.\n // @return {boolean} true if the item already existed, otherwise false.\n //\n\n\n return _Set;\n}();\n\nfunction hasOrAdd(item, shouldAdd, set) {\n var type = typeof item;\n var prevSize, newSize;\n\n switch (type) {\n case 'string':\n case 'number':\n // distinguish between +0 and -0\n if (item === 0 && 1 / item === -Infinity) {\n if (set._items['-0']) {\n return true;\n } else {\n if (shouldAdd) {\n set._items['-0'] = true;\n }\n\n return false;\n }\n } // these types can all utilise the native Set\n\n\n if (set._nativeSet !== null) {\n if (shouldAdd) {\n prevSize = set._nativeSet.size;\n\n set._nativeSet.add(item);\n\n newSize = set._nativeSet.size;\n return newSize === prevSize;\n } else {\n return set._nativeSet.has(item);\n }\n } else {\n if (!(type in set._items)) {\n if (shouldAdd) {\n set._items[type] = {};\n set._items[type][item] = true;\n }\n\n return false;\n } else if (item in set._items[type]) {\n return true;\n } else {\n if (shouldAdd) {\n set._items[type][item] = true;\n }\n\n return false;\n }\n }\n\n case 'boolean':\n // set._items['boolean'] holds a two element array\n // representing [ falseExists, trueExists ]\n if (type in set._items) {\n var bIdx = item ? 1 : 0;\n\n if (set._items[type][bIdx]) {\n return true;\n } else {\n if (shouldAdd) {\n set._items[type][bIdx] = true;\n }\n\n return false;\n }\n } else {\n if (shouldAdd) {\n set._items[type] = item ? [false, true] : [true, false];\n }\n\n return false;\n }\n\n case 'function':\n // compare functions for reference equality\n if (set._nativeSet !== null) {\n if (shouldAdd) {\n prevSize = set._nativeSet.size;\n\n set._nativeSet.add(item);\n\n newSize = set._nativeSet.size;\n return newSize === prevSize;\n } else {\n return set._nativeSet.has(item);\n }\n } else {\n if (!(type in set._items)) {\n if (shouldAdd) {\n set._items[type] = [item];\n }\n\n return false;\n }\n\n if (!_includes(item, set._items[type])) {\n if (shouldAdd) {\n set._items[type].push(item);\n }\n\n return false;\n }\n\n return true;\n }\n\n case 'undefined':\n if (set._items[type]) {\n return true;\n } else {\n if (shouldAdd) {\n set._items[type] = true;\n }\n\n return false;\n }\n\n case 'object':\n if (item === null) {\n if (!set._items['null']) {\n if (shouldAdd) {\n set._items['null'] = true;\n }\n\n return false;\n }\n\n return true;\n }\n\n /* falls through */\n\n default:\n // reduce the search size of heterogeneous sets by creating buckets\n // for each type.\n type = Object.prototype.toString.call(item);\n\n if (!(type in set._items)) {\n if (shouldAdd) {\n set._items[type] = [item];\n }\n\n return false;\n } // scan through all previously applied items\n\n\n if (!_includes(item, set._items[type])) {\n if (shouldAdd) {\n set._items[type].push(item);\n }\n\n return false;\n }\n\n return true;\n }\n} // A simple Set type that honours R.equals semantics\n\n\nexport default _Set;","import _curry2 from \"./internal/_curry2.js\";\nimport _Set from \"./internal/_Set.js\";\n/**\n * Finds the set (i.e. no duplicates) of all elements in the first list not\n * contained in the second list. Objects and Arrays are compared in terms of\n * value equality, not reference equality.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Relation\n * @sig [*] -> [*] -> [*]\n * @param {Array} list1 The first list.\n * @param {Array} list2 The second list.\n * @return {Array} The elements in `list1` that are not in `list2`.\n * @see R.differenceWith, R.symmetricDifference, R.symmetricDifferenceWith, R.without\n * @example\n *\n * R.difference([1,2,3,4], [7,6,5,4,3]); //=> [1,2]\n * R.difference([7,6,5,4,3], [1,2,3,4]); //=> [7,6,5]\n * R.difference([{a: 1}, {b: 2}], [{a: 1}, {c: 3}]) //=> [{b: 2}]\n */\n\nvar difference =\n/*#__PURE__*/\n_curry2(function difference(first, second) {\n var out = [];\n var idx = 0;\n var firstLen = first.length;\n var secondLen = second.length;\n var toFilterOut = new _Set();\n\n for (var i = 0; i < secondLen; i += 1) {\n toFilterOut.add(second[i]);\n }\n\n while (idx < firstLen) {\n if (toFilterOut.add(first[idx])) {\n out[out.length] = first[idx];\n }\n\n idx += 1;\n }\n\n return out;\n});\n\nexport default difference;","import _includesWith from \"./internal/_includesWith.js\";\nimport _curry3 from \"./internal/_curry3.js\";\n/**\n * Finds the set (i.e. no duplicates) of all elements in the first list not\n * contained in the second list. Duplication is determined according to the\n * value returned by applying the supplied predicate to two list elements.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Relation\n * @sig ((a, a) -> Boolean) -> [a] -> [a] -> [a]\n * @param {Function} pred A predicate used to test whether two items are equal.\n * @param {Array} list1 The first list.\n * @param {Array} list2 The second list.\n * @return {Array} The elements in `list1` that are not in `list2`.\n * @see R.difference, R.symmetricDifference, R.symmetricDifferenceWith\n * @example\n *\n * const cmp = (x, y) => x.a === y.a;\n * const l1 = [{a: 1}, {a: 2}, {a: 3}];\n * const l2 = [{a: 3}, {a: 4}];\n * R.differenceWith(cmp, l1, l2); //=> [{a: 1}, {a: 2}]\n *\n * R.differenceWith(R.equals, [1, 2, 3, 3, 3], []); //=> [1, 2, 3]\n * R.differenceWith(R.equals, [1, 2, 3, 3, 3], [1]); //=> [2, 3]\n */\n\nvar differenceWith =\n/*#__PURE__*/\n_curry3(function differenceWith(pred, first, second) {\n var out = [];\n var idx = 0;\n var firstLen = first.length;\n\n while (idx < firstLen) {\n if (!_includesWith(pred, first[idx], second) && !_includesWith(pred, first[idx], out)) {\n out.push(first[idx]);\n }\n\n idx += 1;\n }\n\n return out;\n});\n\nexport default differenceWith;","import _reduced from \"./_reduced.js\";\nimport _xfBase from \"./_xfBase.js\";\n\nvar XTake =\n/*#__PURE__*/\nfunction () {\n function XTake(n, xf) {\n this.xf = xf;\n this.n = n;\n this.i = 0;\n }\n\n XTake.prototype['@@transducer/init'] = _xfBase.init;\n XTake.prototype['@@transducer/result'] = _xfBase.result;\n\n XTake.prototype['@@transducer/step'] = function (result, input) {\n this.i += 1;\n var ret = this.n === 0 ? result : this.xf['@@transducer/step'](result, input);\n return this.n >= 0 && this.i >= this.n ? _reduced(ret) : ret;\n };\n\n return XTake;\n}();\n\nexport default function _xtake(n) {\n return function (xf) {\n return new XTake(n, xf);\n };\n}","import _curry2 from \"./internal/_curry2.js\";\nimport _dispatchable from \"./internal/_dispatchable.js\";\nimport _xtake from \"./internal/_xtake.js\";\nimport slice from \"./slice.js\";\n/**\n * Returns the first `n` elements of the given list, string, or\n * transducer/transformer (or object with a `take` method).\n *\n * Dispatches to the `take` method of the second argument, if present.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @sig Number -> [a] -> [a]\n * @sig Number -> String -> String\n * @param {Number} n\n * @param {*} list\n * @return {*}\n * @see R.drop\n * @example\n *\n * R.take(1, ['foo', 'bar', 'baz']); //=> ['foo']\n * R.take(2, ['foo', 'bar', 'baz']); //=> ['foo', 'bar']\n * R.take(3, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']\n * R.take(4, ['foo', 'bar', 'baz']); //=> ['foo', 'bar', 'baz']\n * R.take(3, 'ramda'); //=> 'ram'\n *\n * const personnel = [\n * 'Dave Brubeck',\n * 'Paul Desmond',\n * 'Eugene Wright',\n * 'Joe Morello',\n * 'Gerry Mulligan',\n * 'Bob Bates',\n * 'Joe Dodge',\n * 'Ron Crotty'\n * ];\n *\n * const takeFive = R.take(5);\n * takeFive(personnel);\n * //=> ['Dave Brubeck', 'Paul Desmond', 'Eugene Wright', 'Joe Morello', 'Gerry Mulligan']\n * @symb R.take(-1, [a, b]) = [a, b]\n * @symb R.take(0, [a, b]) = []\n * @symb R.take(1, [a, b]) = [a]\n * @symb R.take(2, [a, b]) = [a, b]\n */\n\nvar take =\n/*#__PURE__*/\n_curry2(\n/*#__PURE__*/\n_dispatchable(['take'], _xtake, function take(n, xs) {\n return slice(0, n < 0 ? Infinity : n, xs);\n}));\n\nexport default take;","import _curry3 from \"./internal/_curry3.js\";\nimport equals from \"./equals.js\";\n/**\n * Reports whether two objects have the same value, in [`R.equals`](#equals)\n * terms, for the specified property. Useful as a curried predicate.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Object\n * @sig k -> {k: v} -> {k: v} -> Boolean\n * @param {String} prop The name of the property to compare\n * @param {Object} obj1\n * @param {Object} obj2\n * @return {Boolean}\n *\n * @example\n *\n * const o1 = { a: 1, b: 2, c: 3, d: 4 };\n * const o2 = { a: 10, b: 20, c: 3, d: 40 };\n * R.eqProps('a', o1, o2); //=> false\n * R.eqProps('c', o1, o2); //=> true\n */\n\nvar eqProps =\n/*#__PURE__*/\n_curry3(function eqProps(prop, obj1, obj2) {\n return equals(obj1[prop], obj2[prop]);\n});\n\nexport default eqProps;","import _checkForMethod from \"./internal/_checkForMethod.js\";\nimport _curry2 from \"./internal/_curry2.js\";\n/**\n * Iterate over an input `list`, calling a provided function `fn` for each\n * element in the list.\n *\n * `fn` receives one argument: *(value)*.\n *\n * Note: `R.forEach` does not skip deleted or unassigned indices (sparse\n * arrays), unlike the native `Array.prototype.forEach` method. For more\n * details on this behavior, see:\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description\n *\n * Also note that, unlike `Array.prototype.forEach`, Ramda's `forEach` returns\n * the original array. In some libraries this function is named `each`.\n *\n * Dispatches to the `forEach` method of the second argument, if present.\n *\n * @func\n * @memberOf R\n * @since v0.1.1\n * @category List\n * @sig (a -> *) -> [a] -> [a]\n * @param {Function} fn The function to invoke. Receives one argument, `value`.\n * @param {Array} list The list to iterate over.\n * @return {Array} The original list.\n * @see R.addIndex\n * @example\n *\n * const printXPlusFive = x => console.log(x + 5);\n * R.forEach(printXPlusFive, [1, 2, 3]); //=> [1, 2, 3]\n * // logs 6\n * // logs 7\n * // logs 8\n * @symb R.forEach(f, [a, b, c]) = [a, b, c]\n */\n\nvar forEach =\n/*#__PURE__*/\n_curry2(\n/*#__PURE__*/\n_checkForMethod('forEach', function forEach(fn, list) {\n var len = list.length;\n var idx = 0;\n\n while (idx < len) {\n fn(list[idx]);\n idx += 1;\n }\n\n return list;\n}));\n\nexport default forEach;","import _curry2 from \"./internal/_curry2.js\";\n/**\n * Takes a list and returns a list of lists where each sublist's elements are\n * all satisfied pairwise comparison according to the provided function.\n * Only adjacent elements are passed to the comparison function.\n *\n * @func\n * @memberOf R\n * @since v0.21.0\n * @category List\n * @sig ((a, a) → Boolean) → [a] → [[a]]\n * @param {Function} fn Function for determining whether two given (adjacent)\n * elements should be in the same group\n * @param {Array} list The array to group. Also accepts a string, which will be\n * treated as a list of characters.\n * @return {List} A list that contains sublists of elements,\n * whose concatenations are equal to the original list.\n * @example\n *\n * R.groupWith(R.equals, [0, 1, 1, 2, 3, 5, 8, 13, 21])\n * //=> [[0], [1, 1], [2], [3], [5], [8], [13], [21]]\n *\n * R.groupWith((a, b) => a + 1 === b, [0, 1, 1, 2, 3, 5, 8, 13, 21])\n * //=> [[0, 1], [1, 2, 3], [5], [8], [13], [21]]\n *\n * R.groupWith((a, b) => a % 2 === b % 2, [0, 1, 1, 2, 3, 5, 8, 13, 21])\n * //=> [[0], [1, 1], [2], [3, 5], [8], [13, 21]]\n *\n * const isVowel = R.test(/^[aeiou]$/i);\n * R.groupWith(R.eqBy(isVowel), 'aestiou')\n * //=> ['ae', 'st', 'iou']\n */\n\nvar groupWith =\n/*#__PURE__*/\n_curry2(function (fn, list) {\n var res = [];\n var idx = 0;\n var len = list.length;\n\n while (idx < len) {\n var nextidx = idx + 1;\n\n while (nextidx < len && fn(list[nextidx - 1], list[nextidx])) {\n nextidx += 1;\n }\n\n res.push(list.slice(idx, nextidx));\n idx = nextidx;\n }\n\n return res;\n});\n\nexport default groupWith;","import _curry2 from \"./internal/_curry2.js\";\n/**\n * Returns `true` if the first argument is greater than the second; `false`\n * otherwise.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Relation\n * @sig Ord a => a -> a -> Boolean\n * @param {*} a\n * @param {*} b\n * @return {Boolean}\n * @see R.lt\n * @example\n *\n * R.gt(2, 1); //=> true\n * R.gt(2, 2); //=> false\n * R.gt(2, 3); //=> false\n * R.gt('a', 'z'); //=> false\n * R.gt('z', 'a'); //=> true\n */\n\nvar gt =\n/*#__PURE__*/\n_curry2(function gt(a, b) {\n return a > b;\n});\n\nexport default gt;","export default function _identity(x) {\n return x;\n}","import _curry1 from \"./internal/_curry1.js\";\nimport _identity from \"./internal/_identity.js\";\n/**\n * A function that does nothing but return the parameter supplied to it. Good\n * as a default or placeholder function.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Function\n * @sig a -> a\n * @param {*} x The value to return.\n * @return {*} The input value, `x`.\n * @example\n *\n * R.identity(1); //=> 1\n *\n * const obj = {};\n * R.identity(obj) === obj; //=> true\n * @symb R.identity(a) = a\n */\n\nvar identity =\n/*#__PURE__*/\n_curry1(_identity);\n\nexport default identity;","import _curry3 from \"./internal/_curry3.js\";\nimport curryN from \"./curryN.js\";\n/**\n * Creates a function that will process either the `onTrue` or the `onFalse`\n * function depending upon the result of the `condition` predicate.\n *\n * Note that `ifElse` takes its arity from the longest of the three functions passed to it.\n *\n * @func\n * @memberOf R\n * @since v0.8.0\n * @category Logic\n * @sig (*... -> Boolean) -> (*... -> *) -> (*... -> *) -> (*... -> *)\n * @param {Function} condition A predicate function\n * @param {Function} onTrue A function to invoke when the `condition` evaluates to a truthy value.\n * @param {Function} onFalse A function to invoke when the `condition` evaluates to a falsy value.\n * @return {Function} A new function that will process either the `onTrue` or the `onFalse`\n * function depending upon the result of the `condition` predicate.\n * @see R.unless, R.when, R.cond\n * @example\n *\n * const incCount = R.ifElse(\n * R.has('count'),\n * R.over(R.lensProp('count'), R.inc),\n * R.assoc('count', 1)\n * );\n * incCount({ count: 1 }); //=> { count: 2 }\n * incCount({}); //=> { count: 1 }\n */\n\nvar ifElse =\n/*#__PURE__*/\n_curry3(function ifElse(condition, onTrue, onFalse) {\n return curryN(Math.max(condition.length, onTrue.length, onFalse.length), function _ifElse() {\n return condition.apply(this, arguments) ? onTrue.apply(this, arguments) : onFalse.apply(this, arguments);\n });\n});\n\nexport default ifElse;","import reduceBy from \"./reduceBy.js\";\n/**\n * Given a function that generates a key, turns a list of objects into an\n * object indexing the objects by the given key. Note that if multiple\n * objects generate the same value for the indexing key only the last value\n * will be included in the generated object.\n *\n * Acts as a transducer if a transformer is given in list position.\n *\n * @func\n * @memberOf R\n * @since v0.19.0\n * @category List\n * @typedefn Idx = String | Int | Symbol\n * @sig Idx a => (b -> a) -> [b] -> {a: b}\n * @param {Function} fn Function :: a -> Idx\n * @param {Array} array The array of objects to index\n * @return {Object} An object indexing each array element by the given property.\n * @see R.groupBy\n * @example\n *\n * const list = [{id: 'xyz', title: 'A'}, {id: 'abc', title: 'B'}];\n * R.indexBy(R.prop('id'), list);\n * //=> {abc: {id: 'abc', title: 'B'}, xyz: {id: 'xyz', title: 'A'}}\n */\n\nvar indexBy =\n/*#__PURE__*/\nreduceBy(function (acc, elem) {\n return elem;\n}, null);\nexport default indexBy;","import _Set from \"./_Set.js\";\nimport _xfBase from \"./_xfBase.js\";\n\nvar XUniqBy =\n/*#__PURE__*/\nfunction () {\n function XUniqBy(f, xf) {\n this.xf = xf;\n this.f = f;\n this.set = new _Set();\n }\n\n XUniqBy.prototype['@@transducer/init'] = _xfBase.init;\n XUniqBy.prototype['@@transducer/result'] = _xfBase.result;\n\n XUniqBy.prototype['@@transducer/step'] = function (result, input) {\n return this.set.add(this.f(input)) ? this.xf['@@transducer/step'](result, input) : result;\n };\n\n return XUniqBy;\n}();\n\nexport default function _xuniqBy(f) {\n return function (xf) {\n return new XUniqBy(f, xf);\n };\n}","import _Set from \"./internal/_Set.js\";\nimport _curry2 from \"./internal/_curry2.js\";\nimport _dispatchable from \"./internal/_dispatchable.js\";\nimport _xuniqBy from \"./internal/_xuniqBy.js\";\n/**\n * Returns a new list containing only one copy of each element in the original\n * list, based upon the value returned by applying the supplied function to\n * each list element. Prefers the first item if the supplied function produces\n * the same value on two items. [`R.equals`](#equals) is used for comparison.\n *\n * Acts as a transducer if a transformer is given in list position.\n *\n * @func\n * @memberOf R\n * @since v0.16.0\n * @category List\n * @sig (a -> b) -> [a] -> [a]\n * @param {Function} fn A function used to produce a value to use during comparisons.\n * @param {Array} list The array to consider.\n * @return {Array} The list of unique items.\n * @example\n *\n * R.uniqBy(Math.abs, [-1, -5, 2, 10, 1, 2]); //=> [-1, -5, 2, 10]\n */\n\nvar uniqBy =\n/*#__PURE__*/\n_curry2(\n/*#__PURE__*/\n_dispatchable([], _xuniqBy, function (fn, list) {\n var set = new _Set();\n var result = [];\n var idx = 0;\n var appliedItem, item;\n\n while (idx < list.length) {\n item = list[idx];\n appliedItem = fn(item);\n\n if (set.add(appliedItem)) {\n result.push(item);\n }\n\n idx += 1;\n }\n\n return result;\n}));\n\nexport default uniqBy;","import identity from \"./identity.js\";\nimport uniqBy from \"./uniqBy.js\";\n/**\n * Returns a new list containing only one copy of each element in the original\n * list. [`R.equals`](#equals) is used to determine equality.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @sig [a] -> [a]\n * @param {Array} list The array to consider.\n * @return {Array} The list of unique items.\n * @example\n *\n * R.uniq([1, 1, 2, 1]); //=> [1, 2]\n * R.uniq([1, '1']); //=> [1, '1']\n * R.uniq([[42], [42]]); //=> [[42]]\n */\n\nvar uniq =\n/*#__PURE__*/\nuniqBy(identity);\nexport default uniq;","import _curry2 from \"./internal/_curry2.js\";\nimport _filter from \"./internal/_filter.js\";\nimport _Set from \"./internal/_Set.js\";\nimport uniq from \"./uniq.js\";\n/**\n * Combines two lists into a set (i.e. no duplicates) composed of those\n * elements common to both lists.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Relation\n * @sig [*] -> [*] -> [*]\n * @param {Array} list1 The first list.\n * @param {Array} list2 The second list.\n * @return {Array} The list of elements found in both `list1` and `list2`.\n * @see R.innerJoin\n * @example\n *\n * R.intersection([1,2,3,4], [7,6,5,4,3]); //=> [4, 3]\n */\n\nvar intersection =\n/*#__PURE__*/\n_curry2(function intersection(list1, list2) {\n var toKeep = new _Set();\n\n for (var i = 0; i < list1.length; i += 1) {\n toKeep.add(list1[i]);\n }\n\n return uniq(_filter(toKeep.has.bind(toKeep), list2));\n});\n\nexport default intersection;","import _has from \"./_has.js\"; // Based on https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\n\nfunction _objectAssign(target) {\n if (target == null) {\n throw new TypeError('Cannot convert undefined or null to object');\n }\n\n var output = Object(target);\n var idx = 1;\n var length = arguments.length;\n\n while (idx < length) {\n var source = arguments[idx];\n\n if (source != null) {\n for (var nextKey in source) {\n if (_has(nextKey, source)) {\n output[nextKey] = source[nextKey];\n }\n }\n }\n\n idx += 1;\n }\n\n return output;\n}\n\nexport default typeof Object.assign === 'function' ? Object.assign : _objectAssign;","import _curry2 from \"./internal/_curry2.js\";\nimport _isFunction from \"./internal/_isFunction.js\";\nimport curryN from \"./curryN.js\";\nimport toString from \"./toString.js\";\n/**\n * Given an `arity` (Number) and a `name` (String) the `invoker` function\n * returns a curried function that takes `arity` arguments and a `context`\n * object. It will \"invoke\" the `name`'d function (a method) on the `context`\n * object.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Function\n * @sig Number -> String -> (a -> b -> ... -> n -> Object -> *)\n * @param {Number} arity Number of arguments the returned function should take\n * before the target object.\n * @param {String} method Name of any of the target object's methods to call.\n * @return {Function} A new curried function.\n * @see R.construct\n * @example\n * // A function with no arguments\n * const asJson = invoker(0, \"json\")\n * // Just like calling .then((response) => response.json())\n * fetch(\"http://example.com/index.json\").then(asJson)\n *\n * // A function with one argument\n * const sliceFrom = invoker(1, 'slice');\n * sliceFrom(6, 'abcdefghijklm'); //=> 'ghijklm'\n *\n * // A function with two arguments\n * const sliceFrom6 = invoker(2, 'slice')(6);\n * sliceFrom6(8, 'abcdefghijklm'); //=> 'gh'\n *\n * // NOTE: You can't simply pass some of the arguments to the initial invoker function.\n * const firstCreditCardSection = invoker(2, \"slice\", 0, 4)\n * firstCreditCardSection(\"4242 4242 4242 4242\") // => Function<...>\n *\n * // Since invoker returns a curried function, you may partially apply it to create the function you need.\n * const firstCreditCardSection = invoker(2, \"slice\")(0, 4)\n * firstCreditCardSection(\"4242 4242 4242 4242\") // => \"4242\"\n *\n * @symb R.invoker(0, 'method')(o) = o['method']()\n * @symb R.invoker(1, 'method')(a, o) = o['method'](a)\n * @symb R.invoker(2, 'method')(a, b, o) = o['method'](a, b)\n */\n\nvar invoker =\n/*#__PURE__*/\n_curry2(function invoker(arity, method) {\n return curryN(arity + 1, function () {\n var target = arguments[arity];\n\n if (target != null && _isFunction(target[method])) {\n return target[method].apply(target, Array.prototype.slice.call(arguments, 0, arity));\n }\n\n throw new TypeError(toString(target) + ' does not have a method named \"' + method + '\"');\n });\n});\n\nexport default invoker;","export default function _isFunction(x) {\n var type = Object.prototype.toString.call(x);\n return type === '[object Function]' || type === '[object AsyncFunction]' || type === '[object GeneratorFunction]' || type === '[object AsyncGeneratorFunction]';\n}","import isNil from \"./isNil.js\";\nimport _curry1 from \"./internal/_curry1.js\";\n/**\n * Checks if the input value is not `null` and not `undefined`.\n *\n * @func\n * @memberOf R\n * @since v0.29.0\n * @category Type\n * @sig * -> Boolean\n * @param {*} x The value to test.\n * @return {Boolean} `true` if `x` is not `undefined` or not `null`, otherwise `false`.\n * @example\n *\n * R.isNotNil(null); //=> false\n * R.isNotNil(undefined); //=> false\n * R.isNotNil(0); //=> true\n * R.isNotNil([]); //=> true\n */\n\nvar isNotNil =\n/*#__PURE__*/\n_curry1(function isNotNil(x) {\n return !isNil(x);\n});\n\nexport default isNotNil;","import invoker from \"./invoker.js\";\n/**\n * Returns a string made by inserting the `separator` between each element and\n * concatenating all the elements into a single string.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @sig String -> [a] -> String\n * @param {Number|String} separator The string used to separate the elements.\n * @param {Array} xs The elements to join into a string.\n * @return {String} str The string made by concatenating `xs` with `separator`.\n * @see R.split\n * @example\n *\n * const spacer = R.join(' ');\n * spacer(['a', 2, 3.4]); //=> 'a 2 3.4'\n * R.join('|', [1, 2, 3]); //=> '1|2|3'\n */\n\nvar join =\n/*#__PURE__*/\ninvoker(1, 'join');\nexport default join;","import _curry1 from \"./internal/_curry1.js\";\nimport converge from \"./converge.js\";\n/**\n * juxt applies a list of functions to a list of values.\n *\n * @func\n * @memberOf R\n * @since v0.19.0\n * @category Function\n * @sig [(a, b, ..., m) -> n] -> ((a, b, ..., m) -> [n])\n * @param {Array} fns An array of functions\n * @return {Function} A function that returns a list of values after applying each of the original `fns` to its parameters.\n * @see R.applySpec\n * @example\n *\n * const getRange = R.juxt([Math.min, Math.max]);\n * getRange(3, 4, 9, -3); //=> [-3, 9]\n * @symb R.juxt([f, g, h])(a, b) = [f(a, b), g(a, b), h(a, b)]\n */\n\nvar juxt =\n/*#__PURE__*/\n_curry1(function juxt(fns) {\n return converge(function () {\n return Array.prototype.slice.call(arguments, 0);\n }, fns);\n});\n\nexport default juxt;","import _curry1 from \"./internal/_curry1.js\";\nimport _isNumber from \"./internal/_isNumber.js\";\n/**\n * Returns the number of elements in the array by returning `list.length`.\n *\n * @func\n * @memberOf R\n * @since v0.3.0\n * @category List\n * @sig [a] -> Number\n * @param {Array} list The array to inspect.\n * @return {Number} The length of the array.\n * @example\n *\n * R.length([]); //=> 0\n * R.length([1, 2, 3]); //=> 3\n */\n\nvar length =\n/*#__PURE__*/\n_curry1(function length(list) {\n return list != null && _isNumber(list.length) ? list.length : NaN;\n});\n\nexport default length;","export default function _isNumber(x) {\n return Object.prototype.toString.call(x) === '[object Number]';\n}","import _curry2 from \"./internal/_curry2.js\";\nimport map from \"./map.js\";\n/**\n * Returns a lens for the given getter and setter functions. The getter \"gets\"\n * the value of the focus; the setter \"sets\" the value of the focus. The setter\n * should not mutate the data structure.\n *\n * @func\n * @memberOf R\n * @since v0.8.0\n * @category Object\n * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s\n * @sig (s -> a) -> ((a, s) -> s) -> Lens s a\n * @param {Function} getter\n * @param {Function} setter\n * @return {Lens}\n * @see R.view, R.set, R.over, R.lensIndex, R.lensProp\n * @example\n *\n * const xLens = R.lens(R.prop('x'), R.assoc('x'));\n *\n * R.view(xLens, {x: 1, y: 2}); //=> 1\n * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}\n * R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2}\n */\n\nvar lens =\n/*#__PURE__*/\n_curry2(function lens(getter, setter) {\n return function (toFunctorFn) {\n return function (target) {\n return map(function (focus) {\n return setter(focus, target);\n }, toFunctorFn(getter(target)));\n };\n };\n});\n\nexport default lens;","import _curry2 from \"./internal/_curry2.js\";\nimport _isInteger from \"./internal/_isInteger.js\";\nimport nth from \"./nth.js\";\n/**\n * Retrieves the values at given paths of an object.\n *\n * @func\n * @memberOf R\n * @since v0.27.1\n * @category Object\n * @typedefn Idx = [String | Int | Symbol]\n * @sig [Idx] -> {a} -> [a | Undefined]\n * @param {Array} pathsArray The array of paths to be fetched.\n * @param {Object} obj The object to retrieve the nested properties from.\n * @return {Array} A list consisting of values at paths specified by \"pathsArray\".\n * @see R.path\n * @example\n *\n * R.paths([['a', 'b'], ['p', 0, 'q']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, 3]\n * R.paths([['a', 'b'], ['p', 'r']], {a: {b: 2}, p: [{q: 3}]}); //=> [2, undefined]\n */\n\nvar paths =\n/*#__PURE__*/\n_curry2(function paths(pathsArray, obj) {\n return pathsArray.map(function (paths) {\n var val = obj;\n var idx = 0;\n var p;\n\n while (idx < paths.length) {\n if (val == null) {\n return;\n }\n\n p = paths[idx];\n val = _isInteger(p) ? nth(p, val) : val[p];\n idx += 1;\n }\n\n return val;\n });\n});\n\nexport default paths;","import _curry2 from \"./internal/_curry2.js\";\nimport paths from \"./paths.js\";\n/**\n * Retrieves the value at a given path. The nodes of the path can be arbitrary strings or non-negative integers.\n * For anything else, the value is unspecified. Integer paths are meant to index arrays, strings are meant for objects.\n *\n * @func\n * @memberOf R\n * @since v0.2.0\n * @category Object\n * @typedefn Idx = String | Int | Symbol\n * @sig [Idx] -> {a} -> a | Undefined\n * @sig Idx = String | NonNegativeInt\n * @param {Array} path The path to use.\n * @param {Object} obj The object or array to retrieve the nested property from.\n * @return {*} The data at `path`.\n * @see R.prop, R.nth, R.assocPath, R.dissocPath\n * @example\n *\n * R.path(['a', 'b'], {a: {b: 2}}); //=> 2\n * R.path(['a', 'b'], {c: {b: 2}}); //=> undefined\n * R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1\n * R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2\n * R.path([2], {'2': 2}); //=> 2\n * R.path([-2], {'-2': 'a'}); //=> undefined\n */\n\nvar path =\n/*#__PURE__*/\n_curry2(function path(pathAr, obj) {\n return paths([pathAr], obj)[0];\n});\n\nexport default path;","import _curry1 from \"./internal/_curry1.js\";\nimport assocPath from \"./assocPath.js\";\nimport lens from \"./lens.js\";\nimport path from \"./path.js\";\n/**\n * Returns a lens whose focus is the specified path.\n *\n * @func\n * @memberOf R\n * @since v0.19.0\n * @category Object\n * @typedefn Idx = String | Int | Symbol\n * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s\n * @sig [Idx] -> Lens s a\n * @param {Array} path The path to use.\n * @return {Lens}\n * @see R.view, R.set, R.over\n * @example\n *\n * const xHeadYLens = R.lensPath(['x', 0, 'y']);\n *\n * R.view(xHeadYLens, {x: [{y: 2, z: 3}, {y: 4, z: 5}]});\n * //=> 2\n * R.set(xHeadYLens, 1, {x: [{y: 2, z: 3}, {y: 4, z: 5}]});\n * //=> {x: [{y: 1, z: 3}, {y: 4, z: 5}]}\n * R.over(xHeadYLens, R.negate, {x: [{y: 2, z: 3}, {y: 4, z: 5}]});\n * //=> {x: [{y: -2, z: 3}, {y: 4, z: 5}]}\n */\n\nvar lensPath =\n/*#__PURE__*/\n_curry1(function lensPath(p) {\n return lens(path(p), assocPath(p));\n});\n\nexport default lensPath;","import _curry1 from \"./internal/_curry1.js\";\nimport assoc from \"./assoc.js\";\nimport lens from \"./lens.js\";\nimport prop from \"./prop.js\";\n/**\n * Returns a lens whose focus is the specified property.\n *\n * @func\n * @memberOf R\n * @since v0.14.0\n * @category Object\n * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s\n * @sig String -> Lens s a\n * @param {String} k\n * @return {Lens}\n * @see R.view, R.set, R.over\n * @example\n *\n * const xLens = R.lensProp('x');\n *\n * R.view(xLens, {x: 1, y: 2}); //=> 1\n * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}\n * R.over(xLens, R.negate, {x: 1, y: 2}); //=> {x: -1, y: 2}\n */\n\nvar lensProp =\n/*#__PURE__*/\n_curry1(function lensProp(k) {\n return lens(prop(k), assoc(k));\n});\n\nexport default lensProp;","import _curry2 from \"./internal/_curry2.js\";\n/**\n * Returns `true` if the first argument is less than the second; `false`\n * otherwise.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Relation\n * @sig Ord a => a -> a -> Boolean\n * @param {*} a\n * @param {*} b\n * @return {Boolean}\n * @see R.gt\n * @example\n *\n * R.lt(2, 1); //=> false\n * R.lt(2, 2); //=> false\n * R.lt(2, 3); //=> true\n * R.lt('a', 'z'); //=> true\n * R.lt('z', 'a'); //=> false\n */\n\nvar lt =\n/*#__PURE__*/\n_curry2(function lt(a, b) {\n return a < b;\n});\n\nexport default lt;","import _curry3 from \"./internal/_curry3.js\";\nimport _has from \"./internal/_has.js\";\n/**\n * Creates a new object with the own properties of the two provided objects. If\n * a key exists in both objects, the provided function is applied to the key\n * and the values associated with the key in each object, with the result being\n * used as the value associated with the key in the returned object.\n *\n * @func\n * @memberOf R\n * @since v0.19.0\n * @category Object\n * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}\n * @param {Function} fn\n * @param {Object} l\n * @param {Object} r\n * @return {Object}\n * @see R.mergeDeepWithKey, R.merge, R.mergeWith\n * @example\n *\n * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r\n * R.mergeWithKey(concatValues,\n * { a: true, thing: 'foo', values: [10, 20] },\n * { b: true, thing: 'bar', values: [15, 35] });\n * //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] }\n * @symb R.mergeWithKey(f, { x: 1, y: 2 }, { y: 5, z: 3 }) = { x: 1, y: f('y', 2, 5), z: 3 }\n */\n\nvar mergeWithKey =\n/*#__PURE__*/\n_curry3(function mergeWithKey(fn, l, r) {\n var result = {};\n var k;\n l = l || {};\n r = r || {};\n\n for (k in l) {\n if (_has(k, l)) {\n result[k] = _has(k, r) ? fn(k, l[k], r[k]) : l[k];\n }\n }\n\n for (k in r) {\n if (_has(k, r) && !_has(k, result)) {\n result[k] = r[k];\n }\n }\n\n return result;\n});\n\nexport default mergeWithKey;","import _curry3 from \"./internal/_curry3.js\";\nimport _isObject from \"./internal/_isObject.js\";\nimport mergeWithKey from \"./mergeWithKey.js\";\n/**\n * Creates a new object with the own properties of the two provided objects.\n * If a key exists in both objects:\n * - and both associated values are also objects then the values will be\n * recursively merged.\n * - otherwise the provided function is applied to the key and associated values\n * using the resulting value as the new value associated with the key.\n * If a key only exists in one object, the value will be associated with the key\n * of the resulting object.\n *\n * @func\n * @memberOf R\n * @since v0.24.0\n * @category Object\n * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}\n * @param {Function} fn\n * @param {Object} lObj\n * @param {Object} rObj\n * @return {Object}\n * @see R.mergeWithKey, R.mergeDeepWith\n * @example\n *\n * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r\n * R.mergeDeepWithKey(concatValues,\n * { a: true, c: { thing: 'foo', values: [10, 20] }},\n * { b: true, c: { thing: 'bar', values: [15, 35] }});\n * //=> { a: true, b: true, c: { thing: 'bar', values: [10, 20, 15, 35] }}\n */\n\nvar mergeDeepWithKey =\n/*#__PURE__*/\n_curry3(function mergeDeepWithKey(fn, lObj, rObj) {\n return mergeWithKey(function (k, lVal, rVal) {\n if (_isObject(lVal) && _isObject(rVal)) {\n return mergeDeepWithKey(fn, lVal, rVal);\n } else {\n return fn(k, lVal, rVal);\n }\n }, lObj, rObj);\n});\n\nexport default mergeDeepWithKey;","import _curry2 from \"./internal/_curry2.js\";\nimport mergeDeepWithKey from \"./mergeDeepWithKey.js\";\n/**\n * Creates a new object with the own properties of the first object merged with\n * the own properties of the second object. If a key exists in both objects:\n * - and both values are objects, the two values will be recursively merged\n * - otherwise the value from the first object will be used.\n *\n * @func\n * @memberOf R\n * @since v0.24.0\n * @category Object\n * @sig {a} -> {a} -> {a}\n * @param {Object} lObj\n * @param {Object} rObj\n * @return {Object}\n * @see R.merge, R.mergeDeepRight, R.mergeDeepWith, R.mergeDeepWithKey\n * @example\n *\n * R.mergeDeepLeft({ name: 'fred', age: 10, contact: { email: 'moo@example.com' }},\n * { age: 40, contact: { email: 'baa@example.com' }});\n * //=> { name: 'fred', age: 10, contact: { email: 'moo@example.com' }}\n */\n\nvar mergeDeepLeft =\n/*#__PURE__*/\n_curry2(function mergeDeepLeft(lObj, rObj) {\n return mergeDeepWithKey(function (k, lVal, rVal) {\n return lVal;\n }, lObj, rObj);\n});\n\nexport default mergeDeepLeft;","import _curry2 from \"./internal/_curry2.js\";\nimport mergeDeepWithKey from \"./mergeDeepWithKey.js\";\n/**\n * Creates a new object with the own properties of the first object merged with\n * the own properties of the second object. If a key exists in both objects:\n * - and both values are objects, the two values will be recursively merged\n * - otherwise the value from the second object will be used.\n *\n * @func\n * @memberOf R\n * @since v0.24.0\n * @category Object\n * @sig {a} -> {a} -> {a}\n * @param {Object} lObj\n * @param {Object} rObj\n * @return {Object}\n * @see R.merge, R.mergeDeepLeft, R.mergeDeepWith, R.mergeDeepWithKey\n * @example\n *\n * R.mergeDeepRight({ name: 'fred', age: 10, contact: { email: 'moo@example.com' }},\n * { age: 40, contact: { email: 'baa@example.com' }});\n * //=> { name: 'fred', age: 40, contact: { email: 'baa@example.com' }}\n */\n\nvar mergeDeepRight =\n/*#__PURE__*/\n_curry2(function mergeDeepRight(lObj, rObj) {\n return mergeDeepWithKey(function (k, lVal, rVal) {\n return rVal;\n }, lObj, rObj);\n});\n\nexport default mergeDeepRight;","import _objectAssign from \"./internal/_objectAssign.js\";\nimport _curry2 from \"./internal/_curry2.js\";\n/**\n * Create a new object with the own properties of the first object merged with\n * the own properties of the second object. If a key exists in both objects,\n * the value from the second object will be used.\n *\n * @func\n * @memberOf R\n * @since v0.26.0\n * @category Object\n * @sig {k: v} -> {k: v} -> {k: v}\n * @param {Object} l\n * @param {Object} r\n * @return {Object}\n * @see R.mergeLeft, R.mergeDeepRight, R.mergeWith, R.mergeWithKey\n * @example\n *\n * R.mergeRight({ 'name': 'fred', 'age': 10 }, { 'age': 40 });\n * //=> { 'name': 'fred', 'age': 40 }\n *\n * const withDefaults = R.mergeRight({x: 0, y: 0});\n * withDefaults({y: 2}); //=> {x: 0, y: 2}\n * @symb R.mergeRight(a, b) = {...a, ...b}\n */\n\nvar mergeRight =\n/*#__PURE__*/\n_curry2(function mergeRight(l, r) {\n return _objectAssign({}, l, r);\n});\n\nexport default mergeRight;","import _curry3 from \"./internal/_curry3.js\";\nimport mergeWithKey from \"./mergeWithKey.js\";\n/**\n * Creates a new object with the own properties of the two provided objects. If\n * a key exists in both objects, the provided function is applied to the values\n * associated with the key in each object, with the result being used as the\n * value associated with the key in the returned object.\n *\n * @func\n * @memberOf R\n * @since v0.19.0\n * @category Object\n * @sig ((a, a) -> a) -> {a} -> {a} -> {a}\n * @param {Function} fn\n * @param {Object} l\n * @param {Object} r\n * @return {Object}\n * @see R.mergeDeepWith, R.merge, R.mergeWithKey\n * @example\n *\n * R.mergeWith(R.concat,\n * { a: true, values: [10, 20] },\n * { b: true, values: [15, 35] });\n * //=> { a: true, b: true, values: [10, 20, 15, 35] }\n */\n\nvar mergeWith =\n/*#__PURE__*/\n_curry3(function mergeWith(fn, l, r) {\n return mergeWithKey(function (_, _l, _r) {\n return fn(_l, _r);\n }, l, r);\n});\n\nexport default mergeWith;","import _curry1 from \"./internal/_curry1.js\";\n/**\n * A function that returns the `!` of its argument. It will return `true` when\n * passed false-y value, and `false` when passed a truth-y one.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Logic\n * @sig * -> Boolean\n * @param {*} a any value\n * @return {Boolean} the logical inverse of passed argument.\n * @see R.complement\n * @example\n *\n * R.not(true); //=> false\n * R.not(false); //=> true\n * R.not(0); //=> true\n * R.not(1); //=> false\n */\n\nvar not =\n/*#__PURE__*/\n_curry1(function not(a) {\n return !a;\n});\n\nexport default not;","import _curry2 from \"./internal/_curry2.js\";\n/**\n * Returns the first argument if it is truthy, otherwise the second argument.\n * Acts as the boolean `or` statement if both inputs are `Boolean`s.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Logic\n * @sig a -> b -> a | b\n * @param {Any} a\n * @param {Any} b\n * @return {Any}\n * @see R.either, R.and\n * @example\n *\n * R.or(true, true); //=> true\n * R.or(true, false); //=> true\n * R.or(false, true); //=> true\n * R.or(false, false); //=> false\n */\n\nvar or =\n/*#__PURE__*/\n_curry2(function or(a, b) {\n return a || b;\n});\n\nexport default or;","import _curry3 from \"./internal/_curry3.js\"; // `Identity` is a functor that holds a single value, where `map` simply\n// transforms the held value with the provided function.\n\nvar Identity = function (x) {\n return {\n value: x,\n map: function (f) {\n return Identity(f(x));\n }\n };\n};\n/**\n * Returns the result of \"setting\" the portion of the given data structure\n * focused by the given lens to the result of applying the given function to\n * the focused value.\n *\n * @func\n * @memberOf R\n * @since v0.16.0\n * @category Object\n * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s\n * @sig Lens s a -> (a -> a) -> s -> s\n * @param {Lens} lens\n * @param {*} v\n * @param {*} x\n * @return {*}\n * @see R.view, R.set, R.lens, R.lensIndex, R.lensProp, R.lensPath\n * @example\n *\n * const headLens = R.lensIndex(0);\n *\n * R.over(headLens, R.toUpper, ['foo', 'bar', 'baz']); //=> ['FOO', 'bar', 'baz']\n */\n\n\nvar over =\n/*#__PURE__*/\n_curry3(function over(lens, f, x) {\n // The value returned by the getter function is first transformed with `f`,\n // then set as the value of an `Identity`. This is then mapped over with the\n // setter function of the lens.\n return lens(function (y) {\n return Identity(f(y));\n })(x).value;\n});\n\nexport default over;","import filter from \"./filter.js\";\nimport juxt from \"./juxt.js\";\nimport reject from \"./reject.js\";\n/**\n * Takes a predicate and a list or other `Filterable` object and returns the\n * pair of filterable objects of the same type of elements which do and do not\n * satisfy, the predicate, respectively. Filterable objects include plain objects or any object\n * that has a filter method such as `Array`.\n *\n * @func\n * @memberOf R\n * @since v0.1.4\n * @category List\n * @sig Filterable f => (a -> Boolean) -> f a -> [f a, f a]\n * @param {Function} pred A predicate to determine which side the element belongs to.\n * @param {Array} filterable the list (or other filterable) to partition.\n * @return {Array} An array, containing first the subset of elements that satisfy the\n * predicate, and second the subset of elements that do not satisfy.\n * @see R.filter, R.reject\n * @example\n *\n * R.partition(R.includes('s'), ['sss', 'ttt', 'foo', 'bars']);\n * // => [ [ 'sss', 'bars' ], [ 'ttt', 'foo' ] ]\n *\n * R.partition(R.includes('s'), { a: 'sss', b: 'ttt', foo: 'bars' });\n * // => [ { a: 'sss', foo: 'bars' }, { b: 'ttt' } ]\n */\n\nvar partition =\n/*#__PURE__*/\njuxt([filter, reject]);\nexport default partition;","import _curry2 from \"./internal/_curry2.js\";\n/**\n * Returns a partial copy of an object containing only the keys that satisfy\n * the supplied predicate.\n *\n * @func\n * @memberOf R\n * @since v0.8.0\n * @category Object\n * @sig ((v, k) -> Boolean) -> {k: v} -> {k: v}\n * @param {Function} pred A predicate to determine whether or not a key\n * should be included on the output object.\n * @param {Object} obj The object to copy from\n * @return {Object} A new object with only properties that satisfy `pred`\n * on it.\n * @see R.pick, R.filter\n * @example\n *\n * const isUpperCase = (val, key) => key.toUpperCase() === key;\n * R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}\n */\n\nvar pickBy =\n/*#__PURE__*/\n_curry2(function pickBy(test, obj) {\n var result = {};\n\n for (var prop in obj) {\n if (test(obj[prop], prop, obj)) {\n result[prop] = obj[prop];\n }\n }\n\n return result;\n});\n\nexport default pickBy;","import _curry3 from \"./internal/_curry3.js\";\nimport prop from \"./prop.js\";\nimport equals from \"./equals.js\";\n/**\n * Returns `true` if the specified object property is equal, in\n * [`R.equals`](#equals) terms, to the given value; `false` otherwise.\n * You can test multiple properties with [`R.whereEq`](#whereEq),\n * and test nested path property with [`R.pathEq`](#pathEq).\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Relation\n * @sig a -> String -> Object -> Boolean\n * @param {*} val The value to compare the property with\n * @param {String} name the specified object property's key\n * @param {*} obj The object to check the property in\n * @return {Boolean} `true` if the value equals the specified object property,\n * `false` otherwise.\n * @see R.whereEq, R.pathEq, R.propSatisfies, R.equals\n * @example\n *\n * const abby = {name: 'Abby', age: 7, hair: 'blond'};\n * const fred = {name: 'Fred', age: 12, hair: 'brown'};\n * const rusty = {name: 'Rusty', age: 10, hair: 'brown'};\n * const alois = {name: 'Alois', age: 15, disposition: 'surly'};\n * const kids = [abby, fred, rusty, alois];\n * const hasBrownHair = R.propEq('brown', 'hair');\n * R.filter(hasBrownHair, kids); //=> [fred, rusty]\n */\n\nvar propEq =\n/*#__PURE__*/\n_curry3(function propEq(val, name, obj) {\n return equals(val, prop(name, obj));\n});\n\nexport default propEq;","import _curry2 from \"./internal/_curry2.js\";\n/**\n * Returns the second argument if it is not `null`, `undefined` or `NaN`;\n * otherwise the first argument is returned.\n *\n * @func\n * @memberOf R\n * @since v0.10.0\n * @category Logic\n * @sig a -> b -> a | b\n * @param {a} default The default value.\n * @param {b} val `val` will be returned instead of `default` unless `val` is `null`, `undefined` or `NaN`.\n * @return {*} The second value if it is not `null`, `undefined` or `NaN`, otherwise the default value\n * @example\n *\n * const defaultTo42 = R.defaultTo(42);\n *\n * defaultTo42(null); //=> 42\n * defaultTo42(undefined); //=> 42\n * defaultTo42(false); //=> false\n * defaultTo42('Ramda'); //=> 'Ramda'\n * // parseInt('string') results in NaN\n * defaultTo42(parseInt('string')); //=> 42\n */\n\nvar defaultTo =\n/*#__PURE__*/\n_curry2(function defaultTo(d, v) {\n return v == null || v !== v ? d : v;\n});\n\nexport default defaultTo;","import _curry3 from \"./internal/_curry3.js\";\nimport defaultTo from \"./defaultTo.js\";\nimport prop from \"./prop.js\";\n/**\n * Return the specified property of the given non-null object if the property\n * is present and it's value is not `null`, `undefined` or `NaN`.\n *\n * Otherwise the first argument is returned.\n *\n * @func\n * @memberOf R\n * @since v0.6.0\n * @category Object\n * @sig a -> String -> Object -> a\n * @param {*} val The default value.\n * @param {String} p The name of the property to return.\n * @param {Object} obj The object to query.\n * @return {*} The value of given property of the supplied object or the default value.\n * @example\n *\n * const alice = {\n * name: 'ALICE',\n * age: 101\n * };\n * const favorite = R.prop('favoriteLibrary');\n * const favoriteWithDefault = R.propOr('Ramda', 'favoriteLibrary');\n *\n * favorite(alice); //=> undefined\n * favoriteWithDefault(alice); //=> 'Ramda'\n */\n\nvar propOr =\n/*#__PURE__*/\n_curry3(function propOr(val, p, obj) {\n return defaultTo(val, prop(p, obj));\n});\n\nexport default propOr;","import _curry2 from \"./internal/_curry2.js\";\nimport path from \"./path.js\";\n/**\n * Acts as multiple `prop`: array of keys in, array of values out. Preserves\n * order.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Object\n * @sig [k] -> {k: v} -> [v]\n * @param {Array} ps The property names to fetch\n * @param {Object} obj The object to query\n * @return {Array} The corresponding values or partially applied function.\n * @see R.prop, R.pluck, R.project\n * @example\n *\n * R.props(['x', 'y'], {x: 1, y: 2}); //=> [1, 2]\n * R.props(['c', 'a', 'b'], {b: 2, a: 1}); //=> [undefined, 1, 2]\n *\n * const fullName = R.compose(R.join(' '), R.props(['first', 'last']));\n * fullName({last: 'Bullet-Tooth', age: 33, first: 'Tony'}); //=> 'Tony Bullet-Tooth'\n */\n\nvar props =\n/*#__PURE__*/\n_curry2(function props(ps, obj) {\n return ps.map(function (p) {\n return path([p], obj);\n });\n});\n\nexport default props;","import _curry3 from \"./internal/_curry3.js\";\n/**\n * Removes the sub-list of `list` starting at index `start` and containing\n * `count` elements. _Note that this is not destructive_: it returns a copy of\n * the list with the changes.\n * No lists have been harmed in the application of this function.\n *\n * @func\n * @memberOf R\n * @since v0.2.2\n * @category List\n * @sig Number -> Number -> [a] -> [a]\n * @param {Number} start The position to start removing elements\n * @param {Number} count The number of elements to remove\n * @param {Array} list The list to remove from\n * @return {Array} A new Array with `count` elements from `start` removed.\n * @see R.without\n * @example\n *\n * R.remove(2, 3, [1,2,3,4,5,6,7,8]); //=> [1,2,6,7,8]\n */\n\nvar remove =\n/*#__PURE__*/\n_curry3(function remove(start, count, list) {\n var result = Array.prototype.slice.call(list, 0);\n result.splice(start, count);\n return result;\n});\n\nexport default remove;","import _curry1 from \"./internal/_curry1.js\";\n/**\n * Returns a function that always returns the given value. Note that for\n * non-primitives the value returned is a reference to the original value.\n *\n * This function is known as `const`, `constant`, or `K` (for K combinator) in\n * other languages and libraries.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category Function\n * @sig a -> (* -> a)\n * @param {*} val The value to wrap in a function\n * @return {Function} A Function :: * -> val.\n * @example\n *\n * const t = R.always('Tee');\n * t(); //=> 'Tee'\n */\n\nvar always =\n/*#__PURE__*/\n_curry1(function always(val) {\n return function () {\n return val;\n };\n});\n\nexport default always;","import _curry3 from \"./internal/_curry3.js\";\nimport always from \"./always.js\";\nimport over from \"./over.js\";\n/**\n * Returns the result of \"setting\" the portion of the given data structure\n * focused by the given lens to the given value.\n *\n * @func\n * @memberOf R\n * @since v0.16.0\n * @category Object\n * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s\n * @sig Lens s a -> a -> s -> s\n * @param {Lens} lens\n * @param {*} v\n * @param {*} x\n * @return {*}\n * @see R.view, R.over, R.lens, R.lensIndex, R.lensProp, R.lensPath\n * @example\n *\n * const xLens = R.lensProp('x');\n *\n * R.set(xLens, 4, {x: 1, y: 2}); //=> {x: 4, y: 2}\n * R.set(xLens, 8, {x: 1, y: 2}); //=> {x: 8, y: 2}\n */\n\nvar set =\n/*#__PURE__*/\n_curry3(function set(lens, v, x) {\n return over(lens, always(v), x);\n});\n\nexport default set;","import _curry2 from \"./internal/_curry2.js\";\n/**\n * Returns a copy of the list, sorted according to the comparator function,\n * which should accept two values at a time and return a negative number if the\n * first value is smaller, a positive number if it's larger, and zero if they\n * are equal. Please note that this is a **copy** of the list. It does not\n * modify the original.\n *\n * @func\n * @memberOf R\n * @since v0.1.0\n * @category List\n * @sig ((a, a) -> Number) -> [a] -> [a]\n * @param {Function} comparator A sorting function :: a -> b -> Int\n * @param {Array} list The list to sort\n * @return {Array} a new array with its elements sorted by the comparator function.\n * @see R.ascend, R.descend\n * @example\n *\n * const diff = function(a, b) { return a - b; };\n * R.sort(diff, [4,2,7,5]); //=> [2, 4, 5, 7]\n */\n\nvar sort =\n/*#__PURE__*/\n_curry2(function sort(comparator, list) {\n return Array.prototype.slice.call(list, 0).sort(comparator);\n});\n\nexport default sort;","import _curry2 from \"./internal/_curry2.js\";\n/**\n * Sorts a list according to a list of comparators.\n *\n * @func\n * @memberOf R\n * @since v0.23.0\n * @category Relation\n * @sig [(a, a) -> Number] -> [a] -> [a]\n * @param {Array} functions A list of comparator functions.\n * @param {Array} list The list to sort.\n * @return {Array} A new list sorted according to the comarator functions.\n * @see R.ascend, R.descend\n * @example\n *\n * const alice = {\n * name: 'alice',\n * age: 40\n * };\n * const bob = {\n * name: 'bob',\n * age: 30\n * };\n * const clara = {\n * name: 'clara',\n * age: 40\n * };\n * const people = [clara, bob, alice];\n * const ageNameSort = R.sortWith([\n * R.descend(R.prop('age')),\n * R.ascend(R.prop('name'))\n * ]);\n * ageNameSort(people); //=> [alice, clara, bob]\n */\n\nvar sortWith =\n/*#__PURE__*/\n_curry2(function sortWith(fns, list) {\n return Array.prototype.slice.call(list, 0).sort(function (a, b) {\n var result = 0;\n var i = 0;\n\n while (result === 0 && i < fns.length) {\n result = fns[i](a, b);\n i += 1;\n }\n\n return result;\n });\n});\n\nexport default sortWith;","import _curry2 from \"./internal/_curry2.js\";\nimport equals from \"./equals.js\";\nimport take from \"./take.js\";\n/**\n * Checks if a list starts with the provided sublist.\n *\n * Similarly, checks if a string starts with the provided substring.\n *\n * @func\n * @memberOf R\n * @since v0.24.0\n * @category List\n * @sig [a] -> [a] -> Boolean\n * @sig String -> String -> Boolean\n * @param {*} prefix\n * @param {*} list\n * @return {Boolean}\n * @see R.endsWith\n * @example\n *\n * R.startsWith('a', 'abc') //=> true\n * R.startsWith('b', 'abc') //=> false\n * R.startsWith(['a'], ['a', 'b', 'c']) //=> true\n * R.startsWith(['b'], ['a', 'b', 'c']) //=> false\n */\n\nvar startsWith =\n/*#__PURE__*/\n_curry2(function (prefix, list) {\n return equals(take(prefix.length, list), prefix);\n});\n\nexport default startsWith;","import _curry2 from \"./internal/_curry2.js\"; // `Const` is a functor that effectively ignores the function given to `map`.\n\nvar Const = function (x) {\n return {\n value: x,\n 'fantasy-land/map': function () {\n return this;\n }\n };\n};\n/**\n * Returns a \"view\" of the given data structure, determined by the given lens.\n * The lens's focus determines which portion of the data structure is visible.\n *\n * @func\n * @memberOf R\n * @since v0.16.0\n * @category Object\n * @typedefn Lens s a = Functor f => (a -> f a) -> s -> f s\n * @sig Lens s a -> s -> a\n * @param {Lens} lens\n * @param {*} x\n * @return {*}\n * @see R.set, R.over, R.lens, R.lensIndex, R.lensProp, R.lensPath\n * @example\n *\n * const xLens = R.lensProp('x');\n *\n * R.view(xLens, {x: 1, y: 2}); //=> 1\n * R.view(xLens, {x: 4, y: 2}); //=> 4\n */\n\n\nvar view =\n/*#__PURE__*/\n_curry2(function view(lens, x) {\n // Using `Const` effectively ignores the setter function of the `lens`,\n // leaving the value returned by the getter function unmodified.\n return lens(Const)(x).value;\n});\n\nexport default view;","import _curry3 from \"./internal/_curry3.js\";\n/**\n * Tests the final argument by passing it to the given predicate function. If\n * the predicate is satisfied, the function will return the result of calling\n * the `whenTrueFn` function with the same argument. If the predicate is not\n * satisfied, the argument is returned as is.\n *\n * @func\n * @memberOf R\n * @since v0.18.0\n * @category Logic\n * @sig (a -> Boolean) -> (a -> b) -> a -> a | b\n * @param {Function} pred A predicate function\n * @param {Function} whenTrueFn A function to invoke when the `condition`\n * evaluates to a truthy value.\n * @param {*} x An object to test with the `pred` function and\n * pass to `whenTrueFn` if necessary.\n * @return {*} Either `x` or the result of applying `x` to `whenTrueFn`.\n * @see R.ifElse, R.unless, R.cond\n * @example\n *\n * // truncate :: String -> String\n * const truncate = R.when(\n * R.propSatisfies(R.gt(R.__, 10), 'length'),\n * R.pipe(R.take(10), R.append('…'), R.join(''))\n * );\n * truncate('12345'); //=> '12345'\n * truncate('0123456789ABC'); //=> '0123456789…'\n */\n\nvar when =\n/*#__PURE__*/\n_curry3(function when(pred, whenTrueFn, x) {\n return pred(x) ? whenTrueFn(x) : x;\n});\n\nexport default when;","import _curry2 from \"./internal/_curry2.js\";\nimport _Set from \"./internal/_Set.js\";\nimport reject from \"./reject.js\";\n/**\n * Returns a new list without values in the first argument.\n * [`R.equals`](#equals) is used to determine equality.\n *\n * Acts as a transducer if a transformer is given in list position.\n *\n * @func\n * @memberOf R\n * @since v0.19.0\n * @category List\n * @sig [a] -> [a] -> [a]\n * @param {Array} list1 The values to be removed from `list2`.\n * @param {Array} list2 The array to remove values from.\n * @return {Array} The new array without values in `list1`.\n * @see R.transduce, R.difference, R.remove\n * @example\n *\n * R.without([1, 2], [1, 2, 1, 3, 4]); //=> [3, 4]\n */\n\nvar without =\n/*#__PURE__*/\n_curry2(function without(xs, list) {\n var toRemove = new _Set();\n\n for (var i = 0; i < xs.length; i += 1) {\n toRemove.add(xs[i]);\n }\n\n return reject(toRemove.has.bind(toRemove), list);\n});\n\nexport default without;","/**\n * rambda vs ramda\n * rambda is simply faster than ramda.\n * So whatever the function you find in rambda use it, otherwise use ramda\n * If you list in RB then if there is no function, then typescript will complain for you.\n * https://github.com/selfrefactor/rambda#benchmark\n */\nimport * as RB from 'rambda';\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-ignore\nimport * as R from 'ramda';\n\nexport const {\n and,\n or,\n startsWith,\n lensProp,\n lensPath,\n view,\n add,\n set,\n remove,\n over,\n identity,\n forEach,\n without,\n length,\n compose,\n when,\n anyPass,\n not,\n toString,\n propEq,\n join,\n keys,\n ifElse,\n intersection,\n difference,\n differenceWith,\n curry,\n reverse,\n propOr,\n uniq,\n all,\n uniqBy,\n pickBy,\n comparator,\n gt,\n clone,\n lt,\n sort,\n eqProps,\n groupWith,\n mergeRight,\n indexBy,\n chain,\n map,\n partition,\n pipe,\n applySpec,\n juxt,\n mergeDeepLeft,\n mergeDeepRight,\n props,\n sortWith,\n ascend,\n descend,\n isNotNil,\n} = R;\n\nexport const {\n merge,\n isNil,\n is,\n prop,\n path,\n pathOr,\n equals,\n has,\n isEmpty,\n includes,\n both,\n either,\n multiply,\n toPairs,\n type,\n find,\n complement,\n flatten,\n defaultTo,\n range,\n groupBy,\n toLower,\n concat,\n sum,\n sortBy,\n filter,\n reduce,\n replace,\n flip,\n pluck,\n adjust,\n negate,\n assoc,\n dissoc,\n pick,\n omit,\n values,\n mergeAll,\n // eslint-disable-next-line @typescript-eslint/naming-convention, no-underscore-dangle, id-blacklist, id-match\n any,\n match,\n} = RB;\n\nconst isStringNullOrNil = (val: string | number): boolean =>\n equals('null', val) || equals('undefined', val) || isNil(val);\nexport const isNilOrEmpty: any = either(isStringNullOrNil, isEmpty);\n\nexport const toNumber = (val: string): number | undefined =>\n isNilOrEmpty(val) ? undefined : +val;\n\nexport const isStrNumber = (val: string): boolean => /^\\d+$/.test(val);\n\nexport const propOrZero = propOr(0);\n\nexport const uniqBySpeciesId = uniqBy(prop('speciesId'));\n\n// https://github.com/ramda/ramda/wiki/Cookbook#sql-style-joins\n// tslint:disable-next-line: max-func-args\nexport const joinInner = curry(\n (\n field1: any,\n field2: (arg0: object) => string | number,\n table1: any,\n table2: any\n ) => {\n const indexed = indexBy(field1, table1);\n\n return chain((t2row: object) => {\n const corresponding = indexed[field2(t2row)] as object;\n\n return corresponding ? [mergeRight(t2row, corresponding)] : [];\n }, table2);\n }\n);\n\n// tslint:disable-next-line: max-func-args\nexport const joinRight = R.curry(\n (\n mapper1: any,\n mapper2: (arg0: any) => string | number,\n t1: any,\n t2: any[]\n ) => {\n const indexed = R.indexBy(mapper1, t1);\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return t2.map((t2row) =>\n R.mergeRight(t2row, indexed[mapper2(t2row)] as object)\n );\n }\n);\n\n// tslint:disable-next-line: max-func-args\nexport const joinOuter = curry(\n (field1: any, field2: any, table1: any, table2: any) => {\n const o1 = indexBy(field1, table1);\n const o2 = indexBy(field2, table2);\n\n return values(R.mergeWith(mergeRight, o1, o2));\n }\n);\n\n// tslint:disable-next-line: max-func-args\nexport const joinLeft = R.curry((f1: any, f2: any, t1: any, t2: any) =>\n joinRight(f2, f1, t2, t1)\n);\n\nexport const concatFlipped = flip(concat);\n\nexport const toFixed = (\n value: string | number,\n decimals?: number\n): string | undefined => {\n if (isNilOrEmpty(value)) {\n return;\n }\n\n return Number(value).toFixed(decimals);\n};\n","import { Injectable, inject } from '@angular/core';\nimport { fromEvent, map, merge, Observable, startWith } from 'rxjs';\nimport { Platform } from '@ionic/angular';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class PlatformService {\n private platform = inject(Platform);\n\n public isPWA(): boolean {\n return this.platform.is('pwa');\n }\n\n public isIOS(): boolean {\n return this.platform.is('ios');\n }\n\n public isAndroid(): boolean {\n return this.platform.is('android');\n }\n\n public isMobile(): boolean {\n return !this.platform.is('desktop');\n }\n\n public isMobileWeb(): boolean {\n return this.platform.is('mobileweb');\n }\n\n public isIosPwa(): boolean {\n return window.matchMedia('(display-mode: standalone)').matches;\n }\n\n public isOffline$ = (): Observable => {\n const online$ = fromEvent(window, 'online').pipe(map(() => false));\n const offline$ = fromEvent(window, 'offline').pipe(map(() => true));\n return merge(online$, offline$).pipe(startWith(!navigator.onLine));\n };\n}\n","import { ToastController } from '@ionic/angular';\nimport { inject, Injectable } from '@angular/core';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class ToastService {\n private toastController = inject(ToastController);\n\n async presentToast(\n message: string,\n position: 'top' | 'middle' | 'bottom' = 'bottom',\n duration = 1500\n ) {\n const toast = await this.toastController.create({\n message: message,\n duration: duration,\n position: position,\n });\n\n await toast.present();\n }\n}\n","\n \n \n \n \n\n \n {{ title }}\n \n \n\n \n \n \n \n \n \n\n","import { Component, inject, Input, OnDestroy, OnInit } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { IonicModule } from '@ionic/angular';\nimport { Subscription } from 'rxjs';\nimport { Store } from '@ngrx/store';\nimport { FavouritesState } from '../../../favourites/favourites.reducer';\nimport { selectFavouriteAdded } from '../../../favourites/favourites.selectors';\nimport { FavouritesService } from '../../../favourites/favourites.service';\n\n@Component({\n selector: 'snowylive-header',\n standalone: true,\n imports: [CommonModule, IonicModule],\n templateUrl: './header.component.html',\n styleUrls: ['./header.component.scss'],\n})\nexport class HeaderComponent implements OnInit, OnDestroy {\n private readonly favouritesStore = inject(Store);\n private readonly favouritesService = inject(FavouritesService);\n\n @Input() title!: string;\n @Input() icon!: string;\n @Input() href!: string;\n\n protected isFavorite$$!: Subscription;\n protected isFavorite!: boolean;\n\n ngOnInit() {\n this.initFavourite();\n }\n\n ngOnDestroy() {\n this.isFavorite$$.unsubscribe();\n }\n\n initFavourite() {\n this.isFavorite$$ = this.favouritesStore\n .select(selectFavouriteAdded(this.title))\n .subscribe((isFavorite) => {\n this.isFavorite = isFavorite;\n });\n }\n\n toggleFavorite(event: Event) {\n event.stopPropagation();\n const item = {\n id: this.title,\n href: this.href,\n icon: this.icon,\n };\n this.favouritesService.addOrRemoveFavorites(item, this.isFavorite);\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport { environment } from '../../environments/environment';\nimport { DataFetchType, DBTableName } from '../cache/data-config';\nimport { DBService } from '../cache/db.service';\nimport {\n IConvertedSnowDepth,\n IGroupedSnowDepths,\n ILatestSnowDepth,\n ISnowDepth,\n ISnowDepthJson,\n ISnowDepthValue,\n SnowDepthObjectOrder,\n} from '../models/SnowDepth';\nimport { ItemDescription, TileType } from '../models/Item';\nimport {\n FavouriteHref,\n FavouriteTileIcon,\n} from '../favourites/favourites.models';\nimport { updateFavourites } from '../favourites/favourites.actions';\nimport { Store } from '@ngrx/store';\nimport { FavouritesState } from '../favourites/favourites.reducer';\nimport { equals, isNilOrEmpty } from '../ramda-functions';\nimport { ToastService } from '../shared/services/toast.service';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class SnowDepthsService {\n private dbService = inject(DBService);\n private favouriteStore = inject(Store);\n private toastService = inject(ToastService);\n\n private snowDepths!: ISnowDepth;\n\n setSnowDepths = (snowDepths: ISnowDepth) => {\n this.snowDepths = snowDepths;\n };\n\n getSnowDepths = () => this.snowDepths;\n\n private generateSnowDepthUrl = (year: number) =>\n `${environment.dataUrl}/${DataFetchType.SnowyDepths}${year}.xml`;\n\n private fetchSnowDepthDataByYear = async (year: number) => {\n const url = this.generateSnowDepthUrl(year);\n return await this.dbService.fetchData(url);\n };\n\n loadSnowDepthData = async () => {\n if (await this.dbService.isDataValid(DBTableName.SnowDepths)) {\n return this.dbService.get(DBTableName.SnowDepths);\n }\n return this.initSnowDepthData();\n };\n\n initSnowDepthData = async () => {\n try {\n const thisYear = new Date().getFullYear();\n const formattedSnowDepthsYear = await this.initSnowDepthDataByYear(\n thisYear\n );\n const thisYearHasData = !isNilOrEmpty(formattedSnowDepthsYear);\n const formattedSnowDepthsLastYear = await this.initSnowDepthDataByYear(\n thisYear - 1\n );\n\n const combinedSnowDepths = this.combineSnowDepths(\n formattedSnowDepthsYear,\n formattedSnowDepthsLastYear,\n thisYearHasData\n );\n await this.updateSnowDepthData(combinedSnowDepths);\n return combinedSnowDepths;\n } catch (error) {\n if (await this.dbService.isDataExisted(DBTableName.SnowDepths)) {\n return this.dbService.get(DBTableName.SnowDepths);\n }\n throw error;\n }\n };\n\n private updateSnowDepthData = async (data: ISnowDepth) => {\n await this.dbService.set(DBTableName.SnowDepths, data);\n await this.dbService.updateCacheLastModified(DBTableName.SnowDepths);\n this.updateFavourites(data);\n };\n\n private updateFavourites = (data: ISnowDepth) => {\n const favourites = Object.entries(data).map(([id, snowDepth]) => ({\n id,\n icon: FavouriteTileIcon.snowDepth,\n type: TileType.SnowDepth,\n href: FavouriteHref.snowDepth,\n value: snowDepth.currentValue.value,\n unit: snowDepth.currentValue.unit,\n }));\n this.favouriteStore.dispatch(updateFavourites({ favourites }));\n };\n\n private initSnowDepthDataByYear = async (\n year: number\n ): Promise => {\n try {\n const snowDepthData = (await this.fetchSnowDepthDataByYear(\n year\n )) as ISnowDepthJson;\n const filteredSnowDepthData = structuredClone(snowDepthData);\n filteredSnowDepthData.snowyhydro.level =\n snowDepthData.snowyhydro.level.filter((item) =>\n equals(new Date(item.$.date).getFullYear(), year)\n );\n return this.convertSnowDepthData(filteredSnowDepthData);\n } catch (e) {\n const error = e as Error;\n if (equals(error.name, 'DataNotFoundError')) {\n await this.toastService.presentToast(\n `No snow depth data for year ${year}.`\n );\n return {};\n } else {\n throw error;\n }\n }\n };\n\n private convertSnowDepthData = (snowDepthData: ISnowDepthJson) => {\n const snowDepths = snowDepthData.snowyhydro.level;\n const formattedSnowDepths = snowDepths.flatMap((snowDepth) =>\n snowDepth.snow.map((snowDepth) => ({\n name: snowDepth.$.name,\n date: new Date(snowDepth.$.dataTimestamp),\n quality: snowDepth.$.quality,\n value: parseFloat(snowDepth._),\n }))\n );\n\n return this.groupSnowDepths(formattedSnowDepths);\n };\n\n private groupSnowDepths = (snowDepths: IConvertedSnowDepth[]) => {\n const groupedSnowDepths = snowDepths.reduce((acc, snowDepth) => {\n const name = snowDepth.name;\n if (!acc[name]) {\n acc[name] = [];\n }\n acc[name].push({\n date: snowDepth.date,\n quality: snowDepth.quality,\n value: snowDepth.value,\n });\n return acc;\n }, {} as IGroupedSnowDepths);\n\n return this.sortSnowDepths(groupedSnowDepths);\n };\n\n private sortSnowDepths = (snowDepths: IGroupedSnowDepths) => {\n const sortedSnowDepthObject: IGroupedSnowDepths = {};\n SnowDepthObjectOrder.forEach((snowDepthName) => {\n sortedSnowDepthObject[snowDepthName] = snowDepths[snowDepthName];\n });\n return sortedSnowDepthObject;\n };\n\n combineSnowDepths = (\n snowDepthsThisYear: IGroupedSnowDepths,\n snowDepthsLastYear: IGroupedSnowDepths,\n thisYearHasData: boolean\n ): ISnowDepth => {\n return Object.keys(snowDepthsLastYear).reduce(\n (result: ISnowDepth, snowDepthName) => {\n const snowDepthLastYear = snowDepthsLastYear[snowDepthName];\n const snowDepthThisYear = snowDepthsThisYear[snowDepthName] ?? [];\n const latestSnowDepth = this.calculateLatestSnowDepth(\n thisYearHasData ? snowDepthThisYear : snowDepthLastYear\n );\n result[snowDepthName] = {\n snowDepthThisYear: snowDepthThisYear,\n snowDepthLastYear: snowDepthLastYear,\n currentValue: latestSnowDepth,\n };\n return result;\n },\n {}\n );\n };\n\n private calculateLatestSnowDepth = (\n snowDepth: ISnowDepthValue[]\n ): ILatestSnowDepth => {\n const latestSnowDepth = snowDepth[snowDepth.length - 1];\n return {\n date: latestSnowDepth.date,\n value: latestSnowDepth.value,\n unit: 'cm',\n description: ItemDescription.LatestDepth,\n };\n };\n}\n","import { inject, Injectable } from '@angular/core';\nimport { AppMetadataEntries, IAppMetadata } from '../../contentful/contentful';\nimport { ContentfulService } from '../../contentful/contentful.service';\nimport { not } from '../../ramda-functions';\nimport { environment } from '../../../environments/environment';\nimport { isVersionLessThan } from '../update.utils';\nimport { PlatformService } from '../../shared/services/platform.service';\nimport { AlertService } from '../../alert/alert.service';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class MobileUpdateService {\n private contentfulService = inject(ContentfulService);\n private platformService = inject(PlatformService);\n private alertService = inject(AlertService);\n\n public getLatestVersionFromContentful = async () => {\n try {\n const content: IAppMetadata = (\n await this.contentfulService.getEntryById(\n AppMetadataEntries.LatestVersion\n )\n ).fields;\n\n return content.value;\n } catch (e) {\n console.error(e);\n // anchor value to 0.0.0 if contentful is down, to prevent showing update alert\n return '0.0.0';\n }\n };\n\n public checkAppStoreUpdates = async () => {\n if (not(this.platformService.isMobile())) {\n // no need to check for updates in web app, it is handled by pwa update services\n return;\n }\n const latestVersion = await this.getLatestVersionFromContentful();\n const currentVersion = environment.version;\n\n if (isVersionLessThan(currentVersion, latestVersion)) {\n await this.alertService.presentSingleActionAlert(\n 'App Update Available',\n 'A new version is available in App Store. Please update the app to get the latest content.',\n async () => {}\n );\n }\n };\n}\n","import { environment } from '../../environments/environment';\nimport { compareVersions } from 'compare-versions';\n\nexport const getCurrentAppVersion = async () => {\n return new Promise(environment.version);\n};\n\nexport const generateUnrecoverableStateMessage = (reason: string) => {\n return `An error occurred that we cannot recover from: ${reason}.\n Please reload the page and contact support if the problem persists.`;\n};\n\nexport const generatePwaUpdateMessage = () => {\n return 'Application update detected. Please refresh to apply the latest changes.';\n};\n\nexport const isVersionGreaterThan = (\n version1: string,\n version2: string\n): boolean => {\n return compareVersions(version1, version2) > 0;\n};\n\nexport const isVersionLessThan = (\n version1: string,\n version2: string\n): boolean => {\n return compareVersions(version1, version2) < 0;\n};\n\nexport const isVersionEqual = (version1: string, version2: string): boolean => {\n return compareVersions(version1, version2) === 0;\n};\n\nexport const enum VersionEventType {\n VERSION_DETECTED = 'VERSION_DETECTED',\n VERSION_READY = 'VERSION_READY',\n VERSION_INSTALLATION_FAILED = 'VERSION_INSTALLATION_FAILED',\n}\n","import { inject, Injectable } from '@angular/core';\nimport { ContentfulService } from '../contentful/contentful.service';\nimport { IScheme, ISchemeContent, schemes } from '../models/Scheme';\nimport { equals } from '../ramda-functions';\nimport { IMenuItem } from '../models/Item';\nimport { getId } from '../contentful/contentful';\nimport { Asset, Entry } from 'contentful';\nimport { isNil } from 'rambda';\nimport { DBService } from '../cache/db.service';\nimport { Store } from '@ngrx/store';\nimport { IContentfulState } from '../contentful/contentful.reducer';\nimport { clearNextSyncToken } from '../contentful/contentful.actions';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class VisitTheSchemeService {\n private contentfulService = inject(ContentfulService);\n private dbService = inject(DBService);\n private contentfulStore = inject(Store);\n\n private visitTheSchemeContents = schemes;\n\n getSchemeContents = () => this.visitTheSchemeContents;\n\n setSchemeContents = (schemeContents: IScheme[]) => {\n this.visitTheSchemeContents = schemeContents;\n };\n\n getSchemeContent = (name: string) => {\n return this.visitTheSchemeContents.find((schemeContent) =>\n equals(schemeContent.title, name)\n );\n };\n\n initSchemeContents = async (schemeContents: IScheme[]) => {\n try {\n const schemeContentsWithContent: IScheme[] =\n (await this.loadSchemeContents(schemeContents)) as any;\n this.setSchemeContents(schemeContentsWithContent);\n } catch (error) {\n console.error(error);\n // force clear the NextSyncToken that is causing the error in new version app\n this.contentfulStore.dispatch(clearNextSyncToken());\n }\n };\n\n private loadSchemeContents = async (contents: IScheme[]) => {\n return Promise.all(\n contents.map(async (content) => {\n const schemeContent = (\n await this.contentfulService.getEntryById(content.entryId)\n ).fields;\n\n const coverImage = await this.loadImage(schemeContent.coverImage);\n const detailImages = await this.loadImages(schemeContent.detailImages);\n\n return {\n ...content,\n content: schemeContent.description as Document,\n title: schemeContent.title,\n coverImage,\n detailImages,\n };\n })\n );\n };\n\n private loadImage = async (image: Asset) => {\n const coverImageId = getId(image);\n if (isNil(coverImageId)) {\n return;\n }\n return await this.dbService.get(coverImageId);\n };\n\n private loadImages = async (images: Asset[]) => {\n return Promise.all(images.map((image) => this.loadImage(image)));\n };\n\n generateMenuItems = (): IMenuItem[] =>\n this.getSchemeContents().map(({ title, href, coverImage }) => ({\n name: title as string,\n href,\n image: coverImage,\n }));\n}\n","import { inject, Injectable } from '@angular/core';\nimport { DBService } from '../cache/db.service';\nimport { environment } from '../../environments/environment';\nimport { DataFetchType, DBTableName } from '../cache/data-config';\nimport {\n ICurrentReleaseItem,\n ICurrentWaterReleaseJsonItem,\n ICurrentWaterReleaseJsonItemDam,\n IReleaseValue,\n IWaterRelease,\n IWaterReleaseItem,\n IWaterReleaseJson,\n IWaterReleaseJsonItem,\n IWaterReleaseJsonItemRelease,\n IWaterReleaseValue,\n WaterReleaseDam,\n} from '../models/WaterRelease';\nimport { equals, isNil } from '../ramda-functions';\nimport { GrowthStatus, TileType } from '../models/Item';\nimport { Store } from '@ngrx/store';\nimport { FavouritesState } from '../favourites/favourites.reducer';\nimport {\n FavouriteHref,\n FavouriteTileIcon,\n IFavouritesEntity,\n} from '../favourites/favourites.models';\nimport { updateFavourites } from '../favourites/favourites.actions';\nimport { ToastService } from '../shared/services/toast.service';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class WaterReleasesService {\n private dbService = inject(DBService);\n private favouriteStore = inject(Store);\n private toastService = inject(ToastService);\n\n private waterReleases!: IWaterRelease;\n\n setWaterReleases = (waterReleases: IWaterRelease) => {\n this.waterReleases = waterReleases;\n };\n\n getWaterReleases = () => this.waterReleases;\n\n private generateUrl = (fetchType: DataFetchType) =>\n `${environment.dataUrl}/${fetchType}.xml`;\n\n loadWaterReleasesData = async () => {\n if (await this.dbService.isDataValid(DBTableName.WaterReleases)) {\n return this.dbService.get(DBTableName.WaterReleases);\n }\n return this.initWaterReleasesData();\n };\n\n private fetchData = async (fetchType: DataFetchType) => {\n const url = this.generateUrl(fetchType);\n try {\n return (await this.dbService.fetchData(url)) as IWaterReleaseJson;\n } catch (e) {\n const error = e as Error;\n if (equals(error.name, 'DataNotFoundError')) {\n await this.toastService.presentToast(\n `No water release data found for ${fetchType}.`\n );\n return undefined;\n } else {\n throw error;\n }\n }\n };\n\n private initWaterReleasesData = async (): Promise => {\n try {\n const jintangaraData = await this.fetchData(DataFetchType.Jindabyne);\n const tantangaraData = await this.fetchData(DataFetchType.Tantangara);\n const khancobanData = await this.fetchData(DataFetchType.Khancoban);\n\n const waterReleases: IWaterRelease = {\n ...this.convertData(WaterReleaseDam.Jindabyne, jintangaraData),\n ...this.convertData(WaterReleaseDam.Tantangara, tantangaraData),\n ...this.convertData(WaterReleaseDam.Khancoban, khancobanData),\n };\n\n await this.updateWaterReleasesData(waterReleases);\n return waterReleases;\n } catch (error) {\n if (await this.dbService.isDataExisted(DBTableName.WaterReleases)) {\n return this.dbService.get(DBTableName.WaterReleases);\n }\n throw error;\n }\n };\n\n private updateWaterReleasesData = async (data: IWaterRelease) => {\n await this.dbService.set(DBTableName.WaterReleases, data);\n await this.dbService.updateCacheLastModified(DBTableName.WaterReleases);\n this.updateFavourites(data);\n };\n\n private updateFavourites = (data: IWaterRelease) => {\n const favourites: IFavouritesEntity[] = Object.entries(data).map(\n ([id, waterRelease]) => ({\n id,\n icon: FavouriteTileIcon.waterRelease,\n type: equals(id, WaterReleaseDam.Khancoban)\n ? TileType.CurrentRelease\n : TileType.WaterRelease,\n href: FavouriteHref.waterRelease,\n value: equals(id, WaterReleaseDam.Khancoban)\n ? (waterRelease as ICurrentReleaseItem).value\n : (waterRelease as IWaterReleaseItem).currentValue.value,\n unit: (waterRelease as ICurrentReleaseItem).unit,\n growthStatus: equals(id, WaterReleaseDam.Khancoban)\n ? (waterRelease as ICurrentReleaseItem).growthStatus\n : undefined,\n })\n );\n\n this.favouriteStore.dispatch(updateFavourites({ favourites }));\n };\n\n private convertData = (\n dam: WaterReleaseDam,\n rawJsonData?: IWaterReleaseJson\n ): IWaterRelease => {\n if (isNil(rawJsonData) || isNil(rawJsonData.snowyhydro)) {\n return {};\n }\n return equals(dam, WaterReleaseDam.Khancoban)\n ? this.convertCurrentReleaseData(\n (rawJsonData.snowyhydro as ICurrentWaterReleaseJsonItem).dam,\n dam\n )\n : this.convertReleaseData(\n (rawJsonData.snowyhydro as IWaterReleaseJsonItem).releases,\n dam\n );\n };\n\n private convertReleaseData = (\n jsonReleaseItems: IWaterReleaseJsonItemRelease[],\n dam: WaterReleaseDam\n ): IWaterRelease => {\n const releaseData = jsonReleaseItems[0].release;\n const currentReleaseData: IWaterReleaseValue = {\n value: parseFloat(releaseData[0]._),\n date: new Date(jsonReleaseItems[0].$.date),\n unit: this.generateUnit(dam),\n };\n const releaseSchedule: IWaterReleaseValue[] = releaseData.map(\n (release: IReleaseValue) => ({\n value: parseFloat(release._),\n date: new Date(release.$.date),\n unit: this.generateUnit(dam),\n })\n );\n return {\n [dam]: {\n currentValue: currentReleaseData,\n values: releaseSchedule,\n },\n };\n };\n\n private convertCurrentReleaseData = (\n currentReleases: ICurrentWaterReleaseJsonItemDam[],\n dam: WaterReleaseDam\n ): IWaterRelease => {\n const currentReleaseData = currentReleases[0];\n return {\n [dam]: {\n value: parseFloat(currentReleaseData._),\n date: new Date(currentReleaseData.$.dataTimeStamp),\n growthStatus: this.convertFlowRateChange(\n currentReleaseData.$.flowRateChange\n ),\n unit: this.generateUnit(dam),\n },\n };\n };\n\n private convertFlowRateChange = (flowRateChange: string) => {\n return equals(flowRateChange, 'rising')\n ? GrowthStatus.GROWING\n : equals(flowRateChange, 'falling')\n ? GrowthStatus.FALLING\n : GrowthStatus.STABLE;\n };\n\n private generateUnit = (dam: WaterReleaseDam) =>\n equals(dam, WaterReleaseDam.Khancoban) ? 'cumecs' : 'ML';\n}\n","export const environment = {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n version: require('../../../../package.json').version,\n dataUrl: 'https://www.snowyhydro.com.au/data/SnowyLIVE',\n contentful: {\n context: 'production',\n spaceId: 'z5loi28935cy',\n stagingAccessToken: 'TABjUwY-14UI83fo7SSLe9C1rpw0RKFnBer2EXN8fmA',\n productAccessToken: 'adbd3JFrbnieY-QHcmBHcIVtldbIXd8mCEI6XiO-uCg',\n stagingHost: 'preview.contentful.com',\n productHost: 'cdn.contentful.com',\n },\n\n // sentry related\n targetEnv: 'prod',\n};\n","import { Injectable, inject } from '@angular/core';\nimport {\n createEffect,\n Actions,\n ofType,\n ROOT_EFFECTS_INIT,\n concatLatestFrom,\n} from '@ngrx/effects';\nimport {\n switchMap,\n catchError,\n of,\n tap,\n withLatestFrom,\n map,\n from,\n} from 'rxjs';\nimport { ContentfulService } from './contentful.service';\nimport { isNil, isNilOrEmpty } from '../ramda-functions';\nimport {\n checkUpdateFailure,\n nextSyncTokenUpdate,\n retry,\n switchContentfulContext,\n syncAssets,\n syncAssetsFailure,\n syncAssetsSuccess,\n syncEntries,\n syncEntriesFailure,\n syncEntriesSuccess,\n syncSkipped,\n} from './contentful.actions';\nimport { IContentfulState } from './contentful.reducer';\nimport { Store } from '@ngrx/store';\nimport { selectNextSyncToken } from './contentful.selectors';\nimport { HomeService } from '../home/home.service';\nimport { MobileUpdateService } from '../update/mobile/mobile-update.service';\n\n@Injectable()\nexport class ContentfulEffects {\n private actions$ = inject(Actions);\n private contentfulService = inject(ContentfulService);\n private contentfulStore = inject(Store);\n private homeService = inject(HomeService);\n private mobileUpdateService = inject(MobileUpdateService);\n\n checkUpdate$ = createEffect(() => {\n return this.actions$.pipe(\n ofType(ROOT_EFFECTS_INIT, retry),\n tap(() => this.contentfulService.preventScreenSleep()),\n tap(() => this.mobileUpdateService.checkAppStoreUpdates()),\n switchMap(() => this.contentfulService.checkRemoteUpdate()),\n concatLatestFrom(() =>\n this.contentfulStore\n .select(selectNextSyncToken)\n .pipe(map((nextSyncToken) => isNilOrEmpty(nextSyncToken)))\n ),\n switchMap(([syncCollection, firstLaunch]) =>\n from(\n this.contentfulService.presentNotificationIfHasChanges(\n syncCollection,\n firstLaunch\n )\n ).pipe(\n map(() => syncEntries({ syncCollection })),\n catchError(() =>\n of(\n firstLaunch\n ? checkUpdateFailure({ error: 'Sync Entries Error' })\n : syncSkipped()\n )\n )\n )\n ),\n catchError((err) =>\n of(checkUpdateFailure({ error: err?.message || 'Sync Entries Error' }))\n )\n );\n });\n\n changeStage$ = createEffect(() => {\n return this.actions$.pipe(\n ofType(switchContentfulContext),\n switchMap(() => this.contentfulService.clearCache()),\n map(() => retry())\n );\n });\n\n syncEntries$ = createEffect(() => {\n return this.actions$.pipe(\n ofType(syncEntries),\n switchMap(({ syncCollection }) =>\n this.contentfulService.syncEntries(syncCollection).pipe(\n map((syncCollection) => syncEntriesSuccess({ syncCollection })),\n catchError((err) =>\n of(\n syncEntriesFailure({\n error: err?.message || 'Sync Entries Error',\n })\n )\n )\n )\n )\n );\n });\n\n syncEntriesSuccess$ = createEffect(() => {\n return this.actions$.pipe(\n ofType(syncEntriesSuccess),\n map((syncCollection) => syncAssets(syncCollection))\n );\n });\n\n syncAssets$ = createEffect(() => {\n return this.actions$.pipe(\n ofType(syncAssets),\n switchMap(({ syncCollection }) =>\n this.contentfulService.syncAssets(syncCollection).pipe(\n map((nextSyncToken) => syncAssetsSuccess({ nextSyncToken })),\n catchError((err) =>\n of(\n syncAssetsFailure({\n error: err?.message || 'Sync Assets Error',\n })\n )\n )\n )\n )\n );\n });\n\n syncAssetsSuccess$ = createEffect(\n () => {\n return this.actions$.pipe(\n ofType(syncAssetsSuccess),\n tap(() => this.contentfulService.allowScreenSleep()),\n tap(() => this.homeService.loadContentfulData()),\n map(({ nextSyncToken }) =>\n this.contentfulService.updateNextToken(nextSyncToken)\n )\n );\n },\n { dispatch: false }\n );\n}\n","import {\n ChangeDetectionStrategy,\n ChangeDetectorRef,\n Component,\n inject,\n OnInit,\n ViewChild,\n} from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { HeaderComponent } from '../shared/ui/header/header.component';\nimport { IonContent, IonicModule } from '@ionic/angular';\nimport { ContentfulService } from '../contentful/contentful.service';\nimport { InfoEntries, IInfoContent } from '../contentful/contentful';\nimport { documentToHtmlString } from '@contentful/rich-text-html-renderer';\nimport { environment } from '../../environments/environment';\n\n@Component({\n selector: 'snowylive-info',\n standalone: true,\n imports: [CommonModule, HeaderComponent, IonicModule],\n templateUrl: './info.component.html',\n styleUrls: ['./info.component.scss'],\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport class InfoComponent implements OnInit {\n @ViewChild(IonContent, { static: false }) content!: IonContent;\n\n private contentfulService = inject(ContentfulService);\n private cdr = inject(ChangeDetectorRef);\n private infoContentId = InfoEntries.infoPage;\n protected readonly version = environment.version;\n infoContent!: IInfoContent;\n infoRichText!: string;\n\n async ngOnInit() {\n this.infoContent = (\n await this.contentfulService.getEntryById(this.infoContentId)\n ).fields;\n this.infoRichText = documentToHtmlString(this.infoContent.content);\n this.cdr.detectChanges();\n }\n\n backToTop = async () => {\n await this.content.scrollToTop(500);\n };\n}\n","\n\n\n \n \n
\n
\n
\n
\n\n\n \n Version: {{ version }}\n \n \n \n \n \n \n\n","import { ChangeDetectorRef, Component, inject } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { HeaderComponent } from '../shared/ui/header/header.component';\nimport { IonicModule } from '@ionic/angular';\nimport { ContentfulService } from '../contentful/contentful.service';\nimport { IInfoContent, InfoEntries } from '../contentful/contentful';\nimport { documentToHtmlString } from '@contentful/rich-text-html-renderer';\n\n@Component({\n selector: 'snowylive-contact-us',\n standalone: true,\n imports: [CommonModule, HeaderComponent, IonicModule],\n templateUrl: './contact-us.component.html',\n styleUrls: ['./contact-us.component.scss'],\n})\nexport class ContactUsComponent {\n private contentfulService = inject(ContentfulService);\n private cdr = inject(ChangeDetectorRef);\n\n private contactUsContentId = InfoEntries.contactUs;\n contactUsContent!: IInfoContent;\n contactUsRichText!: string;\n\n async ngOnInit() {\n this.contactUsContent = (\n await this.contentfulService.getEntryById(this.contactUsContentId)\n ).fields;\n this.contactUsRichText = documentToHtmlString(\n this.contactUsContent.content\n );\n this.cdr.detectChanges();\n }\n}\n","\n\n\n \n \n
\n
\n
\n
\n","import { inject, Injectable } from '@angular/core';\nimport { FavouritesService } from './favourites.service';\nimport { Actions, createEffect, ofType } from '@ngrx/effects';\nimport {\n updateFavourites,\n updateFavouritesFailure,\n updateFavouritesSuccess,\n} from './favourites.actions';\nimport { catchError, map, of, switchMap } from 'rxjs';\n\n@Injectable()\nexport class FavouritesEffects {\n private favouritesService = inject(FavouritesService);\n private actions$ = inject(Actions);\n\n updateFavourites$ = createEffect(() => {\n return this.actions$.pipe(\n ofType(updateFavourites),\n switchMap(({ favourites }) => {\n return this.favouritesService.updateFavourites(favourites).pipe(\n map((updatedFavourites) => {\n return updateFavouritesSuccess({ favourites: updatedFavourites });\n }),\n catchError((err) => of(updateFavouritesFailure({ error: err })))\n );\n })\n );\n });\n}\n","import { Route } from '@angular/router';\nimport { provideEffects } from '@ngrx/effects';\nimport { ContentfulEffects } from './contentful/contentful.effects';\nimport { InfoComponent } from './info/info.component';\nimport { ContactUsComponent } from './contact-us/contact-us.component';\nimport { FavouritesEffects } from './favourites/favourites.effects';\n\nexport const appRoutes: Route[] = [\n {\n path: 'sync',\n loadChildren: () =>\n import('./sync/sync.routes').then((mod) => mod.SyncRoutes),\n providers: [provideEffects(ContentfulEffects)],\n },\n {\n path: 'home',\n loadChildren: () =>\n import('./home/home.routes').then((mod) => mod.homeRoutes),\n providers: [provideEffects(ContentfulEffects, FavouritesEffects)],\n },\n {\n path: 'lake-levels',\n loadChildren: () =>\n import('./lake-levels/lake-levels.routes').then(\n (mod) => mod.LakeLevelsRoutes\n ),\n },\n {\n path: 'snow-depths',\n loadChildren: () =>\n import('./snow-depths/snow-depths.routes').then(\n (mod) => mod.SnowDepthsRoutes\n ),\n },\n {\n path: 'water-releases',\n loadChildren: () =>\n import('./water-releases/water-releases.routes').then(\n (mod) => mod.WaterReleasesRoutes\n ),\n },\n {\n path: 'info',\n component: InfoComponent,\n },\n {\n path: 'public-access',\n loadChildren: () =>\n import('./public-access/public-access.routes').then(\n (mod) => mod.publicAccessRoutes\n ),\n },\n {\n path: 'visit-the-scheme',\n loadChildren: () =>\n import('./visit-the-scheme/visit-the-scheme.routes').then(\n (mod) => mod.VisitTheSchemeRoutes\n ),\n },\n {\n path: 'favourites',\n loadChildren: () =>\n import('./favourites/favourites.routes').then(\n (mod) => mod.favouritesRoutes\n ),\n },\n {\n path: 'contact-us',\n component: ContactUsComponent,\n },\n];\n","import { Observable } from '../Observable';\nimport { noop } from '../util/noop';\nexport const NEVER = new Observable(noop);\nexport function never() {\n return NEVER;\n}\n","import { Subject } from '../Subject';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { fromSubscribable } from '../observable/fromSubscribable';\nconst DEFAULT_CONFIG = {\n connector: () => new Subject(),\n};\nexport function connect(selector, config = DEFAULT_CONFIG) {\n const { connector } = config;\n return operate((source, subscriber) => {\n const subject = connector();\n innerFrom(selector(fromSubscribable(subject))).subscribe(subscriber);\n subscriber.add(source.subscribe(subject));\n });\n}\n","import { Observable } from '../Observable';\nexport function fromSubscribable(subscribable) {\n return new Observable((subscriber) => subscribable.subscribe(subscriber));\n}\n","import { concat } from '../observable/concat';\nimport { take } from './take';\nimport { ignoreElements } from './ignoreElements';\nimport { mapTo } from './mapTo';\nimport { mergeMap } from './mergeMap';\nimport { innerFrom } from '../observable/innerFrom';\nexport function delayWhen(delayDurationSelector, subscriptionDelay) {\n if (subscriptionDelay) {\n return (source) => concat(subscriptionDelay.pipe(take(1), ignoreElements()), source.pipe(delayWhen(delayDurationSelector)));\n }\n return mergeMap((value, index) => innerFrom(delayDurationSelector(value, index)).pipe(take(1), mapTo(value)));\n}\n","import { Observable } from '../Observable';\nimport { async as asyncScheduler } from '../scheduler/async';\nimport { isScheduler } from '../util/isScheduler';\nimport { isValidDate } from '../util/isDate';\nexport function timer(dueTime = 0, intervalOrScheduler, scheduler = asyncScheduler) {\n let intervalDuration = -1;\n if (intervalOrScheduler != null) {\n if (isScheduler(intervalOrScheduler)) {\n scheduler = intervalOrScheduler;\n }\n else {\n intervalDuration = intervalOrScheduler;\n }\n }\n return new Observable((subscriber) => {\n let due = isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime;\n if (due < 0) {\n due = 0;\n }\n let n = 0;\n return scheduler.schedule(function () {\n if (!subscriber.closed) {\n subscriber.next(n++);\n if (0 <= intervalDuration) {\n this.schedule(undefined, intervalDuration);\n }\n else {\n subscriber.complete();\n }\n }\n }, due);\n });\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { delayWhen } from './delayWhen';\nimport { timer } from '../observable/timer';\nexport function delay(due, scheduler = asyncScheduler) {\n const duration = timer(due, scheduler);\n return delayWhen(() => duration);\n}\n","/**\n * @license Angular v16.2.1\n * (c) 2010-2022 Google LLC. https://angular.io/\n * License: MIT\n */\n\nimport * as i0 from '@angular/core';\nimport { Injectable, InjectionToken, NgZone, ApplicationRef, makeEnvironmentProviders, PLATFORM_ID, APP_INITIALIZER, Injector, NgModule } from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\nimport { defer, throwError, fromEvent, of, concat, Subject, NEVER, merge } from 'rxjs';\nimport { map, filter, switchMap, publish, take, tap, delay } from 'rxjs/operators';\n\nconst ERR_SW_NOT_SUPPORTED = 'Service workers are disabled or not supported by this browser';\nfunction errorObservable(message) {\n return defer(() => throwError(new Error(message)));\n}\n/**\n * @publicApi\n */\nclass NgswCommChannel {\n constructor(serviceWorker) {\n this.serviceWorker = serviceWorker;\n if (!serviceWorker) {\n this.worker = this.events = this.registration = errorObservable(ERR_SW_NOT_SUPPORTED);\n }\n else {\n const controllerChangeEvents = fromEvent(serviceWorker, 'controllerchange');\n const controllerChanges = controllerChangeEvents.pipe(map(() => serviceWorker.controller));\n const currentController = defer(() => of(serviceWorker.controller));\n const controllerWithChanges = concat(currentController, controllerChanges);\n this.worker = controllerWithChanges.pipe(filter((c) => !!c));\n this.registration = (this.worker.pipe(switchMap(() => serviceWorker.getRegistration())));\n const rawEvents = fromEvent(serviceWorker, 'message');\n const rawEventPayload = rawEvents.pipe(map(event => event.data));\n const eventsUnconnected = rawEventPayload.pipe(filter(event => event && event.type));\n const events = eventsUnconnected.pipe(publish());\n events.connect();\n this.events = events;\n }\n }\n postMessage(action, payload) {\n return this.worker\n .pipe(take(1), tap((sw) => {\n sw.postMessage({\n action,\n ...payload,\n });\n }))\n .toPromise()\n .then(() => undefined);\n }\n postMessageWithOperation(type, payload, operationNonce) {\n const waitForOperationCompleted = this.waitForOperationCompleted(operationNonce);\n const postMessage = this.postMessage(type, payload);\n return Promise.all([postMessage, waitForOperationCompleted]).then(([, result]) => result);\n }\n generateNonce() {\n return Math.round(Math.random() * 10000000);\n }\n eventsOfType(type) {\n let filterFn;\n if (typeof type === 'string') {\n filterFn = (event) => event.type === type;\n }\n else {\n filterFn = (event) => type.includes(event.type);\n }\n return this.events.pipe(filter(filterFn));\n }\n nextEventOfType(type) {\n return this.eventsOfType(type).pipe(take(1));\n }\n waitForOperationCompleted(nonce) {\n return this.eventsOfType('OPERATION_COMPLETED')\n .pipe(filter(event => event.nonce === nonce), take(1), map(event => {\n if (event.result !== undefined) {\n return event.result;\n }\n throw new Error(event.error);\n }))\n .toPromise();\n }\n get isEnabled() {\n return !!this.serviceWorker;\n }\n}\n\n/**\n * Subscribe and listen to\n * [Web Push\n * Notifications](https://developer.mozilla.org/en-US/docs/Web/API/Push_API/Best_Practices) through\n * Angular Service Worker.\n *\n * @usageNotes\n *\n * You can inject a `SwPush` instance into any component or service\n * as a dependency.\n *\n * \n *\n * To subscribe, call `SwPush.requestSubscription()`, which asks the user for permission.\n * The call returns a `Promise` with a new\n * [`PushSubscription`](https://developer.mozilla.org/en-US/docs/Web/API/PushSubscription)\n * instance.\n *\n * \n *\n * A request is rejected if the user denies permission, or if the browser\n * blocks or does not support the Push API or ServiceWorkers.\n * Check `SwPush.isEnabled` to confirm status.\n *\n * Invoke Push Notifications by pushing a message with the following payload.\n *\n * ```ts\n * {\n * \"notification\": {\n * \"actions\": NotificationAction[],\n * \"badge\": USVString,\n * \"body\": DOMString,\n * \"data\": any,\n * \"dir\": \"auto\"|\"ltr\"|\"rtl\",\n * \"icon\": USVString,\n * \"image\": USVString,\n * \"lang\": DOMString,\n * \"renotify\": boolean,\n * \"requireInteraction\": boolean,\n * \"silent\": boolean,\n * \"tag\": DOMString,\n * \"timestamp\": DOMTimeStamp,\n * \"title\": DOMString,\n * \"vibrate\": number[]\n * }\n * }\n * ```\n *\n * Only `title` is required. See `Notification`\n * [instance\n * properties](https://developer.mozilla.org/en-US/docs/Web/API/Notification#Instance_properties).\n *\n * While the subscription is active, Service Worker listens for\n * [PushEvent](https://developer.mozilla.org/en-US/docs/Web/API/PushEvent)\n * occurrences and creates\n * [Notification](https://developer.mozilla.org/en-US/docs/Web/API/Notification)\n * instances in response.\n *\n * Unsubscribe using `SwPush.unsubscribe()`.\n *\n * An application can subscribe to `SwPush.notificationClicks` observable to be notified when a user\n * clicks on a notification. For example:\n *\n * \n *\n * You can read more on handling notification clicks in the [Service worker notifications\n * guide](guide/service-worker-notifications).\n *\n * @see [Push Notifications](https://developers.google.com/web/fundamentals/codelabs/push-notifications/)\n * @see [Angular Push Notifications](https://blog.angular-university.io/angular-push-notifications/)\n * @see [MDN: Push API](https://developer.mozilla.org/en-US/docs/Web/API/Push_API)\n * @see [MDN: Notifications API](https://developer.mozilla.org/en-US/docs/Web/API/Notifications_API)\n * @see [MDN: Web Push API Notifications best practices](https://developer.mozilla.org/en-US/docs/Web/API/Push_API/Best_Practices)\n *\n * @publicApi\n */\nclass SwPush {\n /**\n * True if the Service Worker is enabled (supported by the browser and enabled via\n * `ServiceWorkerModule`).\n */\n get isEnabled() {\n return this.sw.isEnabled;\n }\n constructor(sw) {\n this.sw = sw;\n this.pushManager = null;\n this.subscriptionChanges = new Subject();\n if (!sw.isEnabled) {\n this.messages = NEVER;\n this.notificationClicks = NEVER;\n this.subscription = NEVER;\n return;\n }\n this.messages = this.sw.eventsOfType('PUSH').pipe(map(message => message.data));\n this.notificationClicks =\n this.sw.eventsOfType('NOTIFICATION_CLICK').pipe(map((message) => message.data));\n this.pushManager = this.sw.registration.pipe(map(registration => registration.pushManager));\n const workerDrivenSubscriptions = this.pushManager.pipe(switchMap(pm => pm.getSubscription()));\n this.subscription = merge(workerDrivenSubscriptions, this.subscriptionChanges);\n }\n /**\n * Subscribes to Web Push Notifications,\n * after requesting and receiving user permission.\n *\n * @param options An object containing the `serverPublicKey` string.\n * @returns A Promise that resolves to the new subscription object.\n */\n requestSubscription(options) {\n if (!this.sw.isEnabled || this.pushManager === null) {\n return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED));\n }\n const pushOptions = { userVisibleOnly: true };\n let key = this.decodeBase64(options.serverPublicKey.replace(/_/g, '/').replace(/-/g, '+'));\n let applicationServerKey = new Uint8Array(new ArrayBuffer(key.length));\n for (let i = 0; i < key.length; i++) {\n applicationServerKey[i] = key.charCodeAt(i);\n }\n pushOptions.applicationServerKey = applicationServerKey;\n return this.pushManager.pipe(switchMap(pm => pm.subscribe(pushOptions)), take(1))\n .toPromise()\n .then(sub => {\n this.subscriptionChanges.next(sub);\n return sub;\n });\n }\n /**\n * Unsubscribes from Service Worker push notifications.\n *\n * @returns A Promise that is resolved when the operation succeeds, or is rejected if there is no\n * active subscription or the unsubscribe operation fails.\n */\n unsubscribe() {\n if (!this.sw.isEnabled) {\n return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED));\n }\n const doUnsubscribe = (sub) => {\n if (sub === null) {\n throw new Error('Not subscribed to push notifications.');\n }\n return sub.unsubscribe().then(success => {\n if (!success) {\n throw new Error('Unsubscribe failed!');\n }\n this.subscriptionChanges.next(null);\n });\n };\n return this.subscription.pipe(take(1), switchMap(doUnsubscribe)).toPromise();\n }\n decodeBase64(input) {\n return atob(input);\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"16.2.1\", ngImport: i0, type: SwPush, deps: [{ token: NgswCommChannel }], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"16.2.1\", ngImport: i0, type: SwPush }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"16.2.1\", ngImport: i0, type: SwPush, decorators: [{\n type: Injectable\n }], ctorParameters: function () { return [{ type: NgswCommChannel }]; } });\n\n/**\n * Subscribe to update notifications from the Service Worker, trigger update\n * checks, and forcibly activate updates.\n *\n * @see {@link guide/service-worker-communications Service worker communication guide}\n *\n * @publicApi\n */\nclass SwUpdate {\n /**\n * True if the Service Worker is enabled (supported by the browser and enabled via\n * `ServiceWorkerModule`).\n */\n get isEnabled() {\n return this.sw.isEnabled;\n }\n constructor(sw) {\n this.sw = sw;\n if (!sw.isEnabled) {\n this.versionUpdates = NEVER;\n this.available = NEVER;\n this.activated = NEVER;\n this.unrecoverable = NEVER;\n return;\n }\n this.versionUpdates = this.sw.eventsOfType([\n 'VERSION_DETECTED',\n 'VERSION_INSTALLATION_FAILED',\n 'VERSION_READY',\n 'NO_NEW_VERSION_DETECTED',\n ]);\n this.available = this.versionUpdates.pipe(filter((evt) => evt.type === 'VERSION_READY'), map(evt => ({\n type: 'UPDATE_AVAILABLE',\n current: evt.currentVersion,\n available: evt.latestVersion,\n })));\n this.activated = this.sw.eventsOfType('UPDATE_ACTIVATED');\n this.unrecoverable = this.sw.eventsOfType('UNRECOVERABLE_STATE');\n }\n /**\n * Checks for an update and waits until the new version is downloaded from the server and ready\n * for activation.\n *\n * @returns a promise that\n * - resolves to `true` if a new version was found and is ready to be activated.\n * - resolves to `false` if no new version was found\n * - rejects if any error occurs\n */\n checkForUpdate() {\n if (!this.sw.isEnabled) {\n return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED));\n }\n const nonce = this.sw.generateNonce();\n return this.sw.postMessageWithOperation('CHECK_FOR_UPDATES', { nonce }, nonce);\n }\n /**\n * Updates the current client (i.e. browser tab) to the latest version that is ready for\n * activation.\n *\n * In most cases, you should not use this method and instead should update a client by reloading\n * the page.\n *\n *
\n *\n * Updating a client without reloading can easily result in a broken application due to a version\n * mismatch between the [application shell](guide/glossary#app-shell) and other page resources,\n * such as [lazy-loaded chunks](guide/glossary#lazy-loading), whose filenames may change between\n * versions.\n *\n * Only use this method, if you are certain it is safe for your specific use case.\n *\n *
\n *\n * @returns a promise that\n * - resolves to `true` if an update was activated successfully\n * - resolves to `false` if no update was available (for example, the client was already on the\n * latest version).\n * - rejects if any error occurs\n */\n activateUpdate() {\n if (!this.sw.isEnabled) {\n return Promise.reject(new Error(ERR_SW_NOT_SUPPORTED));\n }\n const nonce = this.sw.generateNonce();\n return this.sw.postMessageWithOperation('ACTIVATE_UPDATE', { nonce }, nonce);\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"16.2.1\", ngImport: i0, type: SwUpdate, deps: [{ token: NgswCommChannel }], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"16.2.1\", ngImport: i0, type: SwUpdate }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"16.2.1\", ngImport: i0, type: SwUpdate, decorators: [{\n type: Injectable\n }], ctorParameters: function () { return [{ type: NgswCommChannel }]; } });\n\n/*!\n * @license\n * Copyright Google LLC All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nconst SCRIPT = new InjectionToken('NGSW_REGISTER_SCRIPT');\nfunction ngswAppInitializer(injector, script, options, platformId) {\n return () => {\n if (!(isPlatformBrowser(platformId) && ('serviceWorker' in navigator) &&\n options.enabled !== false)) {\n return;\n }\n // Wait for service worker controller changes, and fire an INITIALIZE action when a new SW\n // becomes active. This allows the SW to initialize itself even if there is no application\n // traffic.\n navigator.serviceWorker.addEventListener('controllerchange', () => {\n if (navigator.serviceWorker.controller !== null) {\n navigator.serviceWorker.controller.postMessage({ action: 'INITIALIZE' });\n }\n });\n let readyToRegister$;\n if (typeof options.registrationStrategy === 'function') {\n readyToRegister$ = options.registrationStrategy();\n }\n else {\n const [strategy, ...args] = (options.registrationStrategy || 'registerWhenStable:30000').split(':');\n switch (strategy) {\n case 'registerImmediately':\n readyToRegister$ = of(null);\n break;\n case 'registerWithDelay':\n readyToRegister$ = delayWithTimeout(+args[0] || 0);\n break;\n case 'registerWhenStable':\n readyToRegister$ = !args[0] ? whenStable(injector) :\n merge(whenStable(injector), delayWithTimeout(+args[0]));\n break;\n default:\n // Unknown strategy.\n throw new Error(`Unknown ServiceWorker registration strategy: ${options.registrationStrategy}`);\n }\n }\n // Don't return anything to avoid blocking the application until the SW is registered.\n // Also, run outside the Angular zone to avoid preventing the app from stabilizing (especially\n // given that some registration strategies wait for the app to stabilize).\n // Catch and log the error if SW registration fails to avoid uncaught rejection warning.\n const ngZone = injector.get(NgZone);\n ngZone.runOutsideAngular(() => readyToRegister$.pipe(take(1)).subscribe(() => navigator.serviceWorker.register(script, { scope: options.scope })\n .catch(err => console.error('Service worker registration failed with:', err))));\n };\n}\nfunction delayWithTimeout(timeout) {\n return of(null).pipe(delay(timeout));\n}\nfunction whenStable(injector) {\n const appRef = injector.get(ApplicationRef);\n return appRef.isStable.pipe(filter(stable => stable));\n}\nfunction ngswCommChannelFactory(opts, platformId) {\n return new NgswCommChannel(isPlatformBrowser(platformId) && opts.enabled !== false ? navigator.serviceWorker :\n undefined);\n}\n/**\n * Token that can be used to provide options for `ServiceWorkerModule` outside of\n * `ServiceWorkerModule.register()`.\n *\n * You can use this token to define a provider that generates the registration options at runtime,\n * for example via a function call:\n *\n * {@example service-worker/registration-options/module.ts region=\"registration-options\"\n * header=\"app.module.ts\"}\n *\n * @publicApi\n */\nclass SwRegistrationOptions {\n}\n/**\n * @publicApi\n *\n * Sets up providers to register the given Angular Service Worker script.\n *\n * If `enabled` is set to `false` in the given options, the module will behave as if service\n * workers are not supported by the browser, and the service worker will not be registered.\n *\n * Example usage:\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideServiceWorker('ngsw-worker.js')\n * ],\n * });\n * ```\n */\nfunction provideServiceWorker(script, options = {}) {\n return makeEnvironmentProviders([\n SwPush,\n SwUpdate,\n { provide: SCRIPT, useValue: script },\n { provide: SwRegistrationOptions, useValue: options },\n {\n provide: NgswCommChannel,\n useFactory: ngswCommChannelFactory,\n deps: [SwRegistrationOptions, PLATFORM_ID]\n },\n {\n provide: APP_INITIALIZER,\n useFactory: ngswAppInitializer,\n deps: [Injector, SCRIPT, SwRegistrationOptions, PLATFORM_ID],\n multi: true,\n },\n ]);\n}\n\n/**\n * @publicApi\n */\nclass ServiceWorkerModule {\n /**\n * Register the given Angular Service Worker script.\n *\n * If `enabled` is set to `false` in the given options, the module will behave as if service\n * workers are not supported by the browser, and the service worker will not be registered.\n */\n static register(script, options = {}) {\n return {\n ngModule: ServiceWorkerModule,\n providers: [provideServiceWorker(script, options)],\n };\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"16.2.1\", ngImport: i0, type: ServiceWorkerModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }\n static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: \"14.0.0\", version: \"16.2.1\", ngImport: i0, type: ServiceWorkerModule }); }\n static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: \"12.0.0\", version: \"16.2.1\", ngImport: i0, type: ServiceWorkerModule, providers: [SwPush, SwUpdate] }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"16.2.1\", ngImport: i0, type: ServiceWorkerModule, decorators: [{\n type: NgModule,\n args: [{ providers: [SwPush, SwUpdate] }]\n }] });\n\n/**\n * @module\n * @description\n * Entry point for all public APIs of this package.\n */\n// This file only reexports content of the `src` folder. Keep it that way.\n\n// This file is not used to build this module. It is only used during editing\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { ServiceWorkerModule, SwPush, SwRegistrationOptions, SwUpdate, provideServiceWorker };\n","import { Subject } from '../Subject';\nimport { multicast } from './multicast';\nimport { connect } from './connect';\nexport function publish(selector) {\n return selector ? (source) => connect(selector)(source) : (source) => multicast(new Subject())(source);\n}\n","import { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { isFunction } from '../util/isFunction';\nimport { connect } from './connect';\nexport function multicast(subjectOrSubjectFactory, selector) {\n const subjectFactory = isFunction(subjectOrSubjectFactory) ? subjectOrSubjectFactory : () => subjectOrSubjectFactory;\n if (isFunction(selector)) {\n return connect(selector, {\n connector: subjectFactory,\n });\n }\n return (source) => new ConnectableObservable(source, subjectFactory);\n}\n","import { isPlatformServer } from '@angular/common';\nimport * as i0 from '@angular/core';\nimport { InjectionToken, PLATFORM_ID, NgModule } from '@angular/core';\nimport { Storage } from '@ionic/storage';\nexport { Storage } from '@ionic/storage';\n\nconst StorageConfigToken = new InjectionToken('STORAGE_CONFIG_TOKEN');\nclass NoopStorage extends Storage {\n constructor() {\n super();\n }\n async create() {\n return this;\n }\n async defineDriver() { }\n get driver() {\n return 'noop';\n }\n async get(key) {\n return null;\n }\n async set(key, value) { }\n async remove(key) { }\n async clear() { }\n async length() {\n return 0;\n }\n async keys() {\n return [];\n }\n // eslint-disable-next-line @typescript-eslint/ban-types\n async forEach(iteratorCallback) { }\n setEncryptionKey(key) { }\n}\nfunction provideStorage(platformId, storageConfig) {\n if (isPlatformServer(platformId)) {\n // When running in a server context return the NoopStorage\n return new NoopStorage();\n }\n return new Storage(storageConfig);\n}\nclass IonicStorageModule {\n static forRoot(storageConfig = null) {\n return {\n ngModule: IonicStorageModule,\n providers: [\n { provide: StorageConfigToken, useValue: storageConfig },\n {\n provide: Storage,\n useFactory: provideStorage,\n deps: [PLATFORM_ID, StorageConfigToken],\n },\n ],\n };\n }\n}\nIonicStorageModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"15.1.2\", ngImport: i0, type: IonicStorageModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });\nIonicStorageModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: \"14.0.0\", version: \"15.1.2\", ngImport: i0, type: IonicStorageModule });\nIonicStorageModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: \"12.0.0\", version: \"15.1.2\", ngImport: i0, type: IonicStorageModule });\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"15.1.2\", ngImport: i0, type: IonicStorageModule, decorators: [{\n type: NgModule\n }] });\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { IonicStorageModule, StorageConfigToken, provideStorage };\n","import deepmerge from 'deepmerge';\n\n// Cannot import from the @ngrx/store package due to a module resolution issue.\n// See Issue #206.\nconst INIT_ACTION = '@ngrx/store/init';\nconst UPDATE_ACTION = '@ngrx/store/update-reducers';\nconst detectDate = /(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})/;\n// correctly parse dates from local storage\nconst dateReviver = (_key, value) => {\n if (typeof value === 'string' && detectDate.test(value)) {\n return new Date(value);\n }\n return value;\n};\nconst dummyReviver = (_key, value) => value;\nconst checkIsBrowserEnv = () => {\n return typeof window !== 'undefined';\n};\nconst validateStateKeys = (keys) => {\n return keys.map((key) => {\n let attr = key;\n if (typeof key === 'object') {\n attr = Object.keys(key)[0];\n }\n if (typeof attr !== 'string') {\n throw new TypeError(`localStorageSync Unknown Parameter Type: ` + `Expected type of string, got ${typeof attr}`);\n }\n return key;\n });\n};\nconst rehydrateApplicationState = (keys, storage, storageKeySerializer, restoreDates) => {\n return keys.reduce((acc, curr) => {\n let key = curr;\n let reviver = restoreDates ? dateReviver : dummyReviver;\n let deserialize;\n let decrypt;\n if (typeof key === 'object') {\n key = Object.keys(key)[0];\n // use the custom reviver function\n if (typeof curr[key] === 'function') {\n reviver = curr[key];\n }\n else {\n // use custom reviver function if available\n if (curr[key].reviver) {\n reviver = curr[key].reviver;\n }\n // use custom serialize function if available\n if (curr[key].deserialize) {\n deserialize = curr[key].deserialize;\n }\n }\n // Ensure that encrypt and decrypt functions are both present\n if (curr[key].encrypt && curr[key].decrypt) {\n if (typeof curr[key].encrypt === 'function' && typeof curr[key].decrypt === 'function') {\n decrypt = curr[key].decrypt;\n }\n else {\n console.error(`Either encrypt or decrypt is not a function on '${curr[key]}' key object.`);\n }\n }\n else if (curr[key].encrypt || curr[key].decrypt) {\n // Let know that one of the encryption functions is not provided\n console.error(`Either encrypt or decrypt function is not present on '${curr[key]}' key object.`);\n }\n }\n if (storage !== undefined) {\n let stateSlice = storage.getItem(storageKeySerializer(key));\n if (stateSlice) {\n // Use provided decrypt function\n if (decrypt) {\n stateSlice = decrypt(stateSlice);\n }\n const isObjectRegex = new RegExp('{|\\\\[');\n let raw = stateSlice;\n if (stateSlice === 'null' || stateSlice === 'true' || stateSlice === 'false' || isObjectRegex.test(stateSlice.charAt(0))) {\n raw = JSON.parse(stateSlice, reviver);\n }\n return Object.assign({}, acc, {\n [key]: deserialize ? deserialize(raw) : raw,\n });\n }\n }\n return acc;\n }, {});\n};\n// Recursively traverse all properties of the existing slice as defined by the `filter` argument,\n// and output the new object with extraneous properties removed.\nfunction createStateSlice(existingSlice, filter) {\n return filter.reduce((memo, attr) => {\n if (typeof attr === 'string' || typeof attr === 'number') {\n const value = existingSlice?.[attr];\n if (value !== undefined) {\n memo[attr] = value;\n }\n }\n else {\n for (const key in attr) {\n if (Object.prototype.hasOwnProperty.call(attr, key)) {\n const element = attr[key];\n memo[key] = createStateSlice(existingSlice[key], element);\n }\n }\n }\n return memo;\n }, {});\n}\nconst syncStateUpdate = (state, keys, storage, storageKeySerializer, removeOnUndefined, syncCondition) => {\n if (syncCondition) {\n try {\n if (syncCondition(state) !== true) {\n return;\n }\n }\n catch (e) {\n // Treat TypeError as do not sync\n if (e instanceof TypeError) {\n return;\n }\n throw e;\n }\n }\n keys.forEach((key) => {\n let stateSlice = state[key];\n let replacer;\n let space;\n let encrypt;\n if (typeof key === 'object') {\n let name = Object.keys(key)[0];\n stateSlice = state[name];\n if (typeof stateSlice !== 'undefined' && key[name]) {\n // use serialize function if specified.\n if (key[name].serialize) {\n stateSlice = key[name].serialize(stateSlice);\n }\n else {\n // if serialize function is not specified filter on fields if an array has been provided.\n let filter;\n if (key[name].reduce) {\n filter = key[name];\n }\n else if (key[name].filter) {\n filter = key[name].filter;\n }\n if (filter) {\n stateSlice = createStateSlice(stateSlice, filter);\n }\n // Check if encrypt and decrypt are present, also checked at this#rehydrateApplicationState()\n if (key[name].encrypt && key[name].decrypt) {\n if (typeof key[name].encrypt === 'function') {\n encrypt = key[name].encrypt;\n }\n }\n else if (key[name].encrypt || key[name].decrypt) {\n // If one of those is not present, then let know that one is missing\n console.error(`Either encrypt or decrypt function is not present on '${key[name]}' key object.`);\n }\n }\n /*\n Replacer and space arguments to pass to JSON.stringify.\n If these fields don't exist, undefined will be passed.\n */\n replacer = key[name].replacer;\n space = key[name].space;\n }\n key = name;\n }\n if (typeof stateSlice !== 'undefined' && storage !== undefined) {\n try {\n if (encrypt) {\n // ensure that a string message is passed\n stateSlice = encrypt(typeof stateSlice === 'string' ? stateSlice : JSON.stringify(stateSlice, replacer, space));\n }\n storage.setItem(storageKeySerializer(key), typeof stateSlice === 'string' ? stateSlice : JSON.stringify(stateSlice, replacer, space));\n }\n catch (e) {\n console.warn('Unable to save state to localStorage:', e);\n }\n }\n else if (typeof stateSlice === 'undefined' && removeOnUndefined && storage !== undefined) {\n try {\n storage.removeItem(storageKeySerializer(key));\n }\n catch (e) {\n console.warn(`Exception on removing/cleaning undefined '${key}' state`, e);\n }\n }\n });\n};\n// Default merge strategy is a full deep merge.\nconst defaultMergeReducer = (state, rehydratedState, action) => {\n if ((action.type === INIT_ACTION || action.type === UPDATE_ACTION) && rehydratedState) {\n const overwriteMerge = (destinationArray, sourceArray, options) => sourceArray;\n const options = {\n arrayMerge: overwriteMerge,\n };\n state = deepmerge(state, rehydratedState, options);\n }\n return state;\n};\nconst localStorageSync = (config) => (reducer) => {\n if ((config.storage === undefined && !config.checkStorageAvailability) ||\n (config.checkStorageAvailability && checkIsBrowserEnv())) {\n config.storage = localStorage || window.localStorage;\n }\n if (config.storageKeySerializer === undefined) {\n config.storageKeySerializer = (key) => key;\n }\n if (config.restoreDates === undefined) {\n config.restoreDates = true;\n }\n // Use default merge reducer.\n let mergeReducer = config.mergeReducer;\n if (mergeReducer === undefined || typeof mergeReducer !== 'function') {\n mergeReducer = defaultMergeReducer;\n }\n const stateKeys = validateStateKeys(config.keys);\n const rehydratedState = config.rehydrate\n ? rehydrateApplicationState(stateKeys, config.storage, config.storageKeySerializer, config.restoreDates)\n : undefined;\n return function (state, action) {\n let nextState;\n // If state arrives undefined, we need to let it through the supplied reducer\n // in order to get a complete state as defined by user\n if (action.type === INIT_ACTION && !state) {\n nextState = reducer(state, action);\n }\n else {\n nextState = { ...state };\n }\n // Merge the store state with the rehydrated state using\n // either a user-defined reducer or the default.\n nextState = mergeReducer(nextState, rehydratedState, action);\n nextState = reducer(nextState, action);\n if (action.type !== INIT_ACTION) {\n syncStateUpdate(nextState, stateKeys, config.storage, config.storageKeySerializer, config.removeOnUndefined, config.syncCondition);\n }\n return nextState;\n };\n};\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { dateReviver, defaultMergeReducer, localStorageSync, rehydrateApplicationState, syncStateUpdate };\n","import { CONTENTFUL_FEATURE_KEY } from '../contentful/contentful.reducer';\nimport { FAVOURITES_FEATURE_KEY } from '../favourites/favourites.reducer';\n\nexport const persistenceKeys = [\n { [CONTENTFUL_FEATURE_KEY]: ['nextSyncToken'] },\n FAVOURITES_FEATURE_KEY,\n];\n","import { ActionReducer, ActionReducerMap, MetaReducer } from '@ngrx/store';\nimport { LocalStorageConfig, localStorageSync } from 'ngrx-store-localstorage';\nimport { persistenceKeys } from './persistence-keys';\nimport {\n CONTENTFUL_FEATURE_KEY,\n contentfulReducer,\n} from '../contentful/contentful.reducer';\nimport {\n FAVOURITES_FEATURE_KEY,\n favouritesReducer,\n} from '../favourites/favourites.reducer';\n\n// eslint-disable-next-line @typescript-eslint/no-empty-interface\nexport interface State {}\n\nexport const reducers: ActionReducerMap = {\n [CONTENTFUL_FEATURE_KEY]: contentfulReducer,\n [FAVOURITES_FEATURE_KEY]: favouritesReducer,\n};\n\nconst LOCAL_STORAGE_SYNC_CONFIG: LocalStorageConfig = {\n keys: persistenceKeys,\n rehydrate: true,\n restoreDates: false,\n storageKeySerializer: (key: string) => `snowylive-${key}`,\n storage: localStorage,\n};\n\nconst localStorageSyncReducer = (\n reducer: ActionReducer\n): ActionReducer => {\n return localStorageSync(LOCAL_STORAGE_SYNC_CONFIG)(reducer);\n};\n\nexport const metaReducers: MetaReducer[] = [localStorageSyncReducer];\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 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 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 || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal\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 && 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 is NaN\n * {@link isNaN}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isNaN(wat) {\n return typeof wat === 'number' && wat !== 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, isNaN, isPlainObject, isPrimitive, isRegExp, isString, isSyntheticEvent, isThenable, isVueViewModel };\n","import { isString } from './is.js';\nimport { getGlobalObject } from './worldwide.js';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\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\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 let className;\n let classes;\n let key;\n let attr;\n let i;\n\n if (!elem || !elem.tagName) {\n return '';\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 =\n keyAttrs && keyAttrs.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs && 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 // eslint-disable-next-line prefer-const\n className = elem.className;\n if (className && isString(className)) {\n classes = className.split(/\\s+/);\n for (i = 0; i < classes.length; i++) {\n out.push(`.${classes[i]}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (i = 0; i < allowedAttrs.length; i++) {\n key = allowedAttrs[i];\n attr = elem.getAttribute(key);\n if (attr) {\n out.push(`[${key}=\"${attr}\"]`);\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 * Gets a DOM element by using document.querySelector.\n *\n * This wrapper will first check for the existance of the function before\n * actually calling it so that we don't have to take care of this check,\n * every time we want to access the DOM.\n *\n * Reason: DOM/querySelector is not available in all environments.\n *\n * We have to cast to any because utils can be consumed by a variety of environments,\n * and we don't want to break TS users. If you know what element will be selected by\n * `document.querySelector`, specify it as part of the generic call. For example,\n * `const element = getDomElement('selector');`\n *\n * @param selector the selector string passed on to document.querySelector\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getDomElement(selector) {\n if (WINDOW.document && WINDOW.document.querySelector) {\n return WINDOW.document.querySelector(selector) ;\n }\n return null;\n}\n\nexport { getDomElement, getLocationHref, htmlTreeAsString };\n","import { GLOBAL_OBJ } from './worldwide.js';\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\nconst CONSOLE_LEVELS = ['debug', 'info', 'warn', 'error', 'log', 'assert', 'trace'] ;\n\n/** This may be mutated by the console instrumentation. */\nconst originalConsoleMethods\n\n = {};\n\n/** JSDoc */\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nfunction consoleSandbox(callback) {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console ;\n const wrappedFuncs = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) ;\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\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 ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n CONSOLE_LEVELS.forEach(name => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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\nconst logger = makeLogger();\n\nexport { CONSOLE_LEVELS, consoleSandbox, logger, originalConsoleMethods };\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 */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\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","import { htmlTreeAsString } from './browser.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 source[name] = wrapped;\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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && 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 */\nfunction getOriginalFunction(func) {\n return func.__sentry_original__;\n}\n\n/**\n * Encodes given object into url-friendly format\n *\n * @param object An object that contains serializable values\n * @returns string Encoded\n */\nfunction urlEncode(object) {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join('&');\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 argurment 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 if (!keys.length) {\n return '[object has no keys]';\n }\n\n if (keys[0].length >= maxLength) {\n return truncate(keys[0], 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 (isPlainObject(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.keys(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\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 case wat === undefined || wat === null:\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, urlEncode };\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 && crypto.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n if (crypto && crypto.getRandomValues) {\n getRandomByte = () => crypto.getRandomValues(new Uint8Array(1))[0];\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 && event.exception.values ? event.exception.values[0] : undefined;\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 && 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\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], 10);\n const minor = parseInt(match[2], 10);\n const patch = parseInt(match[3], 10);\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 frame.context_line = snipLine(lines[Math.min(maxLines - 1, sourceLine)], 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 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (exception && (exception ).__sentry_captured__) {\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\n/**\n * Checks whether the given input is already an array, and if it isn't, wraps it in one.\n *\n * @param maybeArray Input to turn into an array, if necessary\n * @returns The input, if already an array, or an array with the input as the only element, if not\n */\nfunction arrayify(maybeArray) {\n return Array.isArray(maybeArray) ? maybeArray : [maybeArray];\n}\n\nexport { addContextToFrame, addExceptionMechanism, addExceptionTypeValue, arrayify, checkOrSetAlreadyCaught, getEventDescription, parseSemver, uuid4 };\n","const DEFAULT_ENVIRONMENT = 'production';\n\nexport { DEFAULT_ENVIRONMENT };\n","import { isThenable } from './is.js';\n\n/* eslint-disable @typescript-eslint/explicit-function-return-type */\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(\n executor,\n ) {SyncPromise.prototype.__init.call(this);SyncPromise.prototype.__init2.call(this);SyncPromise.prototype.__init3.call(this);SyncPromise.prototype.__init4.call(this);\n this._state = States.PENDING;\n this._handlers = [];\n\n try {\n executor(this._resolve, this._reject);\n } catch (e) {\n this._reject(e);\n }\n }\n\n /** JSDoc */\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 /** JSDoc */\n catch(\n onrejected,\n ) {\n return this.then(val => val, onrejected);\n }\n\n /** JSDoc */\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 /** JSDoc */\n __init() {this._resolve = (value) => {\n this._setResult(States.RESOLVED, value);\n };}\n\n /** JSDoc */\n __init2() {this._reject = (reason) => {\n this._setResult(States.REJECTED, reason);\n };}\n\n /** JSDoc */\n __init3() {this._setResult = (state, value) => {\n if (this._state !== States.PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value ).then(this._resolve, this._reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };}\n\n /** JSDoc */\n __init4() {this._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 // eslint-disable-next-line @typescript-eslint/no-floating-promises\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\nexport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise };\n","import { getGlobalSingleton, SyncPromise, logger, isThenable } from '@sentry/utils';\n\n/**\n * Returns the global event processors.\n */\nfunction getGlobalEventProcessors() {\n return getGlobalSingleton('globalEventProcessors', () => []);\n}\n\n/**\n * Add a EventProcessor to be kept globally.\n * @param callback EventProcessor to add\n */\nfunction addGlobalEventProcessor(callback) {\n getGlobalEventProcessors().push(callback);\n}\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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n processor.id &&\n result === null &&\n 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 { addGlobalEventProcessor, getGlobalEventProcessors, notifyEventProcessors };\n","import { timestampInSeconds, uuid4, dropUndefinedKeys } from '@sentry/utils';\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 BaseClient.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","import { isPlainObject, dateTimestampInSeconds, arrayify, uuid4 } from '@sentry/utils';\nimport { notifyEventProcessors, getGlobalEventProcessors } from './eventProcessors.js';\nimport { updateSession } from './session.js';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * Holds additional event information. {@link Scope.applyToEvent} will be\n * called by the client before an event will be sent.\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 after {@link applyToEvent}. */\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 // eslint-disable-next-line deprecation/deprecation\n\n /** Transaction Name */\n\n /** Span */\n\n /** Session */\n\n /** Request Mode Session Status */\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 = generatePropagationContext();\n }\n\n /**\n * Inherit values from the parent scope.\n * @param scope to clone.\n */\n static clone(scope) {\n const newScope = new Scope();\n if (scope) {\n newScope._breadcrumbs = [...scope._breadcrumbs];\n newScope._tags = { ...scope._tags };\n newScope._extra = { ...scope._extra };\n newScope._contexts = { ...scope._contexts };\n newScope._user = scope._user;\n newScope._level = scope._level;\n newScope._span = scope._span;\n newScope._session = scope._session;\n newScope._transactionName = scope._transactionName;\n newScope._fingerprint = scope._fingerprint;\n newScope._eventProcessors = [...scope._eventProcessors];\n newScope._requestSession = scope._requestSession;\n newScope._attachments = [...scope._attachments];\n newScope._sdkProcessingMetadata = { ...scope._sdkProcessingMetadata };\n newScope._propagationContext = { ...scope._propagationContext };\n }\n return newScope;\n }\n\n /**\n * Add internal on change listener. Used for sub SDKs that need to store the scope.\n * @hidden\n */\n addScopeListener(callback) {\n this._scopeListeners.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n addEventProcessor(callback) {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setUser(user) {\n this._user = user || {};\n if (this._session) {\n updateSession(this._session, { user });\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getUser() {\n return this._user;\n }\n\n /**\n * @inheritDoc\n */\n getRequestSession() {\n return this._requestSession;\n }\n\n /**\n * @inheritDoc\n */\n setRequestSession(requestSession) {\n this._requestSession = requestSession;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTags(tags) {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n this._tags = { ...this._tags, [key]: value };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setExtras(extras) {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setExtra(key, extra) {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setFingerprint(fingerprint) {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setLevel(\n // eslint-disable-next-line deprecation/deprecation\n level,\n ) {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setTransactionName(name) {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\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 * @inheritDoc\n */\n setSpan(span) {\n this._span = span;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getSpan() {\n return this._span;\n }\n\n /**\n * @inheritDoc\n */\n getTransaction() {\n // Often, this span (if it exists at all) will be a transaction, but it's not guaranteed to be. Regardless, it will\n // have a pointer to the currently-active transaction.\n const span = this.getSpan();\n return span && span.transaction;\n }\n\n /**\n * @inheritDoc\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 * @inheritDoc\n */\n getSession() {\n return this._session;\n }\n\n /**\n * @inheritDoc\n */\n update(captureContext) {\n if (!captureContext) {\n return this;\n }\n\n if (typeof captureContext === 'function') {\n const updatedScope = (captureContext )(this);\n return updatedScope instanceof Scope ? updatedScope : this;\n }\n\n if (captureContext instanceof Scope) {\n this._tags = { ...this._tags, ...captureContext._tags };\n this._extra = { ...this._extra, ...captureContext._extra };\n this._contexts = { ...this._contexts, ...captureContext._contexts };\n if (captureContext._user && Object.keys(captureContext._user).length) {\n this._user = captureContext._user;\n }\n if (captureContext._level) {\n this._level = captureContext._level;\n }\n if (captureContext._fingerprint) {\n this._fingerprint = captureContext._fingerprint;\n }\n if (captureContext._requestSession) {\n this._requestSession = captureContext._requestSession;\n }\n if (captureContext._propagationContext) {\n this._propagationContext = captureContext._propagationContext;\n }\n } else if (isPlainObject(captureContext)) {\n // eslint-disable-next-line no-param-reassign\n captureContext = captureContext ;\n this._tags = { ...this._tags, ...captureContext.tags };\n this._extra = { ...this._extra, ...captureContext.extra };\n this._contexts = { ...this._contexts, ...captureContext.contexts };\n if (captureContext.user) {\n this._user = captureContext.user;\n }\n if (captureContext.level) {\n this._level = captureContext.level;\n }\n if (captureContext.fingerprint) {\n this._fingerprint = captureContext.fingerprint;\n }\n if (captureContext.requestSession) {\n this._requestSession = captureContext.requestSession;\n }\n if (captureContext.propagationContext) {\n this._propagationContext = captureContext.propagationContext;\n }\n }\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n clear() {\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._requestSession = undefined;\n this._span = undefined;\n this._session = undefined;\n this._notifyScopeListeners();\n this._attachments = [];\n this._propagationContext = generatePropagationContext();\n return this;\n }\n\n /**\n * @inheritDoc\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 const breadcrumbs = this._breadcrumbs;\n breadcrumbs.push(mergedBreadcrumb);\n this._breadcrumbs = breadcrumbs.length > maxCrumbs ? breadcrumbs.slice(-maxCrumbs) : breadcrumbs;\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getLastBreadcrumb() {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n clearBreadcrumbs() {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * @inheritDoc\n */\n addAttachment(attachment) {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getAttachments() {\n return this._attachments;\n }\n\n /**\n * @inheritDoc\n */\n clearAttachments() {\n this._attachments = [];\n return this;\n }\n\n /**\n * Applies data from the scope to the event and runs all event processors on it.\n *\n * @param event Event\n * @param hint Object containing additional information about the original exception, for use by the event processors.\n * @hidden\n */\n applyToEvent(\n event,\n hint = {},\n additionalEventProcessors,\n ) {\n if (this._extra && Object.keys(this._extra).length) {\n event.extra = { ...this._extra, ...event.extra };\n }\n if (this._tags && Object.keys(this._tags).length) {\n event.tags = { ...this._tags, ...event.tags };\n }\n if (this._user && Object.keys(this._user).length) {\n event.user = { ...this._user, ...event.user };\n }\n if (this._contexts && Object.keys(this._contexts).length) {\n event.contexts = { ...this._contexts, ...event.contexts };\n }\n if (this._level) {\n event.level = this._level;\n }\n if (this._transactionName) {\n event.transaction = this._transactionName;\n }\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 (this._span) {\n event.contexts = { trace: this._span.getTraceContext(), ...event.contexts };\n const transaction = this._span.transaction;\n if (transaction) {\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: transaction.getDynamicSamplingContext(),\n ...event.sdkProcessingMetadata,\n };\n const transactionName = transaction.name;\n if (transactionName) {\n event.tags = { transaction: transactionName, ...event.tags };\n }\n }\n }\n\n this._applyFingerprint(event);\n\n const scopeBreadcrumbs = this._getBreadcrumbs();\n const breadcrumbs = [...(event.breadcrumbs || []), ...scopeBreadcrumbs];\n event.breadcrumbs = breadcrumbs.length > 0 ? breadcrumbs : undefined;\n\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...this._sdkProcessingMetadata,\n propagationContext: this._propagationContext,\n };\n\n // TODO (v8): Update this order to be: Global > Client > Scope\n return notifyEventProcessors(\n [...(additionalEventProcessors || []), ...getGlobalEventProcessors(), ...this._eventProcessors],\n event,\n hint,\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 = { ...this._sdkProcessingMetadata, ...newData };\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setPropagationContext(context) {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getPropagationContext() {\n return this._propagationContext;\n }\n\n /**\n * Get the breadcrumbs for this scope.\n */\n _getBreadcrumbs() {\n return this._breadcrumbs;\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 /**\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 */\n _applyFingerprint(event) {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint ? arrayify(event.fingerprint) : [];\n\n // If we have something on the scope, then merge it with event\n if (this._fingerprint) {\n event.fingerprint = event.fingerprint.concat(this._fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (event.fingerprint && !event.fingerprint.length) {\n delete event.fingerprint;\n }\n }\n}\n\nfunction generatePropagationContext() {\n return {\n traceId: uuid4(),\n spanId: uuid4().substring(16),\n };\n}\n\nexport { Scope };\n","import { uuid4, dateTimestampInSeconds, consoleSandbox, logger, GLOBAL_OBJ, getGlobalSingleton } from '@sentry/utils';\nimport { DEFAULT_ENVIRONMENT } from './constants.js';\nimport { Scope } from './scope.js';\nimport { closeSession, makeSession, updateSession } from './session.js';\n\n/**\n * API compatibility version of this hub.\n *\n * WARNING: This number should only be increased when the global interface\n * changes and new methods are introduced.\n *\n * @hidden\n */\nconst API_VERSION = 4;\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 * @inheritDoc\n */\nclass Hub {\n /** Is a {@link Layer}[] containing the client and scope */\n\n /** Contains the last event id of a captured event. */\n\n /**\n * Creates a new instance of the hub, will push one {@link Layer} into the\n * internal stack on creation.\n *\n * @param client bound to the hub.\n * @param scope bound to the hub.\n * @param version number, higher number means higher priority.\n */\n constructor(client, scope = new Scope(), _version = API_VERSION) {this._version = _version;\n this._stack = [{ scope }];\n if (client) {\n this.bindClient(client);\n }\n }\n\n /**\n * @inheritDoc\n */\n isOlderThan(version) {\n return this._version < version;\n }\n\n /**\n * @inheritDoc\n */\n bindClient(client) {\n const top = this.getStackTop();\n top.client = client;\n if (client && client.setupIntegrations) {\n client.setupIntegrations();\n }\n }\n\n /**\n * @inheritDoc\n */\n pushScope() {\n // We want to clone the content of prev scope\n const scope = Scope.clone(this.getScope());\n this.getStack().push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * @inheritDoc\n */\n popScope() {\n if (this.getStack().length <= 1) return false;\n return !!this.getStack().pop();\n }\n\n /**\n * @inheritDoc\n */\n withScope(callback) {\n const scope = this.pushScope();\n try {\n callback(scope);\n } finally {\n this.popScope();\n }\n }\n\n /**\n * @inheritDoc\n */\n getClient() {\n return this.getStackTop().client ;\n }\n\n /** Returns the scope of the top stack. */\n getScope() {\n return this.getStackTop().scope;\n }\n\n /** Returns the scope stack for domains or the process. */\n getStack() {\n return this._stack;\n }\n\n /** Returns the topmost scope layer in the order domain > local > process. */\n getStackTop() {\n return this._stack[this._stack.length - 1];\n }\n\n /**\n * @inheritDoc\n */\n captureException(exception, hint) {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error('Sentry syntheticException');\n this._withClient((client, scope) => {\n client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n level,\n hint,\n ) {\n const eventId = (this._lastEventId = hint && hint.event_id ? hint.event_id : uuid4());\n const syntheticException = new Error(message);\n this._withClient((client, scope) => {\n client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n scope,\n );\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint) {\n const eventId = hint && hint.event_id ? hint.event_id : uuid4();\n if (!event.type) {\n this._lastEventId = eventId;\n }\n\n this._withClient((client, scope) => {\n client.captureEvent(event, { ...hint, event_id: eventId }, scope);\n });\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n lastEventId() {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n addBreadcrumb(breadcrumb, hint) {\n const { scope, client } = this.getStackTop();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } =\n (client.getOptions && 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 scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n }\n\n /**\n * @inheritDoc\n */\n setUser(user) {\n this.getScope().setUser(user);\n }\n\n /**\n * @inheritDoc\n */\n setTags(tags) {\n this.getScope().setTags(tags);\n }\n\n /**\n * @inheritDoc\n */\n setExtras(extras) {\n this.getScope().setExtras(extras);\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n this.getScope().setTag(key, value);\n }\n\n /**\n * @inheritDoc\n */\n setExtra(key, extra) {\n this.getScope().setExtra(key, extra);\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setContext(name, context) {\n this.getScope().setContext(name, context);\n }\n\n /**\n * @inheritDoc\n */\n configureScope(callback) {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(scope);\n }\n }\n\n /**\n * @inheritDoc\n */\n run(callback) {\n const oldHub = makeMain(this);\n try {\n callback(this);\n } finally {\n makeMain(oldHub);\n }\n }\n\n /**\n * @inheritDoc\n */\n getIntegration(integration) {\n const client = this.getClient();\n if (!client) return null;\n try {\n return client.getIntegration(integration);\n } catch (_oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Cannot retrieve integration ${integration.id} from the current Hub`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n startTransaction(context, customSamplingContext) {\n const result = this._callExtensionMethod('startTransaction', context, customSamplingContext);\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && !result) {\n const client = this.getClient();\n if (!client) {\n // eslint-disable-next-line no-console\n console.warn(\n \"Tracing extension 'startTransaction' is missing. You should 'init' the SDK before calling 'startTransaction'\",\n );\n } else {\n // eslint-disable-next-line no-console\n console.warn(`Tracing extension 'startTransaction' has not been added. Call 'addTracingExtensions' before calling 'init':\nSentry.addTracingExtensions();\nSentry.init({...});\n`);\n }\n }\n\n return result;\n }\n\n /**\n * @inheritDoc\n */\n traceHeaders() {\n return this._callExtensionMethod('traceHeaders');\n }\n\n /**\n * @inheritDoc\n */\n captureSession(endSession = false) {\n // both send the update and pull the session from the scope\n if (endSession) {\n return this.endSession();\n }\n\n // only send the update\n this._sendSessionUpdate();\n }\n\n /**\n * @inheritDoc\n */\n endSession() {\n const layer = this.getStackTop();\n const scope = layer.scope;\n const session = scope.getSession();\n if (session) {\n closeSession(session);\n }\n this._sendSessionUpdate();\n\n // the session is over; take it off of the scope\n scope.setSession();\n }\n\n /**\n * @inheritDoc\n */\n startSession(context) {\n const { scope, client } = this.getStackTop();\n const { release, environment = DEFAULT_ENVIRONMENT } = (client && client.getOptions()) || {};\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n release,\n environment,\n user: scope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = scope.getSession && scope.getSession();\n if (currentSession && currentSession.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n this.endSession();\n\n // Afterwards we set the new session on the scope\n scope.setSession(session);\n\n return session;\n }\n\n /**\n * Returns if default PII should be sent to Sentry and propagated in ourgoing requests\n * when Tracing is used.\n */\n shouldSendDefaultPii() {\n const client = this.getClient();\n const options = client && client.getOptions();\n return Boolean(options && options.sendDefaultPii);\n }\n\n /**\n * Sends the current Session on the scope\n */\n _sendSessionUpdate() {\n const { scope, client } = this.getStackTop();\n\n const session = scope.getSession();\n if (session && client && client.captureSession) {\n client.captureSession(session);\n }\n }\n\n /**\n * Internal helper function to call a method on the top client if it exists.\n *\n * @param method The method to call on the client.\n * @param args Arguments to pass to the client function.\n */\n _withClient(callback) {\n const { scope, client } = this.getStackTop();\n if (client) {\n callback(client, scope);\n }\n }\n\n /**\n * Calls global extension method and binding current instance to the function call\n */\n // @ts-expect-error Function lacks ending return statement and return type does not include 'undefined'. ts(2366)\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n _callExtensionMethod(method, ...args) {\n const carrier = getMainCarrier();\n const sentry = carrier.__SENTRY__;\n if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') {\n return sentry.extensions[method].apply(this, args);\n }\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Extension method ${method} couldn't be found, doing nothing.`);\n }\n}\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nfunction getMainCarrier() {\n GLOBAL_OBJ.__SENTRY__ = GLOBAL_OBJ.__SENTRY__ || {\n extensions: {},\n hub: undefined,\n };\n return GLOBAL_OBJ;\n}\n\n/**\n * Replaces the current main hub with the passed one on the global object\n *\n * @returns The old replaced hub\n */\nfunction makeMain(hub) {\n const registry = getMainCarrier();\n const oldHub = getHubFromCarrier(registry);\n setHubOnCarrier(registry, hub);\n return oldHub;\n}\n\n/**\n * Returns the default hub instance.\n *\n * If a hub is already registered in the global carrier but this module\n * contains a more recent version, it replaces the registered version.\n * Otherwise, the currently registered hub will be returned.\n */\nfunction getCurrentHub() {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n const hub = registry.__SENTRY__.acs.getCurrentHub();\n\n if (hub) {\n return hub;\n }\n }\n\n // Return hub that lives on a global object\n return getGlobalHub(registry);\n}\n\nfunction getGlobalHub(registry = getMainCarrier()) {\n // If there's no hub, or its an old API, assign a new one\n if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(API_VERSION)) {\n setHubOnCarrier(registry, new Hub());\n }\n\n // Return hub that lives on a global object\n return getHubFromCarrier(registry);\n}\n\n/**\n * @private Private API with no semver guarantees!\n *\n * If the carrier does not contain a hub, a new hub is created with the global hub client and scope.\n */\nfunction ensureHubOnCarrier(carrier, parent = getGlobalHub()) {\n // If there's no hub on current domain, or it's an old API, assign a new one\n if (!hasHubOnCarrier(carrier) || getHubFromCarrier(carrier).isOlderThan(API_VERSION)) {\n const globalHubTopStack = parent.getStackTop();\n setHubOnCarrier(carrier, new Hub(globalHubTopStack.client, Scope.clone(globalHubTopStack.scope)));\n }\n}\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 registry.__SENTRY__ = registry.__SENTRY__ || {};\n registry.__SENTRY__.acs = strategy;\n}\n\n/**\n * Runs the supplied callback in its own async context. Async Context strategies are defined per SDK.\n *\n * @param callback The callback to run in its own async context\n * @param options Options to pass to the async context strategy\n * @returns The result of the callback\n */\nfunction runWithAsyncContext(callback, options = {}) {\n const registry = getMainCarrier();\n\n if (registry.__SENTRY__ && registry.__SENTRY__.acs) {\n return registry.__SENTRY__.acs.runWithAsyncContext(callback, options);\n }\n\n // if there was no strategy, fallback to just calling the callback\n return callback();\n}\n\n/**\n * This will tell whether a carrier has a hub on it or not\n * @param carrier object\n */\nfunction hasHubOnCarrier(carrier) {\n return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub);\n}\n\n/**\n * This will create a new {@link Hub} and add to the passed object on\n * __SENTRY__.hub.\n * @param carrier object\n * @hidden\n */\nfunction getHubFromCarrier(carrier) {\n return getGlobalSingleton('hub', () => new Hub(), carrier);\n}\n\n/**\n * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute\n * @param carrier object\n * @param hub Hub\n * @returns A boolean indicating success or failure\n */\nfunction setHubOnCarrier(carrier, hub) {\n if (!carrier) return false;\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n __SENTRY__.hub = hub;\n return true;\n}\n\nexport { API_VERSION, Hub, ensureHubOnCarrier, getCurrentHub, getHubFromCarrier, getMainCarrier, makeMain, runWithAsyncContext, setAsyncContextStrategy, setHubOnCarrier };\n","import { logger, uuid4, timestampInSeconds, isThenable } from '@sentry/utils';\nimport { getCurrentHub } from './hub.js';\n\n// Note: All functions in this file are typed with a return value of `ReturnType`,\n// where HUB_FUNCTION is some method on the Hub class.\n//\n// This is done to make sure the top level SDK methods stay in sync with the hub methods.\n// Although every method here has an explicit return type, some of them (that map to void returns) do not\n// contain `return` keywords. This is done to save on bundle size, as `return` is not minifiable.\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception An exception-like object.\n * @param captureContext Additional scope data to apply to exception event.\n * @returns The generated eventId.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\nfunction captureException(exception, captureContext) {\n return getCurrentHub().captureException(exception, { captureContext });\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 Severity Define the level of the message.\n * @returns The generated eventId.\n */\nfunction captureMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n captureContext,\n) {\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 getCurrentHub().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 * @returns The generated eventId.\n */\nfunction captureEvent(event, hint) {\n return getCurrentHub().captureEvent(event, hint);\n}\n\n/**\n * Callback to set context information onto the scope.\n * @param callback Callback function that receives Scope.\n */\nfunction configureScope(callback) {\n getCurrentHub().configureScope(callback);\n}\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 *\n * @param breadcrumb The breadcrumb to record.\n */\nfunction addBreadcrumb(breadcrumb) {\n getCurrentHub().addBreadcrumb(breadcrumb);\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 */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction setContext(name, context) {\n getCurrentHub().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 getCurrentHub().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 getCurrentHub().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 getCurrentHub().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 getCurrentHub().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 getCurrentHub().setUser(user);\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 * This is essentially a convenience function for:\n *\n * pushScope();\n * callback();\n * popScope();\n *\n * @param callback that will be enclosed into push/popScope.\n */\nfunction withScope(callback) {\n getCurrentHub().withScope(callback);\n}\n\n/**\n * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation.\n *\n * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a\n * new child span within the transaction or any span, call the respective `.startChild()` method.\n *\n * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded.\n *\n * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its\n * finished child spans will be sent to Sentry.\n *\n * NOTE: This function should only be used for *manual* instrumentation. Auto-instrumentation should call\n * `startTransaction` directly on the hub.\n *\n * @param context Properties of the new `Transaction`.\n * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent\n * default values). See {@link Options.tracesSampler}.\n *\n * @returns The transaction which was just started\n */\nfunction startTransaction(\n context,\n customSamplingContext,\n) {\n return getCurrentHub().startTransaction({ ...context }, customSamplingContext);\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 hub = getCurrentHub();\n const scope = hub.getScope();\n const client = hub.getClient();\n if (!client) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && 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 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 () => {\n finishCheckIn('error');\n },\n );\n } else {\n finishCheckIn('ok');\n }\n\n return maybePromiseResult;\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 = getCurrentHub().getClient();\n if (client) {\n return client.flush(timeout);\n }\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && 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 = getCurrentHub().getClient();\n if (client) {\n return client.close(timeout);\n }\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * This is the getter for lastEventId.\n *\n * @returns The last event id of a captured event.\n */\nfunction lastEventId() {\n return getCurrentHub().lastEventId();\n}\n\nexport { addBreadcrumb, captureCheckIn, captureEvent, captureException, captureMessage, close, configureScope, flush, lastEventId, setContext, setExtra, setExtras, setTag, setTags, setUser, startTransaction, withMonitor, withScope };\n","import { logger, getEventDescription, stringMatchesSomePattern } from '@sentry/utils';\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 = [/^Script error\\.?$/, /^Javascript error: Script error\\.? on line 0$/];\n\nconst DEFAULT_IGNORE_TRANSACTIONS = [\n /^.*\\/healthcheck$/,\n /^.*\\/healthy$/,\n /^.*\\/live$/,\n /^.*\\/ready$/,\n /^.*\\/heartbeat$/,\n /^.*\\/health$/,\n /^.*\\/healthz$/,\n];\n\n/** Options for the InboundFilters integration */\n\n/** Inbound filters configurable by the user */\nclass InboundFilters {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'InboundFilters';}\n\n /**\n * @inheritDoc\n */\n\n constructor(options = {}) {\n this.name = InboundFilters.id;\n this._options = options;\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(_addGlobaleventProcessor, _getCurrentHub) {\n // noop\n }\n\n /** @inheritDoc */\n processEvent(event, _eventHint, client) {\n const clientOptions = client.getOptions();\n const options = _mergeOptions(this._options, clientOptions);\n return _shouldDropEvent(event, options) ? null : event;\n }\n} InboundFilters.__initStatic();\n\n/** JSDoc */\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: [\n ...(internalOptions.ignoreTransactions || []),\n ...(clientOptions.ignoreTransactions || []),\n ...(internalOptions.disableTransactionDefaults ? [] : DEFAULT_IGNORE_TRANSACTIONS),\n ],\n ignoreInternal: internalOptions.ignoreInternal !== undefined ? internalOptions.ignoreInternal : true,\n };\n}\n\n/** JSDoc */\nfunction _shouldDropEvent(event, options) {\n if (options.ignoreInternal && _isSentryError(event)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\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 // TODO: Use Glob instead?\n if (!denyUrls || !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 // TODO: Use Glob instead?\n if (!allowUrls || !allowUrls.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getPossibleEventMessages(event) {\n const possibleMessages = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n let lastException;\n try {\n // @ts-expect-error Try catching to save bundle size\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n lastException = event.exception.values[event.exception.values.length - 1];\n } catch (e) {\n // try catching to save bundle size checking existence of variables\n }\n\n if (lastException) {\n if (lastException.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n }\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && possibleMessages.length === 0) {\n logger.error(`Could not extract message for event ${getEventDescription(event)}`);\n }\n\n return possibleMessages;\n}\n\nfunction _isSentryError(event) {\n try {\n // @ts-expect-error can't be a sentry error if undefined\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n\nexport { InboundFilters, _mergeOptions, _shouldDropEvent };\n","import { getOriginalFunction } from '@sentry/utils';\n\nlet originalFunctionToString;\n\n/** Patch toString calls to return proper name for wrapped functions */\nclass FunctionToString {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'FunctionToString';}\n\n /**\n * @inheritDoc\n */\n\n constructor() {\n this.name = FunctionToString.id;\n }\n\n /**\n * @inheritDoc\n */\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Function.prototype.toString = function ( ...args) {\n const context = getOriginalFunction(this) || this;\n return originalFunctionToString.apply(context, args);\n };\n } catch (e) {\n // ignore errors here, just don't patch this\n }\n }\n} FunctionToString.__initStatic();\n\nexport { FunctionToString };\n","import { arrayify, logger } from '@sentry/utils';\nimport { addGlobalEventProcessor } from './eventProcessors.js';\nimport { getCurrentHub } from './hub.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 * preseve 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.keys(integrationsByName).map(k => integrationsByName[k]);\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 integrations = arrayify(userIntegrations(defaultIntegrations));\n } else {\n integrations = defaultIntegrations;\n }\n\n const finalIntegrations = filterDuplicates(integrations);\n\n // The `Debug` integration prints copies of the `event` and `hint` which will be passed to `beforeSend` or\n // `beforeSendTransaction`. It therefore has to run after all other integrations, so that the changes of all event\n // processors will be reflected in the printed values. For lack of a more elegant way to guarantee that, we therefore\n // locate it and, assuming it exists, pop it out of its current spot and shove it onto the end of the array.\n const debugIndex = findIndex(finalIntegrations, integration => integration.name === 'Debug');\n if (debugIndex !== -1) {\n const [debugInstance] = finalIntegrations.splice(debugIndex, 1);\n finalIntegrations.push(debugInstance);\n }\n\n return finalIntegrations;\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/** Setup a single integration. */\nfunction setupIntegration(client, integration, integrationIndex) {\n integrationIndex[integration.name] = integration;\n\n if (installedIntegrations.indexOf(integration.name) === -1) {\n integration.setupOnce(addGlobalEventProcessor, getCurrentHub);\n installedIntegrations.push(integration.name);\n }\n\n if (client.on && 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 (client.addEventProcessor && 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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current hub's client. */\nfunction addIntegration(integration) {\n const client = getCurrentHub().getClient();\n\n if (!client || !client.addIntegration) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n// Polyfill for Array.findIndex(), which is not supported in ES5\nfunction findIndex(arr, callback) {\n for (let i = 0; i < arr.length; i++) {\n if (callback(arr[i]) === true) {\n return i;\n }\n }\n\n return -1;\n}\n\nexport { addIntegration, getIntegrationsToSetup, installedIntegrations, setupIntegration, setupIntegrations };\n","import { 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 // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\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 (!(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\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","import { makeDsn, dsnToString, urlEncode } from '@sentry/utils';\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 return urlEncode({\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n sentry_key: dsn.publicKey,\n sentry_version: SENTRY_API_VERSION,\n ...(sdkInfo && { sentry_client: `${sdkInfo.name}/${sdkInfo.version}` }),\n });\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(\n dsn,\n // TODO (v8): Remove `tunnelOrOptions` in favor of `options`, and use the substitute code below\n // options: ClientOptions = {} as ClientOptions,\n tunnelOrOptions = {} ,\n) {\n // TODO (v8): Use this code instead\n // const { tunnel, _metadata = {} } = options;\n // return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, _metadata.sdk)}`;\n\n const tunnel = typeof tunnelOrOptions === 'string' ? tunnelOrOptions : tunnelOrOptions.tunnel;\n const sdkInfo =\n typeof tunnelOrOptions === 'string' || !tunnelOrOptions._metadata ? undefined : tunnelOrOptions._metadata.sdk;\n\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nfunction getReportDialogEndpoint(\n dsnLike,\n dialogOptions\n\n,\n) {\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 === '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","import { node } from './node-stack-trace.js';\nexport { filenameIsInApp } from './node-stack-trace.js';\n\nconst STACKTRACE_FRAME_LIMIT = 50;\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, skipFirst = 0) => {\n const frames = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirst; 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) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames);\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(localStack[localStack.length - 1].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(localStack[localStack.length - 1].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 hub itself, making it:\n //\n // Sentry.captureException()\n // getCurrentHub().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(localStack[localStack.length - 1].function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || localStack[localStack.length - 1].filename,\n function: frame.function || '?',\n }));\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 * Node.js stack line parser\n *\n * This is in @sentry/utils so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nfunction nodeStackLineParser(getModule) {\n return [90, node(getModule)];\n}\n\nexport { createStackParser, getFunctionName, nodeStackLineParser, stackParserFromStackParserOptions, stripSentryFramesAndReverse };\n","import { logger } from './logger.js';\nimport { getGlobalObject } from './worldwide.js';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\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 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 * isNativeFetch checks if the given function is a native implementation of fetch()\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isNativeFetch(func) {\n return func && /^function fetch\\(\\)\\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 (isNativeFetch(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 && sandbox.contentWindow.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFetch(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\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 { isNativeFetch, supportsDOMError, supportsDOMException, supportsErrorEvent, supportsFetch, supportsNativeFetch, supportsReferrerPolicy, supportsReportingObserver };\n","import { getGlobalObject } from '../worldwide.js';\n\n// Based on https://github.com/angular/angular.js/pull/13945/files\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\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 // NOTE: in Chrome App environment, touching history.pushState, *even inside\n // a try/catch block*, will cause Chrome to output an error to console.error\n // borrowed from: https://github.com/angular/angular.js/pull/13945/files\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const chrome = (WINDOW ).chrome;\n const isChromePackagedApp = chrome && chrome.app && chrome.app.runtime;\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n const hasHistoryApi = 'history' in WINDOW && !!WINDOW.history.pushState && !!WINDOW.history.replaceState;\n\n return !isChromePackagedApp && hasHistoryApi;\n}\n\nexport { supportsHistory };\n","import { isString } from './is.js';\nimport { logger, CONSOLE_LEVELS, originalConsoleMethods } from './logger.js';\nimport { uuid4 } from './misc.js';\nimport { fill, addNonEnumerableProperty } from './object.js';\nimport { getFunctionName } from './stacktrace.js';\nimport { supportsNativeFetch } from './supports.js';\nimport { getGlobalObject, GLOBAL_OBJ } from './worldwide.js';\nimport { supportsHistory } from './vendor/supportsHistory.js';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\nconst SENTRY_XHR_DATA_KEY = '__sentry_xhr_v2__';\n\n/**\n * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc.\n * - Console API\n * - Fetch API\n * - XHR API\n * - History API\n * - DOM API (click/typing)\n * - Error API\n * - UnhandledRejection API\n */\n\nconst handlers = {};\nconst instrumented = {};\n\n/** Instruments given API */\nfunction instrument(type) {\n if (instrumented[type]) {\n return;\n }\n\n instrumented[type] = true;\n\n switch (type) {\n case 'console':\n instrumentConsole();\n break;\n case 'dom':\n instrumentDOM();\n break;\n case 'xhr':\n instrumentXHR();\n break;\n case 'fetch':\n instrumentFetch();\n break;\n case 'history':\n instrumentHistory();\n break;\n case 'error':\n instrumentError();\n break;\n case 'unhandledrejection':\n instrumentUnhandledRejection();\n break;\n default:\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('unknown instrumentation type:', type);\n return;\n }\n}\n\n/**\n * Add handler that will be called when given type of instrumentation triggers.\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addInstrumentationHandler(type, callback) {\n handlers[type] = handlers[type] || [];\n (handlers[type] ).push(callback);\n instrument(type);\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/** JSDoc */\nfunction triggerHandlers(type, data) {\n if (!type || !handlers[type]) {\n return;\n }\n\n for (const handler of handlers[type] || []) {\n try {\n handler(data);\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\n/** JSDoc */\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 triggerHandlers('console', { args, level });\n\n const log = originalConsoleMethods[level];\n log && log.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n\n/** JSDoc */\nfunction instrumentFetch() {\n if (!supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch) {\n return function (...args) {\n const { method, url } = parseFetchArgs(args);\n\n const handlerData = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: Date.now(),\n };\n\n triggerHandlers('fetch', {\n ...handlerData,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n (response) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n response,\n });\n return response;\n },\n (error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: Date.now(),\n error,\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\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 */\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\n/** JSDoc */\nfunction instrumentXHR() {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (!(WINDOW ).XMLHttpRequest) {\n return;\n }\n\n const xhrproto = XMLHttpRequest.prototype;\n\n fill(xhrproto, 'open', function (originalOpen) {\n return function ( ...args) {\n const startTimestamp = Date.now();\n\n const url = args[1];\n const xhrInfo = (this[SENTRY_XHR_DATA_KEY] = {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n method: isString(args[0]) ? args[0].toUpperCase() : args[0],\n url: args[1],\n request_headers: {},\n });\n\n // if Sentry key appears in URL, don't capture it as a request\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n if (isString(url) && xhrInfo.method === 'POST' && url.match(/sentry_key/)) {\n this.__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 = this[SENTRY_XHR_DATA_KEY];\n\n if (!xhrInfo) {\n return;\n }\n\n if (this.readyState === 4) {\n try {\n // touching statusCode in some platforms throws\n // an exception\n xhrInfo.status_code = this.status;\n } catch (e) {\n /* do nothing */\n }\n\n triggerHandlers('xhr', {\n args: args ,\n endTimestamp: Date.now(),\n startTimestamp,\n xhr: this,\n } );\n }\n };\n\n if ('onreadystatechange' in this && typeof this.onreadystatechange === 'function') {\n fill(this, 'onreadystatechange', function (original) {\n return function ( ...readyStateArgs) {\n onreadystatechangeHandler();\n return original.apply(this, readyStateArgs);\n };\n });\n } else {\n this.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 fill(this, 'setRequestHeader', function (original) {\n return function ( ...setRequestHeaderArgs) {\n const [header, value] = setRequestHeaderArgs ;\n\n const xhrInfo = this[SENTRY_XHR_DATA_KEY];\n\n if (xhrInfo) {\n xhrInfo.request_headers[header.toLowerCase()] = value;\n }\n\n return original.apply(this, setRequestHeaderArgs);\n };\n });\n\n return originalOpen.apply(this, args);\n };\n });\n\n fill(xhrproto, 'send', function (originalSend) {\n return function ( ...args) {\n const sentryXhrData = this[SENTRY_XHR_DATA_KEY];\n if (sentryXhrData && args[0] !== undefined) {\n sentryXhrData.body = args[0];\n }\n\n triggerHandlers('xhr', {\n args,\n startTimestamp: Date.now(),\n xhr: this,\n });\n\n return originalSend.apply(this, args);\n };\n });\n}\n\nlet lastHref;\n\n/** JSDoc */\nfunction instrumentHistory() {\n if (!supportsHistory()) {\n return;\n }\n\n const oldOnPopState = WINDOW.onpopstate;\n WINDOW.onpopstate = function ( ...args) {\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 triggerHandlers('history', {\n from,\n to,\n });\n if (oldOnPopState) {\n // Apparently this can throw in Firefox when incorrectly implemented plugin is installed.\n // https://github.com/getsentry/sentry-javascript/issues/3344\n // https://github.com/bugsnag/bugsnag-js/issues/469\n try {\n return oldOnPopState.apply(this, args);\n } catch (_oO) {\n // no-empty\n }\n }\n };\n\n /** @hidden */\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 triggerHandlers('history', {\n from,\n to,\n });\n }\n return originalHistoryFunction.apply(this, args);\n };\n }\n\n fill(WINDOW.history, 'pushState', historyReplacementFunction);\n fill(WINDOW.history, 'replaceState', historyReplacementFunction);\n}\n\nconst DEBOUNCE_DURATION = 1000;\nlet debounceTimerID;\nlet lastCapturedEventType;\nlet lastCapturedEventTargetId;\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 || !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\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\n/**\n * Wraps addEventListener to capture UI breadcrumbs\n * @param handler function that will be triggered\n * @param globalListener indicates whether event was captured by the global event listener\n * @returns wrapped breadcrumb events handler\n * @hidden\n */\nfunction makeDOMEventHandler(handler, globalListener = false) {\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 handler({\n event: event,\n name,\n global: globalListener,\n });\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\n/** JSDoc */\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 // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = (WINDOW )[target] && (WINDOW )[target].prototype;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (originalAddEventListener) {\n return function (\n\n type,\n listener,\n options,\n ) {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this ;\n const handlers = (el.__sentry_instrumentation_handlers__ = el.__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 `addEventListenrs` 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 (\n\n type,\n listener,\n options,\n ) {\n if (type === 'click' || type == 'keypress') {\n try {\n const el = this ;\n const handlers = el.__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 el.__sentry_instrumentation_handlers__;\n }\n }\n } catch (e) {\n // Accessing dom properties is always fragile.\n // Also allows us to skip `addEventListenrs` calls with no proper `this` context.\n }\n }\n\n return originalRemoveEventListener.call(this, type, listener, options);\n };\n },\n );\n });\n}\n\nlet _oldOnErrorHandler = null;\n/** JSDoc */\nfunction instrumentError() {\n _oldOnErrorHandler = WINDOW.onerror;\n\n WINDOW.onerror = function (msg, url, line, column, error) {\n triggerHandlers('error', {\n column,\n error,\n line,\n msg,\n url,\n });\n\n if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n WINDOW.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n\nlet _oldOnUnhandledRejectionHandler = null;\n/** JSDoc */\nfunction instrumentUnhandledRejection() {\n _oldOnUnhandledRejectionHandler = WINDOW.onunhandledrejection;\n\n WINDOW.onunhandledrejection = function (e) {\n triggerHandlers('unhandledrejection', e);\n\n if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n WINDOW.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n\nexport { SENTRY_XHR_DATA_KEY, addInstrumentationHandler, instrumentDOM, instrumentXHR, parseFetchArgs, resetInstrumentationHandlers };\n","import { isNaN, isVueViewModel, isSyntheticEvent } from './is.js';\nimport { memoBuilder } from './memo.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 normallized 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 (['number', 'boolean', 'string'].includes(typeof value) && !isNaN(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' && value !== value) {\n return '[NaN]';\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\nexport { normalize, normalizeToSize, visit as walk };\n","/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Helper to decycle json objects\n */\nfunction memoBuilder() {\n const hasWeakSet = typeof WeakSet === 'function';\n const inner = hasWeakSet ? new WeakSet() : [];\n function memoize(obj) {\n if (hasWeakSet) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < inner.length; i++) {\n const value = inner[i];\n if (value === obj) {\n return true;\n }\n }\n inner.push(obj);\n return false;\n }\n\n function unmemoize(obj) {\n if (hasWeakSet) {\n inner.delete(obj);\n } else {\n for (let i = 0; i < inner.length; i++) {\n if (inner[i] === obj) {\n inner.splice(i, 1);\n break;\n }\n }\n }\n }\n return [memoize, unmemoize];\n}\n\nexport { memoBuilder };\n","import { dsnToString } from './dsn.js';\nimport { normalize } from './normalize.js';\nimport { dropUndefinedKeys } from './object.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.\n */\nfunction encodeUTF8(input, textEncoder) {\n const utf8 = textEncoder || new TextEncoder();\n return utf8.encode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nfunction serializeEnvelope(envelope, textEncoder) {\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, textEncoder), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next, textEncoder) : 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.strinify()` 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(\n env,\n textEncoder,\n textDecoder,\n) {\n let buffer = typeof env === 'string' ? textEncoder.encode(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(textDecoder.decode(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 attachment envelope items\n */\nfunction createAttachmentEnvelopeItem(\n attachment,\n textEncoder,\n) {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data, textEncoder) : 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 replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n // TODO: This is a temporary workaround until we have a proper data category for metrics\n statsd: 'unknown',\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 from the metadata or an events */\nfunction getSdkMetadataForEnvelopeHeader(metadataOrEvent) {\n if (!metadataOrEvent || !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 && 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, envelopeContainsItemType, envelopeItemTypeToDataCategory, forEachEnvelopeItem, getSdkMetadataForEnvelopeHeader, parseEnvelope, serializeEnvelope };\n","/** An error emitted by Sentry SDKs and related utilities. */\nclass SentryError extends Error {\n /** Display name of this error instance. */\n\n constructor( message, logLevel = 'warn') {\n super(message);this.message = message;\n this.name = new.target.prototype.constructor.name;\n // This sets the prototype to be `Error`, not `SentryError`. It's unclear why we do this, but commenting this line\n // out causes various (seemingly totally unrelated) playwright tests consistently time out. FYI, this makes\n // instances of `SentryError` fail `obj instanceof SentryError` checks.\n Object.setPrototypeOf(this, new.target.prototype);\n this.logLevel = logLevel;\n }\n}\n\nexport { SentryError };\n","import { dropUndefinedKeys } from '@sentry/utils';\nimport { DEFAULT_ENVIRONMENT } from '../constants.js';\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatchs the `createDsc` lifecycle hook as a side effect.\n */\nfunction getDynamicSamplingContextFromClient(\n trace_id,\n client,\n scope,\n) {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n const { segment: user_segment } = (scope && scope.getUser()) || {};\n\n const dsc = dropUndefinedKeys({\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n user_segment,\n public_key,\n trace_id,\n }) ;\n\n client.emit && client.emit('createDsc', dsc);\n\n return dsc;\n}\n\nexport { getDynamicSamplingContextFromClient };\n","import { uuid4, dateTimestampInSeconds, resolvedSyncPromise, truncate, GLOBAL_OBJ, normalize } from '@sentry/utils';\nimport { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { notifyEventProcessors, getGlobalEventProcessors } from '../eventProcessors.js';\nimport { Scope } from '../scope.js';\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 * Note: This also triggers callbacks for `addGlobalEventProcessor`, but not `beforeSend`.\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) {\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 // 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 let finalScope = scope;\n if (hint.captureContext) {\n finalScope = Scope.clone(finalScope).update(hint.captureContext);\n }\n\n // We prepare the result here with a resolved Event.\n let result = resolvedSyncPromise(prepared);\n\n const clientEventProcessors = client && client.getEventProcessors ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Hub.addEventProcessor} gets the finished prepared event.\n //\n // We need to check for the existence of `finalScope.getAttachments`\n // because `getAttachments` can be undefined if users are using an older version\n // of `@sentry/core` that does not have the `getAttachments` method.\n // See: https://github.com/getsentry/sentry-javascript/issues/5229\n if (finalScope) {\n // Collect attachments from the hint and scope\n if (finalScope.getAttachments) {\n const attachments = [...(hint.attachments || []), ...finalScope.getAttachments()];\n\n if (attachments.length) {\n hint.attachments = attachments;\n }\n }\n\n // In case we have a hub we reassign it.\n result = finalScope.applyToEvent(prepared, hint, clientEventProcessors);\n } else {\n // Apply client & global event processors even if there is no scope\n // TODO (v8): Update the order to be Global > Client\n result = notifyEventProcessors([...clientEventProcessors, ...getGlobalEventProcessors()], prepared, hint);\n }\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 * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event, options) {\n const { environment, release, dist, maxValueLength = 250 } = options;\n\n if (!('environment' in event)) {\n event.environment = 'environment' in options ? environment : DEFAULT_ENVIRONMENT;\n }\n\n if (event.release === undefined && release !== undefined) {\n event.release = release;\n }\n\n if (event.dist === undefined && dist !== undefined) {\n event.dist = dist;\n }\n\n if (event.message) {\n event.message = truncate(event.message, maxValueLength);\n }\n\n const exception = event.exception && event.exception.values && event.exception.values[0];\n if (exception && exception.value) {\n exception.value = truncate(exception.value, maxValueLength);\n }\n\n const request = event.request;\n if (request && request.url) {\n request.url = truncate(request.url, maxValueLength);\n }\n}\n\nconst debugIdStackParserCache = new WeakMap();\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nfunction applyDebugIds(event, stackParser) {\n const debugIdMap = GLOBAL_OBJ._sentryDebugIds;\n\n if (!debugIdMap) {\n return;\n }\n\n let debugIdStackFramesCache;\n const cachedDebugIdStackFrameCache = debugIdStackParserCache.get(stackParser);\n if (cachedDebugIdStackFrameCache) {\n debugIdStackFramesCache = cachedDebugIdStackFrameCache;\n } else {\n debugIdStackFramesCache = new Map();\n debugIdStackParserCache.set(stackParser, debugIdStackFramesCache);\n }\n\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = Object.keys(debugIdMap).reduce((acc, debugIdStackTrace) => {\n let parsedStack;\n const cachedParsedStack = debugIdStackFramesCache.get(debugIdStackTrace);\n if (cachedParsedStack) {\n parsedStack = cachedParsedStack;\n } else {\n parsedStack = stackParser(debugIdStackTrace);\n debugIdStackFramesCache.set(debugIdStackTrace, parsedStack);\n }\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n if (stackFrame.filename) {\n acc[stackFrame.filename] = debugIdMap[debugIdStackTrace];\n break;\n }\n }\n return acc;\n }, {});\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception.values.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n exception.stacktrace.frames.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\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 try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n event.exception.values.forEach(exception => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\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 } catch (e) {\n // To save bundle size we're just try catching here instead of checking for the existence of all the different objects.\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.keys(filenameDebugIdMap).forEach(filename => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id: filenameDebugIdMap[filename],\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 && 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 // We cannot use the spread operator here because `toJSON` on `span` is non-enumerable\n if (span.data) {\n span.data = normalize(span.data, depth, maxBreadth);\n }\n return span;\n });\n }\n\n return normalized;\n}\n\nexport { applyDebugIds, applyDebugMeta, prepareEvent };\n","import { makeDsn, logger, checkOrSetAlreadyCaught, isPrimitive, resolvedSyncPromise, addItemToEnvelope, createAttachmentEnvelopeItem, SyncPromise, rejectedSyncPromise, SentryError, isThenable, isPlainObject } from '@sentry/utils';\nimport { getEnvelopeEndpointWithUrlEncodedAuth } from './api.js';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope.js';\nimport { setupIntegrations, setupIntegration } from './integration.js';\nimport { updateSession } from './session.js';\nimport { getDynamicSamplingContextFromClient } from './tracing/dynamicSamplingContext.js';\nimport { prepareEvent } from './utils/prepareEvent.js';\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\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 BaseClient._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 BaseClient {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nclass BaseClient {\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 /** Indicates whether this client's integrations have been set up. */\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._integrationsInitialized = false;\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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(this._dsn, options);\n this._transport = options.transport({\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n captureException(exception, hint, scope) {\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId = hint && hint.event_id;\n\n this._process(\n this.eventFromException(exception, hint)\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureMessage(\n message,\n // eslint-disable-next-line deprecation/deprecation\n level,\n hint,\n scope,\n ) {\n let eventId = hint && hint.event_id;\n\n const promisedEvent = isPrimitive(message)\n ? this.eventFromMessage(String(message), level, hint)\n : this.eventFromException(message, hint);\n\n this._process(\n promisedEvent\n .then(event => this._captureEvent(event, hint, scope))\n .then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint, scope) {\n // ensure we haven't captured this very object before\n if (hint && hint.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(ALREADY_SEEN_ERROR);\n return;\n }\n\n let eventId = hint && hint.event_id;\n\n this._process(\n this._captureEvent(event, hint, scope).then(result => {\n eventId = result;\n }),\n );\n\n return eventId;\n }\n\n /**\n * @inheritDoc\n */\n captureSession(session) {\n if (!(typeof session.release === 'string')) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Discarded session because of missing or non-string release');\n } else {\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 /**\n * @inheritDoc\n */\n getDsn() {\n return this._dsn;\n }\n\n /**\n * @inheritDoc\n */\n getOptions() {\n return this._options;\n }\n\n /**\n * @see SdkMetadata in @sentry/types\n *\n * @return The metadata of the SDK\n */\n getSdkMetadata() {\n return this._options._metadata;\n }\n\n /**\n * @inheritDoc\n */\n getTransport() {\n return this._transport;\n }\n\n /**\n * @inheritDoc\n */\n flush(timeout) {\n const transport = this._transport;\n if (transport) {\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 * @inheritDoc\n */\n close(timeout) {\n return this.flush(timeout).then(result => {\n this.getOptions().enabled = false;\n return result;\n });\n }\n\n /** Get all installed event processors. */\n getEventProcessors() {\n return this._eventProcessors;\n }\n\n /** @inheritDoc */\n addEventProcessor(eventProcessor) {\n this._eventProcessors.push(eventProcessor);\n }\n\n /**\n * Sets up the integrations\n */\n setupIntegrations(forceInitialize) {\n if ((forceInitialize && !this._integrationsInitialized) || (this._isEnabled() && !this._integrationsInitialized)) {\n this._integrations = setupIntegrations(this, this._options.integrations);\n this._integrationsInitialized = true;\n }\n }\n\n /**\n * Gets an installed integration by its `id`.\n *\n * @returns The installed integration or `undefined` if no integration with that `id` was installed.\n */\n getIntegrationById(integrationId) {\n return this._integrations[integrationId];\n }\n\n /**\n * @inheritDoc\n */\n getIntegration(integration) {\n try {\n return (this._integrations[integration.id] ) || null;\n } catch (_oO) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`Cannot retrieve integration ${integration.id} from the current Client`);\n return null;\n }\n }\n\n /**\n * @inheritDoc\n */\n addIntegration(integration) {\n setupIntegration(this, integration, this._integrations);\n }\n\n /**\n * @inheritDoc\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(\n env,\n createAttachmentEnvelopeItem(\n attachment,\n this._options.transportOptions && this._options.transportOptions.textEncoder,\n ),\n );\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 * @inheritDoc\n */\n sendSession(session) {\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n void this._sendEnvelope(env);\n }\n\n /**\n * @inheritDoc\n */\n recordDroppedEvent(reason, category, _event) {\n // Note: we use `event` in replay, where we overwrite this hook.\n\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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Adding outcome: \"${key}\"`);\n\n // The following works because undefined + 1 === NaN and NaN is falsy\n this._outcomes[key] = this._outcomes[key] + 1 || 1;\n }\n }\n\n // Keep on() & emit() signatures in sync with types' client.ts interface\n /* eslint-disable @typescript-eslint/unified-signatures */\n\n /** @inheritdoc */\n\n /** @inheritdoc */\n on(hook, callback) {\n if (!this._hooks[hook]) {\n this._hooks[hook] = [];\n }\n\n // @ts-expect-error We assue the types are correct\n this._hooks[hook].push(callback);\n }\n\n /** @inheritdoc */\n\n /** @inheritdoc */\n emit(hook, ...rest) {\n if (this._hooks[hook]) {\n this._hooks[hook].forEach(callback => callback(...rest));\n }\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Updates existing session based on the provided event */\n _updateSessionFromEvent(session, event) {\n let crashed = false;\n let errored = false;\n const exceptions = event.exception && 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 && 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 scope A scope containing event metadata.\n * @returns A new event with more information.\n */\n _prepareEvent(event, hint, scope) {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations.length > 0) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n return prepareEvent(options, event, hint, scope, this).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n // If a trace context is not set on the event, we use the propagationContext set on the event to\n // generate a trace context. If the propagationContext does not have a dynamic sampling context, we\n // also generate one for it.\n const { propagationContext } = evt.sdkProcessingMetadata || {};\n const trace = evt.contexts && evt.contexts.trace;\n if (!trace && propagationContext) {\n const { traceId: trace_id, spanId, parentSpanId, dsc } = propagationContext ;\n evt.contexts = {\n trace: {\n trace_id,\n span_id: spanId,\n parent_span_id: parentSpanId,\n },\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = dsc ? dsc : getDynamicSamplingContextFromClient(trace_id, this, scope);\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(event, hint = {}, scope) {\n return this._processEvent(event, hint, scope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\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 const sentryError = reason ;\n if (sentryError.logLevel === 'log') {\n logger.log(sentryError.message);\n } else {\n logger.warn(sentryError);\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 scope 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(event, hint, scope) {\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 if (isError && typeof sampleRate === 'number' && Math.random() > sampleRate) {\n this.recordDroppedEvent('sample_rate', 'error', event);\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, scope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory, event);\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(options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory, event);\n throw new SentryError(`${beforeSendLabel} returned \\`null\\`, will not send event.`, 'log');\n }\n\n const session = scope && scope.getSession();\n if (!isTransaction && session) {\n this._updateSessionFromEvent(session, processedEvent);\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 * @inheritdoc\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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Error while sending event:', reason);\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Transport disabled');\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.keys(outcomes).map(key => {\n const [reason, category] = key.split(':') ;\n return {\n reason,\n category,\n quantity: outcomes[key],\n };\n });\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n\n}\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 options,\n event,\n hint,\n) {\n const { beforeSend, beforeSendTransaction } = options;\n\n if (isErrorEvent(event) && beforeSend) {\n return beforeSend(event, hint);\n }\n\n if (isTransactionEvent(event) && beforeSendTransaction) {\n return beforeSendTransaction(event, hint);\n }\n\n return event;\n}\n\nfunction isErrorEvent(event) {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\nexport { BaseClient };\n","import { getSdkMetadataForEnvelopeHeader, createEventEnvelopeHeaders, createEnvelope, dsnToString } from '@sentry/utils';\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 adjut 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 && 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\nexport { createEventEnvelope, createSessionEnvelope };\n","const SDK_VERSION = '7.81.1';\n\nexport { SDK_VERSION };\n","import { getCurrentHub } from '@sentry/core';\nimport { addExceptionMechanism, resolvedSyncPromise, isErrorEvent, isDOMError, isDOMException, addExceptionTypeValue, isError, isPlainObject, isEvent, normalizeToSize, extractExceptionKeysForMessage } from '@sentry/utils';\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: ex && ex.name,\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\n/**\n * @hidden\n */\nfunction eventFromPlainObject(\n stackParser,\n exception,\n syntheticException,\n isUnhandledRejection,\n) {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const normalizeDepth = client && client.getOptions().normalizeDepth;\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 __serialized__: normalizeToSize(exception, normalizeDepth),\n },\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 (event.exception ).values[0].stacktrace = { frames };\n }\n }\n\n return event;\n}\n\n/**\n * @hidden\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 popSize = getPopSize(ex);\n\n try {\n return stackParser(stacktrace, popSize);\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\nfunction getPopSize(ex) {\n if (ex) {\n if (typeof ex.framesToPop === 'number') {\n return ex.framesToPop;\n }\n\n if (reactMinifiedRegexp.test(ex.message)) {\n return 1;\n }\n }\n\n return 0;\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 && ex.message;\n if (!message) {\n return 'No error message';\n }\n if (message.error && typeof message.error.message === 'string') {\n return message.error.message;\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 && 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 && 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 // eslint-disable-next-line deprecation/deprecation\n level = 'info',\n hint,\n attachStacktrace,\n) {\n const syntheticException = (hint && hint.syntheticException) || undefined;\n const event = eventFromString(stackParser, message, syntheticException, attachStacktrace);\n event.level = level;\n if (hint && 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\n/**\n * @hidden\n */\nfunction eventFromString(\n stackParser,\n input,\n syntheticException,\n attachStacktrace,\n) {\n const event = {\n message: input,\n };\n\n if (attachStacktrace && syntheticException) {\n const frames = parseStackFrames(stackParser, syntheticException);\n if (frames.length) {\n event.exception = {\n values: [{ value: input, stacktrace: { frames } }],\n };\n }\n }\n\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\nexport { eventFromError, eventFromException, eventFromMessage, eventFromPlainObject, eventFromString, eventFromUnknownInput, exceptionFromError, parseStackFrames };\n","import { withScope, captureException } from '@sentry/core';\nimport { GLOBAL_OBJ, getOriginalFunction, markFunctionWrapped, addNonEnumerableProperty, addExceptionTypeValue, addExceptionMechanism } from '@sentry/utils';\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/**\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 before,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 if (typeof fn !== 'function') {\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 return wrapper;\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 /* eslint-disable prefer-rest-params */\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped = function () {\n const args = Array.prototype.slice.call(arguments);\n\n try {\n if (before && typeof before === 'function') {\n before.apply(this, arguments);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\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 /* eslint-enable prefer-rest-params */\n\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\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 (_oO) {} // eslint-disable-line no-empty\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 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 // eslint-disable-next-line no-empty\n } catch (_oO) {}\n\n return sentryWrapped;\n}\n\n/**\n * All properties the report dialog supports\n */\n\nexport { WINDOW, ignoreNextOnError, shouldIgnoreOnError, wrap };\n","import { BaseClient, SDK_VERSION } from '@sentry/core';\nimport { getSDKSource, logger, createClientReportEnvelope, dsnToString } from '@sentry/utils';\nimport { eventFromException, eventFromMessage } from './eventbuilder.js';\nimport { WINDOW } from './helpers.js';\nimport { createUserFeedbackEnvelope } from './userfeedback.js';\n\n/**\n * Configuration options for the Sentry Browser SDK.\n * @see @sentry/types 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 BaseClient {\n /**\n * Creates a new Browser SDK instance.\n *\n * @param options Configuration options for this SDK.\n */\n constructor(options) {\n const sdkSource = WINDOW.SENTRY_SDK_SOURCE || getSDKSource();\n\n options._metadata = options._metadata || {};\n options._metadata.sdk = options._metadata.sdk || {\n name: 'sentry.javascript.browser',\n packages: [\n {\n name: `${sdkSource}:@sentry/browser`,\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n\n super(options);\n\n if (options.sendClientReports && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n if (WINDOW.document.visibilityState === 'hidden') {\n this._flushOutcomes();\n }\n });\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 // eslint-disable-next-line deprecation/deprecation\n level = 'info',\n hint,\n ) {\n return eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace);\n }\n\n /**\n * Sends user feedback to Sentry.\n */\n captureUserFeedback(feedback) {\n if (!this._isEnabled()) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('SDK not enabled, will not capture user feedback.');\n return;\n }\n\n const envelope = createUserFeedbackEnvelope(feedback, {\n metadata: this.getSdkMetadata(),\n dsn: this.getDsn(),\n tunnel: this.getOptions().tunnel,\n });\n void this._sendEnvelope(envelope);\n }\n\n /**\n * @inheritDoc\n */\n _prepareEvent(event, hint, scope) {\n event.platform = event.platform || 'javascript';\n return super._prepareEvent(event, hint, scope);\n }\n\n /**\n * Sends client reports as an envelope.\n */\n _flushOutcomes() {\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && 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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('No dsn provided, will not send outcomes');\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n void this._sendEnvelope(envelope);\n }\n}\n\nexport { BrowserClient };\n","import { dsnToString, createEnvelope } from '@sentry/utils';\n\n/**\n * Creates an envelope from a user feedback.\n */\nfunction createUserFeedbackEnvelope(\n feedback,\n {\n metadata,\n tunnel,\n dsn,\n }\n\n,\n) {\n const headers = {\n event_id: feedback.event_id,\n sent_at: new Date().toISOString(),\n ...(metadata &&\n metadata.sdk && {\n sdk: {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n },\n }),\n ...(!!tunnel && !!dsn && { dsn: dsnToString(dsn) }),\n };\n const item = createUserFeedbackEnvelopeItem(feedback);\n\n return createEnvelope(headers, [item]);\n}\n\nfunction createUserFeedbackEnvelopeItem(feedback) {\n const feedbackHeaders = {\n type: 'user_report',\n };\n return [feedbackHeaders, feedback];\n}\n\nexport { createUserFeedbackEnvelope };\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","import { getCurrentHub } from '@sentry/core';\nimport { addInstrumentationHandler, isString, isPrimitive, isErrorEvent, getLocationHref, logger, addExceptionMechanism } from '@sentry/utils';\nimport { eventFromUnknownInput } from '../eventbuilder.js';\nimport { shouldIgnoreOnError } from '../helpers.js';\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n\n/** Global handlers */\nclass GlobalHandlers {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'GlobalHandlers';}\n\n /**\n * @inheritDoc\n */\n\n /** JSDoc */\n\n /**\n * Stores references functions to installing handlers. Will set to undefined\n * after they have been run so that they are not used twice.\n */\n\n /** JSDoc */\n constructor(options) {\n this.name = GlobalHandlers.id;\n this._options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n this._installFunc = {\n onerror: _installGlobalOnErrorHandler,\n onunhandledrejection: _installGlobalOnUnhandledRejectionHandler,\n };\n }\n /**\n * @inheritDoc\n */\n setupOnce() {\n Error.stackTraceLimit = 50;\n const options = this._options;\n\n // We can disable guard-for-in as we construct the options object above + do checks against\n // `this._installFunc` for the property.\n // eslint-disable-next-line guard-for-in\n for (const key in options) {\n const installFunc = this._installFunc[key ];\n if (installFunc && options[key ]) {\n globalHandlerLog(key);\n installFunc();\n this._installFunc[key ] = undefined;\n }\n }\n }\n} GlobalHandlers.__initStatic();\n\n/** JSDoc */\nfunction _installGlobalOnErrorHandler() {\n addInstrumentationHandler(\n 'error',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (data) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n const { msg, url, line, column, error } = data;\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return;\n }\n\n const event =\n error === undefined && isString(msg)\n ? _eventFromIncompleteOnError(msg, url, line, column)\n : _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onerror');\n },\n );\n}\n\n/** JSDoc */\nfunction _installGlobalOnUnhandledRejectionHandler() {\n addInstrumentationHandler(\n 'unhandledrejection',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (e) => {\n const [hub, stackParser, attachStacktrace] = getHubAndOptions();\n if (!hub.getIntegration(GlobalHandlers)) {\n return;\n }\n let error = e;\n\n // dig the object of the rejection out of known event types\n try {\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 e) {\n error = e.reason;\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 else if ('detail' in e && 'reason' in e.detail) {\n error = e.detail.reason;\n }\n } catch (_oO) {\n // no-empty\n }\n\n if (shouldIgnoreOnError() || (error && error.__sentry_own_request__)) {\n return true;\n }\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n addMechanismAndCapture(hub, error, event, 'onunhandledrejection');\n return;\n },\n );\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\n/**\n * This function creates a stack from an old, error-less onerror handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _eventFromIncompleteOnError(msg, url, line, column) {\n const ERROR_TYPES_RE =\n /^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;\n\n // If 'message' is ErrorEvent, get real message from inside\n let message = isErrorEvent(msg) ? msg.message : msg;\n let name = 'Error';\n\n const groups = message.match(ERROR_TYPES_RE);\n if (groups) {\n name = groups[1];\n message = groups[2];\n }\n\n const event = {\n exception: {\n values: [\n {\n type: name,\n value: message,\n },\n ],\n },\n };\n\n return _enhanceEventWithInitialFrame(event, url, line, column);\n}\n\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _enhanceEventWithInitialFrame(event, url, line, column) {\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 = isNaN(parseInt(column, 10)) ? undefined : column;\n const lineno = isNaN(parseInt(line, 10)) ? undefined : 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: '?',\n in_app: true,\n lineno,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Global Handler attached: ${type}`);\n}\n\nfunction addMechanismAndCapture(hub, error, event, type) {\n addExceptionMechanism(event, {\n handled: false,\n type,\n });\n hub.captureEvent(event, {\n originalException: error,\n });\n}\n\nfunction getHubAndOptions() {\n const hub = getCurrentHub();\n const client = hub.getClient();\n const options = (client && client.getOptions()) || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return [hub, options.stackParser, options.attachStacktrace];\n}\n\nexport { GlobalHandlers };\n","import { fill, getFunctionName, getOriginalFunction } from '@sentry/utils';\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\n/** Wrap timer functions and event targets to catch errors and provide better meta data */\nclass TryCatch {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'TryCatch';}\n\n /**\n * @inheritDoc\n */\n\n /** JSDoc */\n\n /**\n * @inheritDoc\n */\n constructor(options) {\n this.name = TryCatch.id;\n this._options = {\n XMLHttpRequest: true,\n eventTarget: true,\n requestAnimationFrame: true,\n setInterval: true,\n setTimeout: true,\n ...options,\n };\n }\n\n /**\n * Wrap timer functions and event targets to catch errors\n * and provide better metadata.\n */\n setupOnce() {\n if (this._options.setTimeout) {\n fill(WINDOW, 'setTimeout', _wrapTimeFunction);\n }\n\n if (this._options.setInterval) {\n fill(WINDOW, 'setInterval', _wrapTimeFunction);\n }\n\n if (this._options.requestAnimationFrame) {\n fill(WINDOW, 'requestAnimationFrame', _wrapRAF);\n }\n\n if (this._options.XMLHttpRequest && 'XMLHttpRequest' in WINDOW) {\n fill(XMLHttpRequest.prototype, 'send', _wrapXHR);\n }\n\n const eventTargetOption = this._options.eventTarget;\n if (eventTargetOption) {\n const eventTarget = Array.isArray(eventTargetOption) ? eventTargetOption : DEFAULT_EVENT_TARGET;\n eventTarget.forEach(_wrapEventTarget);\n }\n }\n} TryCatch.__initStatic();\n\n/** JSDoc */\nfunction _wrapTimeFunction(original) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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\n/** JSDoc */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _wrapRAF(original) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return function ( callback) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\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\n/** JSDoc */\nfunction _wrapXHR(originalSend) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 TryCatch, 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\n/** JSDoc */\nfunction _wrapEventTarget(target) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const globalObject = WINDOW ;\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n const proto = globalObject[target] && globalObject[target].prototype;\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins\n if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) {\n return;\n }\n\n fill(proto, 'addEventListener', function (original)\n\n {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n eventName,\n fn,\n options,\n ) {\n try {\n if (typeof fn.handleEvent === 'function') {\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 (err) {\n // can sometimes get 'Permission denied to access property \"handle Event'\n }\n\n return original.apply(this, [\n eventName,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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(\n proto,\n 'removeEventListener',\n function (\n originalRemoveEventListener,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ) {\n return function (\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n eventName,\n fn,\n options,\n ) {\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 const wrappedEventHandler = fn ;\n try {\n const originalEventHandler = wrappedEventHandler && wrappedEventHandler.__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, wrappedEventHandler, options);\n };\n },\n );\n}\n\nexport { TryCatch };\n","// Note: Ideally the `SeverityLevel` type would be derived from `validSeverityLevels`, but that would mean either\n//\n// a) moving `validSeverityLevels` to `@sentry/types`,\n// b) moving the`SeverityLevel` type here, or\n// c) importing `validSeverityLevels` from here into `@sentry/types`.\n//\n// Option A would make `@sentry/types` a runtime dependency of `@sentry/utils` (not good), and options B and C would\n// create a circular dependency between `@sentry/types` and `@sentry/utils` (also not good). So a TODO accompanying the\n// type, reminding anyone who changes it to change this list also, will have to do.\n\nconst validSeverityLevels = ['fatal', 'error', 'warning', 'log', 'info', 'debug'];\n\n/**\n * Converts a string-based level into a member of the deprecated {@link Severity} enum.\n *\n * @deprecated `severityFromString` is deprecated. Please use `severityLevelFromString` instead.\n *\n * @param level String representation of Severity\n * @returns Severity\n */\nfunction severityFromString(level) {\n return severityLevelFromString(level) ;\n}\n\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 (level === 'warn' ? 'warning' : validSeverityLevels.includes(level) ? level : 'log') ;\n}\n\nexport { severityFromString, severityLevelFromString, validSeverityLevels };\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 // eslint-disable-next-line no-useless-escape\n return urlPath.split(/[\\?#]/, 1)[0];\n}\n\n/**\n * Returns number of URL segments of a passed string URL.\n */\nfunction getNumberOfUrlSegments(url) {\n // split at '/' or at '\\/' to split regex urls correctly\n return url.split(/\\\\?\\//).filter(s => s.length > 0 && s !== ',').length;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span description\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 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 .replace(':80', '')\n .replace(':443', '')) ||\n '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n\nexport { getNumberOfUrlSegments, getSanitizedUrlString, parseUrl, stripUrlQueryAndFragment };\n","import { getCurrentHub } from '@sentry/core';\nimport { addInstrumentationHandler, getEventDescription, severityLevelFromString, safeJoin, SENTRY_XHR_DATA_KEY, parseUrl, logger, htmlTreeAsString } from '@sentry/utils';\nimport { WINDOW } from '../helpers.js';\n\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n\n/** maxStringLength gets capped to prevent 100 breadcrumbs exceeding 1MB event payload size */\nconst MAX_ALLOWED_STRING_LENGTH = 1024;\n\n/**\n * Default Breadcrumbs instrumentations\n * TODO: Deprecated - with v6, this will be renamed to `Instrument`\n */\nclass Breadcrumbs {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Breadcrumbs';}\n\n /**\n * @inheritDoc\n */\n\n /**\n * Options of the breadcrumbs integration.\n */\n // This field is public, because we use it in the browser client to check if the `sentry` option is enabled.\n\n /**\n * @inheritDoc\n */\n constructor(options) {\n this.name = Breadcrumbs.id;\n this.options = {\n console: true,\n dom: true,\n fetch: true,\n history: true,\n sentry: true,\n xhr: true,\n ...options,\n };\n }\n\n /**\n * Instrument browser built-ins w/ breadcrumb capturing\n * - Console API\n * - DOM API (click/typing)\n * - XMLHttpRequest API\n * - Fetch API\n * - History API\n */\n setupOnce() {\n if (this.options.console) {\n addInstrumentationHandler('console', _consoleBreadcrumb);\n }\n if (this.options.dom) {\n addInstrumentationHandler('dom', _domBreadcrumb(this.options.dom));\n }\n if (this.options.xhr) {\n addInstrumentationHandler('xhr', _xhrBreadcrumb);\n }\n if (this.options.fetch) {\n addInstrumentationHandler('fetch', _fetchBreadcrumb);\n }\n if (this.options.history) {\n addInstrumentationHandler('history', _historyBreadcrumb);\n }\n if (this.options.sentry) {\n const client = getCurrentHub().getClient();\n client && client.on && client.on('beforeSendEvent', addSentryBreadcrumb);\n }\n }\n} Breadcrumbs.__initStatic();\n\n/**\n * Adds a breadcrumb for Sentry events or transactions if this option is enabled.\n */\nfunction addSentryBreadcrumb(event) {\n getCurrentHub().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 * A HOC that creaes 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 _domBreadcrumb(dom) {\n function _innerDomBreadcrumb(handlerData) {\n let target;\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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\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 target = _isEvent(event)\n ? htmlTreeAsString(event.target, { keyAttrs, maxStringLength })\n : htmlTreeAsString(event, { keyAttrs, maxStringLength });\n } catch (e) {\n target = '';\n }\n\n if (target.length === 0) {\n return;\n }\n\n getCurrentHub().addBreadcrumb(\n {\n category: `ui.${handlerData.name}`,\n message: target,\n },\n {\n event: handlerData.event,\n name: handlerData.name,\n global: handlerData.global,\n },\n );\n }\n\n return _innerDomBreadcrumb;\n}\n\n/**\n * Creates breadcrumbs from console API calls\n */\nfunction _consoleBreadcrumb(handlerData) {\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 getCurrentHub().addBreadcrumb(breadcrumb, {\n input: handlerData.args,\n level: handlerData.level,\n });\n}\n\n/**\n * Creates breadcrumbs from XHR API calls\n */\nfunction _xhrBreadcrumb(handlerData) {\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 getCurrentHub().addBreadcrumb(\n {\n category: 'xhr',\n data,\n type: 'http',\n },\n hint,\n );\n}\n\n/**\n * Creates breadcrumbs from fetch API calls\n */\nfunction _fetchBreadcrumb(handlerData) {\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 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 getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n level: 'error',\n type: 'http',\n },\n hint,\n );\n } else {\n const data = {\n ...handlerData.fetchData,\n status_code: handlerData.response && handlerData.response.status,\n };\n const hint = {\n input: handlerData.args,\n response: handlerData.response,\n startTimestamp,\n endTimestamp,\n };\n getCurrentHub().addBreadcrumb(\n {\n category: 'fetch',\n data,\n type: 'http',\n },\n hint,\n );\n }\n}\n\n/**\n * Creates breadcrumbs from history API calls\n */\nfunction _historyBreadcrumb(handlerData) {\n let from = handlerData.from;\n let to = handlerData.to;\n const parsedLoc = parseUrl(WINDOW.location.href);\n let parsedFrom = parseUrl(from);\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 getCurrentHub().addBreadcrumb({\n category: 'navigation',\n data: {\n from,\n to,\n },\n });\n}\n\nfunction _isEvent(event) {\n return !!event && !!(event ).target;\n}\n\nexport { Breadcrumbs };\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 || !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 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 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","import { applyAggregateErrorsToEvent } from '@sentry/utils';\nimport { exceptionFromError } from '../eventbuilder.js';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\n/** Adds SDK info to an event. */\nclass LinkedErrors {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'LinkedErrors';}\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {\n this.name = LinkedErrors.id;\n this._key = options.key || DEFAULT_KEY;\n this._limit = options.limit || DEFAULT_LIMIT;\n }\n\n /** @inheritdoc */\n setupOnce() {\n // noop\n }\n\n /**\n * @inheritDoc\n */\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(\n exceptionFromError,\n options.stackParser,\n options.maxValueLength,\n this._key,\n this._limit,\n event,\n hint,\n );\n }\n} LinkedErrors.__initStatic();\n\nexport { LinkedErrors };\n","import { WINDOW } from '../helpers.js';\n\n/** HttpContext integration collects information about HTTP request headers */\nclass HttpContext {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'HttpContext';}\n\n /**\n * @inheritDoc\n */\n\n constructor() {\n this.name = HttpContext.id;\n }\n\n /**\n * @inheritDoc\n */\n setupOnce() {\n // noop\n }\n\n /** @inheritDoc */\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 && event.request.url) || (WINDOW.location && WINDOW.location.href);\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(event.request && event.request.headers),\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = { ...event.request, ...(url && { url }), headers };\n\n event.request = request;\n }\n} HttpContext.__initStatic();\n\nexport { HttpContext };\n","import { logger } from '@sentry/utils';\n\n/** Deduplication filter */\nclass Dedupe {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'Dedupe';}\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n constructor() {\n this.name = Dedupe.id;\n }\n\n /** @inheritDoc */\n setupOnce(_addGlobaleventProcessor, _getCurrentHub) {\n // noop\n }\n\n /**\n * @inheritDoc\n */\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, this._previousEvent)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && 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 (this._previousEvent = currentEvent);\n }\n} Dedupe.__initStatic();\n\n/** JSDoc */\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\n/** JSDoc */\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\n/** JSDoc */\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\n/** JSDoc */\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 const frameA = previousFrames[i];\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\n/** JSDoc */\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\n/** JSDoc */\nfunction _getExceptionFromEvent(event) {\n return event.exception && event.exception.values && event.exception.values[0];\n}\n\n/** JSDoc */\nfunction _getFramesFromEvent(event) {\n const exception = event.exception;\n\n if (exception) {\n try {\n // @ts-expect-error Object could be undefined\n return exception.values[0].stacktrace.frames;\n } catch (_oO) {\n return undefined;\n }\n }\n return undefined;\n}\n\nexport { Dedupe };\n","import { createStackParser } from '@sentry/utils';\n\n// global reference to slice\nconst UNKNOWN_FUNCTION = '?';\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,\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// Chromium based browsers: Chrome, Brave, new Opera, new Edge\nconst chromeRegex =\n /^\\s*at (?:(.+?\\)(?: \\[.+\\])?|.*?) ?\\((?:address at )?)?(?:async )?((?:|[-a-z]+:|.*bundle|\\/)?.*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i;\nconst chromeEvalRegex = /\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/;\n\nconst chrome = line => {\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, chrome];\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, winjsStackLineParser];\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","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];\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","// 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, category) {\n return limits[category] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nfunction isRateLimited(limits, category, now = Date.now()) {\n return disabledUntil(limits, category) > 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 && headers['x-sentry-rate-limits'];\n const retryAfterHeader = headers && 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 */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories] = limit.split(':', 2);\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 updatedRateLimits[category] = now + delay;\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","import { makePromiseBuffer, forEachEnvelopeItem, envelopeItemTypeToDataCategory, isRateLimited, resolvedSyncPromise, createEnvelope, SentryError, logger, serializeEnvelope, updateRateLimits } from '@sentry/utils';\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 30;\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 envelopeItemDataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, envelopeItemDataCategory)) {\n const event = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent('ratelimit_backoff', envelopeItemDataCategory, event);\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 const event = getEventForEnvelopeItem(item, type);\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type), event);\n });\n };\n\n const requestTask = () =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope, options.textEncoder) }).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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && 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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && 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 // We use this to identifify if the transport is the base transport\n // TODO (v8): Remove this again as we'll no longer need it\n send.__sentry__baseTransport__ = true;\n\n return {\n send,\n flush,\n };\n}\n\nfunction getEventForEnvelopeItem(item, type) {\n if (type !== 'event' && type !== 'transaction') {\n return undefined;\n }\n\n return Array.isArray(item) ? (item )[1] : undefined;\n}\n\nexport { DEFAULT_TRANSPORT_BUFFER_SIZE, createTransport };\n","import { isNativeFetch, logger } from '@sentry/utils';\nimport { WINDOW } from '../helpers.js';\n\nlet cachedFetchImpl = undefined;\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 getNativeFetchImplementation() {\n if (cachedFetchImpl) {\n return cachedFetchImpl;\n }\n\n /* eslint-disable @typescript-eslint/unbound-method */\n\n // Fast path to avoid DOM I/O\n if (isNativeFetch(WINDOW.fetch)) {\n return (cachedFetchImpl = WINDOW.fetch.bind(WINDOW));\n }\n\n const document = WINDOW.document;\n let fetchImpl = WINDOW.fetch;\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 && contentWindow.fetch) {\n fetchImpl = contentWindow.fetch;\n }\n document.head.removeChild(sandbox);\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', e);\n }\n }\n\n return (cachedFetchImpl = fetchImpl.bind(WINDOW));\n /* eslint-enable @typescript-eslint/unbound-method */\n}\n\n/** Clears cached fetch impl */\nfunction clearCachedFetchImplementation() {\n cachedFetchImpl = undefined;\n}\n\nexport { clearCachedFetchImplementation, getNativeFetchImplementation };\n","import { createTransport } from '@sentry/core';\nimport { rejectedSyncPromise } from '@sentry/utils';\nimport { getNativeFetchImplementation, clearCachedFetchImplementation } from './utils.js';\n\n/**\n * Creates a Transport that uses the Fetch API to send events to Sentry.\n */\nfunction makeFetchTransport(\n options,\n nativeFetch = getNativeFetchImplementation(),\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: '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. whenfinishing 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 try {\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 clearCachedFetchImplementation();\n pendingBodySize -= requestSize;\n pendingCount--;\n return rejectedSyncPromise(e);\n }\n }\n\n return createTransport(options, makeRequest);\n}\n\nexport { makeFetchTransport };\n","import { createTransport } from '@sentry/core';\nimport { SyncPromise } from '@sentry/utils';\n\n/**\n * The DONE ready state for XmlHttpRequest\n *\n * Defining it here as a constant b/c XMLHttpRequest.DONE is not always defined\n * (e.g. during testing, it is `undefined`)\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/readyState}\n */\nconst XHR_READYSTATE_DONE = 4;\n\n/**\n * Creates a Transport that uses the XMLHttpRequest API to send events to Sentry.\n */\nfunction makeXHRTransport(options) {\n function makeRequest(request) {\n return new SyncPromise((resolve, reject) => {\n const xhr = new XMLHttpRequest();\n\n xhr.onerror = reject;\n\n xhr.onreadystatechange = () => {\n if (xhr.readyState === XHR_READYSTATE_DONE) {\n resolve({\n statusCode: xhr.status,\n headers: {\n 'x-sentry-rate-limits': xhr.getResponseHeader('X-Sentry-Rate-Limits'),\n 'retry-after': xhr.getResponseHeader('Retry-After'),\n },\n });\n }\n };\n\n xhr.open('POST', options.url);\n\n for (const header in options.headers) {\n if (Object.prototype.hasOwnProperty.call(options.headers, header)) {\n xhr.setRequestHeader(header, options.headers[header]);\n }\n }\n\n xhr.send(request.body);\n });\n }\n\n return createTransport(options, makeRequest);\n}\n\nexport { makeXHRTransport };\n","import { Integrations, getIntegrationsToSetup, initAndBind, getReportDialogEndpoint, getCurrentHub } from '@sentry/core';\nimport { stackParserFromStackParserOptions, supportsFetch, logger, addInstrumentationHandler } from '@sentry/utils';\nimport { BrowserClient } from './client.js';\nimport { WINDOW, wrap as wrap$1 } from './helpers.js';\nimport { GlobalHandlers } from './integrations/globalhandlers.js';\nimport { TryCatch } from './integrations/trycatch.js';\nimport { Breadcrumbs } from './integrations/breadcrumbs.js';\nimport { LinkedErrors } from './integrations/linkederrors.js';\nimport { HttpContext } from './integrations/httpcontext.js';\nimport { Dedupe } from './integrations/dedupe.js';\nimport { defaultStackParser } from './stack-parsers.js';\nimport { makeFetchTransport } from './transports/fetch.js';\nimport { makeXHRTransport } from './transports/xhr.js';\n\nconst defaultIntegrations = [\n new Integrations.InboundFilters(),\n new Integrations.FunctionToString(),\n new TryCatch(),\n new Breadcrumbs(),\n new GlobalHandlers(),\n new LinkedErrors(),\n new Dedupe(),\n new HttpContext(),\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 { configureScope } from '@sentry/browser';\n * configureScope((scope: Scope) => {\n * scope.setExtra({ battery: 0.7 });\n * scope.setTag({ user_mode: 'admin' });\n * scope.setUser({ id: '4711' });\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(options = {}) {\n if (options.defaultIntegrations === undefined) {\n options.defaultIntegrations = defaultIntegrations;\n }\n if (options.release === undefined) {\n // This allows build tooling to find-and-replace __SENTRY_RELEASE__ to inject a release value\n if (typeof __SENTRY_RELEASE__ === 'string') {\n options.release = __SENTRY_RELEASE__;\n }\n\n // This supports the variable that sentry-webpack-plugin injects\n if (WINDOW.SENTRY_RELEASE && WINDOW.SENTRY_RELEASE.id) {\n options.release = WINDOW.SENTRY_RELEASE.id;\n }\n }\n if (options.autoSessionTracking === undefined) {\n options.autoSessionTracking = true;\n }\n if (options.sendClientReports === undefined) {\n options.sendClientReports = true;\n }\n\n const clientOptions = {\n ...options,\n stackParser: stackParserFromStackParserOptions(options.stackParser || defaultStackParser),\n integrations: getIntegrationsToSetup(options),\n transport: options.transport || (supportsFetch() ? makeFetchTransport : makeXHRTransport),\n };\n\n initAndBind(BrowserClient, clientOptions);\n\n if (options.autoSessionTracking) {\n startSessionTracking();\n }\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 = {}, hub = getCurrentHub()) {\n // doesn't work without a document (React Native)\n if (!WINDOW.document) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.error('Global document not defined in showReportDialog call');\n return;\n }\n\n const { client, scope } = hub.getStackTop();\n const dsn = options.dsn || (client && client.getDsn());\n if (!dsn) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && 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 options.eventId = hub.lastEventId();\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 injectionPoint = WINDOW.document.head || WINDOW.document.body;\n if (injectionPoint) {\n injectionPoint.appendChild(script);\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && 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\n/**\n * Wrap code within a try/catch block so the SDK is able to capture errors.\n *\n * @deprecated This function will be removed in v8.\n * It is not part of Sentry's official API and it's easily replaceable by using a try/catch block\n * and calling Sentry.captureException.\n *\n * @param fn A function to wrap.\n *\n * @returns The result of wrapped function call.\n */\n// TODO(v8): Remove this function\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction wrap(fn) {\n return wrap$1(fn)();\n}\n\nfunction startSessionOnHub(hub) {\n hub.startSession({ ignoreDuration: true });\n hub.captureSession();\n}\n\n/**\n * Enable automatic Session Tracking for the initial page load.\n */\nfunction startSessionTracking() {\n if (typeof WINDOW.document === 'undefined') {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('Session tracking in non-browser environment with @sentry/browser is not supported.');\n return;\n }\n\n const hub = getCurrentHub();\n\n // The only way for this to be false is for there to be a version mismatch between @sentry/browser (>= 6.0.0) and\n // @sentry/hub (< 5.27.0). In the simple case, there won't ever be such a mismatch, because the two packages are\n // pinned at the same version in package.json, but there are edge cases where it's possible. See\n // https://github.com/getsentry/sentry-javascript/issues/3207 and\n // https://github.com/getsentry/sentry-javascript/issues/3234 and\n // https://github.com/getsentry/sentry-javascript/issues/3278.\n if (!hub.captureSession) {\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 startSessionOnHub(hub);\n\n // We want to create a session for every navigation as well\n addInstrumentationHandler('history', ({ 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 startSessionOnHub(getCurrentHub());\n }\n });\n}\n\n/**\n * Captures user feedback and sends it to Sentry.\n */\nfunction captureUserFeedback(feedback) {\n const client = getCurrentHub().getClient();\n if (client) {\n client.captureUserFeedback(feedback);\n }\n}\n\nexport { captureUserFeedback, defaultIntegrations, forceLoad, init, onLoad, showReportDialog, wrap };\n","import { logger } from '@sentry/utils';\nimport { getCurrentHub } from './hub.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 ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\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 // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n }\n }\n const hub = getCurrentHub();\n const scope = hub.getScope();\n scope.update(options.initialScope);\n\n const client = new clientClass(options);\n hub.bindClient(client);\n}\n\nexport { initAndBind };\n","import * as Sentry from '@sentry/browser';\nimport { defaultIntegrations, SDK_VERSION, init as init$1, setContext, WINDOW, getCurrentHub } from '@sentry/browser';\nexport * from '@sentry/browser';\nimport * as i0 from '@angular/core';\nimport { VERSION, Injectable, Inject, Directive, Input, NgModule } from '@angular/core';\nimport { logger, isString, addExceptionMechanism, stripUrlQueryAndFragment, timestampInSeconds } from '@sentry/utils';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport * as i1 from '@angular/router';\nimport { NavigationStart, ResolveEnd, NavigationEnd, NavigationCancel, NavigationError } from '@angular/router';\nimport { Subscription } from 'rxjs';\nimport { filter, tap } from 'rxjs/operators';\n\n/*\n * This file defines flags and constants that can be modified during compile time in order to facilitate tree shaking\n * for users.\n *\n * We define \"magic strings\" like `__SENTRY_DEBUG__` that may get replaced with actual values during our, or the user's\n * build process. Take care when introducing new flags - they must not throw if they are not replaced. See the Debug\n * Build Flags section in CONTRIBUTING.md.\n */\n/** Flag that is true for debug builds, false otherwise. */\nconst IS_DEBUG_BUILD = typeof __SENTRY_DEBUG__ === 'undefined' ? true : __SENTRY_DEBUG__;\n\n/**\n * Inits the Angular SDK\n */\nfunction init(options) {\n const opts = Object.assign({ _metadata: {}, \n // Filter out TryCatch integration as it interferes with our Angular `ErrorHandler`:\n // TryCatch would catch certain errors before they reach the `ErrorHandler` and thus provide a\n // lower fidelity error than what `SentryErrorHandler` (see errorhandler.ts) would provide.\n // see:\n // - https://github.com/getsentry/sentry-javascript/issues/5417#issuecomment-1453407097\n // - https://github.com/getsentry/sentry-javascript/issues/2744\n defaultIntegrations: defaultIntegrations.filter(integration => {\n return integration.name !== 'TryCatch';\n }) }, options);\n opts._metadata.sdk = opts._metadata.sdk || {\n name: 'sentry.javascript.angular-ivy',\n packages: [\n {\n name: 'npm:@sentry/angular-ivy',\n version: SDK_VERSION,\n },\n ],\n version: SDK_VERSION,\n };\n checkAndSetAngularVersion();\n init$1(opts);\n}\nfunction checkAndSetAngularVersion() {\n const ANGULAR_MINIMUM_VERSION = 12;\n const angularVersion = VERSION && VERSION.major ? parseInt(VERSION.major, 10) : undefined;\n if (angularVersion) {\n if (angularVersion < ANGULAR_MINIMUM_VERSION) {\n IS_DEBUG_BUILD &&\n logger.warn(`This Sentry SDK does not officially support Angular ${angularVersion}.`, `This SDK only supports Angular ${ANGULAR_MINIMUM_VERSION} and above.`, \"If you're using Angular 10 or 11, please use `@sentry/angular` instead.\", 'Otherwise, please consider upgrading your Angular version.');\n }\n setContext('angular', { version: angularVersion });\n }\n}\n\n// There're 2 types of Angular applications:\n// 1) zone-full (by default)\n// 2) zone-less\n// The developer can avoid importing the `zone.js` package and tells Angular that\n// he is responsible for running the change detection by himself. This is done by\n// \"nooping\" the zone through `CompilerOptions` when bootstrapping the root module.\n// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\nconst isNgZoneEnabled = typeof Zone !== 'undefined' && !!Zone.current;\n/**\n * The function that does the same job as `NgZone.runOutsideAngular`.\n */\nfunction runOutsideAngular(callback) {\n // The `Zone.root.run` basically will run the `callback` in the most parent zone.\n // Any asynchronous API used inside the `callback` won't catch Angular's zone\n // since `Zone.current` will reference `Zone.root`.\n // The Angular's zone is forked from the `Zone.root`. In this case, `zone.js` won't\n // trigger change detection, and `ApplicationRef.tick()` will not be run.\n // Caretaker note: we're using `Zone.root` except `NgZone.runOutsideAngular` since this\n // will require injecting the `NgZone` facade. That will create a breaking change for\n // projects already using the `@sentry/angular`.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return isNgZoneEnabled ? Zone.root.run(callback) : callback();\n}\n\n// https://github.com/angular/angular/blob/master/packages/core/src/util/errors.ts\nfunction tryToUnwrapZonejsError(error) {\n // TODO: once Angular14 is the minimum requirement ERROR_ORIGINAL_ERROR and\n // getOriginalError from error.ts can be used directly.\n return error && error.ngOriginalError\n ? error.ngOriginalError\n : error;\n}\nfunction extractHttpModuleError(error) {\n // The `error` property of http exception can be either an `Error` object, which we can use directly...\n if (isErrorOrErrorLikeObject(error.error)) {\n return error.error;\n }\n // ... or an`ErrorEvent`, which can provide us with the message but no stack...\n if (error.error instanceof ErrorEvent && error.error.message) {\n return error.error.message;\n }\n // ...or the request body itself, which we can use as a message instead.\n if (typeof error.error === 'string') {\n return `Server returned code ${error.status} with body \"${error.error}\"`;\n }\n // If we don't have any detailed information, fallback to the request message itself.\n return error.message;\n}\nfunction isErrorOrErrorLikeObject(value) {\n if (value instanceof Error) {\n return true;\n }\n if (value === null || typeof value !== 'object') {\n return false;\n }\n const candidate = value;\n return (isString(candidate.name) &&\n isString(candidate.message) &&\n (undefined === candidate.stack || isString(candidate.stack)));\n}\n/**\n * Implementation of Angular's ErrorHandler provider that can be used as a drop-in replacement for the stock one.\n */\nclass SentryErrorHandler {\n constructor(options) {\n this._registeredAfterSendEventHandler = false;\n this._options = Object.assign({ logErrors: true }, options);\n }\n /**\n * Method called for every value captured through the ErrorHandler\n */\n handleError(error) {\n const extractedError = this._extractError(error) || 'Handled unknown error';\n // Capture handled exception and send it to Sentry.\n const eventId = runOutsideAngular(() => Sentry.captureException(extractedError, (scope) => {\n scope.addEventProcessor(event => {\n addExceptionMechanism(event, {\n type: 'angular',\n handled: false,\n });\n return event;\n });\n return scope;\n }));\n // When in development mode, log the error to console for immediate feedback.\n if (this._options.logErrors) {\n // eslint-disable-next-line no-console\n console.error(extractedError);\n }\n // Optionally show user dialog to provide details on what happened.\n if (this._options.showDialog) {\n const client = Sentry.getCurrentHub().getClient();\n if (client && client.on && !this._registeredAfterSendEventHandler) {\n client.on('afterSendEvent', (event) => {\n if (!event.type) {\n Sentry.showReportDialog(Object.assign(Object.assign({}, this._options.dialogOptions), { eventId: event.event_id }));\n }\n });\n // We only want to register this hook once in the lifetime of the error handler\n this._registeredAfterSendEventHandler = true;\n }\n else if (!client || !client.on) {\n Sentry.showReportDialog(Object.assign(Object.assign({}, this._options.dialogOptions), { eventId }));\n }\n }\n }\n /**\n * Used to pull a desired value that will be used to capture an event out of the raw value captured by ErrorHandler.\n */\n _extractError(error) {\n // Allow custom overrides of extracting function\n if (this._options.extractor) {\n const defaultExtractor = this._defaultExtractor.bind(this);\n return this._options.extractor(error, defaultExtractor);\n }\n return this._defaultExtractor(error);\n }\n /**\n * Default implementation of error extraction that handles default error wrapping, HTTP responses, ErrorEvent and few other known cases.\n */\n _defaultExtractor(errorCandidate) {\n const error = tryToUnwrapZonejsError(errorCandidate);\n // If it's http module error, extract as much information from it as we can.\n if (error instanceof HttpErrorResponse) {\n return extractHttpModuleError(error);\n }\n // We can handle messages and Error objects directly.\n if (typeof error === 'string' || isErrorOrErrorLikeObject(error)) {\n return error;\n }\n // Nothing was extracted, fallback to default error message.\n return null;\n }\n}\nSentryErrorHandler.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"12.2.17\", ngImport: i0, type: SentryErrorHandler, deps: [{ token: 'errorHandlerOptions' }], target: i0.ɵɵFactoryTarget.Injectable });\nSentryErrorHandler.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"12.2.17\", ngImport: i0, type: SentryErrorHandler, providedIn: 'root' });\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"12.2.17\", ngImport: i0, type: SentryErrorHandler, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }], ctorParameters: function () { return [{ type: undefined, decorators: [{\n type: Inject,\n args: ['errorHandlerOptions']\n }] }]; } });\n/**\n * Factory function that creates an instance of a preconfigured ErrorHandler provider.\n */\nfunction createErrorHandler(config) {\n return new SentryErrorHandler(config);\n}\n\nconst ANGULAR_ROUTING_OP = 'ui.angular.routing';\nconst ANGULAR_INIT_OP = 'ui.angular.init';\nconst ANGULAR_OP = 'ui.angular';\n\nlet instrumentationInitialized;\nlet stashedStartTransaction;\nlet stashedStartTransactionOnLocationChange;\n/**\n * Creates routing instrumentation for Angular Router.\n */\nfunction routingInstrumentation(customStartTransaction, startTransactionOnPageLoad = true, startTransactionOnLocationChange = true) {\n instrumentationInitialized = true;\n stashedStartTransaction = customStartTransaction;\n stashedStartTransactionOnLocationChange = startTransactionOnLocationChange;\n if (startTransactionOnPageLoad && WINDOW && WINDOW.location) {\n customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'pageload',\n origin: 'auto.pageload.angular',\n metadata: { source: 'url' },\n });\n }\n}\nconst instrumentAngularRouting = routingInstrumentation;\n/**\n * Grabs active transaction off scope\n */\nfunction getActiveTransaction() {\n const currentHub = getCurrentHub();\n if (currentHub) {\n const scope = currentHub.getScope();\n return scope.getTransaction();\n }\n return undefined;\n}\n/**\n * Angular's Service responsible for hooking into Angular Router and tracking current navigation process.\n * Creates a new transaction for every route change and measures a duration of routing process.\n */\nclass TraceService {\n constructor(_router) {\n this._router = _router;\n this.navStart$ = this._router.events.pipe(filter((event) => event instanceof NavigationStart), tap(navigationEvent => {\n if (!instrumentationInitialized) {\n IS_DEBUG_BUILD &&\n logger.error('Angular integration has tracing enabled, but Tracing integration is not configured');\n return;\n }\n const strippedUrl = stripUrlQueryAndFragment(navigationEvent.url);\n let activeTransaction = getActiveTransaction();\n if (!activeTransaction && stashedStartTransactionOnLocationChange) {\n activeTransaction = stashedStartTransaction({\n name: strippedUrl,\n op: 'navigation',\n origin: 'auto.navigation.angular',\n metadata: { source: 'url' },\n });\n }\n if (activeTransaction) {\n if (this._routingSpan) {\n this._routingSpan.finish();\n }\n this._routingSpan = activeTransaction.startChild({\n description: `${navigationEvent.url}`,\n op: ANGULAR_ROUTING_OP,\n origin: 'auto.ui.angular',\n tags: Object.assign({ 'routing.instrumentation': '@sentry/angular', url: strippedUrl }, (navigationEvent.navigationTrigger && {\n navigationTrigger: navigationEvent.navigationTrigger,\n })),\n });\n }\n }));\n // The ResolveEnd event is fired when the Angular router has resolved the URL and\n // the parameter<->value mapping. It holds the new resolved router state with\n // the mapping and the new URL.\n // Only After this event, the route is activated, meaning that the transaction\n // can be updated with the parameterized route name before e.g. the route's root\n // component is initialized. This should be early enough before outgoing requests\n // are made from the new route, with the exceptions of requests being made during\n // a navigation.\n this.resEnd$ = this._router.events.pipe(filter((event) => event instanceof ResolveEnd), tap(event => {\n const route = getParameterizedRouteFromSnapshot(event.state.root);\n const transaction = getActiveTransaction();\n // TODO (v8 / #5416): revisit the source condition. Do we want to make the parameterized route the default?\n if (transaction && transaction.metadata.source === 'url') {\n transaction.setName(route, 'route');\n }\n }));\n this.navEnd$ = this._router.events.pipe(filter(event => event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError), tap(() => {\n if (this._routingSpan) {\n runOutsideAngular(() => {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n this._routingSpan.finish();\n });\n this._routingSpan = null;\n }\n }));\n this._routingSpan = null;\n this._subscription = new Subscription();\n this._subscription.add(this.navStart$.subscribe());\n this._subscription.add(this.resEnd$.subscribe());\n this._subscription.add(this.navEnd$.subscribe());\n }\n /**\n * This is used to prevent memory leaks when the root view is created and destroyed multiple times,\n * since `subscribe` callbacks capture `this` and prevent many resources from being GC'd.\n */\n ngOnDestroy() {\n this._subscription.unsubscribe();\n }\n}\nTraceService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"12.2.17\", ngImport: i0, type: TraceService, deps: [{ token: i1.Router }], target: i0.ɵɵFactoryTarget.Injectable });\nTraceService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"12.2.17\", ngImport: i0, type: TraceService, providedIn: 'root' });\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"12.2.17\", ngImport: i0, type: TraceService, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }], ctorParameters: function () { return [{ type: i1.Router }]; } });\nconst UNKNOWN_COMPONENT = 'unknown';\n/**\n * A directive that can be used to capture initialization lifecycle of the whole component.\n */\nclass TraceDirective {\n /**\n * Implementation of OnInit lifecycle method\n * @inheritdoc\n */\n ngOnInit() {\n if (!this.componentName) {\n this.componentName = UNKNOWN_COMPONENT;\n }\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n this._tracingSpan = activeTransaction.startChild({\n description: `<${this.componentName}>`,\n op: ANGULAR_INIT_OP,\n origin: 'auto.ui.angular.trace_directive',\n });\n }\n }\n /**\n * Implementation of AfterViewInit lifecycle method\n * @inheritdoc\n */\n ngAfterViewInit() {\n if (this._tracingSpan) {\n this._tracingSpan.finish();\n }\n }\n}\nTraceDirective.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"12.2.17\", ngImport: i0, type: TraceDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });\nTraceDirective.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: \"12.0.0\", version: \"12.2.17\", type: TraceDirective, selector: \"[trace]\", inputs: { componentName: [\"trace\", \"componentName\"] }, ngImport: i0 });\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"12.2.17\", ngImport: i0, type: TraceDirective, decorators: [{\n type: Directive,\n args: [{ selector: '[trace]' }]\n }], propDecorators: { componentName: [{\n type: Input,\n args: ['trace']\n }] } });\n/**\n * A module serves as a single compilation unit for the `TraceDirective` and can be re-used by any other module.\n */\nclass TraceModule {\n}\nTraceModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"12.2.17\", ngImport: i0, type: TraceModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });\nTraceModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: \"12.0.0\", version: \"12.2.17\", ngImport: i0, type: TraceModule, declarations: [TraceDirective], exports: [TraceDirective] });\nTraceModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: \"12.0.0\", version: \"12.2.17\", ngImport: i0, type: TraceModule });\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"12.2.17\", ngImport: i0, type: TraceModule, decorators: [{\n type: NgModule,\n args: [{\n declarations: [TraceDirective],\n exports: [TraceDirective],\n }]\n }] });\n/**\n * Decorator function that can be used to capture initialization lifecycle of the whole component.\n */\nfunction TraceClassDecorator() {\n let tracingSpan;\n /* eslint-disable @typescript-eslint/no-unsafe-member-access */\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n return target => {\n const originalOnInit = target.prototype.ngOnInit;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n target.prototype.ngOnInit = function (...args) {\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n tracingSpan = activeTransaction.startChild({\n description: `<${target.name}>`,\n op: ANGULAR_INIT_OP,\n origin: 'auto.ui.angular.trace_class_decorator',\n });\n }\n if (originalOnInit) {\n return originalOnInit.apply(this, args);\n }\n };\n const originalAfterViewInit = target.prototype.ngAfterViewInit;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n target.prototype.ngAfterViewInit = function (...args) {\n if (tracingSpan) {\n tracingSpan.finish();\n }\n if (originalAfterViewInit) {\n return originalAfterViewInit.apply(this, args);\n }\n };\n };\n /* eslint-enable @typescript-eslint/no-unsafe-member-access */\n}\n/**\n * Decorator function that can be used to capture a single lifecycle methods of the component.\n */\nfunction TraceMethodDecorator() {\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type, @typescript-eslint/ban-types\n return (target, propertyKey, descriptor) => {\n const originalMethod = descriptor.value;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n descriptor.value = function (...args) {\n const now = timestampInSeconds();\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n activeTransaction.startChild({\n description: `<${target.constructor.name}>`,\n endTimestamp: now,\n op: `${ANGULAR_OP}.${String(propertyKey)}`,\n origin: 'auto.ui.angular.trace_method_decorator',\n startTimestamp: now,\n });\n }\n if (originalMethod) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalMethod.apply(this, args);\n }\n };\n return descriptor;\n };\n}\n/**\n * Takes the parameterized route from a given ActivatedRouteSnapshot and concatenates the snapshot's\n * child route with its parent to produce the complete parameterized URL of the activated route.\n * This happens recursively until the last child (i.e. the end of the URL) is reached.\n *\n * @param route the ActivatedRouteSnapshot of which its path and its child's path is concatenated\n *\n * @returns the concatenated parameterized route string\n */\nfunction getParameterizedRouteFromSnapshot(route) {\n const parts = [];\n let currentRoute = route && route.firstChild;\n while (currentRoute) {\n const path = currentRoute && currentRoute.routeConfig && currentRoute.routeConfig.path;\n if (path === null || path === undefined) {\n break;\n }\n parts.push(path);\n currentRoute = currentRoute.firstChild;\n }\n const fullPath = parts.filter(part => part).join('/');\n return fullPath ? `/${fullPath}/` : '/';\n}\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { SentryErrorHandler, TraceClassDecorator, TraceDirective, TraceMethodDecorator, TraceModule, TraceService, createErrorHandler, getActiveTransaction, init, instrumentAngularRouting, routingInstrumentation };\n","import {\n APP_INITIALIZER,\n ApplicationConfig,\n ErrorHandler,\n importProvidersFrom,\n} from '@angular/core';\nimport {\n provideRouter,\n Router,\n withEnabledBlockingInitialNavigation,\n} from '@angular/router';\nimport { appRoutes } from './app.routes';\nimport { provideServiceWorker } from '@angular/service-worker';\nimport { IonicModule } from '@ionic/angular';\nimport { IonicStorageModule } from '@ionic/storage-angular';\nimport { provideHttpClient } from '@angular/common/http';\nimport { provideStore } from '@ngrx/store';\nimport { provideStoreDevtools } from '@ngrx/store-devtools';\nimport { metaReducers, reducers } from './reducers';\nimport * as SentryAngular from '@sentry/angular-ivy';\n\nexport const appConfig: ApplicationConfig = {\n providers: [\n importProvidersFrom(\n IonicModule.forRoot({\n mode: 'md',\n }),\n IonicStorageModule.forRoot()\n ),\n provideRouter(appRoutes, withEnabledBlockingInitialNavigation()),\n provideServiceWorker('ngsw-worker.js', {\n registrationStrategy: 'registerWhenStable:30000',\n }),\n provideHttpClient(),\n provideStore(reducers, { metaReducers }),\n provideStoreDevtools({ maxAge: 25 }),\n {\n provide: ErrorHandler,\n // Attach the Sentry ErrorHandler\n useValue: SentryAngular.createErrorHandler(),\n },\n {\n provide: SentryAngular.TraceService,\n deps: [Router],\n },\n {\n provide: APP_INITIALIZER,\n useFactory: () => () => {},\n deps: [SentryAngular.TraceService],\n multi: true,\n },\n ],\n};\n","import { ApplicationRef, Injectable } from '@angular/core';\nimport { SwUpdate } from '@angular/service-worker';\nimport { concat, interval } from 'rxjs';\nimport { first } from 'rxjs/operators';\n\n@Injectable({ providedIn: 'root' })\nexport class CheckForUpdateService {\n constructor(appRef: ApplicationRef, updates: SwUpdate) {\n // Allow the app to stabilize first, before starting\n // polling for updates with `interval()`.\n const appIsStable$ = appRef.isStable.pipe(first((isStable) => isStable));\n const everySixHours$ = interval(6 * 60 * 60 * 1000);\n const everySixHoursOnceAppIsStable$ = concat(appIsStable$, everySixHours$);\n\n everySixHoursOnceAppIsStable$.subscribe(async () => {\n try {\n const updateFound = await updates.checkForUpdate();\n console.log(\n updateFound\n ? 'A new version is available.'\n : 'Already on the latest version.'\n );\n } catch (err) {\n console.error('Failed to check for updates:', err);\n }\n });\n }\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { timer } from './timer';\nexport function interval(period = 0, scheduler = asyncScheduler) {\n if (period < 0) {\n period = 0;\n }\n return timer(period, period, scheduler);\n}\n","import { Injectable } from '@angular/core';\nimport { SwUpdate } from '@angular/service-worker';\nimport { VersionEventType } from '../update.utils';\n\n@Injectable({ providedIn: 'root' })\nexport class LogUpdateService {\n constructor(updates: SwUpdate) {\n updates.versionUpdates.subscribe((evt) => {\n switch (evt.type) {\n case VersionEventType.VERSION_DETECTED:\n console.log(`Downloading new app version: ${evt.version.hash}`);\n break;\n case VersionEventType.VERSION_READY:\n console.log(`Current app version: ${evt.currentVersion.hash}`);\n console.log(\n `New app version ready for use: ${evt.latestVersion.hash}`\n );\n break;\n case VersionEventType.VERSION_INSTALLATION_FAILED:\n console.log(\n `Failed to install app version '${evt.version}': ${evt.error}`\n );\n break;\n }\n });\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport { SwUpdate, VersionReadyEvent } from '@angular/service-worker';\nimport { filter } from 'rxjs';\nimport { AlertService } from '../../alert/alert.service';\nimport { Store } from '@ngrx/store';\nimport { IContentfulState } from '../../contentful/contentful.reducer';\nimport { clearNextSyncToken } from '../../contentful/contentful.actions';\nimport { generatePwaUpdateMessage, VersionEventType } from '../update.utils';\nimport { equals } from '../../ramda-functions';\n\n@Injectable({ providedIn: 'root' })\nexport class PromptUpdateService {\n private contentfulStore = inject(Store);\n private alertService = inject(AlertService);\n\n constructor(swUpdate: SwUpdate) {\n swUpdate.versionUpdates\n .pipe(\n filter((evt): evt is VersionReadyEvent =>\n equals(evt.type, VersionEventType.VERSION_READY)\n )\n )\n .subscribe(async (evt) => {\n await this.alertService.presentSingleActionAlert(\n 'Refresh to update',\n generatePwaUpdateMessage(),\n () => {\n this.contentfulStore.dispatch(clearNextSyncToken());\n document.location.reload();\n document.location.href = '/';\n },\n 'Refresh'\n );\n });\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport { SwUpdate } from '@angular/service-worker';\nimport { AlertService } from '../../alert/alert.service';\nimport { generateUnrecoverableStateMessage } from '../update.utils';\n\n@Injectable({ providedIn: 'root' })\nexport class UnrecoverableStateService {\n private alertService = inject(AlertService);\n constructor(updates: SwUpdate) {\n updates.unrecoverable.subscribe(async (event) => {\n await this.alertService.presentDoubleActionAlert(\n 'Update error',\n generateUnrecoverableStateMessage(event.reason),\n () => {\n // force clear all localStorage to try to fix the fatal error\n localStorage.clear();\n document.location.reload();\n document.location.href = '/';\n },\n 'Refresh',\n undefined,\n true\n );\n });\n }\n}\n","import {\n Component,\n CUSTOM_ELEMENTS_SCHEMA,\n inject,\n OnInit,\n} from '@angular/core';\nimport { IonicModule } from '@ionic/angular';\nimport { Router, RouterModule } from '@angular/router';\nimport { DBService } from './cache/db.service';\nimport { CheckForUpdateService } from './update/pwa/check-update.service';\nimport { LogUpdateService } from './update/pwa/log-update.service';\nimport { PromptUpdateService } from './update/pwa/prompt-update.service';\nimport { UnrecoverableStateService } from './update/pwa/unrecoverable-state.service';\n\n@Component({\n standalone: true,\n imports: [RouterModule, IonicModule],\n schemas: [CUSTOM_ELEMENTS_SCHEMA],\n selector: 'snowylive-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.scss'],\n})\nexport class AppComponent implements OnInit {\n private dbService = inject(DBService);\n private router = inject(Router);\n\n /*\n * Injecting PWA update services\n */\n protected checkForUpdateService = inject(CheckForUpdateService);\n protected logUpdateService = inject(LogUpdateService);\n protected promptUpdateService = inject(PromptUpdateService);\n protected uncoverableStateService = inject(UnrecoverableStateService);\n\n async ngOnInit() {\n await this.dbService.initDB();\n await this.router.navigateByUrl('sync');\n }\n}\n","\n \n\n","/** Default EventOrigin instrumentation */\nexport class EventOrigin {\n constructor() {\n /**\n * @inheritDoc\n */\n this.name = EventOrigin.id;\n }\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor) {\n addGlobalEventProcessor(event => {\n var _a;\n event.tags = (_a = event.tags) !== null && _a !== void 0 ? _a : {};\n event.tags['event.origin'] = 'javascript';\n event.tags['event.environment'] = 'javascript';\n return event;\n });\n }\n}\n/**\n * @inheritDoc\n */\nEventOrigin.id = 'EventOrigin';\n","import { Plugins } from '@capacitor/core';\n// Left here to support v2. This will be dropped in v4.\n// eslint-disable-next-line deprecation/deprecation\nconst SentryCapacitor = Plugins.SentryCapacitor;\nexport { SentryCapacitor };\n// NOTE: We are leaving this here for when we are going to drop v2 support\n//\n// import { registerPlugin } from '@capacitor/core';\n// import { SentryCapacitorWeb } from './web';\n// const SentryCapacitor = registerPlugin(\n// 'SentryCapacitor',\n// () => ({\n// web: new SentryCapacitorWeb(),\n// }),\n// );\n","import { normalize } from '@sentry/utils';\nconst KEY = 'value';\n/**\n * Converts any input into a valid record with string keys.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function convertToNormalizedObject(data) {\n const normalized = normalize(data);\n if (normalized === null || typeof normalized !== 'object') {\n return {\n [KEY]: normalized,\n };\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return normalized;\n }\n}\n","/* eslint-disable */\n/**\n * Convert a string to a byte array\n *\n * This is a utf8ToBytes function from the buffer module (with added types)\n * https://github.com/feross/buffer/blob/795bbb5bda1b39f1370ebd784bea6107b087e3a7/index.js#L1956\n *\n * License: MIT (https://github.com/feross/buffer)\n */\nexport function utf8ToBytes(string, units) {\n units = units || Infinity;\n let codePoint;\n const length = string.length;\n let leadSurrogate = null;\n const bytes = [];\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i);\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1)\n bytes.push(0xEF, 0xBF, 0xBD);\n continue;\n }\n else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1)\n bytes.push(0xEF, 0xBF, 0xBD);\n continue;\n }\n // valid lead\n leadSurrogate = codePoint;\n continue;\n }\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1)\n bytes.push(0xEF, 0xBF, 0xBD);\n leadSurrogate = codePoint;\n continue;\n }\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;\n }\n else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1)\n bytes.push(0xEF, 0xBF, 0xBD);\n }\n leadSurrogate = null;\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0)\n break;\n bytes.push(codePoint);\n }\n else if (codePoint < 0x800) {\n if ((units -= 2) < 0)\n break;\n bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80);\n }\n else if (codePoint < 0x10000) {\n if ((units -= 3) < 0)\n break;\n bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);\n }\n else if (codePoint < 0x110000) {\n if ((units -= 4) < 0)\n break;\n bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80);\n }\n else {\n throw new Error('Invalid code point');\n }\n }\n return bytes;\n}\n","import { __awaiter, __rest } from \"tslib\";\nimport { Capacitor } from '@capacitor/core';\nimport { dropUndefinedKeys, logger, SentryError } from '@sentry/utils';\nimport { FilterNativeOptions } from './nativeOptions';\nimport { SentryCapacitor } from './plugin';\nimport { convertToNormalizedObject } from './utils/normalize';\nimport { utf8ToBytes } from './vendor';\n/**\n * Internal interface for calling native functions\n */\nexport const NATIVE = {\n /**\n * Sending the event over the bridge to native\n * @param event Event\n */\n sendEnvelope(envelope) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!this.enableNative) {\n throw this._DisabledNativeError;\n }\n if (!this.isNativeClientAvailable()) {\n throw this._NativeClientError;\n }\n const [EOL] = utf8ToBytes('\\n');\n const [envelopeHeader, envelopeItems] = envelope;\n const headerString = JSON.stringify(envelopeHeader);\n let envelopeBytes = utf8ToBytes(headerString);\n envelopeBytes.push(EOL);\n for (const rawItem of envelopeItems) {\n const [itemHeader, itemPayload] = this._processItem(rawItem);\n let bytesContentType;\n let bytesPayload = [];\n if (typeof itemPayload === 'string') {\n bytesContentType = 'text/plain';\n bytesPayload = utf8ToBytes(itemPayload);\n }\n else if (itemPayload instanceof Uint8Array) {\n bytesContentType = typeof itemHeader.content_type === 'string'\n ? itemHeader.content_type\n : 'application/octet-stream';\n bytesPayload = [...itemPayload];\n }\n else {\n bytesContentType = 'application/json';\n bytesPayload = utf8ToBytes(JSON.stringify(itemPayload));\n }\n // Content type is not inside BaseEnvelopeItemHeaders.\n itemHeader.content_type = bytesContentType;\n itemHeader.length = bytesPayload.length;\n const serializedItemHeader = JSON.stringify(itemHeader);\n envelopeBytes.push(...utf8ToBytes(serializedItemHeader));\n envelopeBytes.push(EOL);\n envelopeBytes = envelopeBytes.concat(bytesPayload);\n envelopeBytes.push(EOL);\n }\n let transportStatusCode = 200;\n yield SentryCapacitor.captureEnvelope({ envelope: envelopeBytes })\n .then(_ => _ // We only want to know if it failed.\n , failed => {\n logger.error('Failed to capture Envelope: ', failed);\n transportStatusCode = 500;\n });\n return { statusCode: transportStatusCode };\n });\n },\n /**\n * Starts native with the provided options\n * @param options CapacitorOptions\n */\n initNativeSdk(options) {\n return __awaiter(this, void 0, void 0, function* () {\n if (!options.dsn) {\n logger.warn('Warning: No DSN was provided. The Sentry SDK will be disabled. Native SDK will also not be initalized.');\n return false;\n }\n if (!options.enableNative) {\n if (options.enableNativeNagger) {\n logger.warn('Note: Native Sentry SDK is disabled.');\n }\n this.enableNative = false;\n return false;\n }\n if (!this.isNativeClientAvailable()) {\n throw this._NativeClientError;\n }\n // filter out all options that would crash native\n const filteredOptions = FilterNativeOptions(options);\n return SentryCapacitor.initNativeSdk({ options: filteredOptions });\n });\n },\n /**\n * Fetches the device contexts. Not used on Android.\n */\n fetchNativeDeviceContexts() {\n return __awaiter(this, void 0, void 0, function* () {\n if (!this.enableNative) {\n throw this._DisabledNativeError;\n }\n if (!this.isNativeClientAvailable()) {\n throw this._NativeClientError;\n }\n if (this.platform !== 'ios') {\n // Only ios uses deviceContexts, return an empty object.\n return {};\n }\n return SentryCapacitor.fetchNativeDeviceContexts();\n });\n },\n /**\n * Fetches the release from native\n */\n fetchNativeRelease() {\n return __awaiter(this, void 0, void 0, function* () {\n if (!this.enableNative) {\n throw this._DisabledNativeError;\n }\n return SentryCapacitor.fetchNativeRelease();\n });\n },\n fetchNativeSdkInfo() {\n return __awaiter(this, void 0, void 0, function* () {\n if (!this.enableNative) {\n throw this._DisabledNativeError;\n }\n return SentryCapacitor.fetchNativeSdkInfo();\n });\n },\n /**\n * Triggers a native crash.\n * Use this only for testing purposes.\n */\n crash() {\n if (!this.enableNative) {\n return;\n }\n if (!this.isNativeClientAvailable()) {\n throw this._NativeClientError;\n }\n SentryCapacitor.crash();\n },\n /**\n * Sets the user in the native scope.\n * Passing null clears the user.\n * @param key string\n * @param value string\n */\n setUser(user) {\n if (!this.enableNative) {\n return;\n }\n if (!this.isNativeClientAvailable()) {\n throw this._NativeClientError;\n }\n // separate and serialze all non-default user keys.\n let defaultUserKeys = null;\n let otherUserKeys = null;\n if (user) {\n const { id, ip_address, email, username } = user, otherKeys = __rest(user, [\"id\", \"ip_address\", \"email\", \"username\"]);\n defaultUserKeys = dropUndefinedKeys(this._serializeObject({\n email,\n id,\n ip_address,\n username,\n }));\n otherUserKeys = dropUndefinedKeys(this._serializeObject(otherKeys));\n }\n SentryCapacitor.setUser({ defaultUserKeys, otherUserKeys });\n },\n /**\n * Sets a tag in the native module.\n * @param key string\n * @param value string\n */\n setTag(key, value) {\n if (!this.enableNative) {\n return;\n }\n if (!this.isNativeClientAvailable()) {\n throw this._NativeClientError;\n }\n const stringifiedValue = typeof value === 'string' ? value : JSON.stringify(value);\n SentryCapacitor.setTag({ key, value: stringifiedValue });\n },\n /**\n * Sets an extra in the native scope, will stringify\n * extra value if it isn't already a string.\n * @param key string\n * @param extra any\n */\n setExtra(key, extra) {\n if (!this.enableNative) {\n return;\n }\n if (!this.isNativeClientAvailable()) {\n throw this._NativeClientError;\n }\n // we stringify the extra as native only takes in strings.\n const stringifiedValue = typeof extra === 'string' ? extra : JSON.stringify(extra);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n SentryCapacitor.setExtra({ key, value: stringifiedValue });\n },\n /**\n * Adds breadcrumb to the native scope.\n * @param breadcrumb Breadcrumb\n */\n addBreadcrumb(breadcrumb) {\n if (!this.enableNative) {\n return;\n }\n if (!this.isNativeClientAvailable()) {\n throw this._NativeClientError;\n }\n SentryCapacitor.addBreadcrumb(Object.assign(Object.assign({}, breadcrumb), { \n // Process and convert deprecated levels\n level: breadcrumb.level\n ? this._processLevel(breadcrumb.level)\n : undefined, data: breadcrumb.data\n ? convertToNormalizedObject(breadcrumb.data)\n : undefined }));\n },\n /**\n * Clears breadcrumbs on the native scope.\n */\n clearBreadcrumbs() {\n if (!this.enableNative) {\n return;\n }\n if (!this.isNativeClientAvailable()) {\n throw this._NativeClientError;\n }\n SentryCapacitor.clearBreadcrumbs();\n },\n /**\n * Sets context on the native scope. Not implemented in Android yet.\n * @param key string\n * @param context key-value map\n */\n setContext(key, context) {\n if (!this.enableNative) {\n return;\n }\n if (!this.isNativeClientAvailable()) {\n throw this._NativeClientError;\n }\n if (this.platform === 'android') {\n // setContext not available on the Android SDK yet.\n this.setExtra(key, context);\n }\n else {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n SentryCapacitor.setContext({\n key,\n value: context !== null ? this._serializeObject(context) : null,\n });\n }\n },\n /**\n * Gets the event from envelopeItem and applies the level filter to the selected event.\n * @param data An envelope item containing the event.\n * @returns The event from envelopeItem or undefined.\n */\n _processItem(item) {\n if (NATIVE.platform === 'android') {\n const [itemHeader, itemPayload] = item;\n if (itemHeader.type == 'event' || itemHeader.type == 'transaction') {\n const event = this._processLevels(itemPayload);\n if ('message' in event) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore Android still uses the old message object, without this the serialization of events will break.\n event.message = { message: event.message };\n }\n /*\n We do this to avoid duplicate breadcrumbs on Android as sentry-android applies the breadcrumbs\n from the native scope onto every envelope sent through it. This scope will contain the breadcrumbs\n sent through the scope sync feature. This causes duplicate breadcrumbs.\n We then remove the breadcrumbs in all cases but if it is handled == false,\n this is a signal that the app would crash and android would lose the breadcrumbs by the time the app is restarted to read\n the envelope.\n Since unhandled errors from Javascript are not going to crash the App, we can't rely on the\n handled flag for filtering breadcrumbs.\n */\n if (event.breadcrumbs) {\n event.breadcrumbs = [];\n }\n return [itemHeader, event];\n }\n }\n return item;\n },\n /**\n * Serializes all values of root-level keys into strings.\n * @param data key-value map.\n * @returns An object where all root-level values are strings.\n */\n _serializeObject(data) {\n const serialized = {};\n Object.keys(data).forEach(dataKey => {\n const value = data[dataKey];\n serialized[dataKey] =\n typeof value === 'string' ? value : JSON.stringify(value);\n });\n return serialized;\n },\n /**\n * Convert js severity level in event.level and event.breadcrumbs to more widely supported levels.\n * @param event\n * @returns Event with more widely supported Severity level strings\n */\n _processLevels(event) {\n var _a;\n const processed = Object.assign(Object.assign({}, event), { level: event.level ? this._processLevel(event.level) : undefined, breadcrumbs: (_a = event.breadcrumbs) === null || _a === void 0 ? void 0 : _a.map(breadcrumb => (Object.assign(Object.assign({}, breadcrumb), { level: breadcrumb.level\n ? this._processLevel(breadcrumb.level)\n : undefined }))) });\n return processed;\n },\n /**\n * Convert js severity level which has critical and log to more widely supported levels.\n * @param level\n * @returns More widely supported Severity level strings\n */\n _processLevel(level) {\n if (level == 'log') {\n return 'debug';\n }\n else if (level == 'critical') {\n return 'fatal';\n }\n return level;\n },\n /**\n * Checks whether the SentryCapacitor module is loaded.\n */\n isModuleLoaded() {\n return !!SentryCapacitor;\n },\n /**\n * Checks whether the SentryCapacitor module is loaded and the native client is available\n */\n isNativeClientAvailable() {\n return (this.isModuleLoaded() && Capacitor.isPluginAvailable('SentryCapacitor'));\n },\n _DisabledNativeError: new SentryError('Native is disabled'),\n _NativeClientError: new SentryError(\"Native Client is not available, can't start on native.\"),\n enableNative: true,\n platform: Capacitor.getPlatform(),\n};\n","/**\n * Create a new CapacitorOption without any parameter that could crash the bridge (in short, not being a string, number or boolean).\n * some of the excluded parameters are: Integrations, app, vue, beforeSend, beforeBreadcrumb, integrations, defaultIntegrations, transport, tracesSampler.\n * @param options CapacitorOptions\n */\nexport function FilterNativeOptions(options) {\n var _a;\n return {\n // allowUrls: Only available on the JavaScript Layer.\n attachStacktrace: options.attachStacktrace,\n attachThreads: options.attachThreads,\n debug: options.debug,\n // denyUrls Only available on the JavaScript Layer.\n dist: options.dist,\n dsn: options.dsn,\n enabled: options.enabled,\n enableNdkScopeSync: options.enableNdkScopeSync,\n // eslint-disable-next-line deprecation/deprecation\n enableWatchdogTerminationTracking: (_a = options.enableOutOfMemoryTracking) !== null && _a !== void 0 ? _a : options.enableWatchdogTerminationTracking,\n enableTracing: options.enableTracing,\n environment: options.environment,\n // ignoreErrors: Only available on the JavaScript Layer.\n // ignoreTransactions: Only available on the JavaScript Layer.\n maxBreadcrumbs: options.maxBreadcrumbs,\n // maxValueLength: Only available on the JavaScript Layer.\n release: options.release,\n // replaysOnErrorSampleRate: Only handled on the JavaScript Layer.\n // replaysSessionSampleRate: Only handled on the JavaScript Layer.\n sampleRate: options.sampleRate,\n sendClientReports: options.sendClientReports,\n sendDefaultPii: options.sendDefaultPii,\n sessionTrackingIntervalMillis: options.sessionTrackingIntervalMillis,\n tracesSampleRate: options.tracesSampleRate,\n // tunnel: options.tunnel: Only handled on the JavaScript Layer.\n };\n}\n","import { __awaiter } from \"tslib\";\nimport { logger } from '@sentry/utils';\nimport { SDK_NAME, SDK_VERSION } from '../version';\nimport { NATIVE } from '../wrapper';\n/** Default SdkInfo instrumentation */\nexport class SdkInfo {\n constructor() {\n /**\n * @inheritDoc\n */\n this.name = SdkInfo.id;\n this._nativeSdkPackage = null;\n }\n /**\n * @inheritDoc\n */\n setupOnce(addGlobalEventProcessor) {\n addGlobalEventProcessor((event) => __awaiter(this, void 0, void 0, function* () {\n // The native SDK info package here is only used on iOS as `beforeSend` is not called on `captureEnvelope`.\n // this._nativeSdkInfo should be defined a following time so this call won't always be awaited.\n if (NATIVE.platform === 'ios' && this._nativeSdkPackage === null) {\n try {\n this._nativeSdkPackage = yield NATIVE.fetchNativeSdkInfo();\n }\n catch (_) {\n // If this fails, go ahead as usual as we would rather have the event be sent with a package missing.\n logger.warn('[SdkInfo] Native SDK Info retrieval failed...something could be wrong with your Sentry installation.');\n }\n }\n event.platform = event.platform || 'javascript';\n event.sdk = event.sdk || {};\n event.sdk.name = event.sdk.name || SDK_NAME;\n event.sdk.version = event.sdk.version || SDK_VERSION;\n event.sdk.packages = [\n // default packages are added by baseclient and should not be added here\n ...(event.sdk.packages || []),\n ...((this._nativeSdkPackage && [this._nativeSdkPackage]) || []),\n {\n name: 'npm:@sentry/capacitor',\n version: SDK_VERSION,\n },\n ];\n return event;\n }));\n }\n}\n/**\n * @inheritDoc\n */\nSdkInfo.id = 'SdkInfo';\n","export const SDK_PACKAGE_NAME = 'npm:@sentry/capacitor';\nexport const SDK_NAME = 'sentry.javascript.capacitor';\nexport const SDK_VERSION = '0.15.0';\n","import { __awaiter } from \"tslib\";\nimport { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { NATIVE } from '../wrapper';\n/** Release integration responsible to load release from file. */\nexport class Release {\n constructor() {\n /**\n * @inheritDoc\n */\n this.name = Release.id;\n }\n /**\n * @inheritDoc\n */\n setupOnce() {\n addGlobalEventProcessor((event) => __awaiter(this, void 0, void 0, function* () {\n var _a;\n const self = getCurrentHub().getIntegration(Release);\n if (!self) {\n return event;\n }\n const options = (_a = getCurrentHub().getClient()) === null || _a === void 0 ? void 0 : _a.getOptions();\n /*\n Check for the release and dist in the options passed on init.\n Otherwise, we get the release and dist from the native package.\n */\n if (typeof (options === null || options === void 0 ? void 0 : options.release) === 'string') {\n event.release = options.release;\n }\n if (typeof (options === null || options === void 0 ? void 0 : options.dist) === 'string') {\n event.dist = options.dist;\n }\n if (event.release && event.dist) {\n return event;\n }\n try {\n const nativeRelease = yield NATIVE.fetchNativeRelease();\n if (nativeRelease) {\n if (!event.release) {\n event.release = `${nativeRelease.id}@${nativeRelease.version}+${nativeRelease.build}`;\n }\n if (!event.dist) {\n event.dist = `${nativeRelease.build}`;\n }\n }\n }\n catch (_Oo) {\n // Something went wrong, we just continue\n }\n return event;\n }));\n }\n}\n/**\n * @inheritDoc\n */\nRelease.id = 'Release';\n","import { __awaiter } from \"tslib\";\nimport { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';\nimport { logger } from '@sentry/utils';\nimport { NATIVE } from '../wrapper';\n/** Load device context from native. */\nexport class DeviceContext {\n constructor() {\n /**\n * @inheritDoc\n */\n this.name = DeviceContext.id;\n }\n /**\n * @inheritDoc\n */\n setupOnce() {\n addGlobalEventProcessor((event) => __awaiter(this, void 0, void 0, function* () {\n const self = getCurrentHub().getIntegration(DeviceContext);\n if (!self) {\n return event;\n }\n try {\n const contexts = yield NATIVE.fetchNativeDeviceContexts();\n const context = contexts['context'];\n event.contexts = Object.assign(Object.assign({}, context), event.contexts);\n if ('user' in contexts) {\n const user = contexts['user'];\n if (!event.user) {\n event.user = Object.assign({}, user);\n }\n }\n }\n catch (e) {\n logger.log(`Failed to get device context from native: ${e}`);\n }\n return event;\n }));\n }\n}\n/**\n * @inheritDoc\n */\nDeviceContext.id = 'DeviceContext';\n","// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript\n// https://github.com/calvinmetcalf/rollup-plugin-node-builtins/blob/63ab8aacd013767445ca299e468d9a60a95328d7/src/es6/path.js\n//\n// Copyright Joyent, Inc.and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// 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 permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n/** JSDoc */\nfunction normalizeArray(parts, allowAboveRoot) {\n // if the path tries to go above the root, `up` ends up > 0\n let up = 0;\n for (let i = parts.length - 1; i >= 0; i--) {\n const last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nconst splitPathRe = /^(\\S+:\\\\|\\/?)([\\s\\S]*?)((?:\\.{1,2}|[^/\\\\]+?|)(\\.[^./\\\\]*|))(?:[/\\\\]*)$/;\n/** JSDoc */\nfunction splitPath(filename) {\n // Truncate files names greater than 1024 characters to avoid regex dos\n // https://github.com/getsentry/sentry-javascript/pull/8737#discussion_r1285719172\n const truncated = filename.length > 1024 ? `${filename.slice(-1024)}` : filename;\n const parts = splitPathRe.exec(truncated);\n return parts ? parts.slice(1) : [];\n}\n\n// path.resolve([from ...], to)\n// posix version\n/** JSDoc */\nfunction resolve(...args) {\n let resolvedPath = '';\n let resolvedAbsolute = false;\n\n for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n const path = i >= 0 ? args[i] : '/';\n\n // Skip empty entries\n if (!path) {\n continue;\n }\n\n resolvedPath = `${path}/${resolvedPath}`;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(\n resolvedPath.split('/').filter(p => !!p),\n !resolvedAbsolute,\n ).join('/');\n\n return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';\n}\n\n/** JSDoc */\nfunction trim(arr) {\n let start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') {\n break;\n }\n }\n\n let end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') {\n break;\n }\n }\n\n if (start > end) {\n return [];\n }\n return arr.slice(start, end - start + 1);\n}\n\n// path.relative(from, to)\n// posix version\n/** JSDoc */\nfunction relative(from, to) {\n /* eslint-disable no-param-reassign */\n from = resolve(from).slice(1);\n to = resolve(to).slice(1);\n /* eslint-enable no-param-reassign */\n\n const fromParts = trim(from.split('/'));\n const toParts = trim(to.split('/'));\n\n const length = Math.min(fromParts.length, toParts.length);\n let samePartsLength = length;\n for (let i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n let outputParts = [];\n for (let i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n}\n\n// path.normalize(path)\n// posix version\n/** JSDoc */\nfunction normalizePath(path) {\n const isPathAbsolute = isAbsolute(path);\n const trailingSlash = path.slice(-1) === '/';\n\n // Normalize the path\n let normalizedPath = normalizeArray(\n path.split('/').filter(p => !!p),\n !isPathAbsolute,\n ).join('/');\n\n if (!normalizedPath && !isPathAbsolute) {\n normalizedPath = '.';\n }\n if (normalizedPath && trailingSlash) {\n normalizedPath += '/';\n }\n\n return (isPathAbsolute ? '/' : '') + normalizedPath;\n}\n\n// posix version\n/** JSDoc */\nfunction isAbsolute(path) {\n return path.charAt(0) === '/';\n}\n\n// posix version\n/** JSDoc */\nfunction join(...args) {\n return normalizePath(args.join('/'));\n}\n\n/** JSDoc */\nfunction dirname(path) {\n const result = splitPath(path);\n const root = result[0];\n let dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.slice(0, dir.length - 1);\n }\n\n return root + dir;\n}\n\n/** JSDoc */\nfunction basename(path, ext) {\n let f = splitPath(path)[2];\n if (ext && f.slice(ext.length * -1) === ext) {\n f = f.slice(0, f.length - ext.length);\n }\n return f;\n}\n\nexport { basename, dirname, isAbsolute, join, normalizePath, relative, resolve };\n","import { relative, basename } from '@sentry/utils';\n\n/** Rewrite event frames paths */\nclass RewriteFrames {\n /**\n * @inheritDoc\n */\n static __initStatic() {this.id = 'RewriteFrames';}\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n constructor(options = {}) {RewriteFrames.prototype.__init.call(this);\n this.name = RewriteFrames.id;\n\n if (options.root) {\n this._root = options.root;\n }\n this._prefix = options.prefix || 'app:///';\n if (options.iteratee) {\n this._iteratee = options.iteratee;\n }\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(_addGlobaleventProcessor, _getCurrentHub) {\n // noop\n }\n\n /** @inheritDoc */\n processEvent(event) {\n return this.process(event);\n }\n\n /**\n * TODO (v8): Make this private/internal\n */\n process(originalEvent) {\n let processedEvent = originalEvent;\n\n if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) {\n processedEvent = this._processExceptionsEvent(processedEvent);\n }\n\n return processedEvent;\n }\n\n /**\n * @inheritDoc\n */\n __init() {this._iteratee = (frame) => {\n if (!frame.filename) {\n return frame;\n }\n // Determine if this is a Windows frame by checking for a Windows-style prefix such as `C:\\`\n const isWindowsFrame =\n /^[a-zA-Z]:\\\\/.test(frame.filename) ||\n // or the presence of a backslash without a forward slash (which are not allowed on Windows)\n (frame.filename.includes('\\\\') && !frame.filename.includes('/'));\n // Check if the frame filename begins with `/`\n const startsWithSlash = /^\\//.test(frame.filename);\n if (isWindowsFrame || startsWithSlash) {\n const filename = isWindowsFrame\n ? frame.filename\n .replace(/^[a-zA-Z]:/, '') // remove Windows-style prefix\n .replace(/\\\\/g, '/') // replace all `\\\\` instances with `/`\n : frame.filename;\n const base = this._root ? relative(this._root, filename) : basename(filename);\n frame.filename = `${this._prefix}${base}`;\n }\n return frame;\n };}\n\n /** JSDoc */\n _processExceptionsEvent(event) {\n try {\n return {\n ...event,\n exception: {\n ...event.exception,\n // The check for this is performed inside `process` call itself, safe to skip here\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n values: event.exception.values.map(value => ({\n ...value,\n ...(value.stacktrace && { stacktrace: this._processStacktrace(value.stacktrace) }),\n })),\n },\n };\n } catch (_oO) {\n return event;\n }\n }\n\n /** JSDoc */\n _processStacktrace(stacktrace) {\n return {\n ...stacktrace,\n frames: stacktrace && stacktrace.frames && stacktrace.frames.map(f => this._iteratee(f)),\n };\n }\n} RewriteFrames.__initStatic();\n\nexport { RewriteFrames };\n","import { RewriteFrames } from '@sentry/integrations';\nimport { getCurrentServerUrl } from '../utils/webViewUrl';\n/**\n * Create Capacitor default rewrite frames integration\n * which appends app:// to the beginning of the filename\n * and removes the local server url prefixes.\n */\nexport function createCapacitorRewriteFrames() {\n const rewriteFrames = new RewriteFrames({\n iteratee: (frame) => {\n if (frame.filename) {\n const isReachableHost = /^https?:\\/\\//.test(frame.filename);\n const serverUrl = getCurrentServerUrl();\n if (serverUrl) {\n frame.filename = frame.filename.replace(serverUrl, '');\n }\n else {\n frame.filename = frame.filename.replace(/^https?:\\/\\/localhost(:\\d+)?/, '')\n .replace(/^capacitor:\\/\\/localhost(:\\d+)?/, '');\n }\n frame.filename = frame.filename.replace(/^ng:\\/\\//, '');\n const isNativeFrame = frame.filename === '[native code]' || frame.filename === 'native';\n if (!isNativeFrame) {\n // We don't need to use `app://` protocol for http(s) based hosts\n if (!isReachableHost) {\n // We always want to have a triple slash\n const filename = frame.filename.startsWith('/') ? frame.filename : `/${frame.filename}`;\n const appPrefix = 'app://';\n frame.filename = `${appPrefix}${filename}`;\n }\n frame.in_app = true;\n }\n else {\n frame.in_app = false;\n }\n }\n return frame;\n }\n });\n rewriteFrames.name = 'Capacitor RewriteFrames';\n return rewriteFrames;\n}\n",";\n/**\n * Return the current webview url if found.\n */\nexport function getCurrentServerUrl() {\n if (typeof self !== 'undefined') {\n return self.WEBVIEW_SERVER_URL;\n }\n return undefined;\n}\n","import { Scope } from '@sentry/core';\nimport { convertToNormalizedObject } from './utils/normalize';\nimport { NATIVE } from './wrapper';\n/**\n * Extends the scope methods to set scope on the Native SDKs\n */\nexport class CapacitorScope extends Scope {\n /**\n * @inheritDoc\n */\n setUser(user) {\n NATIVE.setUser(user);\n return super.setUser(user);\n }\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n /* eslint-disable no-console */\n NATIVE.setTag(key, value);\n return super.setTag(key, value);\n }\n /**\n * @inheritDoc\n */\n setTags(tags) {\n /* eslint-disable no-console */\n // As native only has setTag, we just loop through each tag key.\n Object.keys(tags).forEach(key => {\n NATIVE.setTag(key, tags[key]);\n });\n return super.setTags(tags);\n }\n /**\n * @inheritDoc\n */\n setExtras(extras) {\n Object.keys(extras).forEach(key => {\n NATIVE.setExtra(key, extras[key]);\n });\n return super.setExtras(extras);\n }\n /**\n * @inheritDoc\n */\n setExtra(key, extra) {\n NATIVE.setExtra(key, extra);\n return super.setExtra(key, extra);\n }\n /**\n * @inheritDoc\n */\n setContext(key, context) {\n NATIVE.setContext(key, context);\n return super.setContext(key, context);\n }\n /**\n * @inheritDoc\n */\n addBreadcrumb(breadcrumb, maxBreadcrumbs) {\n const mergedBreadcrumb = Object.assign(Object.assign({}, breadcrumb), { data: breadcrumb.data ? convertToNormalizedObject(breadcrumb.data) : undefined });\n NATIVE.addBreadcrumb(mergedBreadcrumb);\n return super.addBreadcrumb(mergedBreadcrumb, maxBreadcrumbs);\n }\n /**\n * @inheritDoc\n */\n clearBreadcrumbs() {\n NATIVE.clearBreadcrumbs();\n return super.clearBreadcrumbs();\n }\n}\n","import { makePromiseBuffer } from '@sentry/utils';\nimport { NATIVE } from '../wrapper';\nexport const DEFAULT_BUFFER_SIZE = 30;\n/** Native Transport class implementation */\nexport class NativeTransport {\n constructor(options = {}) {\n this._buffer = makePromiseBuffer(options.bufferSize || DEFAULT_BUFFER_SIZE);\n }\n /**\n * Sends the envelope to the Store endpoint in Sentry.\n *\n * @param envelope Envelope that should be sent to Sentry.\n */\n send(envelope) {\n return this._buffer.add(() => NATIVE.sendEnvelope(envelope));\n }\n /**\n * Wait for all envelopes to be sent or the timeout to expire, whichever comes first.\n *\n * @param timeout Maximum time in ms the transport should wait for envelopes to be flushed. Omitting this parameter will\n * cause the transport 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 return this._buffer.drain(timeout);\n }\n}\n/**\n * Creates a Native Transport.\n */\nexport function makeNativeTransport(options = {}) {\n return new NativeTransport(options);\n}\n/**\n * Creates a Native Transport factory if the native transport is available.\n */\nexport function makeNativeTransportFactory({ enableNative, }) {\n if (enableNative && NATIVE.isNativeClientAvailable()) {\n return makeNativeTransport;\n }\n return null;\n}\n","import { isString } from './is.js';\nimport { logger } from './logger.js';\n\nconst BAGGAGE_HEADER_NAME = 'baggage';\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 if (!isString(baggageHeader) && !Array.isArray(baggageHeader)) {\n return undefined;\n }\n\n // Intermediary object to store baggage key value pairs of incoming baggage headers on.\n // It is later used to read Sentry-DSC-values from.\n let baggageObject = {};\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 baggageObject = baggageHeader.reduce((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n return {\n ...acc,\n ...currBaggageObject,\n };\n }, {});\n } else {\n // Return undefined if baggage header is an empty string (technically an empty baggage header is not spec conform but\n // this is how we choose to handle it)\n if (!baggageHeader) {\n return undefined;\n }\n\n baggageObject = baggageHeaderToObject(baggageHeader);\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 * 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 acc[key] = value;\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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\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 { BAGGAGE_HEADER_NAME, MAX_BAGGAGE_STRING_LENGTH, SENTRY_BAGGAGE_KEY_PREFIX, SENTRY_BAGGAGE_KEY_PREFIX_REGEX, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader };\n","import { baggageHeaderToDynamicSamplingContext } from './baggage.js';\nimport { uuid4 } from './misc.js';\n\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 tracing context from incoming headers.\n */\nfunction tracingContextFromHeaders(\n sentryTrace,\n baggage,\n)\n\n {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n const { traceId, parentSpanId, parentSampled } = traceparentData || {};\n\n const propagationContext = {\n traceId: traceId || uuid4(),\n spanId: uuid4().substring(16),\n sampled: parentSampled,\n };\n\n if (parentSpanId) {\n propagationContext.parentSpanId = parentSpanId;\n }\n\n if (dynamicSamplingContext) {\n propagationContext.dsc = dynamicSamplingContext ;\n }\n\n return {\n traceparentData,\n dynamicSamplingContext,\n propagationContext,\n };\n}\n\n/**\n * Create sentry-trace header from span context values.\n */\nfunction generateSentryTraceHeader(\n traceId = uuid4(),\n spanId = uuid4().substring(16),\n sampled,\n) {\n let sampledString = '';\n if (sampled !== undefined) {\n sampledString = sampled ? '-1' : '-0';\n }\n return `${traceId}-${spanId}${sampledString}`;\n}\n\nexport { TRACEPARENT_REGEXP, extractTraceparentData, generateSentryTraceHeader, tracingContextFromHeaders };\n","import { uuid4, timestampInSeconds, logger, generateSentryTraceHeader, dropUndefinedKeys } from '@sentry/utils';\n\n/**\n * Keeps track of finished spans for a given transaction\n * @internal\n * @hideconstructor\n * @hidden\n */\nclass SpanRecorder {\n\n constructor(maxlen = 1000) {\n this._maxlen = maxlen;\n this.spans = [];\n }\n\n /**\n * This is just so that we don't run out of memory while recording a lot\n * of spans. At some point we just stop and flush out the start of the\n * trace tree (i.e.the first n spans with the smallest\n * start_timestamp).\n */\n add(span) {\n if (this.spans.length > this._maxlen) {\n span.spanRecorder = undefined;\n } else {\n this.spans.push(span);\n }\n }\n}\n\n/**\n * Span contains all data about a span\n */\nclass Span {\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * Internal keeper of the status\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * Timestamp in seconds when the span was created.\n */\n\n /**\n * Timestamp in seconds when the span ended.\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n /**\n * List of spans that were finalized\n */\n\n /**\n * @inheritDoc\n */\n\n /**\n * The instrumenter that created this span.\n */\n\n /**\n * The origin of the span, giving context about what created the span.\n */\n\n /**\n * You should never call the constructor manually, always use `Sentry.startTransaction()`\n * or call `startChild()` on an existing span.\n * @internal\n * @hideconstructor\n * @hidden\n */\n constructor(spanContext = {}) {\n this.traceId = spanContext.traceId || uuid4();\n this.spanId = spanContext.spanId || uuid4().substring(16);\n this.startTimestamp = spanContext.startTimestamp || timestampInSeconds();\n this.tags = spanContext.tags || {};\n this.data = spanContext.data || {};\n this.instrumenter = spanContext.instrumenter || 'sentry';\n this.origin = spanContext.origin || 'manual';\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.op) {\n this.op = spanContext.op;\n }\n if (spanContext.description) {\n this.description = spanContext.description;\n }\n if (spanContext.name) {\n this.description = spanContext.name;\n }\n if (spanContext.status) {\n this.status = spanContext.status;\n }\n if (spanContext.endTimestamp) {\n this.endTimestamp = spanContext.endTimestamp;\n }\n }\n\n /** An alias for `description` of the Span. */\n get name() {\n return this.description || '';\n }\n /** Update the name of the span. */\n set name(name) {\n this.setName(name);\n }\n\n /**\n * @inheritDoc\n */\n startChild(\n spanContext,\n ) {\n const childSpan = new Span({\n ...spanContext,\n parentSpanId: this.spanId,\n sampled: this.sampled,\n traceId: this.traceId,\n });\n\n childSpan.spanRecorder = this.spanRecorder;\n if (childSpan.spanRecorder) {\n childSpan.spanRecorder.add(childSpan);\n }\n\n childSpan.transaction = this.transaction;\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && childSpan.transaction) {\n const opStr = (spanContext && spanContext.op) || '< unknown op >';\n const nameStr = childSpan.transaction.name || '< unknown name >';\n const idStr = childSpan.transaction.spanId;\n\n const logMessage = `[Tracing] Starting '${opStr}' span on transaction '${nameStr}' (${idStr}).`;\n childSpan.transaction.metadata.spanMetadata[childSpan.spanId] = { logMessage };\n logger.log(logMessage);\n }\n\n return childSpan;\n }\n\n /**\n * @inheritDoc\n */\n setTag(key, value) {\n this.tags = { ...this.tags, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types\n setData(key, value) {\n this.data = { ...this.data, [key]: value };\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setStatus(value) {\n this.status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setHttpStatus(httpStatus) {\n this.setTag('http.status_code', String(httpStatus));\n this.setData('http.response.status_code', httpStatus);\n const spanStatus = spanStatusfromHttpCode(httpStatus);\n if (spanStatus !== 'unknown_error') {\n this.setStatus(spanStatus);\n }\n return this;\n }\n\n /**\n * @inheritDoc\n */\n setName(name) {\n this.description = name;\n }\n\n /**\n * @inheritDoc\n */\n isSuccess() {\n return this.status === 'ok';\n }\n\n /**\n * @inheritDoc\n */\n finish(endTimestamp) {\n if (\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n // Don't call this for transactions\n this.transaction &&\n this.transaction.spanId !== this.spanId\n ) {\n const { logMessage } = this.transaction.metadata.spanMetadata[this.spanId];\n if (logMessage) {\n logger.log((logMessage ).replace('Starting', 'Finishing'));\n }\n }\n\n this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampInSeconds();\n }\n\n /**\n * @inheritDoc\n */\n toTraceparent() {\n return generateSentryTraceHeader(this.traceId, this.spanId, this.sampled);\n }\n\n /**\n * @inheritDoc\n */\n toContext() {\n return dropUndefinedKeys({\n data: this.data,\n description: this.description,\n endTimestamp: this.endTimestamp,\n op: this.op,\n parentSpanId: this.parentSpanId,\n sampled: this.sampled,\n spanId: this.spanId,\n startTimestamp: this.startTimestamp,\n status: this.status,\n tags: this.tags,\n traceId: this.traceId,\n });\n }\n\n /**\n * @inheritDoc\n */\n updateWithContext(spanContext) {\n this.data = spanContext.data || {};\n this.description = spanContext.description;\n this.endTimestamp = spanContext.endTimestamp;\n this.op = spanContext.op;\n this.parentSpanId = spanContext.parentSpanId;\n this.sampled = spanContext.sampled;\n this.spanId = spanContext.spanId || this.spanId;\n this.startTimestamp = spanContext.startTimestamp || this.startTimestamp;\n this.status = spanContext.status;\n this.tags = spanContext.tags || {};\n this.traceId = spanContext.traceId || this.traceId;\n\n return this;\n }\n\n /**\n * @inheritDoc\n */\n getTraceContext() {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n trace_id: this.traceId,\n origin: this.origin,\n });\n }\n\n /**\n * @inheritDoc\n */\n toJSON()\n\n {\n return dropUndefinedKeys({\n data: Object.keys(this.data).length > 0 ? this.data : undefined,\n description: this.description,\n op: this.op,\n parent_span_id: this.parentSpanId,\n span_id: this.spanId,\n start_timestamp: this.startTimestamp,\n status: this.status,\n tags: Object.keys(this.tags).length > 0 ? this.tags : undefined,\n timestamp: this.endTimestamp,\n trace_id: this.traceId,\n origin: this.origin,\n });\n }\n}\n\n/**\n * Converts a HTTP status code into a {@link SpanStatusType}.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or unknown_error.\n */\nfunction spanStatusfromHttpCode(httpStatus) {\n if (httpStatus < 400 && httpStatus >= 100) {\n return 'ok';\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return 'unauthenticated';\n case 403:\n return 'permission_denied';\n case 404:\n return 'not_found';\n case 409:\n return 'already_exists';\n case 413:\n return 'failed_precondition';\n case 429:\n return 'resource_exhausted';\n default:\n return 'invalid_argument';\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return 'unimplemented';\n case 503:\n return 'unavailable';\n case 504:\n return 'deadline_exceeded';\n default:\n return 'internal_error';\n }\n }\n\n return 'unknown_error';\n}\n\nexport { Span, SpanRecorder, spanStatusfromHttpCode };\n","import { dropUndefinedKeys, logger } from '@sentry/utils';\nimport { getCurrentHub } from '../hub.js';\nimport { getDynamicSamplingContextFromClient } from './dynamicSamplingContext.js';\nimport { Span, SpanRecorder } from './span.js';\n\n/** JSDoc */\nclass Transaction extends Span {\n\n /**\n * The reference to the current hub.\n */\n\n /**\n * This constructor should never be called manually. Those instrumenting tracing should use\n * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.\n * @internal\n * @hideconstructor\n * @hidden\n */\n constructor(transactionContext, hub) {\n super(transactionContext);\n // We need to delete description since it's set by the Span class constructor\n // but not needed for transactions.\n delete this.description;\n\n this._measurements = {};\n this._contexts = {};\n\n this._hub = hub || getCurrentHub();\n\n this._name = transactionContext.name || '';\n\n this.metadata = {\n source: 'custom',\n ...transactionContext.metadata,\n spanMetadata: {},\n };\n\n this._trimEnd = transactionContext.trimEnd;\n\n // this is because transactions are also spans, and spans have a transaction pointer\n this.transaction = this;\n\n // If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means\n // there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)\n const incomingDynamicSamplingContext = this.metadata.dynamicSamplingContext;\n if (incomingDynamicSamplingContext) {\n // We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`\n this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };\n }\n }\n\n /** Getter for `name` property */\n get name() {\n return this._name;\n }\n\n /** Setter for `name` property, which also sets `source` as custom */\n set name(newName) {\n this.setName(newName);\n }\n\n /**\n * JSDoc\n */\n setName(name, source = 'custom') {\n this._name = name;\n this.metadata.source = source;\n }\n\n /**\n * Attaches SpanRecorder to the span itself\n * @param maxlen maximum number of spans that can be recorded\n */\n initSpanRecorder(maxlen = 1000) {\n if (!this.spanRecorder) {\n this.spanRecorder = new SpanRecorder(maxlen);\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * @inheritDoc\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\n /**\n * @inheritDoc\n */\n setMeasurement(name, value, unit = '') {\n this._measurements[name] = { value, unit };\n }\n\n /**\n * @inheritDoc\n */\n setMetadata(newMetadata) {\n this.metadata = { ...this.metadata, ...newMetadata };\n }\n\n /**\n * @inheritDoc\n */\n finish(endTimestamp) {\n const transaction = this._finishTransaction(endTimestamp);\n if (!transaction) {\n return undefined;\n }\n return this._hub.captureEvent(transaction);\n }\n\n /**\n * @inheritDoc\n */\n toContext() {\n const spanContext = super.toContext();\n\n return dropUndefinedKeys({\n ...spanContext,\n name: this.name,\n trimEnd: this._trimEnd,\n });\n }\n\n /**\n * @inheritDoc\n */\n updateWithContext(transactionContext) {\n super.updateWithContext(transactionContext);\n\n this.name = transactionContext.name || '';\n\n this._trimEnd = transactionContext.trimEnd;\n\n return this;\n }\n\n /**\n * @inheritdoc\n *\n * @experimental\n */\n getDynamicSamplingContext() {\n if (this._frozenDynamicSamplingContext) {\n return this._frozenDynamicSamplingContext;\n }\n\n const hub = this._hub || getCurrentHub();\n const client = hub.getClient();\n\n if (!client) return {};\n\n const scope = hub.getScope();\n const dsc = getDynamicSamplingContextFromClient(this.traceId, client, scope);\n\n const maybeSampleRate = this.metadata.sampleRate;\n if (maybeSampleRate !== undefined) {\n dsc.sample_rate = `${maybeSampleRate}`;\n }\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 = this.metadata.source;\n if (source && source !== 'url') {\n dsc.transaction = this.name;\n }\n\n if (this.sampled !== undefined) {\n dsc.sampled = String(this.sampled);\n }\n\n // Uncomment if we want to make DSC immutable\n // this._frozenDynamicSamplingContext = dsc;\n\n return dsc;\n }\n\n /**\n * Override the current hub with a new one.\n * Used if you want another hub to finish the transaction.\n *\n * @internal\n */\n setHub(hub) {\n this._hub = hub;\n }\n\n /**\n * Finish the transaction & prepare the event to send to Sentry.\n */\n _finishTransaction(endTimestamp) {\n // This transaction is already finished, so we should not flush it again.\n if (this.endTimestamp !== undefined) {\n return undefined;\n }\n\n if (!this.name) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Transaction has no name, falling back to ``.');\n this.name = '';\n }\n\n // just sets the end timestamp\n super.finish(endTimestamp);\n\n const client = this._hub.getClient();\n if (client && client.emit) {\n client.emit('finishTransaction', this);\n }\n\n if (this.sampled !== true) {\n // At this point if `sampled !== true` we want to discard the transaction.\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');\n\n if (client) {\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n return undefined;\n }\n\n const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : [];\n\n if (this._trimEnd && finishedSpans.length > 0) {\n this.endTimestamp = finishedSpans.reduce((prev, current) => {\n if (prev.endTimestamp && current.endTimestamp) {\n return prev.endTimestamp > current.endTimestamp ? prev : current;\n }\n return prev;\n }).endTimestamp;\n }\n\n const metadata = this.metadata;\n\n const transaction = {\n contexts: {\n ...this._contexts,\n // We don't want to override trace context\n trace: this.getTraceContext(),\n },\n spans: finishedSpans,\n start_timestamp: this.startTimestamp,\n tags: this.tags,\n timestamp: this.endTimestamp,\n transaction: this.name,\n type: 'transaction',\n sdkProcessingMetadata: {\n ...metadata,\n dynamicSamplingContext: this.getDynamicSamplingContext(),\n },\n ...(metadata.source && {\n transaction_info: {\n source: metadata.source,\n },\n }),\n };\n\n const hasMeasurements = Object.keys(this._measurements).length > 0;\n\n if (hasMeasurements) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n '[Measurements] Adding measurements to transaction',\n JSON.stringify(this._measurements, undefined, 2),\n );\n transaction.measurements = this._measurements;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`);\n\n return transaction;\n }\n}\n\nexport { Transaction };\n","import { logger, timestampInSeconds } from '@sentry/utils';\nimport { SpanRecorder } from './span.js';\nimport { Transaction } from './transaction.js';\n\nconst TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n heartbeatInterval: 5000,\n};\n\nconst FINISH_REASON_TAG = 'finishReason';\n\nconst IDLE_TRANSACTION_FINISH_REASONS = [\n 'heartbeatFailed',\n 'idleTimeout',\n 'documentHidden',\n 'finalTimeout',\n 'externalFinish',\n 'cancelled',\n];\n\n/**\n * @inheritDoc\n */\nclass IdleTransactionSpanRecorder extends SpanRecorder {\n constructor(\n _pushActivity,\n _popActivity,\n transactionSpanId,\n maxlen,\n ) {\n super(maxlen);this._pushActivity = _pushActivity;this._popActivity = _popActivity;this.transactionSpanId = transactionSpanId; }\n\n /**\n * @inheritDoc\n */\n add(span) {\n // We should make sure we do not push and pop activities for\n // the transaction that this span recorder belongs to.\n if (span.spanId !== this.transactionSpanId) {\n // We patch span.finish() to pop an activity after setting an endTimestamp.\n span.finish = (endTimestamp) => {\n span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampInSeconds();\n this._popActivity(span.spanId);\n };\n\n // We should only push new activities if the span does not have an end timestamp.\n if (span.endTimestamp === undefined) {\n this._pushActivity(span.spanId);\n }\n }\n\n super.add(span);\n }\n}\n\n/**\n * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.\n * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will\n * put itself on the scope on creation.\n */\nclass IdleTransaction extends Transaction {\n // Activities store a list of active spans\n\n // Track state of activities in previous heartbeat\n\n // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.\n\n // We should not use heartbeat if we finished a transaction\n\n // Idle timeout was canceled and we should finish the transaction with the last span end.\n\n /**\n * Timer that tracks Transaction idleTimeout\n */\n\n constructor(\n transactionContext,\n _idleHub,\n /**\n * The time to wait in ms until the idle transaction will be finished. This timer is started each time\n * there are no active spans on this transaction.\n */\n _idleTimeout = TRACING_DEFAULTS.idleTimeout,\n /**\n * The final value in ms that a transaction cannot exceed\n */\n _finalTimeout = TRACING_DEFAULTS.finalTimeout,\n _heartbeatInterval = TRACING_DEFAULTS.heartbeatInterval,\n // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends\n _onScope = false,\n ) {\n super(transactionContext, _idleHub);this._idleHub = _idleHub;this._idleTimeout = _idleTimeout;this._finalTimeout = _finalTimeout;this._heartbeatInterval = _heartbeatInterval;this._onScope = _onScope;\n this.activities = {};\n this._heartbeatCounter = 0;\n this._finished = false;\n this._idleTimeoutCanceledPermanently = false;\n this._beforeFinishCallbacks = [];\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4];\n\n if (_onScope) {\n // We set the transaction here on the scope so error events pick up the trace\n // context and attach it to the error.\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`);\n _idleHub.configureScope(scope => scope.setSpan(this));\n }\n\n this._restartIdleTimeout();\n setTimeout(() => {\n if (!this._finished) {\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];\n this.finish();\n }\n }, this._finalTimeout);\n }\n\n /** {@inheritDoc} */\n finish(endTimestamp = timestampInSeconds()) {\n this._finished = true;\n this.activities = {};\n\n if (this.op === 'ui.action.click') {\n this.setTag(FINISH_REASON_TAG, this._finishReason);\n }\n\n if (this.spanRecorder) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op);\n\n for (const callback of this._beforeFinishCallbacks) {\n callback(this, endTimestamp);\n }\n\n this.spanRecorder.spans = this.spanRecorder.spans.filter((span) => {\n // If we are dealing with the transaction itself, we just return it\n if (span.spanId === this.spanId) {\n return true;\n }\n\n // We cancel all pending spans with status \"cancelled\" to indicate the idle transaction was finished early\n if (!span.endTimestamp) {\n span.endTimestamp = endTimestamp;\n span.setStatus('cancelled');\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));\n }\n\n const spanStartedBeforeTransactionFinish = span.startTimestamp < endTimestamp;\n\n // Add a delta with idle timeout so that we prevent false positives\n const timeoutWithMarginOfError = (this._finalTimeout + this._idleTimeout) / 1000;\n const spanEndedBeforeFinalTimeout = span.endTimestamp - this.startTimestamp < timeoutWithMarginOfError;\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n const stringifiedSpan = JSON.stringify(span, undefined, 2);\n if (!spanStartedBeforeTransactionFinish) {\n logger.log('[Tracing] discarding Span since it happened after Transaction was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n logger.log('[Tracing] discarding Span since it finished after Transaction final timeout', stringifiedSpan);\n }\n }\n\n return spanStartedBeforeTransactionFinish && spanEndedBeforeFinalTimeout;\n });\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] flushing IdleTransaction');\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] No active IdleTransaction');\n }\n\n // if `this._onScope` is `true`, the transaction put itself on the scope when it started\n if (this._onScope) {\n const scope = this._idleHub.getScope();\n if (scope.getTransaction() === this) {\n scope.setSpan(undefined);\n }\n }\n\n return super.finish(endTimestamp);\n }\n\n /**\n * Register a callback function that gets excecuted before the transaction finishes.\n * Useful for cleanup or if you want to add any additional spans based on current context.\n *\n * This is exposed because users have no other way of running something before an idle transaction\n * finishes.\n */\n registerBeforeFinishCallback(callback) {\n this._beforeFinishCallbacks.push(callback);\n }\n\n /**\n * @inheritDoc\n */\n initSpanRecorder(maxlen) {\n if (!this.spanRecorder) {\n const pushActivity = (id) => {\n if (this._finished) {\n return;\n }\n this._pushActivity(id);\n };\n const popActivity = (id) => {\n if (this._finished) {\n return;\n }\n this._popActivity(id);\n };\n\n this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);\n\n // Start heartbeat so that transactions do not run forever.\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('Starting heartbeat');\n this._pingHeartbeat();\n }\n this.spanRecorder.add(this);\n }\n\n /**\n * Cancels the existing idle timeout, if there is one.\n * @param restartOnChildSpanChange Default is `true`.\n * If set to false the transaction will end\n * with the last child span.\n */\n cancelIdleTimeout(\n endTimestamp,\n {\n restartOnChildSpanChange,\n }\n\n = {\n restartOnChildSpanChange: true,\n },\n ) {\n this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;\n if (this._idleTimeoutID) {\n clearTimeout(this._idleTimeoutID);\n this._idleTimeoutID = undefined;\n\n if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.finish(endTimestamp);\n }\n }\n }\n\n /**\n * Temporary method used to externally set the transaction's `finishReason`\n *\n * ** WARNING**\n * This is for the purpose of experimentation only and will be removed in the near future, do not use!\n *\n * @internal\n *\n */\n setFinishReason(reason) {\n this._finishReason = reason;\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n _restartIdleTimeout(endTimestamp) {\n this.cancelIdleTimeout();\n this._idleTimeoutID = setTimeout(() => {\n if (!this._finished && Object.keys(this.activities).length === 0) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];\n this.finish(endTimestamp);\n }\n }, this._idleTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n _pushActivity(spanId) {\n this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] pushActivity: ${spanId}`);\n this.activities[spanId] = true;\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n _popActivity(spanId) {\n if (this.activities[spanId]) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] popActivity ${spanId}`);\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this.activities[spanId];\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);\n }\n\n if (Object.keys(this.activities).length === 0) {\n const endTimestamp = timestampInSeconds();\n if (this._idleTimeoutCanceledPermanently) {\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];\n this.finish(endTimestamp);\n } else {\n // We need to add the timeout here to have the real endtimestamp of the transaction\n // Remember timestampInSeconds is in seconds, timeout is in ms\n this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000);\n }\n }\n }\n\n /**\n * Checks when entries of this.activities are not changing for 3 beats.\n * If this occurs we finish the transaction.\n */\n _beat() {\n // We should not be running heartbeat if the idle transaction is finished.\n if (this._finished) {\n return;\n }\n\n const heartbeatString = Object.keys(this.activities).join('');\n\n if (heartbeatString === this._prevHeartbeatString) {\n this._heartbeatCounter++;\n } else {\n this._heartbeatCounter = 1;\n }\n\n this._prevHeartbeatString = heartbeatString;\n\n if (this._heartbeatCounter >= 3) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');\n this.setStatus('deadline_exceeded');\n this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];\n this.finish();\n } else {\n this._pingHeartbeat();\n }\n }\n\n /**\n * Pings the heartbeat\n */\n _pingHeartbeat() {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);\n setTimeout(() => {\n this._beat();\n }, this._heartbeatInterval);\n }\n}\n\nexport { IdleTransaction, IdleTransactionSpanRecorder, TRACING_DEFAULTS };\n","import { extractTraceparentData as extractTraceparentData$1 } from '@sentry/utils';\nexport { stripUrlQueryAndFragment } from '@sentry/utils';\nimport { getCurrentHub } from '../hub.js';\n\n/** Grabs active transaction off scope, if any */\nfunction getActiveTransaction(maybeHub) {\n const hub = maybeHub || getCurrentHub();\n const scope = hub.getScope();\n return scope.getTransaction() ;\n}\n\n/**\n * The `extractTraceparentData` function and `TRACEPARENT_REGEXP` constant used\n * to be declared in this file. It was later moved into `@sentry/utils` as part of a\n * move to remove `@sentry/tracing` dependencies from `@sentry/node` (`extractTraceparentData`\n * is the only tracing function used by `@sentry/node`).\n *\n * These exports are kept here for backwards compatability's sake.\n *\n * See https://github.com/getsentry/sentry-javascript/issues/4642 for more details.\n *\n * @deprecated Import this function from `@sentry/utils` instead\n */\nconst extractTraceparentData = extractTraceparentData$1;\n\nexport { extractTraceparentData, getActiveTransaction };\n","import { addInstrumentationHandler, logger } from '@sentry/utils';\nimport { getActiveTransaction } from './utils.js';\n\nlet errorsInstrumented = false;\n\n/**\n * Configures global error listeners\n */\nfunction registerErrorInstrumentation() {\n if (errorsInstrumented) {\n return;\n }\n\n errorsInstrumented = true;\n addInstrumentationHandler('error', errorCallback);\n addInstrumentationHandler('unhandledrejection', errorCallback);\n}\n\n/**\n * If an error or unhandled promise occurs, we mark the active transaction as failed\n */\nfunction errorCallback() {\n const activeTransaction = getActiveTransaction();\n if (activeTransaction) {\n const status = 'internal_error';\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Transaction: ${status} -> Global error occured`);\n activeTransaction.setStatus(status);\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 { registerErrorInstrumentation };\n","import { getCurrentHub } from '../hub.js';\n\n// Treeshakable guard to remove all code related to tracing\n\n/**\n * Determines if tracing is currently enabled.\n *\n * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config.\n */\nfunction hasTracingEnabled(\n maybeOptions,\n) {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const client = getCurrentHub().getClient();\n const options = maybeOptions || (client && client.getOptions());\n return !!options && (options.enableTracing || 'tracesSampleRate' in options || 'tracesSampler' in options);\n}\n\nexport { hasTracingEnabled };\n","import { logger, isNaN } from '@sentry/utils';\nimport { hasTracingEnabled } from '../utils/hasTracingEnabled.js';\n\n/**\n * Makes a sampling decision for the given transaction and stores it on the transaction.\n *\n * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n *\n * This method muttes the given `transaction` and will set the `sampled` value on it.\n * It returns the same transaction, for convenience.\n */\nfunction sampleTransaction(\n transaction,\n options,\n samplingContext,\n) {\n // nothing to do if tracing is not enabled\n if (!hasTracingEnabled(options)) {\n transaction.sampled = false;\n return transaction;\n }\n\n // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that\n if (transaction.sampled !== undefined) {\n transaction.setMetadata({\n sampleRate: Number(transaction.sampled),\n });\n return transaction;\n }\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` nor `enableTracing` 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(samplingContext);\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n transaction.setMetadata({\n sampleRate: Number(sampleRate),\n });\n } else {\n // When `enableTracing === true`, we use a sample rate of 100%\n sampleRate = 1;\n transaction.setMetadata({\n sampleRate,\n });\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The\n // only valid values are booleans or numbers between 0 and 1.)\n if (!isValidSampleRate(sampleRate)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('[Tracing] Discarding transaction because of invalid sample rate.');\n transaction.sampled = false;\n return transaction;\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 (!sampleRate) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\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 transaction.sampled = false;\n return transaction;\n }\n\n // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is\n // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false.\n transaction.sampled = Math.random() < (sampleRate );\n\n // if we're not going to keep it, we're done\n if (!transaction.sampled) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n return transaction;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] starting ${transaction.op} transaction - ${transaction.name}`);\n return transaction;\n}\n\n/**\n * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1).\n */\nfunction isValidSampleRate(rate) {\n // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n rate,\n )} of type ${JSON.stringify(typeof rate)}.`,\n );\n return false;\n }\n\n // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false\n if (rate < 0 || rate > 1) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got ${rate}.`);\n return false;\n }\n return true;\n}\n\nexport { sampleTransaction };\n","import { logger } from '@sentry/utils';\nimport { getMainCarrier } from '../hub.js';\nimport { registerErrorInstrumentation } from './errors.js';\nimport { IdleTransaction } from './idletransaction.js';\nimport { sampleTransaction } from './sampling.js';\nimport { Transaction } from './transaction.js';\n\n/** Returns all trace headers that are currently on the top scope. */\nfunction traceHeaders() {\n const scope = this.getScope();\n const span = scope.getSpan();\n\n return span\n ? {\n 'sentry-trace': span.toTraceparent(),\n }\n : {};\n}\n\n/**\n * Creates a new transaction and adds a sampling decision if it doesn't yet have one.\n *\n * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if\n * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an\n * \"extension method.\"\n *\n * @param this: The Hub starting the transaction\n * @param transactionContext: Data used to configure the transaction\n * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any)\n *\n * @returns The new transaction\n *\n * @see {@link Hub.startTransaction}\n */\nfunction _startTransaction(\n\n transactionContext,\n customSamplingContext,\n) {\n const client = this.getClient();\n const options = (client && client.getOptions()) || {};\n\n const configInstrumenter = options.instrumenter || 'sentry';\n const transactionInstrumenter = transactionContext.instrumenter || 'sentry';\n\n if (configInstrumenter !== transactionInstrumenter) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.error(\n `A transaction was started with instrumenter=\\`${transactionInstrumenter}\\`, but the SDK is configured with the \\`${configInstrumenter}\\` instrumenter.\nThe transaction will not be sampled. Please use the ${configInstrumenter} instrumentation to start transactions.`,\n );\n\n transactionContext.sampled = false;\n }\n\n let transaction = new Transaction(transactionContext, this);\n transaction = sampleTransaction(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans ));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Create new idle transaction.\n */\nfunction startIdleTransaction(\n hub,\n transactionContext,\n idleTimeout,\n finalTimeout,\n onScope,\n customSamplingContext,\n heartbeatInterval,\n) {\n const client = hub.getClient();\n const options = (client && client.getOptions()) || {};\n\n let transaction = new IdleTransaction(transactionContext, hub, idleTimeout, finalTimeout, heartbeatInterval, onScope);\n transaction = sampleTransaction(transaction, options, {\n parentSampled: transactionContext.parentSampled,\n transactionContext,\n ...customSamplingContext,\n });\n if (transaction.sampled) {\n transaction.initSpanRecorder(options._experiments && (options._experiments.maxSpans ));\n }\n if (client && client.emit) {\n client.emit('startTransaction', transaction);\n }\n return transaction;\n}\n\n/**\n * Adds tracing extensions to the global hub.\n */\nfunction addTracingExtensions() {\n const carrier = getMainCarrier();\n if (!carrier.__SENTRY__) {\n return;\n }\n carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {};\n if (!carrier.__SENTRY__.extensions.startTransaction) {\n carrier.__SENTRY__.extensions.startTransaction = _startTransaction;\n }\n if (!carrier.__SENTRY__.extensions.traceHeaders) {\n carrier.__SENTRY__.extensions.traceHeaders = traceHeaders;\n }\n\n registerErrorInstrumentation();\n}\n\nexport { addTracingExtensions, startIdleTransaction };\n","import { GLOBAL_OBJ } from '@sentry/utils';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nexport { WINDOW };\n","const bindReporter = (\n callback,\n metric,\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 callback(metric);\n }\n }\n }\n };\n};\n\nexport { bindReporter };\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\nconst getNavigationEntryFromPerformanceTiming = () => {\n // eslint-disable-next-line deprecation/deprecation\n const timing = WINDOW.performance.timing;\n // eslint-disable-next-line deprecation/deprecation\n const type = WINDOW.performance.navigation.type;\n\n const navigationEntry = {\n entryType: 'navigation',\n startTime: 0,\n type: type == 2 ? 'back_forward' : type === 1 ? 'reload' : 'navigate',\n };\n\n for (const key in timing) {\n if (key !== 'navigationStart' && key !== 'toJSON') {\n // eslint-disable-next-line deprecation/deprecation\n navigationEntry[key] = Math.max((timing[key ] ) - timing.navigationStart, 0);\n }\n }\n return navigationEntry ;\n};\n\nconst getNavigationEntry = () => {\n if (WINDOW.__WEB_VITALS_POLYFILL__) {\n return (\n WINDOW.performance &&\n ((performance.getEntriesByType && performance.getEntriesByType('navigation')[0]) ||\n getNavigationEntryFromPerformanceTiming())\n );\n } else {\n return WINDOW.performance && performance.getEntriesByType && performance.getEntriesByType('navigation')[0];\n }\n};\n\nexport { getNavigationEntry };\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\nconst getActivationStart = () => {\n const navEntry = getNavigationEntry();\n return (navEntry && navEntry.activationStart) || 0;\n};\n\nexport { getActivationStart };\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\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 {\n navigationType = navEntry.type.replace(/_/g, '-') ;\n }\n }\n\n return {\n name,\n value: typeof value === 'undefined' ? -1 : value,\n rating: 'good', // Will be updated if the value changes.\n delta: 0,\n entries: [],\n id: generateUniqueID(),\n navigationType,\n };\n};\n\nexport { initMetric };\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 `v3-${Date.now()}-${Math.floor(Math.random() * (9e12 - 1)) + 1e12}`;\n};\n\nexport { generateUniqueID };\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 callback(list.getEntries() );\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","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\nconst onHidden = (cb, once) => {\n const onHiddenOrPageHide = (event) => {\n if (event.type === 'pagehide' || WINDOW.document.visibilityState === 'hidden') {\n cb(event);\n if (once) {\n removeEventListener('visibilitychange', onHiddenOrPageHide, true);\n removeEventListener('pagehide', onHiddenOrPageHide, true);\n }\n }\n };\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\nexport { onHidden };\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';\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 * Calculates the [CLS](https://web.dev/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/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) => {\n const metric = initMetric('CLS', 0);\n let report;\n\n let sessionValue = 0;\n let sessionEntries = [];\n\n // const handleEntries = (entries: Metric['entries']) => {\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 and\n // less than 5 seconds after the first entry in the session, include the\n // entry in the current session. Otherwise, start a new session.\n if (\n sessionValue &&\n sessionEntries.length !== 0 &&\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 // 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 if (report) {\n report();\n }\n }\n }\n });\n };\n\n const po = observe('layout-shift', handleEntries);\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = () => {\n handleEntries(po.takeRecords() );\n report(true);\n };\n\n onHidden(stopListening);\n\n return stopListening;\n }\n\n return;\n};\n\nexport { onCLS };\n","import { WINDOW } from '../../types.js';\nimport { onHidden } from './onHidden.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\nlet firstHiddenTime = -1;\n\nconst initHiddenTime = () => {\n // If the document is hidden and not prerendering, assume it was always\n // hidden and the page was loaded in the background.\n return WINDOW.document.visibilityState === 'hidden' && !WINDOW.document.prerendering ? 0 : Infinity;\n};\n\nconst trackChanges = () => {\n // Update the time if/when the document becomes hidden.\n onHidden(({ timeStamp }) => {\n firstHiddenTime = timeStamp;\n }, true);\n};\n\nconst getVisibilityWatcher = (\n\n) => {\n if (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 trackChanges();\n }\n return {\n get firstHiddenTime() {\n return firstHiddenTime;\n },\n };\n};\n\nexport { getVisibilityWatcher };\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';\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 * Calculates the [FID](https://web.dev/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) => {\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 report = bindReporter(onReport, metric);\n\n if (po) {\n onHidden(() => {\n handleEntries(po.takeRecords() );\n po.disconnect();\n }, true);\n }\n};\n\nexport { onFID };\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 { onHidden } from './lib/onHidden.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\nconst reportedMetricIDs = {};\n\n/**\n * Calculates the [LCP](https://web.dev/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 */\nconst onLCP = (onReport) => {\n const visibilityWatcher = getVisibilityWatcher();\n const metric = initMetric('LCP');\n let report;\n\n const handleEntries = (entries) => {\n const lastEntry = entries[entries.length - 1] ;\n if (lastEntry) {\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 prerendered.\n const value = Math.max(lastEntry.startTime - getActivationStart(), 0);\n\n // Only report if the page wasn't hidden prior to LCP.\n if (value < visibilityWatcher.firstHiddenTime) {\n metric.value = value;\n metric.entries = [lastEntry];\n report();\n }\n }\n };\n\n const po = observe('largest-contentful-paint', handleEntries);\n\n if (po) {\n report = bindReporter(onReport, metric);\n\n const stopListening = () => {\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 // stop 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 addEventListener(type, stopListening, { once: true, capture: true });\n });\n\n onHidden(stopListening, true);\n\n return stopListening;\n }\n\n return;\n};\n\nexport { onLCP };\n","import { logger, getFunctionName } from '@sentry/utils';\nimport { onCLS } from './web-vitals/getCLS.js';\nimport { onFID } from './web-vitals/getFID.js';\nimport { onLCP } from './web-vitals/getLCP.js';\nimport { observe } from './web-vitals/lib/observe.js';\n\nconst handlers = {};\nconst instrumented = {};\n\nlet _previousCls;\nlet _previousFid;\nlet _previousLcp;\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 */\nfunction addClsInstrumentationHandler(callback) {\n return addMetricObserver('cls', callback, instrumentCls, _previousCls);\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 */\nfunction addLcpInstrumentationHandler(callback) {\n return addMetricObserver('lcp', callback, instrumentLcp, _previousLcp);\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 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 || !typeHandlers.length) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\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 onCLS(metric => {\n triggerHandlers('cls', {\n metric,\n });\n _previousCls = metric;\n });\n}\n\nfunction instrumentFid() {\n onFID(metric => {\n triggerHandlers('fid', {\n metric,\n });\n _previousFid = metric;\n });\n}\n\nfunction instrumentLcp() {\n onLCP(metric => {\n triggerHandlers('lcp', {\n metric,\n });\n _previousLcp = metric;\n });\n}\n\nfunction addMetricObserver(\n type,\n callback,\n instrumentFn,\n previousValue,\n) {\n addHandler(type, callback);\n\n if (!instrumented[type]) {\n instrumentFn();\n instrumented[type] = true;\n }\n\n if (previousValue) {\n callback({ metric: previousValue });\n }\n\n return getCleanupCallback(type, callback);\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(type, callback) {\n return () => {\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\nexport { addClsInstrumentationHandler, addFidInstrumentationHandler, addLcpInstrumentationHandler, addPerformanceInstrumentationHandler };\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 _startChild(transaction, { startTimestamp, ...ctx }) {\n if (startTimestamp && transaction.startTimestamp > startTimestamp) {\n transaction.startTimestamp = startTimestamp;\n }\n\n return transaction.startChild({\n startTimestamp,\n ...ctx,\n });\n}\n\nexport { _startChild, isMeasurementValue };\n","import { getActiveTransaction } from '@sentry/core';\nimport { browserPerformanceTimeOrigin, htmlTreeAsString, logger } from '@sentry/utils';\nimport { addPerformanceInstrumentationHandler, addClsInstrumentationHandler, addLcpInstrumentationHandler, addFidInstrumentationHandler } from '../instrument.js';\nimport { WINDOW } from '../types.js';\nimport { getVisibilityWatcher } from '../web-vitals/lib/getVisibilityWatcher.js';\nimport { _startChild, isMeasurementValue } from './utils.js';\n\n/**\n * Converts from milliseconds to seconds\n * @param time time in ms\n */\nfunction msToSec(time) {\n return time / 1000;\n}\n\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 && WINDOW.addEventListener && WINDOW.performance;\n}\n\nlet _performanceCursor = 0;\n\nlet _measurements = {};\nlet _lcpEntry;\nlet _clsEntry;\n\n/**\n * Start tracking web vitals\n *\n * @returns A function that forces web vitals collection\n */\nfunction startTrackingWebVitals() {\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 fidCallback = _trackFID();\n const clsCallback = _trackCLS();\n const lcpCallback = _trackLCP();\n\n return () => {\n fidCallback();\n clsCallback();\n lcpCallback();\n };\n }\n\n return () => undefined;\n}\n\n/**\n * Start tracking long tasks.\n */\nfunction startTrackingLongTasks() {\n addPerformanceInstrumentationHandler('longtask', ({ entries }) => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() ;\n if (!transaction) {\n return;\n }\n const startTime = msToSec((browserPerformanceTimeOrigin ) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: 'Main UI thread blocked',\n op: 'ui.long-task',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n });\n}\n\n/**\n * Start tracking interaction events.\n */\nfunction startTrackingInteractions() {\n addPerformanceInstrumentationHandler('event', ({ entries }) => {\n for (const entry of entries) {\n const transaction = getActiveTransaction() ;\n if (!transaction) {\n return;\n }\n\n if (entry.name === 'click') {\n const startTime = msToSec((browserPerformanceTimeOrigin ) + entry.startTime);\n const duration = msToSec(entry.duration);\n\n transaction.startChild({\n description: htmlTreeAsString(entry.target),\n op: `ui.interaction.${entry.name}`,\n origin: 'auto.ui.browser.metrics',\n startTimestamp: startTime,\n endTimestamp: startTime + duration,\n });\n }\n }\n });\n}\n\n/** Starts tracking the Cumulative Layout Shift on the current page. */\nfunction _trackCLS() {\n return addClsInstrumentationHandler(({ metric }) => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding CLS');\n _measurements['cls'] = { value: metric.value, unit: '' };\n _clsEntry = entry ;\n });\n}\n\n/** Starts tracking the Largest Contentful Paint on the current page. */\nfunction _trackLCP() {\n return addLcpInstrumentationHandler(({ metric }) => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding LCP');\n _measurements['lcp'] = { value: metric.value, unit: 'millisecond' };\n _lcpEntry = entry ;\n });\n}\n\n/** Starts tracking the First Input Delay on the current page. */\nfunction _trackFID() {\n return addFidInstrumentationHandler(({ metric }) => {\n const entry = metric.entries.pop();\n if (!entry) {\n return;\n }\n\n const timeOrigin = msToSec(browserPerformanceTimeOrigin );\n const startTime = msToSec(entry.startTime);\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding FID');\n _measurements['fid'] = { value: metric.value, unit: 'millisecond' };\n _measurements['mark.fid'] = { value: timeOrigin + startTime, unit: 'second' };\n });\n}\n\n/** Add performance related spans to a transaction */\nfunction addPerformanceEntries(transaction) {\n const performance = getBrowserPerformanceAPI();\n if (!performance || !WINDOW.performance.getEntries || !browserPerformanceTimeOrigin) {\n // Gatekeeper if performance API not available\n return;\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] Adding & adjusting spans using Performance API');\n const timeOrigin = msToSec(browserPerformanceTimeOrigin);\n\n const performanceEntries = performance.getEntries();\n\n let responseStartTimestamp;\n let requestStartTimestamp;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n performanceEntries.slice(_performanceCursor).forEach((entry) => {\n const startTime = msToSec(entry.startTime);\n const duration = msToSec(entry.duration);\n\n if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) {\n return;\n }\n\n switch (entry.entryType) {\n case 'navigation': {\n _addNavigationSpans(transaction, entry, timeOrigin);\n responseStartTimestamp = timeOrigin + msToSec(entry.responseStart);\n requestStartTimestamp = timeOrigin + msToSec(entry.requestStart);\n break;\n }\n case 'mark':\n case 'paint':\n case 'measure': {\n _addMeasureSpans(transaction, 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 (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding FP');\n _measurements['fp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n if (entry.name === 'first-contentful-paint' && shouldRecord) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding FCP');\n _measurements['fcp'] = { value: entry.startTime, unit: 'millisecond' };\n }\n break;\n }\n case 'resource': {\n const resourceName = (entry.name ).replace(WINDOW.location.origin, '');\n _addResourceSpans(transaction, entry, resourceName, 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(transaction);\n\n // Measurements are only available for pageload transactions\n if (transaction.op === 'pageload') {\n // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the\n // start of the response in milliseconds\n if (typeof responseStartTimestamp === 'number') {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding TTFB');\n _measurements['ttfb'] = {\n value: (responseStartTimestamp - transaction.startTimestamp) * 1000,\n unit: 'millisecond',\n };\n\n if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) {\n // Capture the time spent making the request and receiving the first byte of the response.\n // This is the time between the start of the request and the start of the response in milliseconds.\n _measurements['ttfb.requestTime'] = {\n value: (responseStartTimestamp - requestStartTimestamp) * 1000,\n unit: 'millisecond',\n };\n }\n }\n\n ['fcp', 'fp', 'lcp'].forEach(name => {\n if (!_measurements[name] || timeOrigin >= transaction.startTimestamp) {\n return;\n }\n // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin.\n // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need\n // to be adjusted to be relative to transaction.startTimestamp.\n const oldValue = _measurements[name].value;\n const measurementTimestamp = timeOrigin + msToSec(oldValue);\n\n // normalizedValue should be in milliseconds\n const normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000);\n const delta = normalizedValue - oldValue;\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(`[Measurements] Normalized ${name} from ${oldValue} to ${normalizedValue} (${delta})`);\n _measurements[name].value = normalizedValue;\n });\n\n const fidMark = _measurements['mark.fid'];\n if (fidMark && _measurements['fid']) {\n // create span for FID\n _startChild(transaction, {\n description: 'first input delay',\n endTimestamp: fidMark.value + msToSec(_measurements['fid'].value),\n op: 'ui.action',\n origin: 'auto.ui.browser.metrics',\n startTimestamp: fidMark.value,\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 if (!('fcp' in _measurements)) {\n delete _measurements.cls;\n }\n\n Object.keys(_measurements).forEach(measurementName => {\n transaction.setMeasurement(\n measurementName,\n _measurements[measurementName].value,\n _measurements[measurementName].unit,\n );\n });\n\n _tagMetricInfo(transaction);\n }\n\n _lcpEntry = undefined;\n _clsEntry = undefined;\n _measurements = {};\n}\n\n/** Create measure related spans */\nfunction _addMeasureSpans(\n transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry,\n startTime,\n duration,\n timeOrigin,\n) {\n const measureStartTimestamp = timeOrigin + startTime;\n const measureEndTimestamp = measureStartTimestamp + duration;\n\n _startChild(transaction, {\n description: entry.name ,\n endTimestamp: measureEndTimestamp,\n op: entry.entryType ,\n origin: 'auto.resource.browser.metrics',\n startTimestamp: measureStartTimestamp,\n });\n\n return measureStartTimestamp;\n}\n\n/** Instrument navigation entries */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addNavigationSpans(transaction, entry, timeOrigin) {\n ['unloadEvent', 'redirect', 'domContentLoadedEvent', 'loadEvent', 'connect'].forEach(event => {\n _addPerformanceNavigationTiming(transaction, entry, event, timeOrigin);\n });\n _addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'TLS/SSL', 'connectEnd');\n _addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'cache', 'domainLookupStart');\n _addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin, 'DNS');\n _addRequest(transaction, entry, timeOrigin);\n}\n\n/** Create performance navigation related spans */\nfunction _addPerformanceNavigationTiming(\n transaction,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n entry,\n event,\n timeOrigin,\n description,\n eventEnd,\n) {\n const end = eventEnd ? (entry[eventEnd] ) : (entry[`${event}End`] );\n const start = entry[`${event}Start`] ;\n if (!start || !end) {\n return;\n }\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: description || event,\n startTimestamp: timeOrigin + msToSec(start),\n endTimestamp: timeOrigin + msToSec(end),\n });\n}\n\n/** Create request and response related spans */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction _addRequest(transaction, entry, timeOrigin) {\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'request',\n startTimestamp: timeOrigin + msToSec(entry.requestStart ),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd ),\n });\n\n _startChild(transaction, {\n op: 'browser',\n origin: 'auto.browser.browser.metrics',\n description: 'response',\n startTimestamp: timeOrigin + msToSec(entry.responseStart ),\n endTimestamp: timeOrigin + msToSec(entry.responseEnd ),\n });\n}\n\n/** Create resource-related spans */\nfunction _addResourceSpans(\n transaction,\n entry,\n resourceName,\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const data = {};\n if ('transferSize' in entry) {\n data['http.response_transfer_size'] = entry.transferSize;\n }\n if ('encodedBodySize' in entry) {\n data['http.response_content_length'] = entry.encodedBodySize;\n }\n if ('decodedBodySize' in entry) {\n data['http.decoded_response_content_length'] = entry.decodedBodySize;\n }\n if ('renderBlockingStatus' in entry) {\n data['resource.render_blocking_status'] = entry.renderBlockingStatus;\n }\n\n const startTimestamp = timeOrigin + startTime;\n const endTimestamp = startTimestamp + duration;\n\n _startChild(transaction, {\n description: resourceName,\n endTimestamp,\n op: entry.initiatorType ? `resource.${entry.initiatorType}` : 'resource.other',\n origin: 'auto.resource.browser.metrics',\n startTimestamp,\n data,\n });\n}\n\n/**\n * Capture the information of the user agent.\n */\nfunction _trackNavigator(transaction) {\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 transaction.setTag('effectiveConnectionType', connection.effectiveType);\n }\n\n if (connection.type) {\n transaction.setTag('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 transaction.setTag('deviceMemory', `${navigator.deviceMemory} GB`);\n }\n\n if (isMeasurementValue(navigator.hardwareConcurrency)) {\n transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency));\n }\n}\n\n/** Add LCP / CLS data to transaction to allow debugging */\nfunction _tagMetricInfo(transaction) {\n if (_lcpEntry) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding LCP Data');\n\n // Capture Properties of the LCP element that contributes to the LCP.\n\n if (_lcpEntry.element) {\n transaction.setTag('lcp.element', htmlTreeAsString(_lcpEntry.element));\n }\n\n if (_lcpEntry.id) {\n transaction.setTag('lcp.id', _lcpEntry.id);\n }\n\n if (_lcpEntry.url) {\n // Trim URL to the first 200 characters.\n transaction.setTag('lcp.url', _lcpEntry.url.trim().slice(0, 200));\n }\n\n transaction.setTag('lcp.size', _lcpEntry.size);\n }\n\n // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift\n if (_clsEntry && _clsEntry.sources) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Measurements] Adding CLS Data');\n _clsEntry.sources.forEach((source, index) =>\n transaction.setTag(`cls.source.${index + 1}`, htmlTreeAsString(source.node)),\n );\n }\n}\n\nexport { _addMeasureSpans, _addResourceSpans, addPerformanceEntries, startTrackingInteractions, startTrackingLongTasks, startTrackingWebVitals };\n","import { hasTracingEnabled, getCurrentHub, getDynamicSamplingContextFromClient } from '@sentry/core';\nimport { addInstrumentationHandler, SENTRY_XHR_DATA_KEY, dynamicSamplingContextToSentryBaggageHeader, generateSentryTraceHeader, BAGGAGE_HEADER_NAME, browserPerformanceTimeOrigin, stringMatchesSomePattern } from '@sentry/utils';\nimport { instrumentFetchRequest } from '../common/fetch.js';\nimport { addPerformanceInstrumentationHandler } from './instrument.js';\n\n/* eslint-disable max-lines */\n\nconst DEFAULT_TRACE_PROPAGATION_TARGETS = ['localhost', /^\\/(?!\\/)/];\n\n/** Options for Request Instrumentation */\n\nconst defaultRequestInstrumentationOptions = {\n traceFetch: true,\n traceXHR: true,\n enableHTTPTimings: true,\n // TODO (v8): Remove this property\n tracingOrigins: DEFAULT_TRACE_PROPAGATION_TARGETS,\n tracePropagationTargets: DEFAULT_TRACE_PROPAGATION_TARGETS,\n};\n\n/** Registers span creators for xhr and fetch requests */\nfunction instrumentOutgoingRequests(_options) {\n const {\n traceFetch,\n traceXHR,\n // eslint-disable-next-line deprecation/deprecation\n tracePropagationTargets,\n // eslint-disable-next-line deprecation/deprecation\n tracingOrigins,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n } = {\n traceFetch: defaultRequestInstrumentationOptions.traceFetch,\n traceXHR: defaultRequestInstrumentationOptions.traceXHR,\n ..._options,\n };\n\n const shouldCreateSpan =\n typeof shouldCreateSpanForRequest === 'function' ? shouldCreateSpanForRequest : (_) => true;\n\n // TODO(v8) Remove tracingOrigins here\n // The only reason we're passing it in here is because this instrumentOutgoingRequests function is publicly exported\n // and we don't want to break the API. We can remove it in v8.\n const shouldAttachHeadersWithTargets = (url) =>\n shouldAttachHeaders(url, tracePropagationTargets || tracingOrigins);\n\n const spans = {};\n\n if (traceFetch) {\n addInstrumentationHandler('fetch', (handlerData) => {\n const createdSpan = instrumentFetchRequest(handlerData, shouldCreateSpan, shouldAttachHeadersWithTargets, spans);\n if (enableHTTPTimings && createdSpan) {\n addHTTPTimings(createdSpan);\n }\n });\n }\n\n if (traceXHR) {\n addInstrumentationHandler('xhr', (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 = span.data.url;\n\n if (!url) {\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.setData(...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\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\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 * This was extracted from `instrumentOutgoingRequests` to make it easier to test shouldAttachHeaders.\n * We only export this fuction for testing purposes.\n */\nfunction shouldAttachHeaders(url, tracePropagationTargets) {\n return stringMatchesSomePattern(url, tracePropagationTargets || DEFAULT_TRACE_PROPAGATION_TARGETS);\n}\n\n/**\n * Create and track xhr request spans\n *\n * @returns Span if a span was created, otherwise void.\n */\n// eslint-disable-next-line complexity\nfunction xhrCallback(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n) {\n const xhr = handlerData.xhr;\n const sentryXhrData = xhr && xhr[SENTRY_XHR_DATA_KEY];\n\n if (!hasTracingEnabled() || (xhr && xhr.__sentry_own_request__) || !xhr || !sentryXhrData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = 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) {\n span.setHttpStatus(sentryXhrData.status_code);\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const hub = getCurrentHub();\n const scope = hub.getScope();\n const parentSpan = scope.getSpan();\n\n const span =\n shouldCreateSpanResult && parentSpan\n ? parentSpan.startChild({\n data: {\n ...sentryXhrData.data,\n type: 'xhr',\n 'http.method': sentryXhrData.method,\n url: sentryXhrData.url,\n },\n description: `${sentryXhrData.method} ${sentryXhrData.url}`,\n op: 'http.client',\n origin: 'auto.http.browser',\n })\n : undefined;\n\n if (span) {\n xhr.__sentry_xhr_span_id__ = span.spanId;\n spans[xhr.__sentry_xhr_span_id__] = span;\n }\n\n if (xhr.setRequestHeader && shouldAttachHeaders(sentryXhrData.url)) {\n if (span) {\n const transaction = span && span.transaction;\n const dynamicSamplingContext = transaction && transaction.getDynamicSamplingContext();\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n setHeaderOnXhr(xhr, span.toTraceparent(), sentryBaggageHeader);\n } else {\n const client = hub.getClient();\n const { traceId, sampled, dsc } = scope.getPropagationContext();\n const sentryTraceHeader = generateSentryTraceHeader(traceId, undefined, sampled);\n const dynamicSamplingContext =\n dsc || (client ? getDynamicSamplingContextFromClient(traceId, client, scope) : undefined);\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n setHeaderOnXhr(xhr, sentryTraceHeader, sentryBaggageHeader);\n }\n }\n\n return span;\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_HEADER_NAME, sentryBaggageHeader);\n }\n } catch (_) {\n // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.\n }\n}\n\nexport { DEFAULT_TRACE_PROPAGATION_TARGETS, defaultRequestInstrumentationOptions, extractNetworkProtocol, instrumentOutgoingRequests, shouldAttachHeaders, xhrCallback };\n","import { hasTracingEnabled, getCurrentHub, getDynamicSamplingContextFromClient } from '@sentry/core';\nimport { generateSentryTraceHeader, dynamicSamplingContextToSentryBaggageHeader, isInstanceOf, BAGGAGE_HEADER_NAME } from '@sentry/utils';\n\n/**\n * Create and track fetch request spans for usage in combination with `addInstrumentationHandler`.\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 (!hasTracingEnabled() || !handlerData.fetchData) {\n return undefined;\n }\n\n const shouldCreateSpanResult = 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 if (handlerData.response) {\n span.setHttpStatus(handlerData.response.status);\n\n const contentLength =\n handlerData.response && handlerData.response.headers && handlerData.response.headers.get('content-length');\n\n if (contentLength) {\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setData('http.response_content_length', contentLengthNum);\n }\n }\n } else if (handlerData.error) {\n span.setStatus('internal_error');\n }\n span.finish();\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n const hub = getCurrentHub();\n const scope = hub.getScope();\n const client = hub.getClient();\n const parentSpan = scope.getSpan();\n\n const { method, url } = handlerData.fetchData;\n\n const span =\n shouldCreateSpanResult && parentSpan\n ? parentSpan.startChild({\n data: {\n url,\n type: 'fetch',\n 'http.method': method,\n },\n description: `${method} ${url}`,\n op: 'http.client',\n origin: spanOrigin,\n })\n : undefined;\n\n if (span) {\n handlerData.fetchData.__span = span.spanId;\n spans[span.spanId] = span;\n }\n\n if (shouldAttachHeaders(handlerData.fetchData.url) && client) {\n const request = handlerData.args[0];\n\n // In case the user hasn't set the second argument of a fetch call we default it to `{}`.\n handlerData.args[1] = handlerData.args[1] || {};\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const options = handlerData.args[1];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access\n options.headers = addTracingHeadersToFetchRequest(request, client, scope, options, span);\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, // unknown is actually type Request but we can't export DOM types from this package,\n client,\n scope,\n options\n\n,\n requestSpan,\n) {\n const span = requestSpan || scope.getSpan();\n\n const transaction = span && span.transaction;\n\n const { traceId, sampled, dsc } = scope.getPropagationContext();\n\n const sentryTraceHeader = span ? span.toTraceparent() : generateSentryTraceHeader(traceId, undefined, sampled);\n const dynamicSamplingContext = transaction\n ? transaction.getDynamicSamplingContext()\n : dsc\n ? dsc\n : getDynamicSamplingContextFromClient(traceId, client, scope);\n\n const sentryBaggageHeader = dynamicSamplingContextToSentryBaggageHeader(dynamicSamplingContext);\n\n const headers =\n typeof Request !== 'undefined' && isInstanceOf(request, Request) ? (request ).headers : options.headers;\n\n if (!headers) {\n return { 'sentry-trace': sentryTraceHeader, baggage: sentryBaggageHeader };\n } else if (typeof Headers !== 'undefined' && isInstanceOf(headers, Headers)) {\n const newHeaders = new Headers(headers );\n\n newHeaders.append('sentry-trace', sentryTraceHeader);\n\n if (sentryBaggageHeader) {\n // If the same header is appended multiple times 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.append(BAGGAGE_HEADER_NAME, sentryBaggageHeader);\n }\n\n return newHeaders ;\n } else if (Array.isArray(headers)) {\n const newHeaders = [...headers, ['sentry-trace', sentryTraceHeader]];\n\n if (sentryBaggageHeader) {\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_HEADER_NAME, sentryBaggageHeader]);\n }\n\n return newHeaders ;\n } else {\n const existingBaggageHeader = 'baggage' in headers ? headers.baggage : undefined;\n const newBaggageHeaders = [];\n\n if (Array.isArray(existingBaggageHeader)) {\n newBaggageHeaders.push(...existingBaggageHeader);\n } else if (existingBaggageHeader) {\n newBaggageHeaders.push(existingBaggageHeader);\n }\n\n if (sentryBaggageHeader) {\n newBaggageHeaders.push(sentryBaggageHeader);\n }\n\n return {\n ...(headers ),\n 'sentry-trace': sentryTraceHeader,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n }\n}\n\nexport { addTracingHeadersToFetchRequest, instrumentFetchRequest };\n","import { TRACING_DEFAULTS, addTracingExtensions, startIdleTransaction, getActiveTransaction } from '@sentry/core';\nimport { logger, tracingContextFromHeaders, getDomElement } from '@sentry/utils';\nimport { registerBackgroundTabDetection } from './backgroundtab.js';\nimport { startTrackingWebVitals, startTrackingLongTasks, startTrackingInteractions, addPerformanceEntries } from './metrics/index.js';\nimport { defaultRequestInstrumentationOptions, instrumentOutgoingRequests } from './request.js';\nimport { instrumentRoutingWithDefaults } from './router.js';\nimport { WINDOW } from './types.js';\n\nconst BROWSER_TRACING_INTEGRATION_ID = 'BrowserTracing';\n\n/** Options for Browser Tracing integration */\n\nconst DEFAULT_BROWSER_TRACING_OPTIONS = {\n ...TRACING_DEFAULTS,\n markBackgroundTransactions: true,\n routingInstrumentation: instrumentRoutingWithDefaults,\n startTransactionOnLocationChange: true,\n startTransactionOnPageLoad: true,\n enableLongTask: 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. This integration uses {@see IdleTransaction} to create transactions.\n */\nclass BrowserTracing {\n // This class currently doesn't have a static `id` field like the other integration classes, because it prevented\n // @sentry/tracing from being treeshaken. Tree shakers do not like static fields, because they behave like side effects.\n // TODO: Come up with a better plan, than using static fields on integration classes, and use that plan on all\n // integrations.\n\n /** Browser Tracing integration options */\n\n /**\n * @inheritDoc\n */\n\n constructor(_options) {\n this.name = BROWSER_TRACING_INTEGRATION_ID;\n this._hasSetTracePropagationTargets = false;\n\n addTracingExtensions();\n\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__)) {\n this._hasSetTracePropagationTargets = !!(\n _options &&\n // eslint-disable-next-line deprecation/deprecation\n (_options.tracePropagationTargets || _options.tracingOrigins)\n );\n }\n\n this.options = {\n ...DEFAULT_BROWSER_TRACING_OPTIONS,\n ..._options,\n };\n\n // Special case: enableLongTask can be set in _experiments\n // TODO (v8): Remove this in v8\n if (this.options._experiments.enableLongTask !== undefined) {\n this.options.enableLongTask = this.options._experiments.enableLongTask;\n }\n\n // TODO (v8): remove this block after tracingOrigins is removed\n // Set tracePropagationTargets to tracingOrigins if specified by the user\n // In case both are specified, tracePropagationTargets takes precedence\n // eslint-disable-next-line deprecation/deprecation\n if (_options && !_options.tracePropagationTargets && _options.tracingOrigins) {\n // eslint-disable-next-line deprecation/deprecation\n this.options.tracePropagationTargets = _options.tracingOrigins;\n }\n\n this._collectWebVitals = startTrackingWebVitals();\n if (this.options.enableLongTask) {\n startTrackingLongTasks();\n }\n if (this.options._experiments.enableInteractions) {\n startTrackingInteractions();\n }\n }\n\n /**\n * @inheritDoc\n */\n setupOnce(_, getCurrentHub) {\n this._getCurrentHub = getCurrentHub;\n const hub = getCurrentHub();\n const client = hub.getClient();\n const clientOptions = client && client.getOptions();\n\n const {\n routingInstrumentation: instrumentRouting,\n startTransactionOnLocationChange,\n startTransactionOnPageLoad,\n markBackgroundTransactions,\n traceFetch,\n traceXHR,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n _experiments,\n } = this.options;\n\n const clientOptionsTracePropagationTargets = clientOptions && clientOptions.tracePropagationTargets;\n // There are three ways to configure tracePropagationTargets:\n // 1. via top level client option `tracePropagationTargets`\n // 2. via BrowserTracing option `tracePropagationTargets`\n // 3. via BrowserTracing option `tracingOrigins` (deprecated)\n //\n // To avoid confusion, favour top level client option `tracePropagationTargets`, and fallback to\n // BrowserTracing option `tracePropagationTargets` and then `tracingOrigins` (deprecated).\n // This is done as it minimizes bundle size (we don't have to have undefined checks).\n //\n // If both 1 and either one of 2 or 3 are set (from above), we log out a warning.\n // eslint-disable-next-line deprecation/deprecation\n const tracePropagationTargets = clientOptionsTracePropagationTargets || this.options.tracePropagationTargets;\n if ((typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && this._hasSetTracePropagationTargets && clientOptionsTracePropagationTargets) {\n logger.warn(\n '[Tracing] The `tracePropagationTargets` option was set in the BrowserTracing integration and top level `Sentry.init`. The top level `Sentry.init` value is being used.',\n );\n }\n\n instrumentRouting(\n (context) => {\n const transaction = this._createRouteTransaction(context);\n\n this.options._experiments.onStartRouteTransaction &&\n this.options._experiments.onStartRouteTransaction(transaction, context, getCurrentHub);\n\n return transaction;\n },\n startTransactionOnPageLoad,\n startTransactionOnLocationChange,\n );\n\n if (markBackgroundTransactions) {\n registerBackgroundTabDetection();\n }\n\n if (_experiments.enableInteractions) {\n this._registerInteractionListener();\n }\n\n instrumentOutgoingRequests({\n traceFetch,\n traceXHR,\n tracePropagationTargets,\n shouldCreateSpanForRequest,\n enableHTTPTimings,\n });\n }\n\n /** Create routing idle transaction. */\n _createRouteTransaction(context) {\n if (!this._getCurrentHub) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`[Tracing] Did not create ${context.op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n\n const { beforeNavigate, idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n\n const isPageloadTransaction = context.op === 'pageload';\n\n const sentryTrace = isPageloadTransaction ? getMetaContent('sentry-trace') : '';\n const baggage = isPageloadTransaction ? getMetaContent('baggage') : '';\n const { traceparentData, dynamicSamplingContext, propagationContext } = tracingContextFromHeaders(\n sentryTrace,\n baggage,\n );\n\n const expandedContext = {\n ...context,\n ...traceparentData,\n metadata: {\n ...context.metadata,\n dynamicSamplingContext: traceparentData && !dynamicSamplingContext ? {} : dynamicSamplingContext,\n },\n trimEnd: true,\n };\n\n const modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext;\n\n // For backwards compatibility reasons, beforeNavigate can return undefined to \"drop\" the transaction (prevent it\n // from being sent to Sentry).\n const finalContext = modifiedContext === undefined ? { ...expandedContext, sampled: false } : modifiedContext;\n\n // If `beforeNavigate` set a custom name, record that fact\n finalContext.metadata =\n finalContext.name !== expandedContext.name\n ? { ...finalContext.metadata, source: 'custom' }\n : finalContext.metadata;\n\n this._latestRouteName = finalContext.name;\n this._latestRouteSource = finalContext.metadata && finalContext.metadata.source;\n\n if (finalContext.sampled === false) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(`[Tracing] Will not send ${finalContext.op} transaction because of beforeNavigate.`);\n }\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Starting ${finalContext.op} transaction on scope`);\n\n const { location } = WINDOW;\n\n const idleTransaction = startIdleTransaction(\n hub,\n finalContext,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n\n const scope = hub.getScope();\n\n // If it's a pageload and there is a meta tag set\n // use the traceparentData as the propagation context\n if (isPageloadTransaction && traceparentData) {\n scope.setPropagationContext(propagationContext);\n } else {\n // Navigation transactions should set a new propagation context based on the\n // created idle transaction.\n scope.setPropagationContext({\n traceId: idleTransaction.traceId,\n spanId: idleTransaction.spanId,\n parentSpanId: idleTransaction.parentSpanId,\n sampled: idleTransaction.sampled,\n });\n }\n\n idleTransaction.registerBeforeFinishCallback(transaction => {\n this._collectWebVitals();\n addPerformanceEntries(transaction);\n });\n\n return idleTransaction ;\n }\n\n /** Start listener for interaction transactions */\n _registerInteractionListener() {\n let inflightInteractionTransaction;\n const registerInteractionTransaction = () => {\n const { idleTimeout, finalTimeout, heartbeatInterval } = this.options;\n const op = 'ui.action.click';\n\n const currentTransaction = getActiveTransaction();\n if (currentTransaction && currentTransaction.op && ['navigation', 'pageload'].includes(currentTransaction.op)) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(\n `[Tracing] Did not create ${op} transaction because a pageload or navigation transaction is in progress.`,\n );\n return undefined;\n }\n\n if (inflightInteractionTransaction) {\n inflightInteractionTransaction.setFinishReason('interactionInterrupted');\n inflightInteractionTransaction.finish();\n inflightInteractionTransaction = undefined;\n }\n\n if (!this._getCurrentHub) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn(`[Tracing] Did not create ${op} transaction because _getCurrentHub is invalid.`);\n return undefined;\n }\n\n if (!this._latestRouteName) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn(`[Tracing] Did not create ${op} transaction because _latestRouteName is missing.`);\n return undefined;\n }\n\n const hub = this._getCurrentHub();\n const { location } = WINDOW;\n\n const context = {\n name: this._latestRouteName,\n op,\n trimEnd: true,\n metadata: {\n source: this._latestRouteSource || 'url',\n },\n };\n\n inflightInteractionTransaction = startIdleTransaction(\n hub,\n context,\n idleTimeout,\n finalTimeout,\n true,\n { location }, // for use in the tracesSampler\n heartbeatInterval,\n );\n };\n\n ['click'].forEach(type => {\n addEventListener(type, registerInteractionTransaction, { once: false, capture: true });\n });\n }\n}\n\n/** Returns the value of a meta tag */\nfunction getMetaContent(metaName) {\n // Can't specify generic to `getDomElement` because tracing can be used\n // in a variety of environments, have to disable `no-unsafe-member-access`\n // as a result.\n const metaTag = getDomElement(`meta[name=${metaName}]`);\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return metaTag ? metaTag.getAttribute('content') : undefined;\n}\n\nexport { BROWSER_TRACING_INTEGRATION_ID, BrowserTracing, getMetaContent };\n","import { logger, browserPerformanceTimeOrigin, addInstrumentationHandler } from '@sentry/utils';\nimport { WINDOW } from './types.js';\n\n/**\n * Default function implementing pageload and navigation transactions\n */\nfunction instrumentRoutingWithDefaults(\n customStartTransaction,\n startTransactionOnPageLoad = true,\n startTransactionOnLocationChange = true,\n) {\n if (!WINDOW || !WINDOW.location) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.warn('Could not initialize routing instrumentation due to invalid location');\n return;\n }\n\n let startingUrl = WINDOW.location.href;\n\n let activeTransaction;\n if (startTransactionOnPageLoad) {\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n // pageload should always start at timeOrigin (and needs to be in s, not ms)\n startTimestamp: browserPerformanceTimeOrigin ? browserPerformanceTimeOrigin / 1000 : undefined,\n op: 'pageload',\n origin: 'auto.pageload.browser',\n metadata: { source: 'url' },\n });\n }\n\n if (startTransactionOnLocationChange) {\n addInstrumentationHandler('history', ({ 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 && startingUrl.indexOf(to) !== -1) {\n startingUrl = undefined;\n return;\n }\n\n if (from !== to) {\n startingUrl = undefined;\n if (activeTransaction) {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] Finishing current transaction with op: ${activeTransaction.op}`);\n // If there's an open transaction on the scope, we need to finish it before creating an new one.\n activeTransaction.finish();\n }\n activeTransaction = customStartTransaction({\n name: WINDOW.location.pathname,\n op: 'navigation',\n origin: 'auto.navigation.browser',\n metadata: { source: 'url' },\n });\n }\n });\n }\n}\n\nexport { instrumentRoutingWithDefaults };\n","import { defaultIntegrations, init as browserInit } from '@sentry/browser';\nimport { Hub, makeMain } from '@sentry/core';\nimport { DeviceContext, EventOrigin, Release, SdkInfo } from './integrations';\nimport { createCapacitorRewriteFrames } from './integrations/rewriteframes';\nimport { CapacitorScope } from './scope';\nimport { DEFAULT_BUFFER_SIZE, makeNativeTransport } from './transports/native';\nimport { makeUtf8TextEncoder } from './transports/TextEncoder';\nimport { NATIVE } from './wrapper';\n/**\n * Initializes the Capacitor SDK alongside a sibling Sentry SDK\n * @param options Options for the SDK\n * @param originalInit The init function of the sibling SDK, leave blank to initialize with `@sentry/browser`\n */\nexport function init(passedOptions, originalInit = browserInit) {\n var _a, _b, _c;\n const finalOptions = Object.assign({ enableAutoSessionTracking: true, enableWatchdogTerminationTracking: true }, passedOptions);\n if (finalOptions.enabled === false ||\n NATIVE.platform === 'web') {\n finalOptions.enableNative = false;\n finalOptions.enableNativeNagger = false;\n }\n else {\n // keep the original value if user defined it.\n (_a = finalOptions.enableNativeNagger) !== null && _a !== void 0 ? _a : (finalOptions.enableNativeNagger = true);\n (_b = finalOptions.enableNative) !== null && _b !== void 0 ? _b : (finalOptions.enableNative = true);\n }\n const capacitorHub = new Hub(undefined, new CapacitorScope());\n makeMain(capacitorHub);\n finalOptions.defaultIntegrations = [\n ...defaultIntegrations,\n createCapacitorRewriteFrames(),\n new Release(),\n new SdkInfo(),\n new EventOrigin(),\n ];\n if (finalOptions.enableNative) {\n finalOptions.defaultIntegrations.push(new DeviceContext());\n if (!passedOptions.transport && NATIVE.platform !== 'web') {\n finalOptions.transport = passedOptions.transport\n || makeNativeTransport;\n finalOptions.transportOptions = Object.assign(Object.assign({ textEncoder: makeUtf8TextEncoder() }, ((_c = passedOptions.transportOptions) !== null && _c !== void 0 ? _c : {})), { bufferSize: DEFAULT_BUFFER_SIZE });\n }\n }\n const browserOptions = Object.assign(Object.assign({}, finalOptions), { autoSessionTracking: NATIVE.platform === 'web' && finalOptions.enableAutoSessionTracking });\n const mobileOptions = Object.assign(Object.assign({}, finalOptions), { enableAutoSessionTracking: NATIVE.platform !== 'web' && finalOptions.enableAutoSessionTracking });\n // We first initialize the NATIVE SDK to avoid the Javascript SDK to invoke any\n // feature from the NATIVE SDK without the options being set.\n void NATIVE.initNativeSdk(mobileOptions);\n originalInit(browserOptions);\n}\n/**\n * If native client is available it will trigger a native crash\n * Use this only for testing purposes\n */\nexport function nativeCrash() {\n NATIVE.crash();\n}\n","import { utf8ToBytes } from '../vendor';\nexport const makeUtf8TextEncoder = () => {\n const textEncoder = {\n encode: (text) => {\n const bytes = new Uint8Array(utf8ToBytes(text));\n return bytes;\n },\n encoding: 'utf-8',\n };\n return textEncoder;\n};\n","import { bootstrapApplication } from '@angular/platform-browser';\nimport { appConfig } from './app/app.config';\nimport { AppComponent } from './app/app.component';\nimport * as Sentry from '@sentry/capacitor';\nimport * as SentryAngular from '@sentry/angular-ivy';\nimport { environment } from './environments/environment';\n\nSentry.init(\n {\n dsn: 'https://af65d3b66b48c47d1fa4bef6ed24a206@o264253.ingest.sentry.io/4506532654219264',\n // release version\n release: `${environment.version}`,\n // separate environments for error logging\n environment: environment.targetEnv,\n\n integrations: [\n // disable trace on fetch(get) requests to avoid extra header in requests\n new SentryAngular.BrowserTracing({\n traceFetch: false,\n }),\n ],\n\n // Fix issue: Native Client is not available, can't start on native\n // Refer: https://github.com/getsentry/sentry-react-native/issues/920\n // we can disable it safely because it is not a native app\n enableNative: false,\n },\n // Forward the init method from @sentry/angular\n SentryAngular.init\n);\n\nbootstrapApplication(AppComponent, appConfig).catch((err) =>\n console.error('Error bootstrapping application:', err)\n);\n","import { getActiveTransaction } from '@sentry/core';\nimport { logger } from '@sentry/utils';\nimport { WINDOW } from './types.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 && WINDOW.document) {\n WINDOW.document.addEventListener('visibilitychange', () => {\n const activeTransaction = getActiveTransaction() ;\n if (WINDOW.document.hidden && activeTransaction) {\n const statusType = 'cancelled';\n\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.log(\n `[Tracing] Transaction: ${statusType} -> since tab moved to the background, op: ${activeTransaction.op}`,\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 (!activeTransaction.status) {\n activeTransaction.setStatus(statusType);\n }\n activeTransaction.setTag('visibilitychange', 'document.hidden');\n activeTransaction.finish();\n }\n });\n } else {\n (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&\n logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');\n }\n}\n\nexport { registerBackgroundTabDetection };\n","/*! Capacitor: https://capacitorjs.com/ - MIT License */\nconst createCapacitorPlatforms = (win) => {\n const defaultPlatformMap = new Map();\n defaultPlatformMap.set('web', { name: 'web' });\n const capPlatforms = win.CapacitorPlatforms || {\n currentPlatform: { name: 'web' },\n platforms: defaultPlatformMap,\n };\n const addPlatform = (name, platform) => {\n capPlatforms.platforms.set(name, platform);\n };\n const setPlatform = (name) => {\n if (capPlatforms.platforms.has(name)) {\n capPlatforms.currentPlatform = capPlatforms.platforms.get(name);\n }\n };\n capPlatforms.addPlatform = addPlatform;\n capPlatforms.setPlatform = setPlatform;\n return capPlatforms;\n};\nconst initPlatforms = (win) => (win.CapacitorPlatforms = createCapacitorPlatforms(win));\n/**\n * @deprecated Set `CapacitorCustomPlatform` on the window object prior to runtime executing in the web app instead\n */\nconst CapacitorPlatforms = /*#__PURE__*/ initPlatforms((typeof globalThis !== 'undefined'\n ? globalThis\n : typeof self !== 'undefined'\n ? self\n : typeof window !== 'undefined'\n ? window\n : typeof global !== 'undefined'\n ? global\n : {}));\n/**\n * @deprecated Set `CapacitorCustomPlatform` on the window object prior to runtime executing in the web app instead\n */\nconst addPlatform = CapacitorPlatforms.addPlatform;\n/**\n * @deprecated Set `CapacitorCustomPlatform` on the window object prior to runtime executing in the web app instead\n */\nconst setPlatform = CapacitorPlatforms.setPlatform;\n\nconst legacyRegisterWebPlugin = (cap, webPlugin) => {\n var _a;\n const config = webPlugin.config;\n const Plugins = cap.Plugins;\n if (!(config === null || config === void 0 ? void 0 : config.name)) {\n // TODO: add link to upgrade guide\n throw new Error(`Capacitor WebPlugin is using the deprecated \"registerWebPlugin()\" function, but without the config. Please use \"registerPlugin()\" instead to register this web plugin.\"`);\n }\n // TODO: add link to upgrade guide\n console.warn(`Capacitor plugin \"${config.name}\" is using the deprecated \"registerWebPlugin()\" function`);\n if (!Plugins[config.name] || ((_a = config === null || config === void 0 ? void 0 : config.platforms) === null || _a === void 0 ? void 0 : _a.includes(cap.getPlatform()))) {\n // Add the web plugin into the plugins registry if there already isn't\n // an existing one. If it doesn't already exist, that means\n // there's no existing native implementation for it.\n // - OR -\n // If we already have a plugin registered (meaning it was defined in the native layer),\n // then we should only overwrite it if the corresponding web plugin activates on\n // a certain platform. For example: Geolocation uses the WebPlugin on Android but not iOS\n Plugins[config.name] = webPlugin;\n }\n};\n\nvar ExceptionCode;\n(function (ExceptionCode) {\n /**\n * API is not implemented.\n *\n * This usually means the API can't be used because it is not implemented for\n * the current platform.\n */\n ExceptionCode[\"Unimplemented\"] = \"UNIMPLEMENTED\";\n /**\n * API is not available.\n *\n * This means the API can't be used right now because:\n * - it is currently missing a prerequisite, such as network connectivity\n * - it requires a particular platform or browser version\n */\n ExceptionCode[\"Unavailable\"] = \"UNAVAILABLE\";\n})(ExceptionCode || (ExceptionCode = {}));\nclass CapacitorException extends Error {\n constructor(message, code, data) {\n super(message);\n this.message = message;\n this.code = code;\n this.data = data;\n }\n}\nconst getPlatformId = (win) => {\n var _a, _b;\n if (win === null || win === void 0 ? void 0 : win.androidBridge) {\n return 'android';\n }\n else if ((_b = (_a = win === null || win === void 0 ? void 0 : win.webkit) === null || _a === void 0 ? void 0 : _a.messageHandlers) === null || _b === void 0 ? void 0 : _b.bridge) {\n return 'ios';\n }\n else {\n return 'web';\n }\n};\n\nconst createCapacitor = (win) => {\n var _a, _b, _c, _d, _e;\n const capCustomPlatform = win.CapacitorCustomPlatform || null;\n const cap = win.Capacitor || {};\n const Plugins = (cap.Plugins = cap.Plugins || {});\n /**\n * @deprecated Use `capCustomPlatform` instead, default functions like registerPlugin will function with the new object.\n */\n const capPlatforms = win.CapacitorPlatforms;\n const defaultGetPlatform = () => {\n return capCustomPlatform !== null\n ? capCustomPlatform.name\n : getPlatformId(win);\n };\n const getPlatform = ((_a = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _a === void 0 ? void 0 : _a.getPlatform) || defaultGetPlatform;\n const defaultIsNativePlatform = () => getPlatform() !== 'web';\n const isNativePlatform = ((_b = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _b === void 0 ? void 0 : _b.isNativePlatform) || defaultIsNativePlatform;\n const defaultIsPluginAvailable = (pluginName) => {\n const plugin = registeredPlugins.get(pluginName);\n if (plugin === null || plugin === void 0 ? void 0 : plugin.platforms.has(getPlatform())) {\n // JS implementation available for the current platform.\n return true;\n }\n if (getPluginHeader(pluginName)) {\n // Native implementation available.\n return true;\n }\n return false;\n };\n const isPluginAvailable = ((_c = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _c === void 0 ? void 0 : _c.isPluginAvailable) ||\n defaultIsPluginAvailable;\n const defaultGetPluginHeader = (pluginName) => { var _a; return (_a = cap.PluginHeaders) === null || _a === void 0 ? void 0 : _a.find(h => h.name === pluginName); };\n const getPluginHeader = ((_d = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _d === void 0 ? void 0 : _d.getPluginHeader) || defaultGetPluginHeader;\n const handleError = (err) => win.console.error(err);\n const pluginMethodNoop = (_target, prop, pluginName) => {\n return Promise.reject(`${pluginName} does not have an implementation of \"${prop}\".`);\n };\n const registeredPlugins = new Map();\n const defaultRegisterPlugin = (pluginName, jsImplementations = {}) => {\n const registeredPlugin = registeredPlugins.get(pluginName);\n if (registeredPlugin) {\n console.warn(`Capacitor plugin \"${pluginName}\" already registered. Cannot register plugins twice.`);\n return registeredPlugin.proxy;\n }\n const platform = getPlatform();\n const pluginHeader = getPluginHeader(pluginName);\n let jsImplementation;\n const loadPluginImplementation = async () => {\n if (!jsImplementation && platform in jsImplementations) {\n jsImplementation =\n typeof jsImplementations[platform] === 'function'\n ? (jsImplementation = await jsImplementations[platform]())\n : (jsImplementation = jsImplementations[platform]);\n }\n else if (capCustomPlatform !== null &&\n !jsImplementation &&\n 'web' in jsImplementations) {\n jsImplementation =\n typeof jsImplementations['web'] === 'function'\n ? (jsImplementation = await jsImplementations['web']())\n : (jsImplementation = jsImplementations['web']);\n }\n return jsImplementation;\n };\n const createPluginMethod = (impl, prop) => {\n var _a, _b;\n if (pluginHeader) {\n const methodHeader = pluginHeader === null || pluginHeader === void 0 ? void 0 : pluginHeader.methods.find(m => prop === m.name);\n if (methodHeader) {\n if (methodHeader.rtype === 'promise') {\n return (options) => cap.nativePromise(pluginName, prop.toString(), options);\n }\n else {\n return (options, callback) => cap.nativeCallback(pluginName, prop.toString(), options, callback);\n }\n }\n else if (impl) {\n return (_a = impl[prop]) === null || _a === void 0 ? void 0 : _a.bind(impl);\n }\n }\n else if (impl) {\n return (_b = impl[prop]) === null || _b === void 0 ? void 0 : _b.bind(impl);\n }\n else {\n throw new CapacitorException(`\"${pluginName}\" plugin is not implemented on ${platform}`, ExceptionCode.Unimplemented);\n }\n };\n const createPluginMethodWrapper = (prop) => {\n let remove;\n const wrapper = (...args) => {\n const p = loadPluginImplementation().then(impl => {\n const fn = createPluginMethod(impl, prop);\n if (fn) {\n const p = fn(...args);\n remove = p === null || p === void 0 ? void 0 : p.remove;\n return p;\n }\n else {\n throw new CapacitorException(`\"${pluginName}.${prop}()\" is not implemented on ${platform}`, ExceptionCode.Unimplemented);\n }\n });\n if (prop === 'addListener') {\n p.remove = async () => remove();\n }\n return p;\n };\n // Some flair ✨\n wrapper.toString = () => `${prop.toString()}() { [capacitor code] }`;\n Object.defineProperty(wrapper, 'name', {\n value: prop,\n writable: false,\n configurable: false,\n });\n return wrapper;\n };\n const addListener = createPluginMethodWrapper('addListener');\n const removeListener = createPluginMethodWrapper('removeListener');\n const addListenerNative = (eventName, callback) => {\n const call = addListener({ eventName }, callback);\n const remove = async () => {\n const callbackId = await call;\n removeListener({\n eventName,\n callbackId,\n }, callback);\n };\n const p = new Promise(resolve => call.then(() => resolve({ remove })));\n p.remove = async () => {\n console.warn(`Using addListener() without 'await' is deprecated.`);\n await remove();\n };\n return p;\n };\n const proxy = new Proxy({}, {\n get(_, prop) {\n switch (prop) {\n // https://github.com/facebook/react/issues/20030\n case '$$typeof':\n return undefined;\n case 'toJSON':\n return () => ({});\n case 'addListener':\n return pluginHeader ? addListenerNative : addListener;\n case 'removeListener':\n return removeListener;\n default:\n return createPluginMethodWrapper(prop);\n }\n },\n });\n Plugins[pluginName] = proxy;\n registeredPlugins.set(pluginName, {\n name: pluginName,\n proxy,\n platforms: new Set([\n ...Object.keys(jsImplementations),\n ...(pluginHeader ? [platform] : []),\n ]),\n });\n return proxy;\n };\n const registerPlugin = ((_e = capPlatforms === null || capPlatforms === void 0 ? void 0 : capPlatforms.currentPlatform) === null || _e === void 0 ? void 0 : _e.registerPlugin) || defaultRegisterPlugin;\n // Add in convertFileSrc for web, it will already be available in native context\n if (!cap.convertFileSrc) {\n cap.convertFileSrc = filePath => filePath;\n }\n cap.getPlatform = getPlatform;\n cap.handleError = handleError;\n cap.isNativePlatform = isNativePlatform;\n cap.isPluginAvailable = isPluginAvailable;\n cap.pluginMethodNoop = pluginMethodNoop;\n cap.registerPlugin = registerPlugin;\n cap.Exception = CapacitorException;\n cap.DEBUG = !!cap.DEBUG;\n cap.isLoggingEnabled = !!cap.isLoggingEnabled;\n // Deprecated props\n cap.platform = cap.getPlatform();\n cap.isNative = cap.isNativePlatform();\n return cap;\n};\nconst initCapacitorGlobal = (win) => (win.Capacitor = createCapacitor(win));\n\nconst Capacitor = /*#__PURE__*/ initCapacitorGlobal(typeof globalThis !== 'undefined'\n ? globalThis\n : typeof self !== 'undefined'\n ? self\n : typeof window !== 'undefined'\n ? window\n : typeof global !== 'undefined'\n ? global\n : {});\nconst registerPlugin = Capacitor.registerPlugin;\n/**\n * @deprecated Provided for backwards compatibility for Capacitor v2 plugins.\n * Capacitor v3 plugins should import the plugin directly. This \"Plugins\"\n * export is deprecated in v3, and will be removed in v4.\n */\nconst Plugins = Capacitor.Plugins;\n/**\n * Provided for backwards compatibility. Use the registerPlugin() API\n * instead, and provide the web plugin as the \"web\" implmenetation.\n * For example\n *\n * export const Example = registerPlugin('Example', {\n * web: () => import('./web').then(m => new m.Example())\n * })\n *\n * @deprecated Deprecated in v3, will be removed from v4.\n */\nconst registerWebPlugin = (plugin) => legacyRegisterWebPlugin(Capacitor, plugin);\n\n/**\n * Base class web plugins should extend.\n */\nclass WebPlugin {\n constructor(config) {\n this.listeners = {};\n this.windowListeners = {};\n if (config) {\n // TODO: add link to upgrade guide\n console.warn(`Capacitor WebPlugin \"${config.name}\" config object was deprecated in v3 and will be removed in v4.`);\n this.config = config;\n }\n }\n addListener(eventName, listenerFunc) {\n const listeners = this.listeners[eventName];\n if (!listeners) {\n this.listeners[eventName] = [];\n }\n this.listeners[eventName].push(listenerFunc);\n // If we haven't added a window listener for this event and it requires one,\n // go ahead and add it\n const windowListener = this.windowListeners[eventName];\n if (windowListener && !windowListener.registered) {\n this.addWindowListener(windowListener);\n }\n const remove = async () => this.removeListener(eventName, listenerFunc);\n const p = Promise.resolve({ remove });\n Object.defineProperty(p, 'remove', {\n value: async () => {\n console.warn(`Using addListener() without 'await' is deprecated.`);\n await remove();\n },\n });\n return p;\n }\n async removeAllListeners() {\n this.listeners = {};\n for (const listener in this.windowListeners) {\n this.removeWindowListener(this.windowListeners[listener]);\n }\n this.windowListeners = {};\n }\n notifyListeners(eventName, data) {\n const listeners = this.listeners[eventName];\n if (listeners) {\n listeners.forEach(listener => listener(data));\n }\n }\n hasListeners(eventName) {\n return !!this.listeners[eventName].length;\n }\n registerWindowListener(windowEventName, pluginEventName) {\n this.windowListeners[pluginEventName] = {\n registered: false,\n windowEventName,\n pluginEventName,\n handler: event => {\n this.notifyListeners(pluginEventName, event);\n },\n };\n }\n unimplemented(msg = 'not implemented') {\n return new Capacitor.Exception(msg, ExceptionCode.Unimplemented);\n }\n unavailable(msg = 'not available') {\n return new Capacitor.Exception(msg, ExceptionCode.Unavailable);\n }\n async removeListener(eventName, listenerFunc) {\n const listeners = this.listeners[eventName];\n if (!listeners) {\n return;\n }\n const index = listeners.indexOf(listenerFunc);\n this.listeners[eventName].splice(index, 1);\n // If there are no more listeners for this type of event,\n // remove the window listener\n if (!this.listeners[eventName].length) {\n this.removeWindowListener(this.windowListeners[eventName]);\n }\n }\n addWindowListener(handle) {\n window.addEventListener(handle.windowEventName, handle.handler);\n handle.registered = true;\n }\n removeWindowListener(handle) {\n if (!handle) {\n return;\n }\n window.removeEventListener(handle.windowEventName, handle.handler);\n handle.registered = false;\n }\n}\n\nconst WebView = /*#__PURE__*/ registerPlugin('WebView');\n/******** END WEB VIEW PLUGIN ********/\n/******** COOKIES PLUGIN ********/\n/**\n * Safely web encode a string value (inspired by js-cookie)\n * @param str The string value to encode\n */\nconst encode = (str) => encodeURIComponent(str)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n/**\n * Safely web decode a string value (inspired by js-cookie)\n * @param str The string value to decode\n */\nconst decode = (str) => str.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent);\nclass CapacitorCookiesPluginWeb extends WebPlugin {\n async getCookies() {\n const cookies = document.cookie;\n const cookieMap = {};\n cookies.split(';').forEach(cookie => {\n if (cookie.length <= 0)\n return;\n // Replace first \"=\" with CAP_COOKIE to prevent splitting on additional \"=\"\n let [key, value] = cookie.replace(/=/, 'CAP_COOKIE').split('CAP_COOKIE');\n key = decode(key).trim();\n value = decode(value).trim();\n cookieMap[key] = value;\n });\n return cookieMap;\n }\n async setCookie(options) {\n try {\n // Safely Encoded Key/Value\n const encodedKey = encode(options.key);\n const encodedValue = encode(options.value);\n // Clean & sanitize options\n const expires = `; expires=${(options.expires || '').replace('expires=', '')}`; // Default is \"; expires=\"\n const path = (options.path || '/').replace('path=', ''); // Default is \"path=/\"\n const domain = options.url != null && options.url.length > 0\n ? `domain=${options.url}`\n : '';\n document.cookie = `${encodedKey}=${encodedValue || ''}${expires}; path=${path}; ${domain};`;\n }\n catch (error) {\n return Promise.reject(error);\n }\n }\n async deleteCookie(options) {\n try {\n document.cookie = `${options.key}=; Max-Age=0`;\n }\n catch (error) {\n return Promise.reject(error);\n }\n }\n async clearCookies() {\n try {\n const cookies = document.cookie.split(';') || [];\n for (const cookie of cookies) {\n document.cookie = cookie\n .replace(/^ +/, '')\n .replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`);\n }\n }\n catch (error) {\n return Promise.reject(error);\n }\n }\n async clearAllCookies() {\n try {\n await this.clearCookies();\n }\n catch (error) {\n return Promise.reject(error);\n }\n }\n}\nconst CapacitorCookies = registerPlugin('CapacitorCookies', {\n web: () => new CapacitorCookiesPluginWeb(),\n});\n// UTILITY FUNCTIONS\n/**\n * Read in a Blob value and return it as a base64 string\n * @param blob The blob value to convert to a base64 string\n */\nconst readBlobAsBase64 = async (blob) => new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => {\n const base64String = reader.result;\n // remove prefix \"data:application/pdf;base64,\"\n resolve(base64String.indexOf(',') >= 0\n ? base64String.split(',')[1]\n : base64String);\n };\n reader.onerror = (error) => reject(error);\n reader.readAsDataURL(blob);\n});\n/**\n * Normalize an HttpHeaders map by lowercasing all of the values\n * @param headers The HttpHeaders object to normalize\n */\nconst normalizeHttpHeaders = (headers = {}) => {\n const originalKeys = Object.keys(headers);\n const loweredKeys = Object.keys(headers).map(k => k.toLocaleLowerCase());\n const normalized = loweredKeys.reduce((acc, key, index) => {\n acc[key] = headers[originalKeys[index]];\n return acc;\n }, {});\n return normalized;\n};\n/**\n * Builds a string of url parameters that\n * @param params A map of url parameters\n * @param shouldEncode true if you should encodeURIComponent() the values (true by default)\n */\nconst buildUrlParams = (params, shouldEncode = true) => {\n if (!params)\n return null;\n const output = Object.entries(params).reduce((accumulator, entry) => {\n const [key, value] = entry;\n let encodedValue;\n let item;\n if (Array.isArray(value)) {\n item = '';\n value.forEach(str => {\n encodedValue = shouldEncode ? encodeURIComponent(str) : str;\n item += `${key}=${encodedValue}&`;\n });\n // last character will always be \"&\" so slice it off\n item.slice(0, -1);\n }\n else {\n encodedValue = shouldEncode ? encodeURIComponent(value) : value;\n item = `${key}=${encodedValue}`;\n }\n return `${accumulator}&${item}`;\n }, '');\n // Remove initial \"&\" from the reduce\n return output.substr(1);\n};\n/**\n * Build the RequestInit object based on the options passed into the initial request\n * @param options The Http plugin options\n * @param extra Any extra RequestInit values\n */\nconst buildRequestInit = (options, extra = {}) => {\n const output = Object.assign({ method: options.method || 'GET', headers: options.headers }, extra);\n // Get the content-type\n const headers = normalizeHttpHeaders(options.headers);\n const type = headers['content-type'] || '';\n // If body is already a string, then pass it through as-is.\n if (typeof options.data === 'string') {\n output.body = options.data;\n }\n // Build request initializers based off of content-type\n else if (type.includes('application/x-www-form-urlencoded')) {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(options.data || {})) {\n params.set(key, value);\n }\n output.body = params.toString();\n }\n else if (type.includes('multipart/form-data')) {\n const form = new FormData();\n if (options.data instanceof FormData) {\n options.data.forEach((value, key) => {\n form.append(key, value);\n });\n }\n else {\n for (const key of Object.keys(options.data)) {\n form.append(key, options.data[key]);\n }\n }\n output.body = form;\n const headers = new Headers(output.headers);\n headers.delete('content-type'); // content-type will be set by `window.fetch` to includy boundary\n output.headers = headers;\n }\n else if (type.includes('application/json') ||\n typeof options.data === 'object') {\n output.body = JSON.stringify(options.data);\n }\n return output;\n};\n// WEB IMPLEMENTATION\nclass CapacitorHttpPluginWeb extends WebPlugin {\n /**\n * Perform an Http request given a set of options\n * @param options Options to build the HTTP request\n */\n async request(options) {\n const requestInit = buildRequestInit(options, options.webFetchExtra);\n const urlParams = buildUrlParams(options.params, options.shouldEncodeUrlParams);\n const url = urlParams ? `${options.url}?${urlParams}` : options.url;\n const response = await fetch(url, requestInit);\n const contentType = response.headers.get('content-type') || '';\n // Default to 'text' responseType so no parsing happens\n let { responseType = 'text' } = response.ok ? options : {};\n // If the response content-type is json, force the response to be json\n if (contentType.includes('application/json')) {\n responseType = 'json';\n }\n let data;\n let blob;\n switch (responseType) {\n case 'arraybuffer':\n case 'blob':\n blob = await response.blob();\n data = await readBlobAsBase64(blob);\n break;\n case 'json':\n data = await response.json();\n break;\n case 'document':\n case 'text':\n default:\n data = await response.text();\n }\n // Convert fetch headers to Capacitor HttpHeaders\n const headers = {};\n response.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return {\n data,\n headers,\n status: response.status,\n url: response.url,\n };\n }\n /**\n * Perform an Http GET request given a set of options\n * @param options Options to build the HTTP request\n */\n async get(options) {\n return this.request(Object.assign(Object.assign({}, options), { method: 'GET' }));\n }\n /**\n * Perform an Http POST request given a set of options\n * @param options Options to build the HTTP request\n */\n async post(options) {\n return this.request(Object.assign(Object.assign({}, options), { method: 'POST' }));\n }\n /**\n * Perform an Http PUT request given a set of options\n * @param options Options to build the HTTP request\n */\n async put(options) {\n return this.request(Object.assign(Object.assign({}, options), { method: 'PUT' }));\n }\n /**\n * Perform an Http PATCH request given a set of options\n * @param options Options to build the HTTP request\n */\n async patch(options) {\n return this.request(Object.assign(Object.assign({}, options), { method: 'PATCH' }));\n }\n /**\n * Perform an Http DELETE request given a set of options\n * @param options Options to build the HTTP request\n */\n async delete(options) {\n return this.request(Object.assign(Object.assign({}, options), { method: 'DELETE' }));\n }\n}\nconst CapacitorHttp = registerPlugin('CapacitorHttp', {\n web: () => new CapacitorHttpPluginWeb(),\n});\n/******** END HTTP PLUGIN ********/\n\nexport { Capacitor, CapacitorCookies, CapacitorException, CapacitorHttp, CapacitorPlatforms, ExceptionCode, Plugins, WebPlugin, WebView, addPlatform, buildRequestInit, registerPlugin, registerWebPlugin, setPlatform };\n","'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\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};\n\n/*!\n * escape-html\n * Copyright(c) 2012-2013 TJ Holowaychuk\n * Copyright(c) 2015 Andreas Lubbe\n * Copyright(c) 2015 Tiancheng \"Timothy\" Gu\n * MIT Licensed\n */\n\n/**\n * Module variables.\n * @private\n */\n\nvar matchHtmlRegExp = /[\"'&<>]/;\n\n/**\n * Module exports.\n * @public\n */\n\nvar escapeHtml_1 = escapeHtml;\n\n/**\n * Escape special characters in the given string of html.\n *\n * @param {string} string The string to escape for inserting into HTML\n * @return {string}\n * @public\n */\n\nfunction escapeHtml(string) {\n var str = '' + string;\n var match = matchHtmlRegExp.exec(str);\n\n if (!match) {\n return str;\n }\n\n var escape;\n var html = '';\n var index = 0;\n var lastIndex = 0;\n\n for (index = match.index; index < str.length; index++) {\n switch (str.charCodeAt(index)) {\n case 34: // \"\n escape = '"';\n break;\n case 38: // &\n escape = '&';\n break;\n case 39: // '\n escape = ''';\n break;\n case 60: // <\n escape = '<';\n break;\n case 62: // >\n escape = '>';\n break;\n default:\n continue;\n }\n\n if (lastIndex !== index) {\n html += str.substring(lastIndex, index);\n }\n\n lastIndex = index + 1;\n html += escape;\n }\n\n return lastIndex !== index\n ? html + str.substring(lastIndex, index)\n : html;\n}\n\nvar commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\nfunction unwrapExports (x) {\n\treturn x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;\n}\n\nfunction createCommonjsModule(fn, module) {\n\treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n}\n\nvar blocks = createCommonjsModule(function (module, exports) {\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.BLOCKS = void 0;\n/**\n * Map of all Contentful block types. Blocks contain inline or block nodes.\n */\nvar BLOCKS;\n(function (BLOCKS) {\n BLOCKS[\"DOCUMENT\"] = \"document\";\n BLOCKS[\"PARAGRAPH\"] = \"paragraph\";\n BLOCKS[\"HEADING_1\"] = \"heading-1\";\n BLOCKS[\"HEADING_2\"] = \"heading-2\";\n BLOCKS[\"HEADING_3\"] = \"heading-3\";\n BLOCKS[\"HEADING_4\"] = \"heading-4\";\n BLOCKS[\"HEADING_5\"] = \"heading-5\";\n BLOCKS[\"HEADING_6\"] = \"heading-6\";\n BLOCKS[\"OL_LIST\"] = \"ordered-list\";\n BLOCKS[\"UL_LIST\"] = \"unordered-list\";\n BLOCKS[\"LIST_ITEM\"] = \"list-item\";\n BLOCKS[\"HR\"] = \"hr\";\n BLOCKS[\"QUOTE\"] = \"blockquote\";\n BLOCKS[\"EMBEDDED_ENTRY\"] = \"embedded-entry-block\";\n BLOCKS[\"EMBEDDED_ASSET\"] = \"embedded-asset-block\";\n BLOCKS[\"TABLE\"] = \"table\";\n BLOCKS[\"TABLE_ROW\"] = \"table-row\";\n BLOCKS[\"TABLE_CELL\"] = \"table-cell\";\n BLOCKS[\"TABLE_HEADER_CELL\"] = \"table-header-cell\";\n})(BLOCKS = exports.BLOCKS || (exports.BLOCKS = {}));\n\n});\n\nunwrapExports(blocks);\nvar blocks_1 = blocks.BLOCKS;\n\nvar inlines = createCommonjsModule(function (module, exports) {\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.INLINES = void 0;\n/**\n * Map of all Contentful inline types. Inline contain inline or text nodes.\n */\nvar INLINES;\n(function (INLINES) {\n INLINES[\"HYPERLINK\"] = \"hyperlink\";\n INLINES[\"ENTRY_HYPERLINK\"] = \"entry-hyperlink\";\n INLINES[\"ASSET_HYPERLINK\"] = \"asset-hyperlink\";\n INLINES[\"EMBEDDED_ENTRY\"] = \"embedded-entry-inline\";\n})(INLINES = exports.INLINES || (exports.INLINES = {}));\n\n});\n\nunwrapExports(inlines);\nvar inlines_1 = inlines.INLINES;\n\nvar marks = createCommonjsModule(function (module, exports) {\nObject.defineProperty(exports, \"__esModule\", { value: true });\n/**\n * Map of all Contentful marks.\n */\nvar MARKS;\n(function (MARKS) {\n MARKS[\"BOLD\"] = \"bold\";\n MARKS[\"ITALIC\"] = \"italic\";\n MARKS[\"UNDERLINE\"] = \"underline\";\n MARKS[\"CODE\"] = \"code\";\n MARKS[\"SUPERSCRIPT\"] = \"superscript\";\n MARKS[\"SUBSCRIPT\"] = \"subscript\";\n})(MARKS || (MARKS = {}));\nexports.default = MARKS;\n\n});\n\nunwrapExports(marks);\n\nvar schemaConstraints = createCommonjsModule(function (module, exports) {\nvar __spreadArray = (commonjsGlobal && commonjsGlobal.__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};\nvar __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nvar _a;\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.V1_MARKS = exports.V1_NODE_TYPES = exports.TEXT_CONTAINERS = exports.HEADINGS = exports.CONTAINERS = exports.VOID_BLOCKS = exports.TABLE_BLOCKS = exports.LIST_ITEM_BLOCKS = exports.TOP_LEVEL_BLOCKS = void 0;\n\n\nvar marks_1 = __importDefault(marks);\n/**\n * Array of all top level block types.\n * Only these block types can be the direct children of the document.\n */\nexports.TOP_LEVEL_BLOCKS = [\n blocks.BLOCKS.PARAGRAPH,\n blocks.BLOCKS.HEADING_1,\n blocks.BLOCKS.HEADING_2,\n blocks.BLOCKS.HEADING_3,\n blocks.BLOCKS.HEADING_4,\n blocks.BLOCKS.HEADING_5,\n blocks.BLOCKS.HEADING_6,\n blocks.BLOCKS.OL_LIST,\n blocks.BLOCKS.UL_LIST,\n blocks.BLOCKS.HR,\n blocks.BLOCKS.QUOTE,\n blocks.BLOCKS.EMBEDDED_ENTRY,\n blocks.BLOCKS.EMBEDDED_ASSET,\n blocks.BLOCKS.TABLE,\n];\n/**\n * Array of all allowed block types inside list items\n */\nexports.LIST_ITEM_BLOCKS = [\n blocks.BLOCKS.PARAGRAPH,\n blocks.BLOCKS.HEADING_1,\n blocks.BLOCKS.HEADING_2,\n blocks.BLOCKS.HEADING_3,\n blocks.BLOCKS.HEADING_4,\n blocks.BLOCKS.HEADING_5,\n blocks.BLOCKS.HEADING_6,\n blocks.BLOCKS.OL_LIST,\n blocks.BLOCKS.UL_LIST,\n blocks.BLOCKS.HR,\n blocks.BLOCKS.QUOTE,\n blocks.BLOCKS.EMBEDDED_ENTRY,\n blocks.BLOCKS.EMBEDDED_ASSET,\n];\nexports.TABLE_BLOCKS = [\n blocks.BLOCKS.TABLE,\n blocks.BLOCKS.TABLE_ROW,\n blocks.BLOCKS.TABLE_CELL,\n blocks.BLOCKS.TABLE_HEADER_CELL,\n];\n/**\n * Array of all void block types\n */\nexports.VOID_BLOCKS = [blocks.BLOCKS.HR, blocks.BLOCKS.EMBEDDED_ENTRY, blocks.BLOCKS.EMBEDDED_ASSET];\n/**\n * Dictionary of all container block types, and the set block types they accept as children.\n *\n * Note: This does not include `[BLOCKS.DOCUMENT]: TOP_LEVEL_BLOCKS`\n */\nexports.CONTAINERS = (_a = {},\n _a[blocks.BLOCKS.OL_LIST] = [blocks.BLOCKS.LIST_ITEM],\n _a[blocks.BLOCKS.UL_LIST] = [blocks.BLOCKS.LIST_ITEM],\n _a[blocks.BLOCKS.LIST_ITEM] = exports.LIST_ITEM_BLOCKS,\n _a[blocks.BLOCKS.QUOTE] = [blocks.BLOCKS.PARAGRAPH],\n _a[blocks.BLOCKS.TABLE] = [blocks.BLOCKS.TABLE_ROW],\n _a[blocks.BLOCKS.TABLE_ROW] = [blocks.BLOCKS.TABLE_CELL, blocks.BLOCKS.TABLE_HEADER_CELL],\n _a[blocks.BLOCKS.TABLE_CELL] = [blocks.BLOCKS.PARAGRAPH],\n _a[blocks.BLOCKS.TABLE_HEADER_CELL] = [blocks.BLOCKS.PARAGRAPH],\n _a);\n/**\n * Array of all heading levels\n */\nexports.HEADINGS = [\n blocks.BLOCKS.HEADING_1,\n blocks.BLOCKS.HEADING_2,\n blocks.BLOCKS.HEADING_3,\n blocks.BLOCKS.HEADING_4,\n blocks.BLOCKS.HEADING_5,\n blocks.BLOCKS.HEADING_6,\n];\n/**\n * Array of all block types that may contain text and inline nodes.\n */\nexports.TEXT_CONTAINERS = __spreadArray([blocks.BLOCKS.PARAGRAPH], exports.HEADINGS, true);\n/**\n * Node types before `tables` release.\n */\nexports.V1_NODE_TYPES = [\n blocks.BLOCKS.DOCUMENT,\n blocks.BLOCKS.PARAGRAPH,\n blocks.BLOCKS.HEADING_1,\n blocks.BLOCKS.HEADING_2,\n blocks.BLOCKS.HEADING_3,\n blocks.BLOCKS.HEADING_4,\n blocks.BLOCKS.HEADING_5,\n blocks.BLOCKS.HEADING_6,\n blocks.BLOCKS.OL_LIST,\n blocks.BLOCKS.UL_LIST,\n blocks.BLOCKS.LIST_ITEM,\n blocks.BLOCKS.HR,\n blocks.BLOCKS.QUOTE,\n blocks.BLOCKS.EMBEDDED_ENTRY,\n blocks.BLOCKS.EMBEDDED_ASSET,\n inlines.INLINES.HYPERLINK,\n inlines.INLINES.ENTRY_HYPERLINK,\n inlines.INLINES.ASSET_HYPERLINK,\n inlines.INLINES.EMBEDDED_ENTRY,\n 'text',\n];\n/**\n * Marks before `superscript` & `subscript` release.\n */\nexports.V1_MARKS = [marks_1.default.BOLD, marks_1.default.CODE, marks_1.default.ITALIC, marks_1.default.UNDERLINE];\n\n});\n\nunwrapExports(schemaConstraints);\nvar schemaConstraints_1 = schemaConstraints.V1_MARKS;\nvar schemaConstraints_2 = schemaConstraints.V1_NODE_TYPES;\nvar schemaConstraints_3 = schemaConstraints.TEXT_CONTAINERS;\nvar schemaConstraints_4 = schemaConstraints.HEADINGS;\nvar schemaConstraints_5 = schemaConstraints.CONTAINERS;\nvar schemaConstraints_6 = schemaConstraints.VOID_BLOCKS;\nvar schemaConstraints_7 = schemaConstraints.TABLE_BLOCKS;\nvar schemaConstraints_8 = schemaConstraints.LIST_ITEM_BLOCKS;\nvar schemaConstraints_9 = schemaConstraints.TOP_LEVEL_BLOCKS;\n\nvar types = createCommonjsModule(function (module, exports) {\nObject.defineProperty(exports, \"__esModule\", { value: true });\n\n});\n\nunwrapExports(types);\n\nvar nodeTypes = createCommonjsModule(function (module, exports) {\nObject.defineProperty(exports, \"__esModule\", { value: true });\n\n});\n\nunwrapExports(nodeTypes);\n\nvar emptyDocument = createCommonjsModule(function (module, exports) {\nObject.defineProperty(exports, \"__esModule\", { value: true });\n\n/**\n * A rich text document considered to be empty.\n * Any other document structure than this is not considered empty.\n */\nvar EMPTY_DOCUMENT = {\n nodeType: blocks.BLOCKS.DOCUMENT,\n data: {},\n content: [\n {\n nodeType: blocks.BLOCKS.PARAGRAPH,\n data: {},\n content: [\n {\n nodeType: 'text',\n value: '',\n marks: [],\n data: {},\n },\n ],\n },\n ],\n};\nexports.default = EMPTY_DOCUMENT;\n\n});\n\nunwrapExports(emptyDocument);\n\nvar helpers = createCommonjsModule(function (module, exports) {\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.isText = exports.isBlock = exports.isInline = void 0;\n\n\n/**\n * Tiny replacement for Object.values(object).includes(key) to\n * avoid including CoreJS polyfills\n */\nfunction hasValue(obj, value) {\n for (var _i = 0, _a = Object.keys(obj); _i < _a.length; _i++) {\n var key = _a[_i];\n if (value === obj[key]) {\n return true;\n }\n }\n return false;\n}\n/**\n * Checks if the node is an instance of Inline.\n */\nfunction isInline(node) {\n return hasValue(inlines.INLINES, node.nodeType);\n}\nexports.isInline = isInline;\n/**\n * Checks if the node is an instance of Block.\n */\nfunction isBlock(node) {\n return hasValue(blocks.BLOCKS, node.nodeType);\n}\nexports.isBlock = isBlock;\n/**\n * Checks if the node is an instance of Text.\n */\nfunction isText(node) {\n return node.nodeType === 'text';\n}\nexports.isText = isText;\n\n});\n\nunwrapExports(helpers);\nvar helpers_1 = helpers.isText;\nvar helpers_2 = helpers.isBlock;\nvar helpers_3 = helpers.isInline;\n\nvar dist = createCommonjsModule(function (module, exports) {\nvar __createBinding = (commonjsGlobal && commonjsGlobal.__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}));\nvar __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nvar __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nvar __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.helpers = exports.EMPTY_DOCUMENT = exports.MARKS = exports.INLINES = exports.BLOCKS = void 0;\n\nObject.defineProperty(exports, \"BLOCKS\", { enumerable: true, get: function () { return blocks.BLOCKS; } });\n\nObject.defineProperty(exports, \"INLINES\", { enumerable: true, get: function () { return inlines.INLINES; } });\n\nObject.defineProperty(exports, \"MARKS\", { enumerable: true, get: function () { return __importDefault(marks).default; } });\n__exportStar(schemaConstraints, exports);\n__exportStar(types, exports);\n__exportStar(nodeTypes, exports);\n\nObject.defineProperty(exports, \"EMPTY_DOCUMENT\", { enumerable: true, get: function () { return __importDefault(emptyDocument).default; } });\nvar helpers$1 = __importStar(helpers);\nexports.helpers = helpers$1;\n\n});\n\nunwrapExports(dist);\nvar dist_1 = dist.helpers;\nvar dist_2 = dist.EMPTY_DOCUMENT;\nvar dist_3 = dist.MARKS;\nvar dist_4 = dist.INLINES;\nvar dist_5 = dist.BLOCKS;\n\nvar _a, _b;\r\nvar attributeValue = function (value) { return \"\\\"\".concat(value.replace(/\"/g, '"'), \"\\\"\"); };\r\nvar defaultNodeRenderers = (_a = {},\r\n _a[dist_5.PARAGRAPH] = function (node, next) { return \"

\".concat(next(node.content), \"

\"); },\r\n _a[dist_5.HEADING_1] = function (node, next) { return \"

\".concat(next(node.content), \"

\"); },\r\n _a[dist_5.HEADING_2] = function (node, next) { return \"

\".concat(next(node.content), \"

\"); },\r\n _a[dist_5.HEADING_3] = function (node, next) { return \"

\".concat(next(node.content), \"

\"); },\r\n _a[dist_5.HEADING_4] = function (node, next) { return \"

\".concat(next(node.content), \"

\"); },\r\n _a[dist_5.HEADING_5] = function (node, next) { return \"
\".concat(next(node.content), \"
\"); },\r\n _a[dist_5.HEADING_6] = function (node, next) { return \"
\".concat(next(node.content), \"
\"); },\r\n _a[dist_5.EMBEDDED_ENTRY] = function (node, next) { return \"
\".concat(next(node.content), \"
\"); },\r\n _a[dist_5.UL_LIST] = function (node, next) { return \"
    \".concat(next(node.content), \"
\"); },\r\n _a[dist_5.OL_LIST] = function (node, next) { return \"
    \".concat(next(node.content), \"
\"); },\r\n _a[dist_5.LIST_ITEM] = function (node, next) { return \"
  • \".concat(next(node.content), \"
  • \"); },\r\n _a[dist_5.QUOTE] = function (node, next) { return \"
    \".concat(next(node.content), \"
    \"); },\r\n _a[dist_5.HR] = function () { return '
    '; },\r\n _a[dist_5.TABLE] = function (node, next) { return \"\".concat(next(node.content), \"
    \"); },\r\n _a[dist_5.TABLE_ROW] = function (node, next) { return \"\".concat(next(node.content), \"\"); },\r\n _a[dist_5.TABLE_HEADER_CELL] = function (node, next) { return \"\".concat(next(node.content), \"\"); },\r\n _a[dist_5.TABLE_CELL] = function (node, next) { return \"\".concat(next(node.content), \"\"); },\r\n _a[dist_4.ASSET_HYPERLINK] = function (node) { return defaultInline(dist_4.ASSET_HYPERLINK, node); },\r\n _a[dist_4.ENTRY_HYPERLINK] = function (node) { return defaultInline(dist_4.ENTRY_HYPERLINK, node); },\r\n _a[dist_4.EMBEDDED_ENTRY] = function (node) { return defaultInline(dist_4.EMBEDDED_ENTRY, node); },\r\n _a[dist_4.HYPERLINK] = function (node, next) {\r\n var href = typeof node.data.uri === 'string' ? node.data.uri : '';\r\n return \"
    \").concat(next(node.content), \"\");\r\n },\r\n _a);\r\nvar defaultMarkRenderers = (_b = {},\r\n _b[dist_3.BOLD] = function (text) { return \"\".concat(text, \"\"); },\r\n _b[dist_3.ITALIC] = function (text) { return \"\".concat(text, \"\"); },\r\n _b[dist_3.UNDERLINE] = function (text) { return \"\".concat(text, \"\"); },\r\n _b[dist_3.CODE] = function (text) { return \"\".concat(text, \"\"); },\r\n _b[dist_3.SUPERSCRIPT] = function (text) { return \"\".concat(text, \"\"); },\r\n _b[dist_3.SUBSCRIPT] = function (text) { return \"\".concat(text, \"\"); },\r\n _b);\r\nvar defaultInline = function (type, node) {\r\n return \"type: \".concat(escapeHtml_1(type), \" id: \").concat(escapeHtml_1(node.data.target.sys.id), \"\");\r\n};\r\n/**\r\n * Serialize a Contentful Rich Text `document` to an html string.\r\n */\r\nfunction documentToHtmlString(richTextDocument, options) {\r\n if (options === void 0) { options = {}; }\r\n if (!richTextDocument || !richTextDocument.content) {\r\n return '';\r\n }\r\n return nodeListToHtmlString(richTextDocument.content, {\r\n renderNode: __assign(__assign({}, defaultNodeRenderers), options.renderNode),\r\n renderMark: __assign(__assign({}, defaultMarkRenderers), options.renderMark),\r\n });\r\n}\r\nfunction nodeListToHtmlString(nodes, _a) {\r\n var renderNode = _a.renderNode, renderMark = _a.renderMark;\r\n return nodes.map(function (node) { return nodeToHtmlString(node, { renderNode: renderNode, renderMark: renderMark }); }).join('');\r\n}\r\nfunction nodeToHtmlString(node, _a) {\r\n var renderNode = _a.renderNode, renderMark = _a.renderMark;\r\n if (dist_1.isText(node)) {\r\n var nodeValue = escapeHtml_1(node.value);\r\n if (node.marks.length > 0) {\r\n return node.marks.reduce(function (value, mark) {\r\n if (!renderMark[mark.type]) {\r\n return value;\r\n }\r\n return renderMark[mark.type](value);\r\n }, nodeValue);\r\n }\r\n return nodeValue;\r\n }\r\n else {\r\n var nextNode = function (nodes) { return nodeListToHtmlString(nodes, { renderMark: renderMark, renderNode: renderNode }); };\r\n if (!node.nodeType || !renderNode[node.nodeType]) {\r\n // TODO: Figure what to return when passed an unrecognized node.\r\n return '';\r\n }\r\n return renderNode[node.nodeType](node, nextNode);\r\n }\r\n}\n\nexports.documentToHtmlString = documentToHtmlString;\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nconst transitionEndAsync = (el, expectedDuration = 0) => {\n return new Promise((resolve) => {\n transitionEnd(el, expectedDuration, resolve);\n });\n};\n/**\n * Allows developer to wait for a transition\n * to finish and fallback to a timer if the\n * transition is cancelled or otherwise\n * never finishes. Also see transitionEndAsync\n * which is an await-able version of this.\n */\nconst transitionEnd = (el, expectedDuration = 0, callback) => {\n let unRegTrans;\n let animationTimeout;\n const opts = { passive: true };\n const ANIMATION_FALLBACK_TIMEOUT = 500;\n const unregister = () => {\n if (unRegTrans) {\n unRegTrans();\n }\n };\n const onTransitionEnd = (ev) => {\n if (ev === undefined || el === ev.target) {\n unregister();\n callback(ev);\n }\n };\n if (el) {\n el.addEventListener('webkitTransitionEnd', onTransitionEnd, opts);\n el.addEventListener('transitionend', onTransitionEnd, opts);\n animationTimeout = setTimeout(onTransitionEnd, expectedDuration + ANIMATION_FALLBACK_TIMEOUT);\n unRegTrans = () => {\n if (animationTimeout) {\n clearTimeout(animationTimeout);\n animationTimeout = undefined;\n }\n el.removeEventListener('webkitTransitionEnd', onTransitionEnd, opts);\n el.removeEventListener('transitionend', onTransitionEnd, opts);\n };\n }\n return unregister;\n};\n/**\n * Waits for a component to be ready for\n * both custom element and non-custom element builds.\n * If non-custom element build, el.componentOnReady\n * will be used.\n * For custom element builds, we wait a frame\n * so that the inner contents of the component\n * have a chance to render.\n *\n * Use this utility rather than calling\n * el.componentOnReady yourself.\n */\nconst componentOnReady = (el, callback) => {\n if (el.componentOnReady) {\n // eslint-disable-next-line custom-rules/no-component-on-ready-method\n el.componentOnReady().then((resolvedEl) => callback(resolvedEl));\n }\n else {\n raf(() => callback(el));\n }\n};\n/**\n * This functions checks if a Stencil component is using\n * the lazy loaded build of Stencil. Returns `true` if\n * the component is lazy loaded. Returns `false` otherwise.\n */\nconst hasLazyBuild = (stencilEl) => {\n return stencilEl.componentOnReady !== undefined;\n};\n/**\n * Elements inside of web components sometimes need to inherit global attributes\n * set on the host. For example, the inner input in `ion-input` should inherit\n * the `title` attribute that developers set directly on `ion-input`. This\n * helper function should be called in componentWillLoad and assigned to a variable\n * that is later used in the render function.\n *\n * This does not need to be reactive as changing attributes on the host element\n * does not trigger a re-render.\n */\nconst inheritAttributes = (el, attributes = []) => {\n const attributeObject = {};\n attributes.forEach((attr) => {\n if (el.hasAttribute(attr)) {\n const value = el.getAttribute(attr);\n if (value !== null) {\n attributeObject[attr] = el.getAttribute(attr);\n }\n el.removeAttribute(attr);\n }\n });\n return attributeObject;\n};\n/**\n * List of available ARIA attributes + `role`.\n * Removed deprecated attributes.\n * https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes\n */\nconst ariaAttributes = [\n 'role',\n 'aria-activedescendant',\n 'aria-atomic',\n 'aria-autocomplete',\n 'aria-braillelabel',\n 'aria-brailleroledescription',\n 'aria-busy',\n 'aria-checked',\n 'aria-colcount',\n 'aria-colindex',\n 'aria-colindextext',\n 'aria-colspan',\n 'aria-controls',\n 'aria-current',\n 'aria-describedby',\n 'aria-description',\n 'aria-details',\n 'aria-disabled',\n 'aria-errormessage',\n 'aria-expanded',\n 'aria-flowto',\n 'aria-haspopup',\n 'aria-hidden',\n 'aria-invalid',\n 'aria-keyshortcuts',\n 'aria-label',\n 'aria-labelledby',\n 'aria-level',\n 'aria-live',\n 'aria-multiline',\n 'aria-multiselectable',\n 'aria-orientation',\n 'aria-owns',\n 'aria-placeholder',\n 'aria-posinset',\n 'aria-pressed',\n 'aria-readonly',\n 'aria-relevant',\n 'aria-required',\n 'aria-roledescription',\n 'aria-rowcount',\n 'aria-rowindex',\n 'aria-rowindextext',\n 'aria-rowspan',\n 'aria-selected',\n 'aria-setsize',\n 'aria-sort',\n 'aria-valuemax',\n 'aria-valuemin',\n 'aria-valuenow',\n 'aria-valuetext',\n];\n/**\n * Returns an array of aria attributes that should be copied from\n * the shadow host element to a target within the light DOM.\n * @param el The element that the attributes should be copied from.\n * @param ignoreList The list of aria-attributes to ignore reflecting and removing from the host.\n * Use this in instances where we manually specify aria attributes on the `` element.\n */\nconst inheritAriaAttributes = (el, ignoreList) => {\n let attributesToInherit = ariaAttributes;\n if (ignoreList && ignoreList.length > 0) {\n attributesToInherit = attributesToInherit.filter((attr) => !ignoreList.includes(attr));\n }\n return inheritAttributes(el, attributesToInherit);\n};\nconst addEventListener = (el, eventName, callback, opts) => {\n var _a;\n if (typeof window !== 'undefined') {\n const win = window;\n const config = (_a = win === null || win === void 0 ? void 0 : win.Ionic) === null || _a === void 0 ? void 0 : _a.config;\n if (config) {\n const ael = config.get('_ael');\n if (ael) {\n return ael(el, eventName, callback, opts);\n }\n else if (config._ael) {\n return config._ael(el, eventName, callback, opts);\n }\n }\n }\n return el.addEventListener(eventName, callback, opts);\n};\nconst removeEventListener = (el, eventName, callback, opts) => {\n var _a;\n if (typeof window !== 'undefined') {\n const win = window;\n const config = (_a = win === null || win === void 0 ? void 0 : win.Ionic) === null || _a === void 0 ? void 0 : _a.config;\n if (config) {\n const rel = config.get('_rel');\n if (rel) {\n return rel(el, eventName, callback, opts);\n }\n else if (config._rel) {\n return config._rel(el, eventName, callback, opts);\n }\n }\n }\n return el.removeEventListener(eventName, callback, opts);\n};\n/**\n * Gets the root context of a shadow dom element\n * On newer browsers this will be the shadowRoot,\n * but for older browser this may just be the\n * element itself.\n *\n * Useful for whenever you need to explicitly\n * do \"myElement.shadowRoot!.querySelector(...)\".\n */\nconst getElementRoot = (el, fallback = el) => {\n return el.shadowRoot || fallback;\n};\n/**\n * Patched version of requestAnimationFrame that avoids ngzone\n * Use only when you know ngzone should not run\n */\nconst raf = (h) => {\n if (typeof __zone_symbol__requestAnimationFrame === 'function') {\n return __zone_symbol__requestAnimationFrame(h);\n }\n if (typeof requestAnimationFrame === 'function') {\n return requestAnimationFrame(h);\n }\n return setTimeout(h);\n};\nconst hasShadowDom = (el) => {\n return !!el.shadowRoot && !!el.attachShadow;\n};\nconst findItemLabel = (componentEl) => {\n const itemEl = componentEl.closest('ion-item');\n if (itemEl) {\n return itemEl.querySelector('ion-label');\n }\n return null;\n};\nconst focusElement = (el) => {\n el.focus();\n /**\n * When programmatically focusing an element,\n * the focus-visible utility will not run because\n * it is expecting a keyboard event to have triggered this;\n * however, there are times when we need to manually control\n * this behavior so we call the `setFocus` method on ion-app\n * which will let us explicitly set the elements to focus.\n */\n if (el.classList.contains('ion-focusable')) {\n const app = el.closest('ion-app');\n if (app) {\n app.setFocus([el]);\n }\n }\n};\n/**\n * This method is used for Ionic's input components that use Shadow DOM. In\n * order to properly label the inputs to work with screen readers, we need\n * to get the text content of the label outside of the shadow root and pass\n * it to the input inside of the shadow root.\n *\n * Referencing label elements by id from outside of the component is\n * impossible due to the shadow boundary, read more here:\n * https://developer.salesforce.com/blogs/2020/01/accessibility-for-web-components.html\n *\n * @param componentEl The shadow element that needs the aria label\n * @param inputId The unique identifier for the input\n */\nconst getAriaLabel = (componentEl, inputId) => {\n let labelText;\n // If the user provides their own label via the aria-labelledby attr\n // we should use that instead of looking for an ion-label\n const labelledBy = componentEl.getAttribute('aria-labelledby');\n // Grab the id off of the component in case they are using\n // a custom label using the label element\n const componentId = componentEl.id;\n let labelId = labelledBy !== null && labelledBy.trim() !== '' ? labelledBy : inputId + '-lbl';\n let label = labelledBy !== null && labelledBy.trim() !== '' ? document.getElementById(labelledBy) : findItemLabel(componentEl);\n if (label) {\n if (labelledBy === null) {\n label.id = labelId;\n }\n labelText = label.textContent;\n label.setAttribute('aria-hidden', 'true');\n // if there is no label, check to see if the user has provided\n // one by setting an id on the component and using the label element\n }\n else if (componentId.trim() !== '') {\n label = document.querySelector(`label[for=\"${componentId}\"]`);\n if (label) {\n if (label.id !== '') {\n labelId = label.id;\n }\n else {\n label.id = labelId = `${componentId}-lbl`;\n }\n labelText = label.textContent;\n }\n }\n return { label, labelId, labelText };\n};\n/**\n * This method is used to add a hidden input to a host element that contains\n * a Shadow DOM. It does not add the input inside of the Shadow root which\n * allows it to be picked up inside of forms. It should contain the same\n * values as the host element.\n *\n * @param always Add a hidden input even if the container does not use Shadow\n * @param container The element where the input will be added\n * @param name The name of the input\n * @param value The value of the input\n * @param disabled If true, the input is disabled\n */\nconst renderHiddenInput = (always, container, name, value, disabled) => {\n if (always || hasShadowDom(container)) {\n let input = container.querySelector('input.aux-input');\n if (!input) {\n input = container.ownerDocument.createElement('input');\n input.type = 'hidden';\n input.classList.add('aux-input');\n container.appendChild(input);\n }\n input.disabled = disabled;\n input.name = name;\n input.value = value || '';\n }\n};\nconst clamp = (min, n, max) => {\n return Math.max(min, Math.min(n, max));\n};\nconst assert = (actual, reason) => {\n if (!actual) {\n const message = 'ASSERT: ' + reason;\n console.error(message);\n debugger; // eslint-disable-line\n throw new Error(message);\n }\n};\nconst now = (ev) => {\n return ev.timeStamp || Date.now();\n};\nconst pointerCoord = (ev) => {\n // get X coordinates for either a mouse click\n // or a touch depending on the given event\n if (ev) {\n const changedTouches = ev.changedTouches;\n if (changedTouches && changedTouches.length > 0) {\n const touch = changedTouches[0];\n return { x: touch.clientX, y: touch.clientY };\n }\n if (ev.pageX !== undefined) {\n return { x: ev.pageX, y: ev.pageY };\n }\n }\n return { x: 0, y: 0 };\n};\n/**\n * @hidden\n * Given a side, return if it should be on the end\n * based on the value of dir\n * @param side the side\n * @param isRTL whether the application dir is rtl\n */\nconst isEndSide = (side) => {\n const isRTL = document.dir === 'rtl';\n switch (side) {\n case 'start':\n return isRTL;\n case 'end':\n return !isRTL;\n default:\n throw new Error(`\"${side}\" is not a valid value for [side]. Use \"start\" or \"end\" instead.`);\n }\n};\nconst debounceEvent = (event, wait) => {\n const original = event._original || event;\n return {\n _original: event,\n emit: debounce(original.emit.bind(original), wait),\n };\n};\nconst debounce = (func, wait = 0) => {\n let timer;\n return (...args) => {\n clearTimeout(timer);\n timer = setTimeout(func, wait, ...args);\n };\n};\n/**\n * Check whether the two string maps are shallow equal.\n *\n * undefined is treated as an empty map.\n *\n * @returns whether the keys are the same and the values are shallow equal.\n */\nconst shallowEqualStringMap = (map1, map2) => {\n map1 !== null && map1 !== void 0 ? map1 : (map1 = {});\n map2 !== null && map2 !== void 0 ? map2 : (map2 = {});\n if (map1 === map2) {\n return true;\n }\n const keys1 = Object.keys(map1);\n if (keys1.length !== Object.keys(map2).length) {\n return false;\n }\n for (const k1 of keys1) {\n if (!(k1 in map2)) {\n return false;\n }\n if (map1[k1] !== map2[k1]) {\n return false;\n }\n }\n return true;\n};\n\nexport { addEventListener as a, removeEventListener as b, componentOnReady as c, inheritAttributes as d, renderHiddenInput as e, focusElement as f, getElementRoot as g, hasShadowDom as h, inheritAriaAttributes as i, getAriaLabel as j, findItemLabel as k, hasLazyBuild as l, clamp as m, debounceEvent as n, isEndSide as o, assert as p, debounce as q, raf as r, shallowEqualStringMap as s, transitionEndAsync as t, now as u, pointerCoord as v };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nimport { writeTask, Build } from '@stencil/core/internal/client';\nimport { r as raf } from './helpers.js';\n\nconst LIFECYCLE_WILL_ENTER = 'ionViewWillEnter';\nconst LIFECYCLE_DID_ENTER = 'ionViewDidEnter';\nconst LIFECYCLE_WILL_LEAVE = 'ionViewWillLeave';\nconst LIFECYCLE_DID_LEAVE = 'ionViewDidLeave';\nconst LIFECYCLE_WILL_UNLOAD = 'ionViewWillUnload';\n\nconst iosTransitionAnimation = () => import('./ios.transition.js');\nconst mdTransitionAnimation = () => import('./md.transition.js');\n// TODO(FW-2832): types\nconst transition = (opts) => {\n return new Promise((resolve, reject) => {\n writeTask(() => {\n beforeTransition(opts);\n runTransition(opts).then((result) => {\n if (result.animation) {\n result.animation.destroy();\n }\n afterTransition(opts);\n resolve(result);\n }, (error) => {\n afterTransition(opts);\n reject(error);\n });\n });\n });\n};\nconst beforeTransition = (opts) => {\n const enteringEl = opts.enteringEl;\n const leavingEl = opts.leavingEl;\n setZIndex(enteringEl, leavingEl, opts.direction);\n if (opts.showGoBack) {\n enteringEl.classList.add('can-go-back');\n }\n else {\n enteringEl.classList.remove('can-go-back');\n }\n setPageHidden(enteringEl, false);\n /**\n * When transitioning, the page should not\n * respond to click events. This resolves small\n * issues like users double tapping the ion-back-button.\n * These pointer events are removed in `afterTransition`.\n */\n enteringEl.style.setProperty('pointer-events', 'none');\n if (leavingEl) {\n setPageHidden(leavingEl, false);\n leavingEl.style.setProperty('pointer-events', 'none');\n }\n};\nconst runTransition = async (opts) => {\n const animationBuilder = await getAnimationBuilder(opts);\n const ani = animationBuilder && Build.isBrowser ? animation(animationBuilder, opts) : noAnimation(opts); // fast path for no animation\n return ani;\n};\nconst afterTransition = (opts) => {\n const enteringEl = opts.enteringEl;\n const leavingEl = opts.leavingEl;\n enteringEl.classList.remove('ion-page-invisible');\n enteringEl.style.removeProperty('pointer-events');\n if (leavingEl !== undefined) {\n leavingEl.classList.remove('ion-page-invisible');\n leavingEl.style.removeProperty('pointer-events');\n }\n};\nconst getAnimationBuilder = async (opts) => {\n if (!opts.leavingEl || !opts.animated || opts.duration === 0) {\n return undefined;\n }\n if (opts.animationBuilder) {\n return opts.animationBuilder;\n }\n const getAnimation = opts.mode === 'ios'\n ? (await iosTransitionAnimation()).iosTransitionAnimation\n : (await mdTransitionAnimation()).mdTransitionAnimation;\n return getAnimation;\n};\nconst animation = async (animationBuilder, opts) => {\n await waitForReady(opts, true);\n const trans = animationBuilder(opts.baseEl, opts);\n fireWillEvents(opts.enteringEl, opts.leavingEl);\n const didComplete = await playTransition(trans, opts);\n if (opts.progressCallback) {\n opts.progressCallback(undefined);\n }\n if (didComplete) {\n fireDidEvents(opts.enteringEl, opts.leavingEl);\n }\n return {\n hasCompleted: didComplete,\n animation: trans,\n };\n};\nconst noAnimation = async (opts) => {\n const enteringEl = opts.enteringEl;\n const leavingEl = opts.leavingEl;\n await waitForReady(opts, false);\n fireWillEvents(enteringEl, leavingEl);\n fireDidEvents(enteringEl, leavingEl);\n return {\n hasCompleted: true,\n };\n};\nconst waitForReady = async (opts, defaultDeep) => {\n const deep = opts.deepWait !== undefined ? opts.deepWait : defaultDeep;\n if (deep) {\n await Promise.all([deepReady(opts.enteringEl), deepReady(opts.leavingEl)]);\n }\n await notifyViewReady(opts.viewIsReady, opts.enteringEl);\n};\nconst notifyViewReady = async (viewIsReady, enteringEl) => {\n if (viewIsReady) {\n await viewIsReady(enteringEl);\n }\n};\nconst playTransition = (trans, opts) => {\n const progressCallback = opts.progressCallback;\n const promise = new Promise((resolve) => {\n trans.onFinish((currentStep) => resolve(currentStep === 1));\n });\n // cool, let's do this, start the transition\n if (progressCallback) {\n // this is a swipe to go back, just get the transition progress ready\n // kick off the swipe animation start\n trans.progressStart(true);\n progressCallback(trans);\n }\n else {\n // only the top level transition should actually start \"play\"\n // kick it off and let it play through\n // ******** DOM WRITE ****************\n trans.play();\n }\n // create a callback for when the animation is done\n return promise;\n};\nconst fireWillEvents = (enteringEl, leavingEl) => {\n lifecycle(leavingEl, LIFECYCLE_WILL_LEAVE);\n lifecycle(enteringEl, LIFECYCLE_WILL_ENTER);\n};\nconst fireDidEvents = (enteringEl, leavingEl) => {\n lifecycle(enteringEl, LIFECYCLE_DID_ENTER);\n lifecycle(leavingEl, LIFECYCLE_DID_LEAVE);\n};\nconst lifecycle = (el, eventName) => {\n if (el) {\n const ev = new CustomEvent(eventName, {\n bubbles: false,\n cancelable: false,\n });\n el.dispatchEvent(ev);\n }\n};\n/**\n * Wait two request animation frame loops.\n * This allows the framework implementations enough time to mount\n * the user-defined contents. This is often needed when using inline\n * modals and popovers that accept user components. For popover,\n * the contents must be mounted for the popover to be sized correctly.\n * For modals, the contents must be mounted for iOS to run the\n * transition correctly.\n *\n * On Angular and React, a single raf is enough time, but for Vue\n * we need to wait two rafs. As a result we are using two rafs for\n * all frameworks to ensure contents are mounted.\n */\nconst waitForMount = () => {\n return new Promise((resolve) => raf(() => raf(() => resolve())));\n};\nconst deepReady = async (el) => {\n const element = el;\n if (element) {\n if (element.componentOnReady != null) {\n // eslint-disable-next-line custom-rules/no-component-on-ready-method\n const stencilEl = await element.componentOnReady();\n if (stencilEl != null) {\n return;\n }\n /**\n * Custom elements in Stencil will have __registerHost.\n */\n }\n else if (element.__registerHost != null) {\n /**\n * Non-lazy loaded custom elements need to wait\n * one frame for component to be loaded.\n */\n const waitForCustomElement = new Promise((resolve) => raf(resolve));\n await waitForCustomElement;\n return;\n }\n await Promise.all(Array.from(element.children).map(deepReady));\n }\n};\nconst setPageHidden = (el, hidden) => {\n if (hidden) {\n el.setAttribute('aria-hidden', 'true');\n el.classList.add('ion-page-hidden');\n }\n else {\n el.hidden = false;\n el.removeAttribute('aria-hidden');\n el.classList.remove('ion-page-hidden');\n }\n};\nconst setZIndex = (enteringEl, leavingEl, direction) => {\n if (enteringEl !== undefined) {\n enteringEl.style.zIndex = direction === 'back' ? '99' : '101';\n }\n if (leavingEl !== undefined) {\n leavingEl.style.zIndex = '100';\n }\n};\nconst getIonPageElement = (element) => {\n if (element.classList.contains('ion-page')) {\n return element;\n }\n const ionPage = element.querySelector(':scope > .ion-page, :scope > ion-nav, :scope > ion-tabs');\n if (ionPage) {\n return ionPage;\n }\n // idk, return the original element so at least something animates and we don't have a null pointer\n return element;\n};\n\nexport { LIFECYCLE_WILL_ENTER as L, LIFECYCLE_DID_ENTER as a, LIFECYCLE_WILL_LEAVE as b, LIFECYCLE_DID_LEAVE as c, LIFECYCLE_WILL_UNLOAD as d, deepReady as e, getIonPageElement as g, lifecycle as l, setPageHidden as s, transition as t, waitForMount as w };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nimport { w as win } from './index-7a14ecec.js';\nimport { r as raf } from './helpers-3379ba19.js';\n\nlet animationPrefix;\n/**\n * Web Animations requires hyphenated CSS properties\n * to be written in camelCase when animating\n */\nconst processKeyframes = (keyframes) => {\n keyframes.forEach((keyframe) => {\n for (const key in keyframe) {\n // eslint-disable-next-line no-prototype-builtins\n if (keyframe.hasOwnProperty(key)) {\n const value = keyframe[key];\n if (key === 'easing') {\n const newKey = 'animation-timing-function';\n keyframe[newKey] = value;\n delete keyframe[key];\n }\n else {\n const newKey = convertCamelCaseToHypen(key);\n if (newKey !== key) {\n keyframe[newKey] = value;\n delete keyframe[key];\n }\n }\n }\n }\n });\n return keyframes;\n};\nconst convertCamelCaseToHypen = (str) => {\n return str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n};\nconst getAnimationPrefix = (el) => {\n if (animationPrefix === undefined) {\n const supportsUnprefixed = el.style.animationName !== undefined;\n const supportsWebkitPrefix = el.style.webkitAnimationName !== undefined;\n animationPrefix = !supportsUnprefixed && supportsWebkitPrefix ? '-webkit-' : '';\n }\n return animationPrefix;\n};\nconst setStyleProperty = (element, propertyName, value) => {\n const prefix = propertyName.startsWith('animation') ? getAnimationPrefix(element) : '';\n element.style.setProperty(prefix + propertyName, value);\n};\nconst removeStyleProperty = (element, propertyName) => {\n const prefix = propertyName.startsWith('animation') ? getAnimationPrefix(element) : '';\n element.style.removeProperty(prefix + propertyName);\n};\nconst animationEnd = (el, callback) => {\n let unRegTrans;\n const opts = { passive: true };\n const unregister = () => {\n if (unRegTrans) {\n unRegTrans();\n }\n };\n const onTransitionEnd = (ev) => {\n if (el === ev.target) {\n unregister();\n callback(ev);\n }\n };\n if (el) {\n el.addEventListener('webkitAnimationEnd', onTransitionEnd, opts);\n el.addEventListener('animationend', onTransitionEnd, opts);\n unRegTrans = () => {\n el.removeEventListener('webkitAnimationEnd', onTransitionEnd, opts);\n el.removeEventListener('animationend', onTransitionEnd, opts);\n };\n }\n return unregister;\n};\n// TODO(FW-2832): type\nconst generateKeyframeRules = (keyframes = []) => {\n return keyframes\n .map((keyframe) => {\n const offset = keyframe.offset;\n const frameString = [];\n for (const property in keyframe) {\n // eslint-disable-next-line no-prototype-builtins\n if (keyframe.hasOwnProperty(property) && property !== 'offset') {\n frameString.push(`${property}: ${keyframe[property]};`);\n }\n }\n return `${offset * 100}% { ${frameString.join(' ')} }`;\n })\n .join(' ');\n};\nconst keyframeIds = [];\nconst generateKeyframeName = (keyframeRules) => {\n let index = keyframeIds.indexOf(keyframeRules);\n if (index < 0) {\n index = keyframeIds.push(keyframeRules) - 1;\n }\n return `ion-animation-${index}`;\n};\nconst getStyleContainer = (element) => {\n // getRootNode is not always available in SSR environments.\n // TODO(FW-2832): types\n const rootNode = element.getRootNode !== undefined ? element.getRootNode() : element;\n return rootNode.head || rootNode;\n};\nconst createKeyframeStylesheet = (keyframeName, keyframeRules, element) => {\n var _a;\n const styleContainer = getStyleContainer(element);\n const keyframePrefix = getAnimationPrefix(element);\n const existingStylesheet = styleContainer.querySelector('#' + keyframeName);\n if (existingStylesheet) {\n return existingStylesheet;\n }\n const stylesheet = ((_a = element.ownerDocument) !== null && _a !== void 0 ? _a : document).createElement('style');\n stylesheet.id = keyframeName;\n stylesheet.textContent = `@${keyframePrefix}keyframes ${keyframeName} { ${keyframeRules} } @${keyframePrefix}keyframes ${keyframeName}-alt { ${keyframeRules} }`;\n styleContainer.appendChild(stylesheet);\n return stylesheet;\n};\nconst addClassToArray = (classes = [], className) => {\n if (className !== undefined) {\n const classNameToAppend = Array.isArray(className) ? className : [className];\n return [...classes, ...classNameToAppend];\n }\n return classes;\n};\n\nconst createAnimation = (animationId) => {\n let _delay;\n let _duration;\n let _easing;\n let _iterations;\n let _fill;\n let _direction;\n let _keyframes = [];\n let beforeAddClasses = [];\n let beforeRemoveClasses = [];\n let initialized = false;\n let parentAnimation;\n let beforeStylesValue = {};\n let afterAddClasses = [];\n let afterRemoveClasses = [];\n let afterStylesValue = {};\n let numAnimationsRunning = 0;\n let shouldForceLinearEasing = false;\n let shouldForceSyncPlayback = false;\n let cssAnimationsTimerFallback;\n let forceDirectionValue;\n let forceDurationValue;\n let forceDelayValue;\n let willComplete = true;\n let finished = false;\n let shouldCalculateNumAnimations = true;\n let keyframeName;\n let ani;\n let paused = false;\n const id = animationId;\n const onFinishCallbacks = [];\n const onFinishOneTimeCallbacks = [];\n const onStopOneTimeCallbacks = [];\n const elements = [];\n const childAnimations = [];\n const stylesheets = [];\n const _beforeAddReadFunctions = [];\n const _beforeAddWriteFunctions = [];\n const _afterAddReadFunctions = [];\n const _afterAddWriteFunctions = [];\n const webAnimations = [];\n const supportsAnimationEffect = typeof AnimationEffect === 'function' ||\n (win !== undefined && typeof win.AnimationEffect === 'function');\n const supportsWebAnimations = typeof Element === 'function' &&\n typeof Element.prototype.animate === 'function' &&\n supportsAnimationEffect;\n const ANIMATION_END_FALLBACK_PADDING_MS = 100;\n const getWebAnimations = () => {\n return webAnimations;\n };\n const destroy = (clearStyleSheets) => {\n childAnimations.forEach((childAnimation) => {\n childAnimation.destroy(clearStyleSheets);\n });\n cleanUp(clearStyleSheets);\n elements.length = 0;\n childAnimations.length = 0;\n _keyframes.length = 0;\n clearOnFinish();\n initialized = false;\n shouldCalculateNumAnimations = true;\n return ani;\n };\n /**\n * Cancels any Web Animations, removes\n * any animation properties from the\n * animation's elements, and removes the\n * animation's stylesheets from the DOM.\n */\n const cleanUp = (clearStyleSheets) => {\n cleanUpElements();\n if (clearStyleSheets) {\n cleanUpStyleSheets();\n }\n };\n const resetFlags = () => {\n shouldForceLinearEasing = false;\n shouldForceSyncPlayback = false;\n shouldCalculateNumAnimations = true;\n forceDirectionValue = undefined;\n forceDurationValue = undefined;\n forceDelayValue = undefined;\n numAnimationsRunning = 0;\n finished = false;\n willComplete = true;\n paused = false;\n };\n const isRunning = () => {\n return numAnimationsRunning !== 0 && !paused;\n };\n /**\n * @internal\n * Remove a callback from a chosen callback array\n * @param callbackToRemove: A reference to the callback that should be removed\n * @param callbackObjects: An array of callbacks that callbackToRemove should be removed from.\n */\n const clearCallback = (callbackToRemove, callbackObjects) => {\n const index = callbackObjects.findIndex((callbackObject) => callbackObject.c === callbackToRemove);\n if (index > -1) {\n callbackObjects.splice(index, 1);\n }\n };\n /**\n * @internal\n * Add a callback to be fired when an animation is stopped/cancelled.\n * @param callback: A reference to the callback that should be fired\n * @param opts: Any options associated with this particular callback\n */\n const onStop = (callback, opts) => {\n onStopOneTimeCallbacks.push({ c: callback, o: opts });\n return ani;\n };\n const onFinish = (callback, opts) => {\n const callbacks = (opts === null || opts === void 0 ? void 0 : opts.oneTimeCallback) ? onFinishOneTimeCallbacks : onFinishCallbacks;\n callbacks.push({ c: callback, o: opts });\n return ani;\n };\n const clearOnFinish = () => {\n onFinishCallbacks.length = 0;\n onFinishOneTimeCallbacks.length = 0;\n return ani;\n };\n /**\n * Cancels any Web Animations and removes\n * any animation properties from the\n * the animation's elements.\n */\n const cleanUpElements = () => {\n if (supportsWebAnimations) {\n webAnimations.forEach((animation) => {\n animation.cancel();\n });\n webAnimations.length = 0;\n }\n else {\n const elementsArray = elements.slice();\n raf(() => {\n elementsArray.forEach((element) => {\n removeStyleProperty(element, 'animation-name');\n removeStyleProperty(element, 'animation-duration');\n removeStyleProperty(element, 'animation-timing-function');\n removeStyleProperty(element, 'animation-iteration-count');\n removeStyleProperty(element, 'animation-delay');\n removeStyleProperty(element, 'animation-play-state');\n removeStyleProperty(element, 'animation-fill-mode');\n removeStyleProperty(element, 'animation-direction');\n });\n });\n }\n };\n /**\n * Removes the animation's stylesheets\n * from the DOM.\n */\n const cleanUpStyleSheets = () => {\n stylesheets.forEach((stylesheet) => {\n /**\n * When sharing stylesheets, it's possible\n * for another animation to have already\n * cleaned up a particular stylesheet\n */\n if (stylesheet === null || stylesheet === void 0 ? void 0 : stylesheet.parentNode) {\n stylesheet.parentNode.removeChild(stylesheet);\n }\n });\n stylesheets.length = 0;\n };\n const beforeAddRead = (readFn) => {\n _beforeAddReadFunctions.push(readFn);\n return ani;\n };\n const beforeAddWrite = (writeFn) => {\n _beforeAddWriteFunctions.push(writeFn);\n return ani;\n };\n const afterAddRead = (readFn) => {\n _afterAddReadFunctions.push(readFn);\n return ani;\n };\n const afterAddWrite = (writeFn) => {\n _afterAddWriteFunctions.push(writeFn);\n return ani;\n };\n const beforeAddClass = (className) => {\n beforeAddClasses = addClassToArray(beforeAddClasses, className);\n return ani;\n };\n const beforeRemoveClass = (className) => {\n beforeRemoveClasses = addClassToArray(beforeRemoveClasses, className);\n return ani;\n };\n /**\n * Set CSS inline styles to the animation's\n * elements before the animation begins.\n */\n const beforeStyles = (styles = {}) => {\n beforeStylesValue = styles;\n return ani;\n };\n /**\n * Clear CSS inline styles from the animation's\n * elements before the animation begins.\n */\n const beforeClearStyles = (propertyNames = []) => {\n for (const property of propertyNames) {\n beforeStylesValue[property] = '';\n }\n return ani;\n };\n const afterAddClass = (className) => {\n afterAddClasses = addClassToArray(afterAddClasses, className);\n return ani;\n };\n const afterRemoveClass = (className) => {\n afterRemoveClasses = addClassToArray(afterRemoveClasses, className);\n return ani;\n };\n const afterStyles = (styles = {}) => {\n afterStylesValue = styles;\n return ani;\n };\n const afterClearStyles = (propertyNames = []) => {\n for (const property of propertyNames) {\n afterStylesValue[property] = '';\n }\n return ani;\n };\n const getFill = () => {\n if (_fill !== undefined) {\n return _fill;\n }\n if (parentAnimation) {\n return parentAnimation.getFill();\n }\n return 'both';\n };\n const getDirection = () => {\n if (forceDirectionValue !== undefined) {\n return forceDirectionValue;\n }\n if (_direction !== undefined) {\n return _direction;\n }\n if (parentAnimation) {\n return parentAnimation.getDirection();\n }\n return 'normal';\n };\n const getEasing = () => {\n if (shouldForceLinearEasing) {\n return 'linear';\n }\n if (_easing !== undefined) {\n return _easing;\n }\n if (parentAnimation) {\n return parentAnimation.getEasing();\n }\n return 'linear';\n };\n const getDuration = () => {\n if (shouldForceSyncPlayback) {\n return 0;\n }\n if (forceDurationValue !== undefined) {\n return forceDurationValue;\n }\n if (_duration !== undefined) {\n return _duration;\n }\n if (parentAnimation) {\n return parentAnimation.getDuration();\n }\n return 0;\n };\n const getIterations = () => {\n if (_iterations !== undefined) {\n return _iterations;\n }\n if (parentAnimation) {\n return parentAnimation.getIterations();\n }\n return 1;\n };\n const getDelay = () => {\n if (forceDelayValue !== undefined) {\n return forceDelayValue;\n }\n if (_delay !== undefined) {\n return _delay;\n }\n if (parentAnimation) {\n return parentAnimation.getDelay();\n }\n return 0;\n };\n const getKeyframes = () => {\n return _keyframes;\n };\n const direction = (animationDirection) => {\n _direction = animationDirection;\n update(true);\n return ani;\n };\n const fill = (animationFill) => {\n _fill = animationFill;\n update(true);\n return ani;\n };\n const delay = (animationDelay) => {\n _delay = animationDelay;\n update(true);\n return ani;\n };\n const easing = (animationEasing) => {\n _easing = animationEasing;\n update(true);\n return ani;\n };\n const duration = (animationDuration) => {\n /**\n * CSS Animation Durations of 0ms work fine on Chrome\n * but do not run on Safari, so force it to 1ms to\n * get it to run on both platforms.\n */\n if (!supportsWebAnimations && animationDuration === 0) {\n animationDuration = 1;\n }\n _duration = animationDuration;\n update(true);\n return ani;\n };\n const iterations = (animationIterations) => {\n _iterations = animationIterations;\n update(true);\n return ani;\n };\n const parent = (animation) => {\n parentAnimation = animation;\n return ani;\n };\n const addElement = (el) => {\n if (el != null) {\n if (el.nodeType === 1) {\n elements.push(el);\n }\n else if (el.length >= 0) {\n for (let i = 0; i < el.length; i++) {\n elements.push(el[i]);\n }\n }\n else {\n console.error('Invalid addElement value');\n }\n }\n return ani;\n };\n const addAnimation = (animationToAdd) => {\n if (animationToAdd != null) {\n if (Array.isArray(animationToAdd)) {\n for (const animation of animationToAdd) {\n animation.parent(ani);\n childAnimations.push(animation);\n }\n }\n else {\n animationToAdd.parent(ani);\n childAnimations.push(animationToAdd);\n }\n }\n return ani;\n };\n const keyframes = (keyframeValues) => {\n const different = _keyframes !== keyframeValues;\n _keyframes = keyframeValues;\n if (different) {\n updateKeyframes(_keyframes);\n }\n return ani;\n };\n const updateKeyframes = (keyframeValues) => {\n if (supportsWebAnimations) {\n getWebAnimations().forEach((animation) => {\n /**\n * animation.effect's type is AnimationEffect.\n * However, in this case we have a more specific\n * type of AnimationEffect called KeyframeEffect which\n * inherits from AnimationEffect. As a result,\n * we cast animation.effect to KeyframeEffect.\n */\n const keyframeEffect = animation.effect;\n /**\n * setKeyframes is not supported in all browser\n * versions that Ionic supports, so we need to\n * check for support before using it.\n */\n // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions\n if (keyframeEffect.setKeyframes) {\n keyframeEffect.setKeyframes(keyframeValues);\n }\n else {\n const newEffect = new KeyframeEffect(keyframeEffect.target, keyframeValues, keyframeEffect.getTiming());\n animation.effect = newEffect;\n }\n });\n }\n else {\n initializeCSSAnimation();\n }\n };\n /**\n * Run all \"before\" animation hooks.\n */\n const beforeAnimation = () => {\n // Runs all before read callbacks\n _beforeAddReadFunctions.forEach((callback) => callback());\n // Runs all before write callbacks\n _beforeAddWriteFunctions.forEach((callback) => callback());\n // Updates styles and classes before animation runs\n const addClasses = beforeAddClasses;\n const removeClasses = beforeRemoveClasses;\n const styles = beforeStylesValue;\n elements.forEach((el) => {\n const elementClassList = el.classList;\n addClasses.forEach((c) => elementClassList.add(c));\n removeClasses.forEach((c) => elementClassList.remove(c));\n for (const property in styles) {\n // eslint-disable-next-line no-prototype-builtins\n if (styles.hasOwnProperty(property)) {\n setStyleProperty(el, property, styles[property]);\n }\n }\n });\n };\n /**\n * Run all \"after\" animation hooks.\n */\n const afterAnimation = () => {\n clearCSSAnimationsTimeout();\n // Runs all after read callbacks\n _afterAddReadFunctions.forEach((callback) => callback());\n // Runs all after write callbacks\n _afterAddWriteFunctions.forEach((callback) => callback());\n // Updates styles and classes before animation ends\n const currentStep = willComplete ? 1 : 0;\n const addClasses = afterAddClasses;\n const removeClasses = afterRemoveClasses;\n const styles = afterStylesValue;\n elements.forEach((el) => {\n const elementClassList = el.classList;\n addClasses.forEach((c) => elementClassList.add(c));\n removeClasses.forEach((c) => elementClassList.remove(c));\n for (const property in styles) {\n // eslint-disable-next-line no-prototype-builtins\n if (styles.hasOwnProperty(property)) {\n setStyleProperty(el, property, styles[property]);\n }\n }\n });\n onFinishCallbacks.forEach((onFinishCallback) => {\n return onFinishCallback.c(currentStep, ani);\n });\n onFinishOneTimeCallbacks.forEach((onFinishCallback) => {\n return onFinishCallback.c(currentStep, ani);\n });\n onFinishOneTimeCallbacks.length = 0;\n shouldCalculateNumAnimations = true;\n if (willComplete) {\n finished = true;\n }\n willComplete = true;\n };\n const animationFinish = () => {\n if (numAnimationsRunning === 0) {\n return;\n }\n numAnimationsRunning--;\n if (numAnimationsRunning === 0) {\n afterAnimation();\n if (parentAnimation) {\n parentAnimation.animationFinish();\n }\n }\n };\n const initializeCSSAnimation = (toggleAnimationName = true) => {\n cleanUpStyleSheets();\n const processedKeyframes = processKeyframes(_keyframes);\n elements.forEach((element) => {\n if (processedKeyframes.length > 0) {\n const keyframeRules = generateKeyframeRules(processedKeyframes);\n keyframeName = animationId !== undefined ? animationId : generateKeyframeName(keyframeRules);\n const stylesheet = createKeyframeStylesheet(keyframeName, keyframeRules, element);\n stylesheets.push(stylesheet);\n setStyleProperty(element, 'animation-duration', `${getDuration()}ms`);\n setStyleProperty(element, 'animation-timing-function', getEasing());\n setStyleProperty(element, 'animation-delay', `${getDelay()}ms`);\n setStyleProperty(element, 'animation-fill-mode', getFill());\n setStyleProperty(element, 'animation-direction', getDirection());\n const iterationsCount = getIterations() === Infinity ? 'infinite' : getIterations().toString();\n setStyleProperty(element, 'animation-iteration-count', iterationsCount);\n setStyleProperty(element, 'animation-play-state', 'paused');\n if (toggleAnimationName) {\n setStyleProperty(element, 'animation-name', `${stylesheet.id}-alt`);\n }\n raf(() => {\n setStyleProperty(element, 'animation-name', stylesheet.id || null);\n });\n }\n });\n };\n const initializeWebAnimation = () => {\n elements.forEach((element) => {\n const animation = element.animate(_keyframes, {\n id,\n delay: getDelay(),\n duration: getDuration(),\n easing: getEasing(),\n iterations: getIterations(),\n fill: getFill(),\n direction: getDirection(),\n });\n animation.pause();\n webAnimations.push(animation);\n });\n if (webAnimations.length > 0) {\n webAnimations[0].onfinish = () => {\n animationFinish();\n };\n }\n };\n const initializeAnimation = (toggleAnimationName = true) => {\n beforeAnimation();\n if (_keyframes.length > 0) {\n if (supportsWebAnimations) {\n initializeWebAnimation();\n }\n else {\n initializeCSSAnimation(toggleAnimationName);\n }\n }\n initialized = true;\n };\n const setAnimationStep = (step) => {\n step = Math.min(Math.max(step, 0), 0.9999);\n if (supportsWebAnimations) {\n webAnimations.forEach((animation) => {\n // When creating the animation the delay is guaranteed to be set to a number.\n animation.currentTime = animation.effect.getComputedTiming().delay + getDuration() * step;\n animation.pause();\n });\n }\n else {\n const animationDuration = `-${getDuration() * step}ms`;\n elements.forEach((element) => {\n if (_keyframes.length > 0) {\n setStyleProperty(element, 'animation-delay', animationDuration);\n setStyleProperty(element, 'animation-play-state', 'paused');\n }\n });\n }\n };\n const updateWebAnimation = (step) => {\n webAnimations.forEach((animation) => {\n animation.effect.updateTiming({\n delay: getDelay(),\n duration: getDuration(),\n easing: getEasing(),\n iterations: getIterations(),\n fill: getFill(),\n direction: getDirection(),\n });\n });\n if (step !== undefined) {\n setAnimationStep(step);\n }\n };\n const updateCSSAnimation = (toggleAnimationName = true, step) => {\n raf(() => {\n elements.forEach((element) => {\n setStyleProperty(element, 'animation-name', keyframeName || null);\n setStyleProperty(element, 'animation-duration', `${getDuration()}ms`);\n setStyleProperty(element, 'animation-timing-function', getEasing());\n setStyleProperty(element, 'animation-delay', step !== undefined ? `-${step * getDuration()}ms` : `${getDelay()}ms`);\n setStyleProperty(element, 'animation-fill-mode', getFill() || null);\n setStyleProperty(element, 'animation-direction', getDirection() || null);\n const iterationsCount = getIterations() === Infinity ? 'infinite' : getIterations().toString();\n setStyleProperty(element, 'animation-iteration-count', iterationsCount);\n if (toggleAnimationName) {\n setStyleProperty(element, 'animation-name', `${keyframeName}-alt`);\n }\n raf(() => {\n setStyleProperty(element, 'animation-name', keyframeName || null);\n });\n });\n });\n };\n const update = (deep = false, toggleAnimationName = true, step) => {\n if (deep) {\n childAnimations.forEach((animation) => {\n animation.update(deep, toggleAnimationName, step);\n });\n }\n if (supportsWebAnimations) {\n updateWebAnimation(step);\n }\n else {\n updateCSSAnimation(toggleAnimationName, step);\n }\n return ani;\n };\n const progressStart = (forceLinearEasing = false, step) => {\n childAnimations.forEach((animation) => {\n animation.progressStart(forceLinearEasing, step);\n });\n pauseAnimation();\n shouldForceLinearEasing = forceLinearEasing;\n if (!initialized) {\n initializeAnimation();\n }\n update(false, true, step);\n return ani;\n };\n const progressStep = (step) => {\n childAnimations.forEach((animation) => {\n animation.progressStep(step);\n });\n setAnimationStep(step);\n return ani;\n };\n const progressEnd = (playTo, step, dur) => {\n shouldForceLinearEasing = false;\n childAnimations.forEach((animation) => {\n animation.progressEnd(playTo, step, dur);\n });\n if (dur !== undefined) {\n forceDurationValue = dur;\n }\n finished = false;\n willComplete = true;\n if (playTo === 0) {\n forceDirectionValue = getDirection() === 'reverse' ? 'normal' : 'reverse';\n if (forceDirectionValue === 'reverse') {\n willComplete = false;\n }\n if (supportsWebAnimations) {\n update();\n setAnimationStep(1 - step);\n }\n else {\n forceDelayValue = (1 - step) * getDuration() * -1;\n update(false, false);\n }\n }\n else if (playTo === 1) {\n if (supportsWebAnimations) {\n update();\n setAnimationStep(step);\n }\n else {\n forceDelayValue = step * getDuration() * -1;\n update(false, false);\n }\n }\n if (playTo !== undefined) {\n onFinish(() => {\n forceDurationValue = undefined;\n forceDirectionValue = undefined;\n forceDelayValue = undefined;\n }, {\n oneTimeCallback: true,\n });\n if (!parentAnimation) {\n play();\n }\n }\n return ani;\n };\n const pauseAnimation = () => {\n if (initialized) {\n if (supportsWebAnimations) {\n webAnimations.forEach((animation) => {\n animation.pause();\n });\n }\n else {\n elements.forEach((element) => {\n setStyleProperty(element, 'animation-play-state', 'paused');\n });\n }\n paused = true;\n }\n };\n const pause = () => {\n childAnimations.forEach((animation) => {\n animation.pause();\n });\n pauseAnimation();\n return ani;\n };\n const onAnimationEndFallback = () => {\n cssAnimationsTimerFallback = undefined;\n animationFinish();\n };\n const clearCSSAnimationsTimeout = () => {\n if (cssAnimationsTimerFallback) {\n clearTimeout(cssAnimationsTimerFallback);\n }\n };\n const playCSSAnimations = () => {\n clearCSSAnimationsTimeout();\n raf(() => {\n elements.forEach((element) => {\n if (_keyframes.length > 0) {\n setStyleProperty(element, 'animation-play-state', 'running');\n }\n });\n });\n if (_keyframes.length === 0 || elements.length === 0) {\n animationFinish();\n }\n else {\n /**\n * This is a catchall in the event that a CSS Animation did not finish.\n * The Web Animations API has mechanisms in place for preventing this.\n * CSS Animations will not fire an `animationend` event\n * for elements with `display: none`. The Web Animations API\n * accounts for this, but using raw CSS Animations requires\n * this workaround.\n */\n const animationDelay = getDelay() || 0;\n const animationDuration = getDuration() || 0;\n const animationIterations = getIterations() || 1;\n // No need to set a timeout when animation has infinite iterations\n if (isFinite(animationIterations)) {\n cssAnimationsTimerFallback = setTimeout(onAnimationEndFallback, animationDelay + animationDuration * animationIterations + ANIMATION_END_FALLBACK_PADDING_MS);\n }\n animationEnd(elements[0], () => {\n clearCSSAnimationsTimeout();\n /**\n * Ensure that clean up\n * is always done a frame\n * before the onFinish handlers\n * are fired. Otherwise, there\n * may be flickering if a new\n * animation is started on the same\n * element too quickly\n */\n raf(() => {\n clearCSSAnimationPlayState();\n raf(animationFinish);\n });\n });\n }\n };\n const clearCSSAnimationPlayState = () => {\n elements.forEach((element) => {\n removeStyleProperty(element, 'animation-duration');\n removeStyleProperty(element, 'animation-delay');\n removeStyleProperty(element, 'animation-play-state');\n });\n };\n const playWebAnimations = () => {\n webAnimations.forEach((animation) => {\n animation.play();\n });\n if (_keyframes.length === 0 || elements.length === 0) {\n animationFinish();\n }\n };\n const resetAnimation = () => {\n if (supportsWebAnimations) {\n setAnimationStep(0);\n updateWebAnimation();\n }\n else {\n updateCSSAnimation();\n }\n };\n const play = (opts) => {\n return new Promise((resolve) => {\n if (opts === null || opts === void 0 ? void 0 : opts.sync) {\n shouldForceSyncPlayback = true;\n onFinish(() => (shouldForceSyncPlayback = false), { oneTimeCallback: true });\n }\n if (!initialized) {\n initializeAnimation();\n }\n if (finished) {\n resetAnimation();\n finished = false;\n }\n if (shouldCalculateNumAnimations) {\n numAnimationsRunning = childAnimations.length + 1;\n shouldCalculateNumAnimations = false;\n }\n /**\n * When one of these callbacks fires we\n * need to clear the other's callback otherwise\n * you can potentially get these callbacks\n * firing multiple times if the play method\n * is subsequently called.\n * Example:\n * animation.play() (onStop and onFinish callbacks are registered)\n * animation.stop() (onStop callback is fired, onFinish is not)\n * animation.play() (onStop and onFinish callbacks are registered)\n * Total onStop callbacks: 1\n * Total onFinish callbacks: 2\n */\n const onStopCallback = () => {\n clearCallback(onFinishCallback, onFinishOneTimeCallbacks);\n resolve();\n };\n const onFinishCallback = () => {\n clearCallback(onStopCallback, onStopOneTimeCallbacks);\n resolve();\n };\n /**\n * The play method resolves when an animation\n * run either finishes or is cancelled.\n */\n onFinish(onFinishCallback, { oneTimeCallback: true });\n onStop(onStopCallback, { oneTimeCallback: true });\n childAnimations.forEach((animation) => {\n animation.play();\n });\n if (supportsWebAnimations) {\n playWebAnimations();\n }\n else {\n playCSSAnimations();\n }\n paused = false;\n });\n };\n /**\n * Stops an animation and resets it state to the\n * beginning. This does not fire any onFinish\n * callbacks because the animation did not finish.\n * However, since the animation was not destroyed\n * (i.e. the animation could run again) we do not\n * clear the onFinish callbacks.\n */\n const stop = () => {\n childAnimations.forEach((animation) => {\n animation.stop();\n });\n if (initialized) {\n cleanUpElements();\n initialized = false;\n }\n resetFlags();\n onStopOneTimeCallbacks.forEach((onStopCallback) => onStopCallback.c(0, ani));\n onStopOneTimeCallbacks.length = 0;\n };\n const from = (property, value) => {\n const firstFrame = _keyframes[0];\n if (firstFrame !== undefined && (firstFrame.offset === undefined || firstFrame.offset === 0)) {\n firstFrame[property] = value;\n }\n else {\n _keyframes = [{ offset: 0, [property]: value }, ..._keyframes];\n }\n return ani;\n };\n const to = (property, value) => {\n const lastFrame = _keyframes[_keyframes.length - 1];\n if (lastFrame !== undefined && (lastFrame.offset === undefined || lastFrame.offset === 1)) {\n lastFrame[property] = value;\n }\n else {\n _keyframes = [..._keyframes, { offset: 1, [property]: value }];\n }\n return ani;\n };\n const fromTo = (property, fromValue, toValue) => {\n return from(property, fromValue).to(property, toValue);\n };\n return (ani = {\n parentAnimation,\n elements,\n childAnimations,\n id,\n animationFinish,\n from,\n to,\n fromTo,\n parent,\n play,\n pause,\n stop,\n destroy,\n keyframes,\n addAnimation,\n addElement,\n update,\n fill,\n direction,\n iterations,\n duration,\n easing,\n delay,\n getWebAnimations,\n getKeyframes,\n getFill,\n getDirection,\n getDelay,\n getIterations,\n getEasing,\n getDuration,\n afterAddRead,\n afterAddWrite,\n afterClearStyles,\n afterStyles,\n afterRemoveClass,\n afterAddClass,\n beforeAddRead,\n beforeAddWrite,\n beforeClearStyles,\n beforeStyles,\n beforeRemoveClass,\n beforeAddClass,\n onFinish,\n isRunning,\n progressStart,\n progressStep,\n progressEnd,\n });\n};\n\nexport { createAnimation as c };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\n/**\n * Does a simple sanitization of all elements\n * in an untrusted string\n */\nconst sanitizeDOMString = (untrustedString) => {\n try {\n if (untrustedString instanceof IonicSafeString) {\n return untrustedString.value;\n }\n if (!isSanitizerEnabled() || typeof untrustedString !== 'string' || untrustedString === '') {\n return untrustedString;\n }\n /**\n * onload is fired when appending to a document\n * fragment in Chrome. If a string\n * contains onload then we should not\n * attempt to add this to the fragment.\n */\n if (untrustedString.includes('onload=')) {\n return '';\n }\n /**\n * Create a document fragment\n * separate from the main DOM,\n * create a div to do our work in\n */\n const documentFragment = document.createDocumentFragment();\n const workingDiv = document.createElement('div');\n documentFragment.appendChild(workingDiv);\n workingDiv.innerHTML = untrustedString;\n /**\n * Remove any elements\n * that are blocked\n */\n blockedTags.forEach((blockedTag) => {\n const getElementsToRemove = documentFragment.querySelectorAll(blockedTag);\n for (let elementIndex = getElementsToRemove.length - 1; elementIndex >= 0; elementIndex--) {\n const element = getElementsToRemove[elementIndex];\n if (element.parentNode) {\n element.parentNode.removeChild(element);\n }\n else {\n documentFragment.removeChild(element);\n }\n /**\n * We still need to sanitize\n * the children of this element\n * as they are left behind\n */\n const childElements = getElementChildren(element);\n /* eslint-disable-next-line */\n for (let childIndex = 0; childIndex < childElements.length; childIndex++) {\n sanitizeElement(childElements[childIndex]);\n }\n }\n });\n /**\n * Go through remaining elements and remove\n * non-allowed attribs\n */\n // IE does not support .children on document fragments, only .childNodes\n const dfChildren = getElementChildren(documentFragment);\n /* eslint-disable-next-line */\n for (let childIndex = 0; childIndex < dfChildren.length; childIndex++) {\n sanitizeElement(dfChildren[childIndex]);\n }\n // Append document fragment to div\n const fragmentDiv = document.createElement('div');\n fragmentDiv.appendChild(documentFragment);\n // First child is always the div we did our work in\n const getInnerDiv = fragmentDiv.querySelector('div');\n return getInnerDiv !== null ? getInnerDiv.innerHTML : fragmentDiv.innerHTML;\n }\n catch (err) {\n console.error(err);\n return '';\n }\n};\n/**\n * Clean up current element based on allowed attributes\n * and then recursively dig down into any child elements to\n * clean those up as well\n */\n// TODO(FW-2832): type (using Element triggers other type errors as well)\nconst sanitizeElement = (element) => {\n // IE uses childNodes, so ignore nodes that are not elements\n if (element.nodeType && element.nodeType !== 1) {\n return;\n }\n /**\n * If attributes is not a NamedNodeMap\n * then we should remove the element entirely.\n * This helps avoid DOM Clobbering attacks where\n * attributes is overridden.\n */\n if (typeof NamedNodeMap !== 'undefined' && !(element.attributes instanceof NamedNodeMap)) {\n element.remove();\n return;\n }\n for (let i = element.attributes.length - 1; i >= 0; i--) {\n const attribute = element.attributes.item(i);\n const attributeName = attribute.name;\n // remove non-allowed attribs\n if (!allowedAttributes.includes(attributeName.toLowerCase())) {\n element.removeAttribute(attributeName);\n continue;\n }\n // clean up any allowed attribs\n // that attempt to do any JS funny-business\n const attributeValue = attribute.value;\n /**\n * We also need to check the property value\n * as javascript: can allow special characters\n * such as and still be valid (i.e. java script)\n */\n const propertyValue = element[attributeName];\n /* eslint-disable */\n if ((attributeValue != null && attributeValue.toLowerCase().includes('javascript:')) ||\n (propertyValue != null && propertyValue.toLowerCase().includes('javascript:'))) {\n element.removeAttribute(attributeName);\n }\n /* eslint-enable */\n }\n /**\n * Sanitize any nested children\n */\n const childElements = getElementChildren(element);\n /* eslint-disable-next-line */\n for (let i = 0; i < childElements.length; i++) {\n sanitizeElement(childElements[i]);\n }\n};\n/**\n * IE doesn't always support .children\n * so we revert to .childNodes instead\n */\n// TODO(FW-2832): type\nconst getElementChildren = (el) => {\n return el.children != null ? el.children : el.childNodes;\n};\nconst isSanitizerEnabled = () => {\n var _a;\n const win = window;\n const config = (_a = win === null || win === void 0 ? void 0 : win.Ionic) === null || _a === void 0 ? void 0 : _a.config;\n if (config) {\n if (config.get) {\n return config.get('sanitizerEnabled', true);\n }\n else {\n return config.sanitizerEnabled === true || config.sanitizerEnabled === undefined;\n }\n }\n return true;\n};\nconst allowedAttributes = ['class', 'id', 'href', 'src', 'name', 'slot'];\nconst blockedTags = ['script', 'style', 'iframe', 'meta', 'link', 'object', 'embed'];\nclass IonicSafeString {\n constructor(value) {\n this.value = value;\n }\n}\n\nconst setupConfig = (config) => {\n const win = window;\n const Ionic = win.Ionic;\n // eslint-disable-next-line @typescript-eslint/prefer-optional-chain\n if (Ionic && Ionic.config && Ionic.config.constructor.name !== 'Object') {\n return;\n }\n win.Ionic = win.Ionic || {};\n win.Ionic.config = Object.assign(Object.assign({}, win.Ionic.config), config);\n return win.Ionic.config;\n};\nconst getMode = () => {\n var _a;\n const win = window;\n const config = (_a = win === null || win === void 0 ? void 0 : win.Ionic) === null || _a === void 0 ? void 0 : _a.config;\n if (config) {\n if (config.mode) {\n return config.mode;\n }\n else {\n return config.get('mode');\n }\n }\n return 'md';\n};\nconst ENABLE_HTML_CONTENT_DEFAULT = false;\n\nexport { ENABLE_HTML_CONTENT_DEFAULT as E, IonicSafeString as I, sanitizeDOMString as a, getMode as g, setupConfig as s };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nimport { c as componentOnReady } from './helpers-3379ba19.js';\n\n// TODO(FW-2832): types\nconst attachComponent = async (delegate, container, component, cssClasses, componentProps, inline) => {\n var _a;\n if (delegate) {\n return delegate.attachViewToDom(container, component, componentProps, cssClasses);\n }\n if (!inline && typeof component !== 'string' && !(component instanceof HTMLElement)) {\n throw new Error('framework delegate is missing');\n }\n const el = typeof component === 'string' ? (_a = container.ownerDocument) === null || _a === void 0 ? void 0 : _a.createElement(component) : component;\n if (cssClasses) {\n cssClasses.forEach((c) => el.classList.add(c));\n }\n if (componentProps) {\n Object.assign(el, componentProps);\n }\n container.appendChild(el);\n await new Promise((resolve) => componentOnReady(el, resolve));\n return el;\n};\nconst detachComponent = (delegate, element) => {\n if (element) {\n if (delegate) {\n const container = element.parentElement;\n return delegate.removeViewFromDom(container, element);\n }\n element.remove();\n }\n return Promise.resolve();\n};\nconst CoreDelegate = () => {\n let BaseComponent;\n let Reference;\n const attachViewToDom = async (parentElement, userComponent, userComponentProps = {}, cssClasses = []) => {\n var _a, _b;\n BaseComponent = parentElement;\n let ChildComponent;\n /**\n * If passing in a component via the `component` props\n * we need to append it inside of our overlay component.\n */\n if (userComponent) {\n /**\n * If passing in the tag name, create\n * the element otherwise just get a reference\n * to the component.\n */\n const el = typeof userComponent === 'string' ? (_a = BaseComponent.ownerDocument) === null || _a === void 0 ? void 0 : _a.createElement(userComponent) : userComponent;\n /**\n * Add any css classes passed in\n * via the cssClasses prop on the overlay.\n */\n cssClasses.forEach((c) => el.classList.add(c));\n /**\n * Add any props passed in\n * via the componentProps prop on the overlay.\n */\n Object.assign(el, userComponentProps);\n /**\n * Finally, append the component\n * inside of the overlay component.\n */\n BaseComponent.appendChild(el);\n ChildComponent = el;\n await new Promise((resolve) => componentOnReady(el, resolve));\n }\n else if (BaseComponent.children.length > 0 &&\n (BaseComponent.tagName === 'ION-MODAL' || BaseComponent.tagName === 'ION-POPOVER')) {\n /**\n * The delegate host wrapper el is only needed for modals and popovers\n * because they allow the dev to provide custom content to the overlay.\n */\n const root = (ChildComponent = BaseComponent.children[0]);\n if (!root.classList.contains('ion-delegate-host')) {\n /**\n * If the root element is not a delegate host, it means\n * that the overlay has not been presented yet and we need\n * to create the containing element with the specified classes.\n */\n const el = (_b = BaseComponent.ownerDocument) === null || _b === void 0 ? void 0 : _b.createElement('div');\n // Add a class to track if the root element was created by the delegate.\n el.classList.add('ion-delegate-host');\n cssClasses.forEach((c) => el.classList.add(c));\n // Move each child from the original template to the new parent element.\n el.append(...BaseComponent.children);\n // Append the new parent element to the original parent element.\n BaseComponent.appendChild(el);\n /**\n * Update the ChildComponent to be the\n * newly created div in the event that one\n * does not already exist.\n */\n ChildComponent = el;\n }\n }\n /**\n * Get the root of the app and\n * add the overlay there.\n */\n const app = document.querySelector('ion-app') || document.body;\n /**\n * Create a placeholder comment so that\n * we can return this component to where\n * it was previously.\n */\n Reference = document.createComment('ionic teleport');\n BaseComponent.parentNode.insertBefore(Reference, BaseComponent);\n app.appendChild(BaseComponent);\n /**\n * We return the child component rather than the overlay\n * reference itself since modal and popover will\n * use this to wait for any Ionic components in the child view\n * to be ready (i.e. componentOnReady) when using the\n * lazy loaded component bundle.\n *\n * However, we fall back to returning BaseComponent\n * in the event that a modal or popover is presented\n * with no child content.\n */\n return ChildComponent !== null && ChildComponent !== void 0 ? ChildComponent : BaseComponent;\n };\n const removeViewFromDom = () => {\n /**\n * Return component to where it was previously in the DOM.\n */\n if (BaseComponent && Reference) {\n Reference.parentNode.insertBefore(BaseComponent, Reference);\n Reference.remove();\n }\n return Promise.resolve();\n };\n return { attachViewToDom, removeViewFromDom };\n};\n\nexport { CoreDelegate as C, attachComponent as a, detachComponent as d };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nclass GestureController {\n constructor() {\n this.gestureId = 0;\n this.requestedStart = new Map();\n this.disabledGestures = new Map();\n this.disabledScroll = new Set();\n }\n /**\n * Creates a gesture delegate based on the GestureConfig passed\n */\n createGesture(config) {\n var _a;\n return new GestureDelegate(this, this.newID(), config.name, (_a = config.priority) !== null && _a !== void 0 ? _a : 0, !!config.disableScroll);\n }\n /**\n * Creates a blocker that will block any other gesture events from firing. Set in the ion-gesture component.\n */\n createBlocker(opts = {}) {\n return new BlockerDelegate(this, this.newID(), opts.disable, !!opts.disableScroll);\n }\n start(gestureName, id, priority) {\n if (!this.canStart(gestureName)) {\n this.requestedStart.delete(id);\n return false;\n }\n this.requestedStart.set(id, priority);\n return true;\n }\n capture(gestureName, id, priority) {\n if (!this.start(gestureName, id, priority)) {\n return false;\n }\n const requestedStart = this.requestedStart;\n let maxPriority = -10000;\n requestedStart.forEach((value) => {\n maxPriority = Math.max(maxPriority, value);\n });\n if (maxPriority === priority) {\n this.capturedId = id;\n requestedStart.clear();\n const event = new CustomEvent('ionGestureCaptured', { detail: { gestureName } });\n document.dispatchEvent(event);\n return true;\n }\n requestedStart.delete(id);\n return false;\n }\n release(id) {\n this.requestedStart.delete(id);\n if (this.capturedId === id) {\n this.capturedId = undefined;\n }\n }\n disableGesture(gestureName, id) {\n let set = this.disabledGestures.get(gestureName);\n if (set === undefined) {\n set = new Set();\n this.disabledGestures.set(gestureName, set);\n }\n set.add(id);\n }\n enableGesture(gestureName, id) {\n const set = this.disabledGestures.get(gestureName);\n if (set !== undefined) {\n set.delete(id);\n }\n }\n disableScroll(id) {\n this.disabledScroll.add(id);\n if (this.disabledScroll.size === 1) {\n document.body.classList.add(BACKDROP_NO_SCROLL);\n }\n }\n enableScroll(id) {\n this.disabledScroll.delete(id);\n if (this.disabledScroll.size === 0) {\n document.body.classList.remove(BACKDROP_NO_SCROLL);\n }\n }\n canStart(gestureName) {\n if (this.capturedId !== undefined) {\n // a gesture already captured\n return false;\n }\n if (this.isDisabled(gestureName)) {\n return false;\n }\n return true;\n }\n isCaptured() {\n return this.capturedId !== undefined;\n }\n isScrollDisabled() {\n return this.disabledScroll.size > 0;\n }\n isDisabled(gestureName) {\n const disabled = this.disabledGestures.get(gestureName);\n if (disabled && disabled.size > 0) {\n return true;\n }\n return false;\n }\n newID() {\n this.gestureId++;\n return this.gestureId;\n }\n}\nclass GestureDelegate {\n constructor(ctrl, id, name, priority, disableScroll) {\n this.id = id;\n this.name = name;\n this.disableScroll = disableScroll;\n this.priority = priority * 1000000 + id;\n this.ctrl = ctrl;\n }\n canStart() {\n if (!this.ctrl) {\n return false;\n }\n return this.ctrl.canStart(this.name);\n }\n start() {\n if (!this.ctrl) {\n return false;\n }\n return this.ctrl.start(this.name, this.id, this.priority);\n }\n capture() {\n if (!this.ctrl) {\n return false;\n }\n const captured = this.ctrl.capture(this.name, this.id, this.priority);\n if (captured && this.disableScroll) {\n this.ctrl.disableScroll(this.id);\n }\n return captured;\n }\n release() {\n if (this.ctrl) {\n this.ctrl.release(this.id);\n if (this.disableScroll) {\n this.ctrl.enableScroll(this.id);\n }\n }\n }\n destroy() {\n this.release();\n this.ctrl = undefined;\n }\n}\nclass BlockerDelegate {\n constructor(ctrl, id, disable, disableScroll) {\n this.id = id;\n this.disable = disable;\n this.disableScroll = disableScroll;\n this.ctrl = ctrl;\n }\n block() {\n if (!this.ctrl) {\n return;\n }\n if (this.disable) {\n for (const gesture of this.disable) {\n this.ctrl.disableGesture(gesture, this.id);\n }\n }\n if (this.disableScroll) {\n this.ctrl.disableScroll(this.id);\n }\n }\n unblock() {\n if (!this.ctrl) {\n return;\n }\n if (this.disable) {\n for (const gesture of this.disable) {\n this.ctrl.enableGesture(gesture, this.id);\n }\n }\n if (this.disableScroll) {\n this.ctrl.enableScroll(this.id);\n }\n }\n destroy() {\n this.unblock();\n this.ctrl = undefined;\n }\n}\nconst BACKDROP_NO_SCROLL = 'backdrop-no-scroll';\nconst GESTURE_CONTROLLER = new GestureController();\n\nexport { GESTURE_CONTROLLER as G };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\n/**\n * When hardwareBackButton: false in config,\n * we need to make sure we also block the default\n * webview behavior. If we don't then it will be\n * possible for users to navigate backward while\n * an overlay is still open. Additionally, it will\n * give the appearance that the hardwareBackButton\n * config is not working as the page transition\n * will still happen.\n */\nconst blockHardwareBackButton = () => {\n document.addEventListener('backbutton', () => { }); // eslint-disable-line\n};\nconst startHardwareBackButton = () => {\n const doc = document;\n let busy = false;\n doc.addEventListener('backbutton', () => {\n if (busy) {\n return;\n }\n let index = 0;\n let handlers = [];\n const ev = new CustomEvent('ionBackButton', {\n bubbles: false,\n detail: {\n register(priority, handler) {\n handlers.push({ priority, handler, id: index++ });\n },\n },\n });\n doc.dispatchEvent(ev);\n const executeAction = async (handlerRegister) => {\n try {\n if (handlerRegister === null || handlerRegister === void 0 ? void 0 : handlerRegister.handler) {\n const result = handlerRegister.handler(processHandlers);\n if (result != null) {\n await result;\n }\n }\n }\n catch (e) {\n console.error(e);\n }\n };\n const processHandlers = () => {\n if (handlers.length > 0) {\n let selectedHandler = {\n priority: Number.MIN_SAFE_INTEGER,\n handler: () => undefined,\n id: -1,\n };\n handlers.forEach((handler) => {\n if (handler.priority >= selectedHandler.priority) {\n selectedHandler = handler;\n }\n });\n busy = true;\n handlers = handlers.filter((handler) => handler.id !== selectedHandler.id);\n executeAction(selectedHandler).then(() => (busy = false));\n }\n };\n processHandlers();\n });\n};\nconst OVERLAY_BACK_BUTTON_PRIORITY = 100;\nconst MENU_BACK_BUTTON_PRIORITY = 99; // 1 less than overlay priority since menu is displayed behind overlays\n\nexport { MENU_BACK_BUTTON_PRIORITY, OVERLAY_BACK_BUTTON_PRIORITY, blockHardwareBackButton, startHardwareBackButton };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nconst transitionEndAsync = (el, expectedDuration = 0) => {\n return new Promise((resolve) => {\n transitionEnd(el, expectedDuration, resolve);\n });\n};\n/**\n * Allows developer to wait for a transition\n * to finish and fallback to a timer if the\n * transition is cancelled or otherwise\n * never finishes. Also see transitionEndAsync\n * which is an await-able version of this.\n */\nconst transitionEnd = (el, expectedDuration = 0, callback) => {\n let unRegTrans;\n let animationTimeout;\n const opts = { passive: true };\n const ANIMATION_FALLBACK_TIMEOUT = 500;\n const unregister = () => {\n if (unRegTrans) {\n unRegTrans();\n }\n };\n const onTransitionEnd = (ev) => {\n if (ev === undefined || el === ev.target) {\n unregister();\n callback(ev);\n }\n };\n if (el) {\n el.addEventListener('webkitTransitionEnd', onTransitionEnd, opts);\n el.addEventListener('transitionend', onTransitionEnd, opts);\n animationTimeout = setTimeout(onTransitionEnd, expectedDuration + ANIMATION_FALLBACK_TIMEOUT);\n unRegTrans = () => {\n if (animationTimeout) {\n clearTimeout(animationTimeout);\n animationTimeout = undefined;\n }\n el.removeEventListener('webkitTransitionEnd', onTransitionEnd, opts);\n el.removeEventListener('transitionend', onTransitionEnd, opts);\n };\n }\n return unregister;\n};\n/**\n * Waits for a component to be ready for\n * both custom element and non-custom element builds.\n * If non-custom element build, el.componentOnReady\n * will be used.\n * For custom element builds, we wait a frame\n * so that the inner contents of the component\n * have a chance to render.\n *\n * Use this utility rather than calling\n * el.componentOnReady yourself.\n */\nconst componentOnReady = (el, callback) => {\n if (el.componentOnReady) {\n // eslint-disable-next-line custom-rules/no-component-on-ready-method\n el.componentOnReady().then((resolvedEl) => callback(resolvedEl));\n }\n else {\n raf(() => callback(el));\n }\n};\n/**\n * This functions checks if a Stencil component is using\n * the lazy loaded build of Stencil. Returns `true` if\n * the component is lazy loaded. Returns `false` otherwise.\n */\nconst hasLazyBuild = (stencilEl) => {\n return stencilEl.componentOnReady !== undefined;\n};\n/**\n * Elements inside of web components sometimes need to inherit global attributes\n * set on the host. For example, the inner input in `ion-input` should inherit\n * the `title` attribute that developers set directly on `ion-input`. This\n * helper function should be called in componentWillLoad and assigned to a variable\n * that is later used in the render function.\n *\n * This does not need to be reactive as changing attributes on the host element\n * does not trigger a re-render.\n */\nconst inheritAttributes = (el, attributes = []) => {\n const attributeObject = {};\n attributes.forEach((attr) => {\n if (el.hasAttribute(attr)) {\n const value = el.getAttribute(attr);\n if (value !== null) {\n attributeObject[attr] = el.getAttribute(attr);\n }\n el.removeAttribute(attr);\n }\n });\n return attributeObject;\n};\n/**\n * List of available ARIA attributes + `role`.\n * Removed deprecated attributes.\n * https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes\n */\nconst ariaAttributes = [\n 'role',\n 'aria-activedescendant',\n 'aria-atomic',\n 'aria-autocomplete',\n 'aria-braillelabel',\n 'aria-brailleroledescription',\n 'aria-busy',\n 'aria-checked',\n 'aria-colcount',\n 'aria-colindex',\n 'aria-colindextext',\n 'aria-colspan',\n 'aria-controls',\n 'aria-current',\n 'aria-describedby',\n 'aria-description',\n 'aria-details',\n 'aria-disabled',\n 'aria-errormessage',\n 'aria-expanded',\n 'aria-flowto',\n 'aria-haspopup',\n 'aria-hidden',\n 'aria-invalid',\n 'aria-keyshortcuts',\n 'aria-label',\n 'aria-labelledby',\n 'aria-level',\n 'aria-live',\n 'aria-multiline',\n 'aria-multiselectable',\n 'aria-orientation',\n 'aria-owns',\n 'aria-placeholder',\n 'aria-posinset',\n 'aria-pressed',\n 'aria-readonly',\n 'aria-relevant',\n 'aria-required',\n 'aria-roledescription',\n 'aria-rowcount',\n 'aria-rowindex',\n 'aria-rowindextext',\n 'aria-rowspan',\n 'aria-selected',\n 'aria-setsize',\n 'aria-sort',\n 'aria-valuemax',\n 'aria-valuemin',\n 'aria-valuenow',\n 'aria-valuetext',\n];\n/**\n * Returns an array of aria attributes that should be copied from\n * the shadow host element to a target within the light DOM.\n * @param el The element that the attributes should be copied from.\n * @param ignoreList The list of aria-attributes to ignore reflecting and removing from the host.\n * Use this in instances where we manually specify aria attributes on the `` element.\n */\nconst inheritAriaAttributes = (el, ignoreList) => {\n let attributesToInherit = ariaAttributes;\n if (ignoreList && ignoreList.length > 0) {\n attributesToInherit = attributesToInherit.filter((attr) => !ignoreList.includes(attr));\n }\n return inheritAttributes(el, attributesToInherit);\n};\nconst addEventListener = (el, eventName, callback, opts) => {\n var _a;\n if (typeof window !== 'undefined') {\n const win = window;\n const config = (_a = win === null || win === void 0 ? void 0 : win.Ionic) === null || _a === void 0 ? void 0 : _a.config;\n if (config) {\n const ael = config.get('_ael');\n if (ael) {\n return ael(el, eventName, callback, opts);\n }\n else if (config._ael) {\n return config._ael(el, eventName, callback, opts);\n }\n }\n }\n return el.addEventListener(eventName, callback, opts);\n};\nconst removeEventListener = (el, eventName, callback, opts) => {\n var _a;\n if (typeof window !== 'undefined') {\n const win = window;\n const config = (_a = win === null || win === void 0 ? void 0 : win.Ionic) === null || _a === void 0 ? void 0 : _a.config;\n if (config) {\n const rel = config.get('_rel');\n if (rel) {\n return rel(el, eventName, callback, opts);\n }\n else if (config._rel) {\n return config._rel(el, eventName, callback, opts);\n }\n }\n }\n return el.removeEventListener(eventName, callback, opts);\n};\n/**\n * Gets the root context of a shadow dom element\n * On newer browsers this will be the shadowRoot,\n * but for older browser this may just be the\n * element itself.\n *\n * Useful for whenever you need to explicitly\n * do \"myElement.shadowRoot!.querySelector(...)\".\n */\nconst getElementRoot = (el, fallback = el) => {\n return el.shadowRoot || fallback;\n};\n/**\n * Patched version of requestAnimationFrame that avoids ngzone\n * Use only when you know ngzone should not run\n */\nconst raf = (h) => {\n if (typeof __zone_symbol__requestAnimationFrame === 'function') {\n return __zone_symbol__requestAnimationFrame(h);\n }\n if (typeof requestAnimationFrame === 'function') {\n return requestAnimationFrame(h);\n }\n return setTimeout(h);\n};\nconst hasShadowDom = (el) => {\n return !!el.shadowRoot && !!el.attachShadow;\n};\nconst findItemLabel = (componentEl) => {\n const itemEl = componentEl.closest('ion-item');\n if (itemEl) {\n return itemEl.querySelector('ion-label');\n }\n return null;\n};\nconst focusElement = (el) => {\n el.focus();\n /**\n * When programmatically focusing an element,\n * the focus-visible utility will not run because\n * it is expecting a keyboard event to have triggered this;\n * however, there are times when we need to manually control\n * this behavior so we call the `setFocus` method on ion-app\n * which will let us explicitly set the elements to focus.\n */\n if (el.classList.contains('ion-focusable')) {\n const app = el.closest('ion-app');\n if (app) {\n app.setFocus([el]);\n }\n }\n};\n/**\n * This method is used for Ionic's input components that use Shadow DOM. In\n * order to properly label the inputs to work with screen readers, we need\n * to get the text content of the label outside of the shadow root and pass\n * it to the input inside of the shadow root.\n *\n * Referencing label elements by id from outside of the component is\n * impossible due to the shadow boundary, read more here:\n * https://developer.salesforce.com/blogs/2020/01/accessibility-for-web-components.html\n *\n * @param componentEl The shadow element that needs the aria label\n * @param inputId The unique identifier for the input\n */\nconst getAriaLabel = (componentEl, inputId) => {\n let labelText;\n // If the user provides their own label via the aria-labelledby attr\n // we should use that instead of looking for an ion-label\n const labelledBy = componentEl.getAttribute('aria-labelledby');\n // Grab the id off of the component in case they are using\n // a custom label using the label element\n const componentId = componentEl.id;\n let labelId = labelledBy !== null && labelledBy.trim() !== '' ? labelledBy : inputId + '-lbl';\n let label = labelledBy !== null && labelledBy.trim() !== '' ? document.getElementById(labelledBy) : findItemLabel(componentEl);\n if (label) {\n if (labelledBy === null) {\n label.id = labelId;\n }\n labelText = label.textContent;\n label.setAttribute('aria-hidden', 'true');\n // if there is no label, check to see if the user has provided\n // one by setting an id on the component and using the label element\n }\n else if (componentId.trim() !== '') {\n label = document.querySelector(`label[for=\"${componentId}\"]`);\n if (label) {\n if (label.id !== '') {\n labelId = label.id;\n }\n else {\n label.id = labelId = `${componentId}-lbl`;\n }\n labelText = label.textContent;\n }\n }\n return { label, labelId, labelText };\n};\n/**\n * This method is used to add a hidden input to a host element that contains\n * a Shadow DOM. It does not add the input inside of the Shadow root which\n * allows it to be picked up inside of forms. It should contain the same\n * values as the host element.\n *\n * @param always Add a hidden input even if the container does not use Shadow\n * @param container The element where the input will be added\n * @param name The name of the input\n * @param value The value of the input\n * @param disabled If true, the input is disabled\n */\nconst renderHiddenInput = (always, container, name, value, disabled) => {\n if (always || hasShadowDom(container)) {\n let input = container.querySelector('input.aux-input');\n if (!input) {\n input = container.ownerDocument.createElement('input');\n input.type = 'hidden';\n input.classList.add('aux-input');\n container.appendChild(input);\n }\n input.disabled = disabled;\n input.name = name;\n input.value = value || '';\n }\n};\nconst clamp = (min, n, max) => {\n return Math.max(min, Math.min(n, max));\n};\nconst assert = (actual, reason) => {\n if (!actual) {\n const message = 'ASSERT: ' + reason;\n console.error(message);\n debugger; // eslint-disable-line\n throw new Error(message);\n }\n};\nconst now = (ev) => {\n return ev.timeStamp || Date.now();\n};\nconst pointerCoord = (ev) => {\n // get X coordinates for either a mouse click\n // or a touch depending on the given event\n if (ev) {\n const changedTouches = ev.changedTouches;\n if (changedTouches && changedTouches.length > 0) {\n const touch = changedTouches[0];\n return { x: touch.clientX, y: touch.clientY };\n }\n if (ev.pageX !== undefined) {\n return { x: ev.pageX, y: ev.pageY };\n }\n }\n return { x: 0, y: 0 };\n};\n/**\n * @hidden\n * Given a side, return if it should be on the end\n * based on the value of dir\n * @param side the side\n * @param isRTL whether the application dir is rtl\n */\nconst isEndSide = (side) => {\n const isRTL = document.dir === 'rtl';\n switch (side) {\n case 'start':\n return isRTL;\n case 'end':\n return !isRTL;\n default:\n throw new Error(`\"${side}\" is not a valid value for [side]. Use \"start\" or \"end\" instead.`);\n }\n};\nconst debounceEvent = (event, wait) => {\n const original = event._original || event;\n return {\n _original: event,\n emit: debounce(original.emit.bind(original), wait),\n };\n};\nconst debounce = (func, wait = 0) => {\n let timer;\n return (...args) => {\n clearTimeout(timer);\n timer = setTimeout(func, wait, ...args);\n };\n};\n/**\n * Check whether the two string maps are shallow equal.\n *\n * undefined is treated as an empty map.\n *\n * @returns whether the keys are the same and the values are shallow equal.\n */\nconst shallowEqualStringMap = (map1, map2) => {\n map1 !== null && map1 !== void 0 ? map1 : (map1 = {});\n map2 !== null && map2 !== void 0 ? map2 : (map2 = {});\n if (map1 === map2) {\n return true;\n }\n const keys1 = Object.keys(map1);\n if (keys1.length !== Object.keys(map2).length) {\n return false;\n }\n for (const k1 of keys1) {\n if (!(k1 in map2)) {\n return false;\n }\n if (map1[k1] !== map2[k1]) {\n return false;\n }\n }\n return true;\n};\n\nexport { addEventListener as a, removeEventListener as b, componentOnReady as c, renderHiddenInput as d, getAriaLabel as e, focusElement as f, getElementRoot as g, findItemLabel as h, inheritAriaAttributes as i, debounceEvent as j, inheritAttributes as k, clamp as l, hasLazyBuild as m, hasShadowDom as n, assert as o, isEndSide as p, debounce as q, raf as r, shallowEqualStringMap as s, transitionEndAsync as t, now as u, pointerCoord as v };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nimport { p as printIonWarning } from './index-595d62c9.js';\nimport { MENU_BACK_BUTTON_PRIORITY } from './hardware-back-button-39299f84.js';\nimport { c as componentOnReady } from './helpers-3379ba19.js';\nimport { b as getIonMode } from './ionic-global-40e42e7f.js';\nimport { c as createAnimation } from './animation-8aa13916.js';\n\n/**\n * baseAnimation\n * Base class which is extended by the various types. Each\n * type will provide their own animations for open and close\n * and registers itself with Menu.\n */\nconst baseAnimation = (isIos) => {\n // https://material.io/guidelines/motion/movement.html#movement-movement-in-out-of-screen-bounds\n // https://material.io/guidelines/motion/duration-easing.html#duration-easing-natural-easing-curves\n /**\n * \"Apply the sharp curve to items temporarily leaving the screen that may return\n * from the same exit point. When they return, use the deceleration curve. On mobile,\n * this transition typically occurs over 300ms\" -- MD Motion Guide\n */\n return createAnimation().duration(isIos ? 400 : 300);\n};\n\n/**\n * Menu Overlay Type\n * The menu slides over the content. The content\n * itself, which is under the menu, does not move.\n */\nconst menuOverlayAnimation = (menu) => {\n let closedX;\n let openedX;\n const width = menu.width + 8;\n const menuAnimation = createAnimation();\n const backdropAnimation = createAnimation();\n if (menu.isEndSide) {\n // right side\n closedX = width + 'px';\n openedX = '0px';\n }\n else {\n // left side\n closedX = -width + 'px';\n openedX = '0px';\n }\n menuAnimation.addElement(menu.menuInnerEl).fromTo('transform', `translateX(${closedX})`, `translateX(${openedX})`);\n const mode = getIonMode(menu);\n const isIos = mode === 'ios';\n const opacity = isIos ? 0.2 : 0.25;\n backdropAnimation.addElement(menu.backdropEl).fromTo('opacity', 0.01, opacity);\n return baseAnimation(isIos).addAnimation([menuAnimation, backdropAnimation]);\n};\n\n/**\n * Menu Push Type\n * The content slides over to reveal the menu underneath.\n * The menu itself also slides over to reveal its bad self.\n */\nconst menuPushAnimation = (menu) => {\n let contentOpenedX;\n let menuClosedX;\n const mode = getIonMode(menu);\n const width = menu.width;\n if (menu.isEndSide) {\n contentOpenedX = -width + 'px';\n menuClosedX = width + 'px';\n }\n else {\n contentOpenedX = width + 'px';\n menuClosedX = -width + 'px';\n }\n const menuAnimation = createAnimation()\n .addElement(menu.menuInnerEl)\n .fromTo('transform', `translateX(${menuClosedX})`, 'translateX(0px)');\n const contentAnimation = createAnimation()\n .addElement(menu.contentEl)\n .fromTo('transform', 'translateX(0px)', `translateX(${contentOpenedX})`);\n const backdropAnimation = createAnimation().addElement(menu.backdropEl).fromTo('opacity', 0.01, 0.32);\n return baseAnimation(mode === 'ios').addAnimation([menuAnimation, contentAnimation, backdropAnimation]);\n};\n\n/**\n * Menu Reveal Type\n * The content slides over to reveal the menu underneath.\n * The menu itself, which is under the content, does not move.\n */\nconst menuRevealAnimation = (menu) => {\n const mode = getIonMode(menu);\n const openedX = menu.width * (menu.isEndSide ? -1 : 1) + 'px';\n const contentOpen = createAnimation()\n .addElement(menu.contentEl) // REVIEW\n .fromTo('transform', 'translateX(0px)', `translateX(${openedX})`);\n return baseAnimation(mode === 'ios').addAnimation(contentOpen);\n};\n\nconst createMenuController = () => {\n const menuAnimations = new Map();\n const menus = [];\n const open = async (menu) => {\n const menuEl = await get(menu, true);\n if (menuEl) {\n return menuEl.open();\n }\n return false;\n };\n const close = async (menu) => {\n const menuEl = await (menu !== undefined ? get(menu, true) : getOpen());\n if (menuEl !== undefined) {\n return menuEl.close();\n }\n return false;\n };\n const toggle = async (menu) => {\n const menuEl = await get(menu, true);\n if (menuEl) {\n return menuEl.toggle();\n }\n return false;\n };\n const enable = async (shouldEnable, menu) => {\n const menuEl = await get(menu);\n if (menuEl) {\n menuEl.disabled = !shouldEnable;\n }\n return menuEl;\n };\n const swipeGesture = async (shouldEnable, menu) => {\n const menuEl = await get(menu);\n if (menuEl) {\n menuEl.swipeGesture = shouldEnable;\n }\n return menuEl;\n };\n const isOpen = async (menu) => {\n if (menu != null) {\n const menuEl = await get(menu);\n // eslint-disable-next-line @typescript-eslint/prefer-optional-chain\n return menuEl !== undefined && menuEl.isOpen();\n }\n else {\n const menuEl = await getOpen();\n return menuEl !== undefined;\n }\n };\n const isEnabled = async (menu) => {\n const menuEl = await get(menu);\n if (menuEl) {\n return !menuEl.disabled;\n }\n return false;\n };\n /**\n * Finds and returns the menu specified by \"menu\" if registered.\n * @param menu - The side or ID of the desired menu\n * @param logOnMultipleSideMenus - If true, this function will log a warning\n * if \"menu\" is a side but multiple menus on the same side were found. Since this function\n * is used in multiple places, we default this log to false so that the calling\n * functions can choose whether or not it is appropriate to log this warning.\n */\n const get = async (menu, logOnMultipleSideMenus = false) => {\n await waitUntilReady();\n if (menu === 'start' || menu === 'end') {\n // there could be more than one menu on the same side\n // so first try to get the enabled one\n const menuRefs = menus.filter((m) => m.side === menu && !m.disabled);\n if (menuRefs.length >= 1) {\n if (menuRefs.length > 1 && logOnMultipleSideMenus) {\n printIonWarning(`menuController queried for a menu on the \"${menu}\" side, but ${menuRefs.length} menus were found. The first menu reference will be used. If this is not the behavior you want then pass the ID of the menu instead of its side.`, menuRefs.map((m) => m.el));\n }\n return menuRefs[0].el;\n }\n // didn't find a menu side that is enabled\n // so try to get the first menu side found\n const sideMenuRefs = menus.filter((m) => m.side === menu);\n if (sideMenuRefs.length >= 1) {\n if (sideMenuRefs.length > 1 && logOnMultipleSideMenus) {\n printIonWarning(`menuController queried for a menu on the \"${menu}\" side, but ${sideMenuRefs.length} menus were found. The first menu reference will be used. If this is not the behavior you want then pass the ID of the menu instead of its side.`, sideMenuRefs.map((m) => m.el));\n }\n return sideMenuRefs[0].el;\n }\n }\n else if (menu != null) {\n // the menuId was not left or right\n // so try to get the menu by its \"id\"\n return find((m) => m.menuId === menu);\n }\n // return the first enabled menu\n const menuEl = find((m) => !m.disabled);\n if (menuEl) {\n return menuEl;\n }\n // get the first menu in the array, if one exists\n return menus.length > 0 ? menus[0].el : undefined;\n };\n /**\n * Get the instance of the opened menu. Returns `null` if a menu is not found.\n */\n const getOpen = async () => {\n await waitUntilReady();\n return _getOpenSync();\n };\n /**\n * Get all menu instances.\n */\n const getMenus = async () => {\n await waitUntilReady();\n return getMenusSync();\n };\n /**\n * Get whether or not a menu is animating. Returns `true` if any\n * menu is currently animating.\n */\n const isAnimating = async () => {\n await waitUntilReady();\n return isAnimatingSync();\n };\n const registerAnimation = (name, animation) => {\n menuAnimations.set(name, animation);\n };\n const _register = (menu) => {\n if (menus.indexOf(menu) < 0) {\n menus.push(menu);\n }\n };\n const _unregister = (menu) => {\n const index = menus.indexOf(menu);\n if (index > -1) {\n menus.splice(index, 1);\n }\n };\n const _setOpen = async (menu, shouldOpen, animated) => {\n if (isAnimatingSync()) {\n return false;\n }\n if (shouldOpen) {\n const openedMenu = await getOpen();\n if (openedMenu && menu.el !== openedMenu) {\n await openedMenu.setOpen(false, false);\n }\n }\n return menu._setOpen(shouldOpen, animated);\n };\n const _createAnimation = (type, menuCmp) => {\n const animationBuilder = menuAnimations.get(type); // TODO(FW-2832): type\n if (!animationBuilder) {\n throw new Error('animation not registered');\n }\n const animation = animationBuilder(menuCmp);\n return animation;\n };\n const _getOpenSync = () => {\n return find((m) => m._isOpen);\n };\n const getMenusSync = () => {\n return menus.map((menu) => menu.el);\n };\n const isAnimatingSync = () => {\n return menus.some((menu) => menu.isAnimating);\n };\n const find = (predicate) => {\n const instance = menus.find(predicate);\n if (instance !== undefined) {\n return instance.el;\n }\n return undefined;\n };\n const waitUntilReady = () => {\n return Promise.all(Array.from(document.querySelectorAll('ion-menu')).map((menu) => new Promise((resolve) => componentOnReady(menu, resolve))));\n };\n registerAnimation('reveal', menuRevealAnimation);\n registerAnimation('push', menuPushAnimation);\n registerAnimation('overlay', menuOverlayAnimation);\n if (typeof document !== 'undefined') {\n document.addEventListener('ionBackButton', (ev) => {\n // TODO(FW-2832): type\n const openMenu = _getOpenSync();\n if (openMenu) {\n ev.detail.register(MENU_BACK_BUTTON_PRIORITY, () => {\n return openMenu.close();\n });\n }\n });\n }\n return {\n registerAnimation,\n get,\n getMenus,\n getOpen,\n isEnabled,\n swipeGesture,\n isAnimating,\n isOpen,\n enable,\n toggle,\n close,\n open,\n _getOpenSync,\n _createAnimation,\n _register,\n _unregister,\n _setOpen,\n };\n};\nconst menuController = /*@__PURE__*/ createMenuController();\n\nexport { menuController as m };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\n/**\n * Logs a warning to the console with an Ionic prefix\n * to indicate the library that is warning the developer.\n *\n * @param message - The string message to be logged to the console.\n */\nconst printIonWarning = (message, ...params) => {\n return console.warn(`[Ionic Warning]: ${message}`, ...params);\n};\n/*\n * Logs an error to the console with an Ionic prefix\n * to indicate the library that is warning the developer.\n *\n * @param message - The string message to be logged to the console.\n * @param params - Additional arguments to supply to the console.error.\n */\nconst printIonError = (message, ...params) => {\n return console.error(`[Ionic Error]: ${message}`, ...params);\n};\n/**\n * Prints an error informing developers that an implementation requires an element to be used\n * within a specific selector.\n *\n * @param el The web component element this is requiring the element.\n * @param targetSelectors The selector or selectors that were not found.\n */\nconst printRequiredElementError = (el, ...targetSelectors) => {\n return console.error(`<${el.tagName.toLowerCase()}> must be used inside ${targetSelectors.join(' or ')}.`);\n};\n\nexport { printIonError as a, printRequiredElementError as b, printIonWarning as p };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nimport { w as writeTask, B as Build } from './index-7c9b1bca.js';\nimport { r as raf } from './helpers-3379ba19.js';\n\nconst LIFECYCLE_WILL_ENTER = 'ionViewWillEnter';\nconst LIFECYCLE_DID_ENTER = 'ionViewDidEnter';\nconst LIFECYCLE_WILL_LEAVE = 'ionViewWillLeave';\nconst LIFECYCLE_DID_LEAVE = 'ionViewDidLeave';\nconst LIFECYCLE_WILL_UNLOAD = 'ionViewWillUnload';\n\nconst iosTransitionAnimation = () => import('./ios.transition-1651c430.js');\nconst mdTransitionAnimation = () => import('./md.transition-66f18369.js');\n// TODO(FW-2832): types\nconst transition = (opts) => {\n return new Promise((resolve, reject) => {\n writeTask(() => {\n beforeTransition(opts);\n runTransition(opts).then((result) => {\n if (result.animation) {\n result.animation.destroy();\n }\n afterTransition(opts);\n resolve(result);\n }, (error) => {\n afterTransition(opts);\n reject(error);\n });\n });\n });\n};\nconst beforeTransition = (opts) => {\n const enteringEl = opts.enteringEl;\n const leavingEl = opts.leavingEl;\n setZIndex(enteringEl, leavingEl, opts.direction);\n if (opts.showGoBack) {\n enteringEl.classList.add('can-go-back');\n }\n else {\n enteringEl.classList.remove('can-go-back');\n }\n setPageHidden(enteringEl, false);\n /**\n * When transitioning, the page should not\n * respond to click events. This resolves small\n * issues like users double tapping the ion-back-button.\n * These pointer events are removed in `afterTransition`.\n */\n enteringEl.style.setProperty('pointer-events', 'none');\n if (leavingEl) {\n setPageHidden(leavingEl, false);\n leavingEl.style.setProperty('pointer-events', 'none');\n }\n};\nconst runTransition = async (opts) => {\n const animationBuilder = await getAnimationBuilder(opts);\n const ani = animationBuilder && Build.isBrowser ? animation(animationBuilder, opts) : noAnimation(opts); // fast path for no animation\n return ani;\n};\nconst afterTransition = (opts) => {\n const enteringEl = opts.enteringEl;\n const leavingEl = opts.leavingEl;\n enteringEl.classList.remove('ion-page-invisible');\n enteringEl.style.removeProperty('pointer-events');\n if (leavingEl !== undefined) {\n leavingEl.classList.remove('ion-page-invisible');\n leavingEl.style.removeProperty('pointer-events');\n }\n};\nconst getAnimationBuilder = async (opts) => {\n if (!opts.leavingEl || !opts.animated || opts.duration === 0) {\n return undefined;\n }\n if (opts.animationBuilder) {\n return opts.animationBuilder;\n }\n const getAnimation = opts.mode === 'ios'\n ? (await iosTransitionAnimation()).iosTransitionAnimation\n : (await mdTransitionAnimation()).mdTransitionAnimation;\n return getAnimation;\n};\nconst animation = async (animationBuilder, opts) => {\n await waitForReady(opts, true);\n const trans = animationBuilder(opts.baseEl, opts);\n fireWillEvents(opts.enteringEl, opts.leavingEl);\n const didComplete = await playTransition(trans, opts);\n if (opts.progressCallback) {\n opts.progressCallback(undefined);\n }\n if (didComplete) {\n fireDidEvents(opts.enteringEl, opts.leavingEl);\n }\n return {\n hasCompleted: didComplete,\n animation: trans,\n };\n};\nconst noAnimation = async (opts) => {\n const enteringEl = opts.enteringEl;\n const leavingEl = opts.leavingEl;\n await waitForReady(opts, false);\n fireWillEvents(enteringEl, leavingEl);\n fireDidEvents(enteringEl, leavingEl);\n return {\n hasCompleted: true,\n };\n};\nconst waitForReady = async (opts, defaultDeep) => {\n const deep = opts.deepWait !== undefined ? opts.deepWait : defaultDeep;\n if (deep) {\n await Promise.all([deepReady(opts.enteringEl), deepReady(opts.leavingEl)]);\n }\n await notifyViewReady(opts.viewIsReady, opts.enteringEl);\n};\nconst notifyViewReady = async (viewIsReady, enteringEl) => {\n if (viewIsReady) {\n await viewIsReady(enteringEl);\n }\n};\nconst playTransition = (trans, opts) => {\n const progressCallback = opts.progressCallback;\n const promise = new Promise((resolve) => {\n trans.onFinish((currentStep) => resolve(currentStep === 1));\n });\n // cool, let's do this, start the transition\n if (progressCallback) {\n // this is a swipe to go back, just get the transition progress ready\n // kick off the swipe animation start\n trans.progressStart(true);\n progressCallback(trans);\n }\n else {\n // only the top level transition should actually start \"play\"\n // kick it off and let it play through\n // ******** DOM WRITE ****************\n trans.play();\n }\n // create a callback for when the animation is done\n return promise;\n};\nconst fireWillEvents = (enteringEl, leavingEl) => {\n lifecycle(leavingEl, LIFECYCLE_WILL_LEAVE);\n lifecycle(enteringEl, LIFECYCLE_WILL_ENTER);\n};\nconst fireDidEvents = (enteringEl, leavingEl) => {\n lifecycle(enteringEl, LIFECYCLE_DID_ENTER);\n lifecycle(leavingEl, LIFECYCLE_DID_LEAVE);\n};\nconst lifecycle = (el, eventName) => {\n if (el) {\n const ev = new CustomEvent(eventName, {\n bubbles: false,\n cancelable: false,\n });\n el.dispatchEvent(ev);\n }\n};\n/**\n * Wait two request animation frame loops.\n * This allows the framework implementations enough time to mount\n * the user-defined contents. This is often needed when using inline\n * modals and popovers that accept user components. For popover,\n * the contents must be mounted for the popover to be sized correctly.\n * For modals, the contents must be mounted for iOS to run the\n * transition correctly.\n *\n * On Angular and React, a single raf is enough time, but for Vue\n * we need to wait two rafs. As a result we are using two rafs for\n * all frameworks to ensure contents are mounted.\n */\nconst waitForMount = () => {\n return new Promise((resolve) => raf(() => raf(() => resolve())));\n};\nconst deepReady = async (el) => {\n const element = el;\n if (element) {\n if (element.componentOnReady != null) {\n // eslint-disable-next-line custom-rules/no-component-on-ready-method\n const stencilEl = await element.componentOnReady();\n if (stencilEl != null) {\n return;\n }\n /**\n * Custom elements in Stencil will have __registerHost.\n */\n }\n else if (element.__registerHost != null) {\n /**\n * Non-lazy loaded custom elements need to wait\n * one frame for component to be loaded.\n */\n const waitForCustomElement = new Promise((resolve) => raf(resolve));\n await waitForCustomElement;\n return;\n }\n await Promise.all(Array.from(element.children).map(deepReady));\n }\n};\nconst setPageHidden = (el, hidden) => {\n if (hidden) {\n el.setAttribute('aria-hidden', 'true');\n el.classList.add('ion-page-hidden');\n }\n else {\n el.hidden = false;\n el.removeAttribute('aria-hidden');\n el.classList.remove('ion-page-hidden');\n }\n};\nconst setZIndex = (enteringEl, leavingEl, direction) => {\n if (enteringEl !== undefined) {\n enteringEl.style.zIndex = direction === 'back' ? '99' : '101';\n }\n if (leavingEl !== undefined) {\n leavingEl.style.zIndex = '100';\n }\n};\nconst getIonPageElement = (element) => {\n if (element.classList.contains('ion-page')) {\n return element;\n }\n const ionPage = element.querySelector(':scope > .ion-page, :scope > ion-nav, :scope > ion-tabs');\n if (ionPage) {\n return ionPage;\n }\n // idk, return the original element so at least something animates and we don't have a null pointer\n return element;\n};\n\nexport { LIFECYCLE_WILL_ENTER as L, LIFECYCLE_DID_ENTER as a, LIFECYCLE_WILL_LEAVE as b, LIFECYCLE_DID_LEAVE as c, LIFECYCLE_WILL_UNLOAD as d, deepReady as e, getIonPageElement as g, lifecycle as l, setPageHidden as s, transition as t, waitForMount as w };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\n/**\n * When accessing the document or window, it is important\n * to account for SSR applications where the\n * window is not available. Code that accesses\n * window when it is not available will crash.\n * Even checking if `window === undefined` will cause\n * apps to crash in SSR.\n *\n * Use win below to access an SSR-safe version\n * of the window.\n *\n * Example 1:\n * Before:\n * if (window.innerWidth > 768) { ... }\n *\n * After:\n * import { win } from 'path/to/this/file';\n * if (win?.innerWidth > 768) { ... }\n *\n * Note: Code inside of this if-block will\n * not run in an SSR environment.\n */\nconst win = typeof window !== 'undefined' ? window : undefined;\nconst doc = typeof document !== 'undefined' ? document : undefined;\n\nexport { doc as d, win as w };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nconst NAMESPACE = 'ionic';\nconst BUILD = /* ionic */ { allRenderFn: false, appendChildSlotFix: false, asyncLoading: true, asyncQueue: false, attachStyles: true, cloneNodeFix: false, cmpDidLoad: true, cmpDidRender: true, cmpDidUnload: false, cmpDidUpdate: true, cmpShouldUpdate: false, cmpWillLoad: true, cmpWillRender: true, cmpWillUpdate: false, connectedCallback: true, constructableCSS: true, cssAnnotations: true, devTools: false, disconnectedCallback: true, element: false, event: true, experimentalSlotFixes: false, formAssociated: false, hasRenderFn: true, hostListener: true, hostListenerTarget: true, hostListenerTargetBody: true, hostListenerTargetDocument: true, hostListenerTargetParent: false, hostListenerTargetWindow: true, hotModuleReplacement: false, hydrateClientSide: true, hydrateServerSide: false, hydratedAttribute: false, hydratedClass: true, initializeNextTick: false, invisiblePrehydration: true, isDebug: false, isDev: false, isTesting: false, lazyLoad: true, lifecycle: true, lifecycleDOMEvents: false, member: true, method: true, mode: true, observeAttribute: true, profile: false, prop: true, propBoolean: true, propMutable: true, propNumber: true, propString: true, reflect: true, scoped: true, scopedSlotTextContentFix: false, scriptDataOpts: false, shadowDelegatesFocus: true, shadowDom: true, slot: true, slotChildNodesFix: false, slotRelocation: true, state: true, style: true, svg: true, taskQueue: true, transformTagName: false, updatable: true, vdomAttribute: true, vdomClass: true, vdomFunctional: true, vdomKey: true, vdomListener: true, vdomPropOrAttr: true, vdomRef: true, vdomRender: true, vdomStyle: true, vdomText: true, vdomXlink: true, watchCallback: true };\n\n/**\n * Virtual DOM patching algorithm based on Snabbdom by\n * Simon Friis Vindum (@paldepind)\n * Licensed under the MIT License\n * https://github.com/snabbdom/snabbdom/blob/master/LICENSE\n *\n * Modified for Stencil's renderer and slot projection\n */\nlet scopeId;\nlet contentRef;\nlet hostTagName;\nlet useNativeShadowDom = false;\nlet checkSlotFallbackVisibility = false;\nlet checkSlotRelocate = false;\nlet isSvgMode = false;\nlet queuePending = false;\nconst Build = {\n isDev: false,\n isBrowser: true,\n isServer: false,\n isTesting: false,\n};\nconst getAssetPath = (path) => {\n const assetUrl = new URL(path, plt.$resourcesUrl$);\n return assetUrl.origin !== win.location.origin ? assetUrl.href : assetUrl.pathname;\n};\nconst createTime = (fnName, tagName = '') => {\n {\n return () => {\n return;\n };\n }\n};\nconst uniqueTime = (key, measureText) => {\n {\n return () => {\n return;\n };\n }\n};\nconst CONTENT_REF_ID = 'r';\nconst ORG_LOCATION_ID = 'o';\nconst SLOT_NODE_ID = 's';\nconst TEXT_NODE_ID = 't';\nconst HYDRATE_ID = 's-id';\nconst HYDRATED_STYLE_ID = 'sty-id';\nconst HYDRATE_CHILD_ID = 'c-id';\nconst HYDRATED_CSS = '{visibility:hidden}.hydrated{visibility:inherit}';\n/**\n * Constant for styles to be globally applied to `slot-fb` elements for pseudo-slot behavior.\n *\n * Two cascading rules must be used instead of a `:not()` selector due to Stencil browser\n * support as of Stencil v4.\n */\nconst SLOT_FB_CSS = 'slot-fb{display:contents}slot-fb[hidden]{display:none}';\nconst XLINK_NS = 'http://www.w3.org/1999/xlink';\n/**\n * Default style mode id\n */\n/**\n * Reusable empty obj/array\n * Don't add values to these!!\n */\nconst EMPTY_OBJ = {};\n/**\n * Namespaces\n */\nconst SVG_NS = 'http://www.w3.org/2000/svg';\nconst HTML_NS = 'http://www.w3.org/1999/xhtml';\nconst isDef = (v) => v != null;\n/**\n * Check whether a value is a 'complex type', defined here as an object or a\n * function.\n *\n * @param o the value to check\n * @returns whether it's a complex type or not\n */\nconst isComplexType = (o) => {\n // https://jsperf.com/typeof-fn-object/5\n o = typeof o;\n return o === 'object' || o === 'function';\n};\n/**\n * Helper method for querying a `meta` tag that contains a nonce value\n * out of a DOM's head.\n *\n * @param doc The DOM containing the `head` to query against\n * @returns The content of the meta tag representing the nonce value, or `undefined` if no tag\n * exists or the tag has no content.\n */\nfunction queryNonceMetaTagContent(doc) {\n var _a, _b, _c;\n return (_c = (_b = (_a = doc.head) === null || _a === void 0 ? void 0 : _a.querySelector('meta[name=\"csp-nonce\"]')) === null || _b === void 0 ? void 0 : _b.getAttribute('content')) !== null && _c !== void 0 ? _c : undefined;\n}\n/**\n * Production h() function based on Preact by\n * Jason Miller (@developit)\n * Licensed under the MIT License\n * https://github.com/developit/preact/blob/master/LICENSE\n *\n * Modified for Stencil's compiler and vdom\n */\n// export function h(nodeName: string | d.FunctionalComponent, vnodeData: d.PropsType, child?: d.ChildType): d.VNode;\n// export function h(nodeName: string | d.FunctionalComponent, vnodeData: d.PropsType, ...children: d.ChildType[]): d.VNode;\nconst h = (nodeName, vnodeData, ...children) => {\n let child = null;\n let key = null;\n let slotName = null;\n let simple = false;\n let lastSimple = false;\n const vNodeChildren = [];\n const walk = (c) => {\n for (let i = 0; i < c.length; i++) {\n child = c[i];\n if (Array.isArray(child)) {\n walk(child);\n }\n else if (child != null && typeof child !== 'boolean') {\n if ((simple = typeof nodeName !== 'function' && !isComplexType(child))) {\n child = String(child);\n }\n if (simple && lastSimple) {\n // If the previous child was simple (string), we merge both\n vNodeChildren[vNodeChildren.length - 1].$text$ += child;\n }\n else {\n // Append a new vNode, if it's text, we create a text vNode\n vNodeChildren.push(simple ? newVNode(null, child) : child);\n }\n lastSimple = simple;\n }\n }\n };\n walk(children);\n if (vnodeData) {\n if (vnodeData.key) {\n key = vnodeData.key;\n }\n if (vnodeData.name) {\n slotName = vnodeData.name;\n }\n // normalize class / className attributes\n {\n const classData = vnodeData.className || vnodeData.class;\n if (classData) {\n vnodeData.class =\n typeof classData !== 'object'\n ? classData\n : Object.keys(classData)\n .filter((k) => classData[k])\n .join(' ');\n }\n }\n }\n if (typeof nodeName === 'function') {\n // nodeName is a functional component\n return nodeName(vnodeData === null ? {} : vnodeData, vNodeChildren, vdomFnUtils);\n }\n const vnode = newVNode(nodeName, null);\n vnode.$attrs$ = vnodeData;\n if (vNodeChildren.length > 0) {\n vnode.$children$ = vNodeChildren;\n }\n {\n vnode.$key$ = key;\n }\n {\n vnode.$name$ = slotName;\n }\n return vnode;\n};\n/**\n * A utility function for creating a virtual DOM node from a tag and some\n * possible text content.\n *\n * @param tag the tag for this element\n * @param text possible text content for the node\n * @returns a newly-minted virtual DOM node\n */\nconst newVNode = (tag, text) => {\n const vnode = {\n $flags$: 0,\n $tag$: tag,\n $text$: text,\n $elm$: null,\n $children$: null,\n };\n {\n vnode.$attrs$ = null;\n }\n {\n vnode.$key$ = null;\n }\n {\n vnode.$name$ = null;\n }\n return vnode;\n};\nconst Host = {};\n/**\n * Check whether a given node is a Host node or not\n *\n * @param node the virtual DOM node to check\n * @returns whether it's a Host node or not\n */\nconst isHost = (node) => node && node.$tag$ === Host;\n/**\n * Implementation of {@link d.FunctionalUtilities} for Stencil's VDom.\n *\n * Note that these functions convert from {@link d.VNode} to\n * {@link d.ChildNode} to give functional component developers a friendly\n * interface.\n */\nconst vdomFnUtils = {\n forEach: (children, cb) => children.map(convertToPublic).forEach(cb),\n map: (children, cb) => children.map(convertToPublic).map(cb).map(convertToPrivate),\n};\n/**\n * Convert a {@link d.VNode} to a {@link d.ChildNode} in order to present a\n * friendlier public interface (hence, 'convertToPublic').\n *\n * @param node the virtual DOM node to convert\n * @returns a converted child node\n */\nconst convertToPublic = (node) => ({\n vattrs: node.$attrs$,\n vchildren: node.$children$,\n vkey: node.$key$,\n vname: node.$name$,\n vtag: node.$tag$,\n vtext: node.$text$,\n});\n/**\n * Convert a {@link d.ChildNode} back to an equivalent {@link d.VNode} in\n * order to use the resulting object in the virtual DOM. The initial object was\n * likely created as part of presenting a public API, so converting it back\n * involved making it 'private' again (hence, `convertToPrivate`).\n *\n * @param node the child node to convert\n * @returns a converted virtual DOM node\n */\nconst convertToPrivate = (node) => {\n if (typeof node.vtag === 'function') {\n const vnodeData = Object.assign({}, node.vattrs);\n if (node.vkey) {\n vnodeData.key = node.vkey;\n }\n if (node.vname) {\n vnodeData.name = node.vname;\n }\n return h(node.vtag, vnodeData, ...(node.vchildren || []));\n }\n const vnode = newVNode(node.vtag, node.vtext);\n vnode.$attrs$ = node.vattrs;\n vnode.$children$ = node.vchildren;\n vnode.$key$ = node.vkey;\n vnode.$name$ = node.vname;\n return vnode;\n};\nconst initializeClientHydrate = (hostElm, tagName, hostId, hostRef) => {\n const endHydrate = createTime('hydrateClient', tagName);\n const shadowRoot = hostElm.shadowRoot;\n const childRenderNodes = [];\n const slotNodes = [];\n const shadowRootNodes = shadowRoot ? [] : null;\n const vnode = (hostRef.$vnode$ = newVNode(tagName, null));\n if (!plt.$orgLocNodes$) {\n initializeDocumentHydrate(doc.body, (plt.$orgLocNodes$ = new Map()));\n }\n hostElm[HYDRATE_ID] = hostId;\n hostElm.removeAttribute(HYDRATE_ID);\n clientHydrate(vnode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, hostElm, hostId);\n childRenderNodes.map((c) => {\n const orgLocationId = c.$hostId$ + '.' + c.$nodeId$;\n const orgLocationNode = plt.$orgLocNodes$.get(orgLocationId);\n const node = c.$elm$;\n if (orgLocationNode && supportsShadow && orgLocationNode['s-en'] === '') {\n orgLocationNode.parentNode.insertBefore(node, orgLocationNode.nextSibling);\n }\n if (!shadowRoot) {\n node['s-hn'] = tagName;\n if (orgLocationNode) {\n node['s-ol'] = orgLocationNode;\n node['s-ol']['s-nr'] = node;\n }\n }\n plt.$orgLocNodes$.delete(orgLocationId);\n });\n if (shadowRoot) {\n shadowRootNodes.map((shadowRootNode) => {\n if (shadowRootNode) {\n shadowRoot.appendChild(shadowRootNode);\n }\n });\n }\n endHydrate();\n};\nconst clientHydrate = (parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node, hostId) => {\n let childNodeType;\n let childIdSplt;\n let childVNode;\n let i;\n if (node.nodeType === 1 /* NODE_TYPE.ElementNode */) {\n childNodeType = node.getAttribute(HYDRATE_CHILD_ID);\n if (childNodeType) {\n // got the node data from the element's attribute\n // `${hostId}.${nodeId}.${depth}.${index}`\n childIdSplt = childNodeType.split('.');\n if (childIdSplt[0] === hostId || childIdSplt[0] === '0') {\n childVNode = {\n $flags$: 0,\n $hostId$: childIdSplt[0],\n $nodeId$: childIdSplt[1],\n $depth$: childIdSplt[2],\n $index$: childIdSplt[3],\n $tag$: node.tagName.toLowerCase(),\n $elm$: node,\n $attrs$: null,\n $children$: null,\n $key$: null,\n $name$: null,\n $text$: null,\n };\n childRenderNodes.push(childVNode);\n node.removeAttribute(HYDRATE_CHILD_ID);\n // this is a new child vnode\n // so ensure its parent vnode has the vchildren array\n if (!parentVNode.$children$) {\n parentVNode.$children$ = [];\n }\n // add our child vnode to a specific index of the vnode's children\n parentVNode.$children$[childVNode.$index$] = childVNode;\n // this is now the new parent vnode for all the next child checks\n parentVNode = childVNode;\n if (shadowRootNodes && childVNode.$depth$ === '0') {\n shadowRootNodes[childVNode.$index$] = childVNode.$elm$;\n }\n }\n }\n // recursively drill down, end to start so we can remove nodes\n for (i = node.childNodes.length - 1; i >= 0; i--) {\n clientHydrate(parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node.childNodes[i], hostId);\n }\n if (node.shadowRoot) {\n // keep drilling down through the shadow root nodes\n for (i = node.shadowRoot.childNodes.length - 1; i >= 0; i--) {\n clientHydrate(parentVNode, childRenderNodes, slotNodes, shadowRootNodes, hostElm, node.shadowRoot.childNodes[i], hostId);\n }\n }\n }\n else if (node.nodeType === 8 /* NODE_TYPE.CommentNode */) {\n // `${COMMENT_TYPE}.${hostId}.${nodeId}.${depth}.${index}`\n childIdSplt = node.nodeValue.split('.');\n if (childIdSplt[1] === hostId || childIdSplt[1] === '0') {\n // comment node for either the host id or a 0 host id\n childNodeType = childIdSplt[0];\n childVNode = {\n $flags$: 0,\n $hostId$: childIdSplt[1],\n $nodeId$: childIdSplt[2],\n $depth$: childIdSplt[3],\n $index$: childIdSplt[4],\n $elm$: node,\n $attrs$: null,\n $children$: null,\n $key$: null,\n $name$: null,\n $tag$: null,\n $text$: null,\n };\n if (childNodeType === TEXT_NODE_ID) {\n childVNode.$elm$ = node.nextSibling;\n if (childVNode.$elm$ && childVNode.$elm$.nodeType === 3 /* NODE_TYPE.TextNode */) {\n childVNode.$text$ = childVNode.$elm$.textContent;\n childRenderNodes.push(childVNode);\n // remove the text comment since it's no longer needed\n node.remove();\n if (!parentVNode.$children$) {\n parentVNode.$children$ = [];\n }\n parentVNode.$children$[childVNode.$index$] = childVNode;\n if (shadowRootNodes && childVNode.$depth$ === '0') {\n shadowRootNodes[childVNode.$index$] = childVNode.$elm$;\n }\n }\n }\n else if (childVNode.$hostId$ === hostId) {\n // this comment node is specifically for this host id\n if (childNodeType === SLOT_NODE_ID) {\n // `${SLOT_NODE_ID}.${hostId}.${nodeId}.${depth}.${index}.${slotName}`;\n childVNode.$tag$ = 'slot';\n if (childIdSplt[5]) {\n node['s-sn'] = childVNode.$name$ = childIdSplt[5];\n }\n else {\n node['s-sn'] = '';\n }\n node['s-sr'] = true;\n if (shadowRootNodes) {\n // browser support shadowRoot and this is a shadow dom component\n // create an actual slot element\n childVNode.$elm$ = doc.createElement(childVNode.$tag$);\n if (childVNode.$name$) {\n // add the slot name attribute\n childVNode.$elm$.setAttribute('name', childVNode.$name$);\n }\n // insert the new slot element before the slot comment\n node.parentNode.insertBefore(childVNode.$elm$, node);\n // remove the slot comment since it's not needed for shadow\n node.remove();\n if (childVNode.$depth$ === '0') {\n shadowRootNodes[childVNode.$index$] = childVNode.$elm$;\n }\n }\n slotNodes.push(childVNode);\n if (!parentVNode.$children$) {\n parentVNode.$children$ = [];\n }\n parentVNode.$children$[childVNode.$index$] = childVNode;\n }\n else if (childNodeType === CONTENT_REF_ID) {\n // `${CONTENT_REF_ID}.${hostId}`;\n if (shadowRootNodes) {\n // remove the content ref comment since it's not needed for shadow\n node.remove();\n }\n else {\n hostElm['s-cr'] = node;\n node['s-cn'] = true;\n }\n }\n }\n }\n }\n else if (parentVNode && parentVNode.$tag$ === 'style') {\n const vnode = newVNode(null, node.textContent);\n vnode.$elm$ = node;\n vnode.$index$ = '0';\n parentVNode.$children$ = [vnode];\n }\n};\nconst initializeDocumentHydrate = (node, orgLocNodes) => {\n if (node.nodeType === 1 /* NODE_TYPE.ElementNode */) {\n let i = 0;\n for (; i < node.childNodes.length; i++) {\n initializeDocumentHydrate(node.childNodes[i], orgLocNodes);\n }\n if (node.shadowRoot) {\n for (i = 0; i < node.shadowRoot.childNodes.length; i++) {\n initializeDocumentHydrate(node.shadowRoot.childNodes[i], orgLocNodes);\n }\n }\n }\n else if (node.nodeType === 8 /* NODE_TYPE.CommentNode */) {\n const childIdSplt = node.nodeValue.split('.');\n if (childIdSplt[0] === ORG_LOCATION_ID) {\n orgLocNodes.set(childIdSplt[1] + '.' + childIdSplt[2], node);\n node.nodeValue = '';\n // useful to know if the original location is\n // the root light-dom of a shadow dom component\n node['s-en'] = childIdSplt[3];\n }\n }\n};\n// Private\nconst computeMode = (elm) => modeResolutionChain.map((h) => h(elm)).find((m) => !!m);\n// Public\nconst setMode = (handler) => modeResolutionChain.push(handler);\nconst getMode = (ref) => getHostRef(ref).$modeName$;\n/**\n * Parse a new property value for a given property type.\n *\n * While the prop value can reasonably be expected to be of `any` type as far as TypeScript's type checker is concerned,\n * it is not safe to assume that the string returned by evaluating `typeof propValue` matches:\n * 1. `any`, the type given to `propValue` in the function signature\n * 2. the type stored from `propType`.\n *\n * This function provides the capability to parse/coerce a property's value to potentially any other JavaScript type.\n *\n * Property values represented in TSX preserve their type information. In the example below, the number 0 is passed to\n * a component. This `propValue` will preserve its type information (`typeof propValue === 'number'`). Note that is\n * based on the type of the value being passed in, not the type declared of the class member decorated with `@Prop`.\n * ```tsx\n * \n * ```\n *\n * HTML prop values on the other hand, will always a string\n *\n * @param propValue the new value to coerce to some type\n * @param propType the type of the prop, expressed as a binary number\n * @returns the parsed/coerced value\n */\nconst parsePropertyValue = (propValue, propType) => {\n // ensure this value is of the correct prop type\n if (propValue != null && !isComplexType(propValue)) {\n if (propType & 4 /* MEMBER_FLAGS.Boolean */) {\n // per the HTML spec, any string value means it is a boolean true value\n // but we'll cheat here and say that the string \"false\" is the boolean false\n return propValue === 'false' ? false : propValue === '' || !!propValue;\n }\n if (propType & 2 /* MEMBER_FLAGS.Number */) {\n // force it to be a number\n return parseFloat(propValue);\n }\n if (propType & 1 /* MEMBER_FLAGS.String */) {\n // could have been passed as a number or boolean\n // but we still want it as a string\n return String(propValue);\n }\n // redundant return here for better minification\n return propValue;\n }\n // not sure exactly what type we want\n // so no need to change to a different type\n return propValue;\n};\nconst getElement = (ref) => (getHostRef(ref).$hostElement$ );\nconst createEvent = (ref, name, flags) => {\n const elm = getElement(ref);\n return {\n emit: (detail) => {\n return emitEvent(elm, name, {\n bubbles: !!(flags & 4 /* EVENT_FLAGS.Bubbles */),\n composed: !!(flags & 2 /* EVENT_FLAGS.Composed */),\n cancelable: !!(flags & 1 /* EVENT_FLAGS.Cancellable */),\n detail,\n });\n },\n };\n};\n/**\n * Helper function to create & dispatch a custom Event on a provided target\n * @param elm the target of the Event\n * @param name the name to give the custom Event\n * @param opts options for configuring a custom Event\n * @returns the custom Event\n */\nconst emitEvent = (elm, name, opts) => {\n const ev = plt.ce(name, opts);\n elm.dispatchEvent(ev);\n return ev;\n};\nconst rootAppliedStyles = /*@__PURE__*/ new WeakMap();\nconst registerStyle = (scopeId, cssText, allowCS) => {\n let style = styles.get(scopeId);\n if (supportsConstructableStylesheets && allowCS) {\n style = (style || new CSSStyleSheet());\n if (typeof style === 'string') {\n style = cssText;\n }\n else {\n style.replaceSync(cssText);\n }\n }\n else {\n style = cssText;\n }\n styles.set(scopeId, style);\n};\nconst addStyle = (styleContainerNode, cmpMeta, mode) => {\n var _a;\n const scopeId = getScopeId(cmpMeta, mode);\n const style = styles.get(scopeId);\n // if an element is NOT connected then getRootNode() will return the wrong root node\n // so the fallback is to always use the document for the root node in those cases\n styleContainerNode = styleContainerNode.nodeType === 11 /* NODE_TYPE.DocumentFragment */ ? styleContainerNode : doc;\n if (style) {\n if (typeof style === 'string') {\n styleContainerNode = styleContainerNode.head || styleContainerNode;\n let appliedStyles = rootAppliedStyles.get(styleContainerNode);\n let styleElm;\n if (!appliedStyles) {\n rootAppliedStyles.set(styleContainerNode, (appliedStyles = new Set()));\n }\n if (!appliedStyles.has(scopeId)) {\n if (styleContainerNode.host &&\n (styleElm = styleContainerNode.querySelector(`[${HYDRATED_STYLE_ID}=\"${scopeId}\"]`))) {\n // This is only happening on native shadow-dom, do not needs CSS var shim\n styleElm.innerHTML = style;\n }\n else {\n styleElm = doc.createElement('style');\n styleElm.innerHTML = style;\n // Apply CSP nonce to the style tag if it exists\n const nonce = (_a = plt.$nonce$) !== null && _a !== void 0 ? _a : queryNonceMetaTagContent(doc);\n if (nonce != null) {\n styleElm.setAttribute('nonce', nonce);\n }\n styleContainerNode.insertBefore(styleElm, styleContainerNode.querySelector('link'));\n }\n // Add styles for `slot-fb` elements if we're using slots outside the Shadow DOM\n if (cmpMeta.$flags$ & 4 /* CMP_FLAGS.hasSlotRelocation */) {\n styleElm.innerHTML += SLOT_FB_CSS;\n }\n if (appliedStyles) {\n appliedStyles.add(scopeId);\n }\n }\n }\n else if (!styleContainerNode.adoptedStyleSheets.includes(style)) {\n styleContainerNode.adoptedStyleSheets = [...styleContainerNode.adoptedStyleSheets, style];\n }\n }\n return scopeId;\n};\nconst attachStyles = (hostRef) => {\n const cmpMeta = hostRef.$cmpMeta$;\n const elm = hostRef.$hostElement$;\n const flags = cmpMeta.$flags$;\n const endAttachStyles = createTime('attachStyles', cmpMeta.$tagName$);\n const scopeId = addStyle(elm.shadowRoot ? elm.shadowRoot : elm.getRootNode(), cmpMeta, hostRef.$modeName$);\n if (flags & 10 /* CMP_FLAGS.needsScopedEncapsulation */) {\n // only required when we're NOT using native shadow dom (slot)\n // or this browser doesn't support native shadow dom\n // and this host element was NOT created with SSR\n // let's pick out the inner content for slot projection\n // create a node to represent where the original\n // content was first placed, which is useful later on\n // DOM WRITE!!\n elm['s-sc'] = scopeId;\n elm.classList.add(scopeId + '-h');\n if (flags & 2 /* CMP_FLAGS.scopedCssEncapsulation */) {\n elm.classList.add(scopeId + '-s');\n }\n }\n endAttachStyles();\n};\nconst getScopeId = (cmp, mode) => 'sc-' + (mode && cmp.$flags$ & 32 /* CMP_FLAGS.hasMode */ ? cmp.$tagName$ + '-' + mode : cmp.$tagName$);\nconst convertScopedToShadow = (css) => css.replace(/\\/\\*!@([^\\/]+)\\*\\/[^\\{]+\\{/g, '$1{');\n/**\n * Production setAccessor() function based on Preact by\n * Jason Miller (@developit)\n * Licensed under the MIT License\n * https://github.com/developit/preact/blob/master/LICENSE\n *\n * Modified for Stencil's compiler and vdom\n */\n/**\n * When running a VDom render set properties present on a VDom node onto the\n * corresponding HTML element.\n *\n * Note that this function has special functionality for the `class`,\n * `style`, `key`, and `ref` attributes, as well as event handlers (like\n * `onClick`, etc). All others are just passed through as-is.\n *\n * @param elm the HTMLElement onto which attributes should be set\n * @param memberName the name of the attribute to set\n * @param oldValue the old value for the attribute\n * @param newValue the new value for the attribute\n * @param isSvg whether we're in an svg context or not\n * @param flags bitflags for Vdom variables\n */\nconst setAccessor = (elm, memberName, oldValue, newValue, isSvg, flags) => {\n if (oldValue !== newValue) {\n let isProp = isMemberInElement(elm, memberName);\n let ln = memberName.toLowerCase();\n if (memberName === 'class') {\n const classList = elm.classList;\n const oldClasses = parseClassList(oldValue);\n const newClasses = parseClassList(newValue);\n classList.remove(...oldClasses.filter((c) => c && !newClasses.includes(c)));\n classList.add(...newClasses.filter((c) => c && !oldClasses.includes(c)));\n }\n else if (memberName === 'style') {\n // update style attribute, css properties and values\n {\n for (const prop in oldValue) {\n if (!newValue || newValue[prop] == null) {\n if (prop.includes('-')) {\n elm.style.removeProperty(prop);\n }\n else {\n elm.style[prop] = '';\n }\n }\n }\n }\n for (const prop in newValue) {\n if (!oldValue || newValue[prop] !== oldValue[prop]) {\n if (prop.includes('-')) {\n elm.style.setProperty(prop, newValue[prop]);\n }\n else {\n elm.style[prop] = newValue[prop];\n }\n }\n }\n }\n else if (memberName === 'key')\n ;\n else if (memberName === 'ref') {\n // minifier will clean this up\n if (newValue) {\n newValue(elm);\n }\n }\n else if ((!isProp ) &&\n memberName[0] === 'o' &&\n memberName[1] === 'n') {\n // Event Handlers\n // so if the member name starts with \"on\" and the 3rd characters is\n // a capital letter, and it's not already a member on the element,\n // then we're assuming it's an event listener\n if (memberName[2] === '-') {\n // on- prefixed events\n // allows to be explicit about the dom event to listen without any magic\n // under the hood:\n // // listens for \"click\"\n // // listens for \"Click\"\n // // listens for \"ionChange\"\n // // listens for \"EVENTS\"\n memberName = memberName.slice(3);\n }\n else if (isMemberInElement(win, ln)) {\n // standard event\n // the JSX attribute could have been \"onMouseOver\" and the\n // member name \"onmouseover\" is on the window's prototype\n // so let's add the listener \"mouseover\", which is all lowercased\n memberName = ln.slice(2);\n }\n else {\n // custom event\n // the JSX attribute could have been \"onMyCustomEvent\"\n // so let's trim off the \"on\" prefix and lowercase the first character\n // and add the listener \"myCustomEvent\"\n // except for the first character, we keep the event name case\n memberName = ln[2] + memberName.slice(3);\n }\n if (oldValue || newValue) {\n // Need to account for \"capture\" events.\n // If the event name ends with \"Capture\", we'll update the name to remove\n // the \"Capture\" suffix and make sure the event listener is setup to handle the capture event.\n const capture = memberName.endsWith(CAPTURE_EVENT_SUFFIX);\n // Make sure we only replace the last instance of \"Capture\"\n memberName = memberName.replace(CAPTURE_EVENT_REGEX, '');\n if (oldValue) {\n plt.rel(elm, memberName, oldValue, capture);\n }\n if (newValue) {\n plt.ael(elm, memberName, newValue, capture);\n }\n }\n }\n else {\n // Set property if it exists and it's not a SVG\n const isComplex = isComplexType(newValue);\n if ((isProp || (isComplex && newValue !== null)) && !isSvg) {\n try {\n if (!elm.tagName.includes('-')) {\n const n = newValue == null ? '' : newValue;\n // Workaround for Safari, moving the caret when re-assigning the same valued\n if (memberName === 'list') {\n isProp = false;\n }\n else if (oldValue == null || elm[memberName] != n) {\n elm[memberName] = n;\n }\n }\n else {\n elm[memberName] = newValue;\n }\n }\n catch (e) { }\n }\n /**\n * Need to manually update attribute if:\n * - memberName is not an attribute\n * - if we are rendering the host element in order to reflect attribute\n * - if it's a SVG, since properties might not work in \n * - if the newValue is null/undefined or 'false'.\n */\n let xlink = false;\n {\n if (ln !== (ln = ln.replace(/^xlink\\:?/, ''))) {\n memberName = ln;\n xlink = true;\n }\n }\n if (newValue == null || newValue === false) {\n if (newValue !== false || elm.getAttribute(memberName) === '') {\n if (xlink) {\n elm.removeAttributeNS(XLINK_NS, memberName);\n }\n else {\n elm.removeAttribute(memberName);\n }\n }\n }\n else if ((!isProp || flags & 4 /* VNODE_FLAGS.isHost */ || isSvg) && !isComplex) {\n newValue = newValue === true ? '' : newValue;\n if (xlink) {\n elm.setAttributeNS(XLINK_NS, memberName, newValue);\n }\n else {\n elm.setAttribute(memberName, newValue);\n }\n }\n }\n }\n};\nconst parseClassListRegex = /\\s/;\nconst parseClassList = (value) => (!value ? [] : value.split(parseClassListRegex));\nconst CAPTURE_EVENT_SUFFIX = 'Capture';\nconst CAPTURE_EVENT_REGEX = new RegExp(CAPTURE_EVENT_SUFFIX + '$');\nconst updateElement = (oldVnode, newVnode, isSvgMode, memberName) => {\n // if the element passed in is a shadow root, which is a document fragment\n // then we want to be adding attrs/props to the shadow root's \"host\" element\n // if it's not a shadow root, then we add attrs/props to the same element\n const elm = newVnode.$elm$.nodeType === 11 /* NODE_TYPE.DocumentFragment */ && newVnode.$elm$.host\n ? newVnode.$elm$.host\n : newVnode.$elm$;\n const oldVnodeAttrs = (oldVnode && oldVnode.$attrs$) || EMPTY_OBJ;\n const newVnodeAttrs = newVnode.$attrs$ || EMPTY_OBJ;\n {\n // remove attributes no longer present on the vnode by setting them to undefined\n for (memberName in oldVnodeAttrs) {\n if (!(memberName in newVnodeAttrs)) {\n setAccessor(elm, memberName, oldVnodeAttrs[memberName], undefined, isSvgMode, newVnode.$flags$);\n }\n }\n }\n // add new & update changed attributes\n for (memberName in newVnodeAttrs) {\n setAccessor(elm, memberName, oldVnodeAttrs[memberName], newVnodeAttrs[memberName], isSvgMode, newVnode.$flags$);\n }\n};\n/**\n * Create a DOM Node corresponding to one of the children of a given VNode.\n *\n * @param oldParentVNode the parent VNode from the previous render\n * @param newParentVNode the parent VNode from the current render\n * @param childIndex the index of the VNode, in the _new_ parent node's\n * children, for which we will create a new DOM node\n * @param parentElm the parent DOM node which our new node will be a child of\n * @returns the newly created node\n */\nconst createElm = (oldParentVNode, newParentVNode, childIndex, parentElm) => {\n var _a;\n // tslint:disable-next-line: prefer-const\n const newVNode = newParentVNode.$children$[childIndex];\n let i = 0;\n let elm;\n let childNode;\n let oldVNode;\n if (!useNativeShadowDom) {\n // remember for later we need to check to relocate nodes\n checkSlotRelocate = true;\n if (newVNode.$tag$ === 'slot') {\n if (scopeId) {\n // scoped css needs to add its scoped id to the parent element\n parentElm.classList.add(scopeId + '-s');\n }\n newVNode.$flags$ |= newVNode.$children$\n ? // slot element has fallback content\n 2 /* VNODE_FLAGS.isSlotFallback */\n : // slot element does not have fallback content\n 1 /* VNODE_FLAGS.isSlotReference */;\n }\n }\n if (newVNode.$text$ !== null) {\n // create text node\n elm = newVNode.$elm$ = doc.createTextNode(newVNode.$text$);\n }\n else if (newVNode.$flags$ & 1 /* VNODE_FLAGS.isSlotReference */) {\n // create a slot reference node\n elm = newVNode.$elm$ =\n doc.createTextNode('');\n }\n else {\n if (!isSvgMode) {\n isSvgMode = newVNode.$tag$ === 'svg';\n }\n // create element\n elm = newVNode.$elm$ = (doc.createElementNS(isSvgMode ? SVG_NS : HTML_NS, newVNode.$flags$ & 2 /* VNODE_FLAGS.isSlotFallback */\n ? 'slot-fb'\n : newVNode.$tag$)\n );\n if (isSvgMode && newVNode.$tag$ === 'foreignObject') {\n isSvgMode = false;\n }\n // add css classes, attrs, props, listeners, etc.\n {\n updateElement(null, newVNode, isSvgMode);\n }\n if (isDef(scopeId) && elm['s-si'] !== scopeId) {\n // if there is a scopeId and this is the initial render\n // then let's add the scopeId as a css class\n elm.classList.add((elm['s-si'] = scopeId));\n }\n if (newVNode.$children$) {\n for (i = 0; i < newVNode.$children$.length; ++i) {\n // create the node\n childNode = createElm(oldParentVNode, newVNode, i, elm);\n // return node could have been null\n if (childNode) {\n // append our new node\n elm.appendChild(childNode);\n }\n }\n }\n {\n if (newVNode.$tag$ === 'svg') {\n // Only reset the SVG context when we're exiting element\n isSvgMode = false;\n }\n else if (elm.tagName === 'foreignObject') {\n // Reenter SVG context when we're exiting element\n isSvgMode = true;\n }\n }\n }\n {\n elm['s-hn'] = hostTagName;\n if (newVNode.$flags$ & (2 /* VNODE_FLAGS.isSlotFallback */ | 1 /* VNODE_FLAGS.isSlotReference */)) {\n // remember the content reference comment\n elm['s-sr'] = true;\n // Persist the name of the slot that this slot was going to be projected into.\n elm['s-fs'] = (_a = newVNode.$attrs$) === null || _a === void 0 ? void 0 : _a.slot;\n // remember the content reference comment\n elm['s-cr'] = contentRef;\n // remember the slot name, or empty string for default slot\n elm['s-sn'] = newVNode.$name$ || '';\n // check if we've got an old vnode for this slot\n oldVNode = oldParentVNode && oldParentVNode.$children$ && oldParentVNode.$children$[childIndex];\n if (oldVNode && oldVNode.$tag$ === newVNode.$tag$ && oldParentVNode.$elm$) {\n // we've got an old slot vnode and the wrapper is being replaced\n // so let's move the old slot content back to it's original location\n putBackInOriginalLocation(oldParentVNode.$elm$, false);\n }\n }\n }\n return elm;\n};\nconst putBackInOriginalLocation = (parentElm, recursive) => {\n var _a;\n plt.$flags$ |= 1 /* PLATFORM_FLAGS.isTmpDisconnected */;\n const oldSlotChildNodes = parentElm.childNodes;\n for (let i = oldSlotChildNodes.length - 1; i >= 0; i--) {\n const childNode = oldSlotChildNodes[i];\n if (childNode['s-hn'] !== hostTagName && childNode['s-ol']) {\n // // this child node in the old element is from another component\n // // remove this node from the old slot's parent\n // childNode.remove();\n // and relocate it back to it's original location\n parentReferenceNode(childNode).insertBefore(childNode, referenceNode(childNode));\n // remove the old original location comment entirely\n // later on the patch function will know what to do\n // and move this to the correct spot if need be\n childNode['s-ol'].remove();\n childNode['s-ol'] = undefined;\n // Reset so we can correctly move the node around again.\n childNode['s-sh'] = undefined;\n // When putting an element node back in its original location,\n // we need to reset the `slot` attribute back to the value it originally had\n // so we can correctly relocate it again in the future\n if (childNode.nodeType === 1 /* NODE_TYPE.ElementNode */) {\n childNode.setAttribute('slot', (_a = childNode['s-sn']) !== null && _a !== void 0 ? _a : '');\n }\n checkSlotRelocate = true;\n }\n if (recursive) {\n putBackInOriginalLocation(childNode, recursive);\n }\n }\n plt.$flags$ &= ~1 /* PLATFORM_FLAGS.isTmpDisconnected */;\n};\n/**\n * Create DOM nodes corresponding to a list of {@link d.Vnode} objects and\n * add them to the DOM in the appropriate place.\n *\n * @param parentElm the DOM node which should be used as a parent for the new\n * DOM nodes\n * @param before a child of the `parentElm` which the new children should be\n * inserted before (optional)\n * @param parentVNode the parent virtual DOM node\n * @param vnodes the new child virtual DOM nodes to produce DOM nodes for\n * @param startIdx the index in the child virtual DOM nodes at which to start\n * creating DOM nodes (inclusive)\n * @param endIdx the index in the child virtual DOM nodes at which to stop\n * creating DOM nodes (inclusive)\n */\nconst addVnodes = (parentElm, before, parentVNode, vnodes, startIdx, endIdx) => {\n let containerElm = ((parentElm['s-cr'] && parentElm['s-cr'].parentNode) || parentElm);\n let childNode;\n if (containerElm.shadowRoot && containerElm.tagName === hostTagName) {\n containerElm = containerElm.shadowRoot;\n }\n for (; startIdx <= endIdx; ++startIdx) {\n if (vnodes[startIdx]) {\n childNode = createElm(null, parentVNode, startIdx, parentElm);\n if (childNode) {\n vnodes[startIdx].$elm$ = childNode;\n containerElm.insertBefore(childNode, referenceNode(before) );\n }\n }\n }\n};\n/**\n * Remove the DOM elements corresponding to a list of {@link d.VNode} objects.\n * This can be used to, for instance, clean up after a list of children which\n * should no longer be shown.\n *\n * This function also handles some of Stencil's slot relocation logic.\n *\n * @param vnodes a list of virtual DOM nodes to remove\n * @param startIdx the index at which to start removing nodes (inclusive)\n * @param endIdx the index at which to stop removing nodes (inclusive)\n */\nconst removeVnodes = (vnodes, startIdx, endIdx) => {\n for (let index = startIdx; index <= endIdx; ++index) {\n const vnode = vnodes[index];\n if (vnode) {\n const elm = vnode.$elm$;\n nullifyVNodeRefs(vnode);\n if (elm) {\n {\n // we're removing this element\n // so it's possible we need to show slot fallback content now\n checkSlotFallbackVisibility = true;\n if (elm['s-ol']) {\n // remove the original location comment\n elm['s-ol'].remove();\n }\n else {\n // it's possible that child nodes of the node\n // that's being removed are slot nodes\n putBackInOriginalLocation(elm, true);\n }\n }\n // remove the vnode's element from the dom\n elm.remove();\n }\n }\n }\n};\n/**\n * Reconcile the children of a new VNode with the children of an old VNode by\n * traversing the two collections of children, identifying nodes that are\n * conserved or changed, calling out to `patch` to make any necessary\n * updates to the DOM, and rearranging DOM nodes as needed.\n *\n * The algorithm for reconciling children works by analyzing two 'windows' onto\n * the two arrays of children (`oldCh` and `newCh`). We keep track of the\n * 'windows' by storing start and end indices and references to the\n * corresponding array entries. Initially the two 'windows' are basically equal\n * to the entire array, but we progressively narrow the windows until there are\n * no children left to update by doing the following:\n *\n * 1. Skip any `null` entries at the beginning or end of the two arrays, so\n * that if we have an initial array like the following we'll end up dealing\n * only with a window bounded by the highlighted elements:\n *\n * [null, null, VNode1 , ... , VNode2, null, null]\n * ^^^^^^ ^^^^^^\n *\n * 2. Check to see if the elements at the head and tail positions are equal\n * across the windows. This will basically detect elements which haven't\n * been added, removed, or changed position, i.e. if you had the following\n * VNode elements (represented as HTML):\n *\n * oldVNode: `

    HEY

    `\n * newVNode: `

    THERE

    `\n *\n * Then when comparing the children of the `
    ` tag we check the equality\n * of the VNodes corresponding to the `

    ` tags and, since they are the\n * same tag in the same position, we'd be able to avoid completely\n * re-rendering the subtree under them with a new DOM element and would just\n * call out to `patch` to handle reconciling their children and so on.\n *\n * 3. Check, for both windows, to see if the element at the beginning of the\n * window corresponds to the element at the end of the other window. This is\n * a heuristic which will let us identify _some_ situations in which\n * elements have changed position, for instance it _should_ detect that the\n * children nodes themselves have not changed but merely moved in the\n * following example:\n *\n * oldVNode: `

    `\n * newVNode: `
    `\n *\n * If we find cases like this then we also need to move the concrete DOM\n * elements corresponding to the moved children to write the re-order to the\n * DOM.\n *\n * 4. Finally, if VNodes have the `key` attribute set on them we check for any\n * nodes in the old children which have the same key as the first element in\n * our window on the new children. If we find such a node we handle calling\n * out to `patch`, moving relevant DOM nodes, and so on, in accordance with\n * what we find.\n *\n * Finally, once we've narrowed our 'windows' to the point that either of them\n * collapse (i.e. they have length 0) we then handle any remaining VNode\n * insertion or deletion that needs to happen to get a DOM state that correctly\n * reflects the new child VNodes. If, for instance, after our window on the old\n * children has collapsed we still have more nodes on the new children that\n * we haven't dealt with yet then we need to add them, or if the new children\n * collapse but we still have unhandled _old_ children then we need to make\n * sure the corresponding DOM nodes are removed.\n *\n * @param parentElm the node into which the parent VNode is rendered\n * @param oldCh the old children of the parent node\n * @param newVNode the new VNode which will replace the parent\n * @param newCh the new children of the parent node\n */\nconst updateChildren = (parentElm, oldCh, newVNode, newCh) => {\n let oldStartIdx = 0;\n let newStartIdx = 0;\n let idxInOld = 0;\n let i = 0;\n let oldEndIdx = oldCh.length - 1;\n let oldStartVnode = oldCh[0];\n let oldEndVnode = oldCh[oldEndIdx];\n let newEndIdx = newCh.length - 1;\n let newStartVnode = newCh[0];\n let newEndVnode = newCh[newEndIdx];\n let node;\n let elmToMove;\n while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) {\n if (oldStartVnode == null) {\n // VNode might have been moved left\n oldStartVnode = oldCh[++oldStartIdx];\n }\n else if (oldEndVnode == null) {\n oldEndVnode = oldCh[--oldEndIdx];\n }\n else if (newStartVnode == null) {\n newStartVnode = newCh[++newStartIdx];\n }\n else if (newEndVnode == null) {\n newEndVnode = newCh[--newEndIdx];\n }\n else if (isSameVnode(oldStartVnode, newStartVnode)) {\n // if the start nodes are the same then we should patch the new VNode\n // onto the old one, and increment our `newStartIdx` and `oldStartIdx`\n // indices to reflect that. We don't need to move any DOM Nodes around\n // since things are matched up in order.\n patch(oldStartVnode, newStartVnode);\n oldStartVnode = oldCh[++oldStartIdx];\n newStartVnode = newCh[++newStartIdx];\n }\n else if (isSameVnode(oldEndVnode, newEndVnode)) {\n // likewise, if the end nodes are the same we patch new onto old and\n // decrement our end indices, and also likewise in this case we don't\n // need to move any DOM Nodes.\n patch(oldEndVnode, newEndVnode);\n oldEndVnode = oldCh[--oldEndIdx];\n newEndVnode = newCh[--newEndIdx];\n }\n else if (isSameVnode(oldStartVnode, newEndVnode)) {\n // case: \"Vnode moved right\"\n //\n // We've found that the last node in our window on the new children is\n // the same VNode as the _first_ node in our window on the old children\n // we're dealing with now. Visually, this is the layout of these two\n // nodes:\n //\n // newCh: [..., newStartVnode , ... , newEndVnode , ...]\n // ^^^^^^^^^^^\n // oldCh: [..., oldStartVnode , ... , oldEndVnode , ...]\n // ^^^^^^^^^^^^^\n //\n // In this situation we need to patch `newEndVnode` onto `oldStartVnode`\n // and move the DOM element for `oldStartVnode`.\n if ((oldStartVnode.$tag$ === 'slot' || newEndVnode.$tag$ === 'slot')) {\n putBackInOriginalLocation(oldStartVnode.$elm$.parentNode, false);\n }\n patch(oldStartVnode, newEndVnode);\n // We need to move the element for `oldStartVnode` into a position which\n // will be appropriate for `newEndVnode`. For this we can use\n // `.insertBefore` and `oldEndVnode.$elm$.nextSibling`. If there is a\n // sibling for `oldEndVnode.$elm$` then we want to move the DOM node for\n // `oldStartVnode` between `oldEndVnode` and it's sibling, like so:\n //\n // \n // \n // \n // \n // \n // \n // ```\n // In this case if we do not un-shadow here and use the value of the shadowing property, attributeChangedCallback\n // will be called with `newValue = \"some-value\"` and will set the shadowed property (this.someAttribute = \"another-value\")\n // to the value that was set inline i.e. \"some-value\" from above example. When\n // the connectedCallback attempts to un-shadow it will use \"some-value\" as the initial value rather than \"another-value\"\n //\n // The case where the attribute was NOT set inline but was not set programmatically shall be handled/un-shadowed\n // by connectedCallback as this attributeChangedCallback will not fire.\n //\n // https://developers.google.com/web/fundamentals/web-components/best-practices#lazy-properties\n //\n // TODO(STENCIL-16) we should think about whether or not we actually want to be reflecting the attributes to\n // properties here given that this goes against best practices outlined here\n // https://developers.google.com/web/fundamentals/web-components/best-practices#avoid-reentrancy\n if (this.hasOwnProperty(propName)) {\n newValue = this[propName];\n delete this[propName];\n }\n else if (prototype.hasOwnProperty(propName) &&\n typeof this[propName] === 'number' &&\n this[propName] == newValue) {\n // if the propName exists on the prototype of `Cstr`, this update may be a result of Stencil using native\n // APIs to reflect props as attributes. Calls to `setAttribute(someElement, propName)` will result in\n // `propName` to be converted to a `DOMString`, which may not be what we want for other primitive props.\n return;\n }\n else if (propName == null) {\n // At this point we should know this is not a \"member\", so we can treat it like watching an attribute\n // on a vanilla web component\n const hostRef = getHostRef(this);\n const flags = hostRef === null || hostRef === void 0 ? void 0 : hostRef.$flags$;\n // We only want to trigger the callback(s) if:\n // 1. The instance is ready\n // 2. The watchers are ready\n // 3. The value has changed\n if (!(flags & 8 /* HOST_FLAGS.isConstructingInstance */) &&\n flags & 128 /* HOST_FLAGS.isWatchReady */ &&\n newValue !== oldValue) {\n const instance = hostRef.$lazyInstance$ ;\n const entry = cmpMeta.$watchers$[attrName];\n entry === null || entry === void 0 ? void 0 : entry.forEach((callbackName) => {\n if (instance[callbackName] != null) {\n instance[callbackName].call(instance, newValue, oldValue, attrName);\n }\n });\n }\n return;\n }\n this[propName] = newValue === null && typeof this[propName] === 'boolean' ? false : newValue;\n });\n };\n // Create an array of attributes to observe\n // This list in comprised of all strings used within a `@Watch()` decorator\n // on a component as well as any Stencil-specific \"members\" (`@Prop()`s and `@State()`s).\n // As such, there is no way to guarantee type-safety here that a user hasn't entered\n // an invalid attribute.\n Cstr.observedAttributes = Array.from(new Set([\n ...Object.keys((_a = cmpMeta.$watchers$) !== null && _a !== void 0 ? _a : {}),\n ...members\n .filter(([_, m]) => m[0] & 15 /* MEMBER_FLAGS.HasAttribute */)\n .map(([propName, m]) => {\n const attrName = m[1] || propName;\n attrNameToPropName.set(attrName, propName);\n if (m[0] & 512 /* MEMBER_FLAGS.ReflectAttr */) {\n cmpMeta.$attrsToReflect$.push([propName, attrName]);\n }\n return attrName;\n }),\n ]));\n }\n }\n return Cstr;\n};\n/**\n * Initialize a Stencil component given a reference to its host element, its\n * runtime bookkeeping data structure, runtime metadata about the component,\n * and (optionally) an HMR version ID.\n *\n * @param elm a host element\n * @param hostRef the element's runtime bookkeeping object\n * @param cmpMeta runtime metadata for the Stencil component\n * @param hmrVersionId an (optional) HMR version ID\n */\nconst initializeComponent = async (elm, hostRef, cmpMeta, hmrVersionId) => {\n let Cstr;\n // initializeComponent\n if ((hostRef.$flags$ & 32 /* HOST_FLAGS.hasInitializedComponent */) === 0) {\n // Let the runtime know that the component has been initialized\n hostRef.$flags$ |= 32 /* HOST_FLAGS.hasInitializedComponent */;\n {\n // lazy loaded components\n // request the component's implementation to be\n // wired up with the host element\n Cstr = loadModule(cmpMeta);\n if (Cstr.then) {\n // Await creates a micro-task avoid if possible\n const endLoad = uniqueTime();\n Cstr = await Cstr;\n endLoad();\n }\n if (!Cstr.isProxied) {\n // we've never proxied this Constructor before\n // let's add the getters/setters to its prototype before\n // the first time we create an instance of the implementation\n {\n cmpMeta.$watchers$ = Cstr.watchers;\n }\n proxyComponent(Cstr, cmpMeta, 2 /* PROXY_FLAGS.proxyState */);\n Cstr.isProxied = true;\n }\n const endNewInstance = createTime('createInstance', cmpMeta.$tagName$);\n // ok, time to construct the instance\n // but let's keep track of when we start and stop\n // so that the getters/setters don't incorrectly step on data\n {\n hostRef.$flags$ |= 8 /* HOST_FLAGS.isConstructingInstance */;\n }\n // construct the lazy-loaded component implementation\n // passing the hostRef is very important during\n // construction in order to directly wire together the\n // host element and the lazy-loaded instance\n try {\n new Cstr(hostRef);\n }\n catch (e) {\n consoleError(e);\n }\n {\n hostRef.$flags$ &= ~8 /* HOST_FLAGS.isConstructingInstance */;\n }\n {\n hostRef.$flags$ |= 128 /* HOST_FLAGS.isWatchReady */;\n }\n endNewInstance();\n fireConnectedCallback(hostRef.$lazyInstance$);\n }\n if (Cstr.style) {\n // this component has styles but we haven't registered them yet\n let style = Cstr.style;\n if (typeof style !== 'string') {\n style = style[(hostRef.$modeName$ = computeMode(elm))];\n }\n const scopeId = getScopeId(cmpMeta, hostRef.$modeName$);\n if (!styles.has(scopeId)) {\n const endRegisterStyles = createTime('registerStyles', cmpMeta.$tagName$);\n registerStyle(scopeId, style, !!(cmpMeta.$flags$ & 1 /* CMP_FLAGS.shadowDomEncapsulation */));\n endRegisterStyles();\n }\n }\n }\n // we've successfully created a lazy instance\n const ancestorComponent = hostRef.$ancestorComponent$;\n const schedule = () => scheduleUpdate(hostRef, true);\n if (ancestorComponent && ancestorComponent['s-rc']) {\n // this is the initial load and this component it has an ancestor component\n // but the ancestor component has NOT fired its will update lifecycle yet\n // so let's just cool our jets and wait for the ancestor to continue first\n // this will get fired off when the ancestor component\n // finally gets around to rendering its lazy self\n // fire off the initial update\n ancestorComponent['s-rc'].push(schedule);\n }\n else {\n schedule();\n }\n};\nconst fireConnectedCallback = (instance) => {\n {\n safeCall(instance, 'connectedCallback');\n }\n};\nconst connectedCallback = (elm) => {\n if ((plt.$flags$ & 1 /* PLATFORM_FLAGS.isTmpDisconnected */) === 0) {\n const hostRef = getHostRef(elm);\n const cmpMeta = hostRef.$cmpMeta$;\n const endConnected = createTime('connectedCallback', cmpMeta.$tagName$);\n if (!(hostRef.$flags$ & 1 /* HOST_FLAGS.hasConnected */)) {\n // first time this component has connected\n hostRef.$flags$ |= 1 /* HOST_FLAGS.hasConnected */;\n let hostId;\n {\n hostId = elm.getAttribute(HYDRATE_ID);\n if (hostId) {\n if (cmpMeta.$flags$ & 1 /* CMP_FLAGS.shadowDomEncapsulation */) {\n const scopeId = addStyle(elm.shadowRoot, cmpMeta, elm.getAttribute('s-mode'))\n ;\n elm.classList.remove(scopeId + '-h', scopeId + '-s');\n }\n initializeClientHydrate(elm, cmpMeta.$tagName$, hostId, hostRef);\n }\n }\n if (!hostId) {\n // initUpdate\n // if the slot polyfill is required we'll need to put some nodes\n // in here to act as original content anchors as we move nodes around\n // host element has been connected to the DOM\n if ((// TODO(STENCIL-854): Remove code related to legacy shadowDomShim field\n cmpMeta.$flags$ & (4 /* CMP_FLAGS.hasSlotRelocation */ | 8 /* CMP_FLAGS.needsShadowDomShim */))) {\n setContentReference(elm);\n }\n }\n {\n // find the first ancestor component (if there is one) and register\n // this component as one of the actively loading child components for its ancestor\n let ancestorComponent = elm;\n while ((ancestorComponent = ancestorComponent.parentNode || ancestorComponent.host)) {\n // climb up the ancestors looking for the first\n // component that hasn't finished its lifecycle update yet\n if ((ancestorComponent.nodeType === 1 /* NODE_TYPE.ElementNode */ &&\n ancestorComponent.hasAttribute('s-id') &&\n ancestorComponent['s-p']) ||\n ancestorComponent['s-p']) {\n // we found this components first ancestor component\n // keep a reference to this component's ancestor component\n attachToAncestor(hostRef, (hostRef.$ancestorComponent$ = ancestorComponent));\n break;\n }\n }\n }\n // Lazy properties\n // https://developers.google.com/web/fundamentals/web-components/best-practices#lazy-properties\n if (cmpMeta.$members$) {\n Object.entries(cmpMeta.$members$).map(([memberName, [memberFlags]]) => {\n if (memberFlags & 31 /* MEMBER_FLAGS.Prop */ && elm.hasOwnProperty(memberName)) {\n const value = elm[memberName];\n delete elm[memberName];\n elm[memberName] = value;\n }\n });\n }\n {\n initializeComponent(elm, hostRef, cmpMeta);\n }\n }\n else {\n // not the first time this has connected\n // reattach any event listeners to the host\n // since they would have been removed when disconnected\n addHostEventListeners(elm, hostRef, cmpMeta.$listeners$);\n // fire off connectedCallback() on component instance\n if (hostRef === null || hostRef === void 0 ? void 0 : hostRef.$lazyInstance$) {\n fireConnectedCallback(hostRef.$lazyInstance$);\n }\n else if (hostRef === null || hostRef === void 0 ? void 0 : hostRef.$onReadyPromise$) {\n hostRef.$onReadyPromise$.then(() => fireConnectedCallback(hostRef.$lazyInstance$));\n }\n }\n endConnected();\n }\n};\nconst setContentReference = (elm) => {\n // only required when we're NOT using native shadow dom (slot)\n // or this browser doesn't support native shadow dom\n // and this host element was NOT created with SSR\n // let's pick out the inner content for slot projection\n // create a node to represent where the original\n // content was first placed, which is useful later on\n const contentRefElm = (elm['s-cr'] = doc.createComment(''));\n contentRefElm['s-cn'] = true;\n elm.insertBefore(contentRefElm, elm.firstChild);\n};\nconst disconnectInstance = (instance) => {\n {\n safeCall(instance, 'disconnectedCallback');\n }\n};\nconst disconnectedCallback = async (elm) => {\n if ((plt.$flags$ & 1 /* PLATFORM_FLAGS.isTmpDisconnected */) === 0) {\n const hostRef = getHostRef(elm);\n {\n if (hostRef.$rmListeners$) {\n hostRef.$rmListeners$.map((rmListener) => rmListener());\n hostRef.$rmListeners$ = undefined;\n }\n }\n if (hostRef === null || hostRef === void 0 ? void 0 : hostRef.$lazyInstance$) {\n disconnectInstance(hostRef.$lazyInstance$);\n }\n else if (hostRef === null || hostRef === void 0 ? void 0 : hostRef.$onReadyPromise$) {\n hostRef.$onReadyPromise$.then(() => disconnectInstance(hostRef.$lazyInstance$));\n }\n }\n};\nconst bootstrapLazy = (lazyBundles, options = {}) => {\n var _a;\n const endBootstrap = createTime();\n const cmpTags = [];\n const exclude = options.exclude || [];\n const customElements = win.customElements;\n const head = doc.head;\n const metaCharset = /*@__PURE__*/ head.querySelector('meta[charset]');\n const dataStyles = /*@__PURE__*/ doc.createElement('style');\n const deferredConnectedCallbacks = [];\n const styles = /*@__PURE__*/ doc.querySelectorAll(`[${HYDRATED_STYLE_ID}]`);\n let appLoadFallback;\n let isBootstrapping = true;\n let i = 0;\n Object.assign(plt, options);\n plt.$resourcesUrl$ = new URL(options.resourcesUrl || './', doc.baseURI).href;\n {\n // If the app is already hydrated there is not point to disable the\n // async queue. This will improve the first input delay\n plt.$flags$ |= 2 /* PLATFORM_FLAGS.appLoaded */;\n }\n {\n for (; i < styles.length; i++) {\n registerStyle(styles[i].getAttribute(HYDRATED_STYLE_ID), convertScopedToShadow(styles[i].innerHTML), true);\n }\n }\n let hasSlotRelocation = false;\n lazyBundles.map((lazyBundle) => {\n lazyBundle[1].map((compactMeta) => {\n var _a;\n const cmpMeta = {\n $flags$: compactMeta[0],\n $tagName$: compactMeta[1],\n $members$: compactMeta[2],\n $listeners$: compactMeta[3],\n };\n // Check if we are using slots outside the shadow DOM in this component.\n // We'll use this information later to add styles for `slot-fb` elements\n if (cmpMeta.$flags$ & 4 /* CMP_FLAGS.hasSlotRelocation */) {\n hasSlotRelocation = true;\n }\n {\n cmpMeta.$members$ = compactMeta[2];\n }\n {\n cmpMeta.$listeners$ = compactMeta[3];\n }\n {\n cmpMeta.$attrsToReflect$ = [];\n }\n {\n cmpMeta.$watchers$ = (_a = compactMeta[4]) !== null && _a !== void 0 ? _a : {};\n }\n const tagName = cmpMeta.$tagName$;\n const HostElement = class extends HTMLElement {\n // StencilLazyHost\n constructor(self) {\n // @ts-ignore\n super(self);\n self = this;\n registerHost(self, cmpMeta);\n if (cmpMeta.$flags$ & 1 /* CMP_FLAGS.shadowDomEncapsulation */) {\n // this component is using shadow dom\n // and this browser supports shadow dom\n // add the read-only property \"shadowRoot\" to the host element\n // adding the shadow root build conditionals to minimize runtime\n {\n {\n self.attachShadow({\n mode: 'open',\n delegatesFocus: !!(cmpMeta.$flags$ & 16 /* CMP_FLAGS.shadowDelegatesFocus */),\n });\n }\n }\n }\n }\n connectedCallback() {\n if (appLoadFallback) {\n clearTimeout(appLoadFallback);\n appLoadFallback = null;\n }\n if (isBootstrapping) {\n // connectedCallback will be processed once all components have been registered\n deferredConnectedCallbacks.push(this);\n }\n else {\n plt.jmp(() => connectedCallback(this));\n }\n }\n disconnectedCallback() {\n plt.jmp(() => disconnectedCallback(this));\n }\n componentOnReady() {\n return getHostRef(this).$onReadyPromise$;\n }\n };\n cmpMeta.$lazyBundleId$ = lazyBundle[0];\n if (!exclude.includes(tagName) && !customElements.get(tagName)) {\n cmpTags.push(tagName);\n customElements.define(tagName, proxyComponent(HostElement, cmpMeta, 1 /* PROXY_FLAGS.isElementConstructor */));\n }\n });\n });\n // Add styles for `slot-fb` elements if any of our components are using slots outside the Shadow DOM\n if (hasSlotRelocation) {\n dataStyles.innerHTML += SLOT_FB_CSS;\n }\n // Add hydration styles\n {\n dataStyles.innerHTML += cmpTags + HYDRATED_CSS;\n }\n // If we have styles, add them to the DOM\n if (dataStyles.innerHTML.length) {\n dataStyles.setAttribute('data-styles', '');\n head.insertBefore(dataStyles, metaCharset ? metaCharset.nextSibling : head.firstChild);\n // Apply CSP nonce to the style tag if it exists\n const nonce = (_a = plt.$nonce$) !== null && _a !== void 0 ? _a : queryNonceMetaTagContent(doc);\n if (nonce != null) {\n dataStyles.setAttribute('nonce', nonce);\n }\n }\n // Process deferred connectedCallbacks now all components have been registered\n isBootstrapping = false;\n if (deferredConnectedCallbacks.length) {\n deferredConnectedCallbacks.map((host) => host.connectedCallback());\n }\n else {\n {\n plt.jmp(() => (appLoadFallback = setTimeout(appDidLoad, 30)));\n }\n }\n // Fallback appLoad event\n endBootstrap();\n};\nconst addHostEventListeners = (elm, hostRef, listeners, attachParentListeners) => {\n if (listeners) {\n listeners.map(([flags, name, method]) => {\n const target = getHostListenerTarget(elm, flags) ;\n const handler = hostListenerProxy(hostRef, method);\n const opts = hostListenerOpts(flags);\n plt.ael(target, name, handler, opts);\n (hostRef.$rmListeners$ = hostRef.$rmListeners$ || []).push(() => plt.rel(target, name, handler, opts));\n });\n }\n};\nconst hostListenerProxy = (hostRef, methodName) => (ev) => {\n try {\n {\n if (hostRef.$flags$ & 256 /* HOST_FLAGS.isListenReady */) {\n // instance is ready, let's call it's member method for this event\n hostRef.$lazyInstance$[methodName](ev);\n }\n else {\n (hostRef.$queuedListeners$ = hostRef.$queuedListeners$ || []).push([methodName, ev]);\n }\n }\n }\n catch (e) {\n consoleError(e);\n }\n};\nconst getHostListenerTarget = (elm, flags) => {\n if (flags & 4 /* LISTENER_FLAGS.TargetDocument */)\n return doc;\n if (flags & 8 /* LISTENER_FLAGS.TargetWindow */)\n return win;\n if (flags & 16 /* LISTENER_FLAGS.TargetBody */)\n return doc.body;\n return elm;\n};\n// prettier-ignore\nconst hostListenerOpts = (flags) => (flags & 2 /* LISTENER_FLAGS.Capture */) !== 0;\n/**\n * Assigns the given value to the nonce property on the runtime platform object.\n * During runtime, this value is used to set the nonce attribute on all dynamically created script and style tags.\n * @param nonce The value to be assigned to the platform nonce property.\n * @returns void\n */\nconst setNonce = (nonce) => (plt.$nonce$ = nonce);\n/**\n * A WeakMap mapping runtime component references to their corresponding host reference\n * instances.\n */\nconst hostRefs = /*@__PURE__*/ new WeakMap();\n/**\n * Given a {@link d.RuntimeRef} retrieve the corresponding {@link d.HostRef}\n *\n * @param ref the runtime ref of interest\n * @returns the Host reference (if found) or undefined\n */\nconst getHostRef = (ref) => hostRefs.get(ref);\n/**\n * Register a lazy instance with the {@link hostRefs} object so it's\n * corresponding {@link d.HostRef} can be retrieved later.\n *\n * @param lazyInstance the lazy instance of interest\n * @param hostRef that instances `HostRef` object\n * @returns a reference to the host ref WeakMap\n */\nconst registerInstance = (lazyInstance, hostRef) => hostRefs.set((hostRef.$lazyInstance$ = lazyInstance), hostRef);\n/**\n * Register a host element for a Stencil component, setting up various metadata\n * and callbacks based on {@link BUILD} flags as well as the component's runtime\n * metadata.\n *\n * @param hostElement the host element to register\n * @param cmpMeta runtime metadata for that component\n * @returns a reference to the host ref WeakMap\n */\nconst registerHost = (hostElement, cmpMeta) => {\n const hostRef = {\n $flags$: 0,\n $hostElement$: hostElement,\n $cmpMeta$: cmpMeta,\n $instanceValues$: new Map(),\n };\n {\n hostRef.$onInstancePromise$ = new Promise((r) => (hostRef.$onInstanceResolve$ = r));\n }\n {\n hostRef.$onReadyPromise$ = new Promise((r) => (hostRef.$onReadyResolve$ = r));\n hostElement['s-p'] = [];\n hostElement['s-rc'] = [];\n }\n addHostEventListeners(hostElement, hostRef, cmpMeta.$listeners$);\n return hostRefs.set(hostElement, hostRef);\n};\nconst isMemberInElement = (elm, memberName) => memberName in elm;\nconst consoleError = (e, el) => (0, console.error)(e, el);\nconst cmpModules = /*@__PURE__*/ new Map();\nconst loadModule = (cmpMeta, hostRef, hmrVersionId) => {\n // loadModuleImport\n const exportName = cmpMeta.$tagName$.replace(/-/g, '_');\n const bundleId = cmpMeta.$lazyBundleId$;\n const module = cmpModules.get(bundleId) ;\n if (module) {\n return module[exportName];\n }\n /*!__STENCIL_STATIC_IMPORT_SWITCH__*/\n return import(\n /* @vite-ignore */\n /* webpackInclude: /\\.entry\\.js$/ */\n /* webpackExclude: /\\.system\\.entry\\.js$/ */\n /* webpackMode: \"lazy\" */\n `./${bundleId}.entry.js${''}`).then((importedModule) => {\n {\n cmpModules.set(bundleId, importedModule);\n }\n return importedModule[exportName];\n }, consoleError);\n};\nconst styles = /*@__PURE__*/ new Map();\nconst modeResolutionChain = [];\nconst win = typeof window !== 'undefined' ? window : {};\nconst doc = win.document || { head: {} };\nconst plt = {\n $flags$: 0,\n $resourcesUrl$: '',\n jmp: (h) => h(),\n raf: (h) => requestAnimationFrame(h),\n ael: (el, eventName, listener, opts) => el.addEventListener(eventName, listener, opts),\n rel: (el, eventName, listener, opts) => el.removeEventListener(eventName, listener, opts),\n ce: (eventName, opts) => new CustomEvent(eventName, opts),\n};\nconst setPlatformHelpers = (helpers) => {\n Object.assign(plt, helpers);\n};\nconst supportsShadow = \n// TODO(STENCIL-854): Remove code related to legacy shadowDomShim field\ntrue;\nconst promiseResolve = (v) => Promise.resolve(v);\nconst supportsConstructableStylesheets = /*@__PURE__*/ (() => {\n try {\n new CSSStyleSheet();\n return typeof new CSSStyleSheet().replaceSync === 'function';\n }\n catch (e) { }\n return false;\n })()\n ;\nconst queueDomReads = [];\nconst queueDomWrites = [];\nconst queueTask = (queue, write) => (cb) => {\n queue.push(cb);\n if (!queuePending) {\n queuePending = true;\n if (write && plt.$flags$ & 4 /* PLATFORM_FLAGS.queueSync */) {\n nextTick(flush);\n }\n else {\n plt.raf(flush);\n }\n }\n};\nconst consume = (queue) => {\n for (let i = 0; i < queue.length; i++) {\n try {\n queue[i](performance.now());\n }\n catch (e) {\n consoleError(e);\n }\n }\n queue.length = 0;\n};\nconst flush = () => {\n // always force a bunch of medium callbacks to run, but still have\n // a throttle on how many can run in a certain time\n // DOM READS!!!\n consume(queueDomReads);\n // DOM WRITES!!!\n {\n consume(queueDomWrites);\n if ((queuePending = queueDomReads.length > 0)) {\n // still more to do yet, but we've run out of time\n // let's let this thing cool off and try again in the next tick\n plt.raf(flush);\n }\n }\n};\nconst nextTick = (cb) => promiseResolve().then(cb);\nconst readTask = /*@__PURE__*/ queueTask(queueDomReads, false);\nconst writeTask = /*@__PURE__*/ queueTask(queueDomWrites, true);\n\nexport { Build as B, Host as H, setPlatformHelpers as a, bootstrapLazy as b, setMode as c, createEvent as d, readTask as e, getElement as f, getMode as g, h, forceUpdate as i, getAssetPath as j, promiseResolve as p, registerInstance as r, setNonce as s, writeTask as w };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nimport { G as GESTURE_CONTROLLER } from './gesture-controller-0fa396c4.js';\nexport { G as GESTURE_CONTROLLER } from './gesture-controller-0fa396c4.js';\n\nconst addEventListener = (el, // TODO(FW-2832): type\neventName, callback, opts) => {\n // use event listener options when supported\n // otherwise it's just a boolean for the \"capture\" arg\n const listenerOpts = supportsPassive(el)\n ? {\n capture: !!opts.capture,\n passive: !!opts.passive,\n }\n : !!opts.capture;\n let add;\n let remove;\n if (el['__zone_symbol__addEventListener']) {\n add = '__zone_symbol__addEventListener';\n remove = '__zone_symbol__removeEventListener';\n }\n else {\n add = 'addEventListener';\n remove = 'removeEventListener';\n }\n el[add](eventName, callback, listenerOpts);\n return () => {\n el[remove](eventName, callback, listenerOpts);\n };\n};\nconst supportsPassive = (node) => {\n if (_sPassive === undefined) {\n try {\n const opts = Object.defineProperty({}, 'passive', {\n get: () => {\n _sPassive = true;\n },\n });\n node.addEventListener('optsTest', () => {\n return;\n }, opts);\n }\n catch (e) {\n _sPassive = false;\n }\n }\n return !!_sPassive;\n};\nlet _sPassive;\n\nconst MOUSE_WAIT = 2000;\n// TODO(FW-2832): types\nconst createPointerEvents = (el, pointerDown, pointerMove, pointerUp, options) => {\n let rmTouchStart;\n let rmTouchMove;\n let rmTouchEnd;\n let rmTouchCancel;\n let rmMouseStart;\n let rmMouseMove;\n let rmMouseUp;\n let lastTouchEvent = 0;\n const handleTouchStart = (ev) => {\n lastTouchEvent = Date.now() + MOUSE_WAIT;\n if (!pointerDown(ev)) {\n return;\n }\n if (!rmTouchMove && pointerMove) {\n rmTouchMove = addEventListener(el, 'touchmove', pointerMove, options);\n }\n /**\n * Events are dispatched on the element that is tapped and bubble up to\n * the reference element in the gesture. In the event that the element this\n * event was first dispatched on is removed from the DOM, the event will no\n * longer bubble up to our reference element. This leaves the gesture in an\n * unusable state. To account for this, the touchend and touchcancel listeners\n * should be added to the event target so that they still fire even if the target\n * is removed from the DOM.\n */\n if (!rmTouchEnd) {\n rmTouchEnd = addEventListener(ev.target, 'touchend', handleTouchEnd, options);\n }\n if (!rmTouchCancel) {\n rmTouchCancel = addEventListener(ev.target, 'touchcancel', handleTouchEnd, options);\n }\n };\n const handleMouseDown = (ev) => {\n if (lastTouchEvent > Date.now()) {\n return;\n }\n if (!pointerDown(ev)) {\n return;\n }\n if (!rmMouseMove && pointerMove) {\n rmMouseMove = addEventListener(getDocument(el), 'mousemove', pointerMove, options);\n }\n if (!rmMouseUp) {\n rmMouseUp = addEventListener(getDocument(el), 'mouseup', handleMouseUp, options);\n }\n };\n const handleTouchEnd = (ev) => {\n stopTouch();\n if (pointerUp) {\n pointerUp(ev);\n }\n };\n const handleMouseUp = (ev) => {\n stopMouse();\n if (pointerUp) {\n pointerUp(ev);\n }\n };\n const stopTouch = () => {\n if (rmTouchMove) {\n rmTouchMove();\n }\n if (rmTouchEnd) {\n rmTouchEnd();\n }\n if (rmTouchCancel) {\n rmTouchCancel();\n }\n rmTouchMove = rmTouchEnd = rmTouchCancel = undefined;\n };\n const stopMouse = () => {\n if (rmMouseMove) {\n rmMouseMove();\n }\n if (rmMouseUp) {\n rmMouseUp();\n }\n rmMouseMove = rmMouseUp = undefined;\n };\n const stop = () => {\n stopTouch();\n stopMouse();\n };\n const enable = (isEnabled = true) => {\n if (!isEnabled) {\n if (rmTouchStart) {\n rmTouchStart();\n }\n if (rmMouseStart) {\n rmMouseStart();\n }\n rmTouchStart = rmMouseStart = undefined;\n stop();\n }\n else {\n if (!rmTouchStart) {\n rmTouchStart = addEventListener(el, 'touchstart', handleTouchStart, options);\n }\n if (!rmMouseStart) {\n rmMouseStart = addEventListener(el, 'mousedown', handleMouseDown, options);\n }\n }\n };\n const destroy = () => {\n enable(false);\n pointerUp = pointerMove = pointerDown = undefined;\n };\n return {\n enable,\n stop,\n destroy,\n };\n};\nconst getDocument = (node) => {\n return node instanceof Document ? node : node.ownerDocument;\n};\n\nconst createPanRecognizer = (direction, thresh, maxAngle) => {\n const radians = maxAngle * (Math.PI / 180);\n const isDirX = direction === 'x';\n const maxCosine = Math.cos(radians);\n const threshold = thresh * thresh;\n let startX = 0;\n let startY = 0;\n let dirty = false;\n let isPan = 0;\n return {\n start(x, y) {\n startX = x;\n startY = y;\n isPan = 0;\n dirty = true;\n },\n detect(x, y) {\n if (!dirty) {\n return false;\n }\n const deltaX = x - startX;\n const deltaY = y - startY;\n const distance = deltaX * deltaX + deltaY * deltaY;\n if (distance < threshold) {\n return false;\n }\n const hypotenuse = Math.sqrt(distance);\n const cosine = (isDirX ? deltaX : deltaY) / hypotenuse;\n if (cosine > maxCosine) {\n isPan = 1;\n }\n else if (cosine < -maxCosine) {\n isPan = -1;\n }\n else {\n isPan = 0;\n }\n dirty = false;\n return true;\n },\n isGesture() {\n return isPan !== 0;\n },\n getDirection() {\n return isPan;\n },\n };\n};\n\n// TODO(FW-2832): types\nconst createGesture = (config) => {\n let hasCapturedPan = false;\n let hasStartedPan = false;\n let hasFiredStart = true;\n let isMoveQueued = false;\n const finalConfig = Object.assign({ disableScroll: false, direction: 'x', gesturePriority: 0, passive: true, maxAngle: 40, threshold: 10 }, config);\n const canStart = finalConfig.canStart;\n const onWillStart = finalConfig.onWillStart;\n const onStart = finalConfig.onStart;\n const onEnd = finalConfig.onEnd;\n const notCaptured = finalConfig.notCaptured;\n const onMove = finalConfig.onMove;\n const threshold = finalConfig.threshold;\n const passive = finalConfig.passive;\n const blurOnStart = finalConfig.blurOnStart;\n const detail = {\n type: 'pan',\n startX: 0,\n startY: 0,\n startTime: 0,\n currentX: 0,\n currentY: 0,\n velocityX: 0,\n velocityY: 0,\n deltaX: 0,\n deltaY: 0,\n currentTime: 0,\n event: undefined,\n data: undefined,\n };\n const pan = createPanRecognizer(finalConfig.direction, finalConfig.threshold, finalConfig.maxAngle);\n const gesture = GESTURE_CONTROLLER.createGesture({\n name: config.gestureName,\n priority: config.gesturePriority,\n disableScroll: config.disableScroll,\n });\n const pointerDown = (ev) => {\n const timeStamp = now(ev);\n if (hasStartedPan || !hasFiredStart) {\n return false;\n }\n updateDetail(ev, detail);\n detail.startX = detail.currentX;\n detail.startY = detail.currentY;\n detail.startTime = detail.currentTime = timeStamp;\n detail.velocityX = detail.velocityY = detail.deltaX = detail.deltaY = 0;\n detail.event = ev;\n // Check if gesture can start\n if (canStart && canStart(detail) === false) {\n return false;\n }\n // Release fallback\n gesture.release();\n // Start gesture\n if (!gesture.start()) {\n return false;\n }\n hasStartedPan = true;\n if (threshold === 0) {\n return tryToCapturePan();\n }\n pan.start(detail.startX, detail.startY);\n return true;\n };\n const pointerMove = (ev) => {\n // fast path, if gesture is currently captured\n // do minimum job to get user-land even dispatched\n if (hasCapturedPan) {\n if (!isMoveQueued && hasFiredStart) {\n isMoveQueued = true;\n calcGestureData(detail, ev);\n requestAnimationFrame(fireOnMove);\n }\n return;\n }\n // gesture is currently being detected\n calcGestureData(detail, ev);\n if (pan.detect(detail.currentX, detail.currentY)) {\n if (!pan.isGesture() || !tryToCapturePan()) {\n abortGesture();\n }\n }\n };\n const fireOnMove = () => {\n // Since fireOnMove is called inside a RAF, onEnd() might be called,\n // we must double check hasCapturedPan\n if (!hasCapturedPan) {\n return;\n }\n isMoveQueued = false;\n if (onMove) {\n onMove(detail);\n }\n };\n const tryToCapturePan = () => {\n if (!gesture.capture()) {\n return false;\n }\n hasCapturedPan = true;\n hasFiredStart = false;\n // reset start position since the real user-land event starts here\n // If the pan detector threshold is big, not resetting the start position\n // will cause a jump in the animation equal to the detector threshold.\n // the array of positions used to calculate the gesture velocity does not\n // need to be cleaned, more points in the positions array always results in a\n // more accurate value of the velocity.\n detail.startX = detail.currentX;\n detail.startY = detail.currentY;\n detail.startTime = detail.currentTime;\n if (onWillStart) {\n onWillStart(detail).then(fireOnStart);\n }\n else {\n fireOnStart();\n }\n return true;\n };\n const blurActiveElement = () => {\n if (typeof document !== 'undefined') {\n const activeElement = document.activeElement;\n if (activeElement === null || activeElement === void 0 ? void 0 : activeElement.blur) {\n activeElement.blur();\n }\n }\n };\n const fireOnStart = () => {\n if (blurOnStart) {\n blurActiveElement();\n }\n if (onStart) {\n onStart(detail);\n }\n hasFiredStart = true;\n };\n const reset = () => {\n hasCapturedPan = false;\n hasStartedPan = false;\n isMoveQueued = false;\n hasFiredStart = true;\n gesture.release();\n };\n // END *************************\n const pointerUp = (ev) => {\n const tmpHasCaptured = hasCapturedPan;\n const tmpHasFiredStart = hasFiredStart;\n reset();\n if (!tmpHasFiredStart) {\n return;\n }\n calcGestureData(detail, ev);\n // Try to capture press\n if (tmpHasCaptured) {\n if (onEnd) {\n onEnd(detail);\n }\n return;\n }\n // Not captured any event\n if (notCaptured) {\n notCaptured(detail);\n }\n };\n const pointerEvents = createPointerEvents(finalConfig.el, pointerDown, pointerMove, pointerUp, {\n capture: false,\n passive,\n });\n const abortGesture = () => {\n reset();\n pointerEvents.stop();\n if (notCaptured) {\n notCaptured(detail);\n }\n };\n return {\n enable(enable = true) {\n if (!enable) {\n if (hasCapturedPan) {\n pointerUp(undefined);\n }\n reset();\n }\n pointerEvents.enable(enable);\n },\n destroy() {\n gesture.destroy();\n pointerEvents.destroy();\n },\n };\n};\nconst calcGestureData = (detail, ev) => {\n if (!ev) {\n return;\n }\n const prevX = detail.currentX;\n const prevY = detail.currentY;\n const prevT = detail.currentTime;\n updateDetail(ev, detail);\n const currentX = detail.currentX;\n const currentY = detail.currentY;\n const timestamp = (detail.currentTime = now(ev));\n const timeDelta = timestamp - prevT;\n if (timeDelta > 0 && timeDelta < 100) {\n const velocityX = (currentX - prevX) / timeDelta;\n const velocityY = (currentY - prevY) / timeDelta;\n detail.velocityX = velocityX * 0.7 + detail.velocityX * 0.3;\n detail.velocityY = velocityY * 0.7 + detail.velocityY * 0.3;\n }\n detail.deltaX = currentX - detail.startX;\n detail.deltaY = currentY - detail.startY;\n detail.event = ev;\n};\nconst updateDetail = (ev, detail) => {\n // get X coordinates for either a mouse click\n // or a touch depending on the given event\n let x = 0;\n let y = 0;\n if (ev) {\n const changedTouches = ev.changedTouches;\n if (changedTouches && changedTouches.length > 0) {\n const touch = changedTouches[0];\n x = touch.clientX;\n y = touch.clientY;\n }\n else if (ev.pageX !== undefined) {\n x = ev.pageX;\n y = ev.pageY;\n }\n }\n detail.currentX = x;\n detail.currentY = y;\n};\nconst now = (ev) => {\n return ev.timeStamp || Date.now();\n};\n\nexport { createGesture };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nimport { a as setPlatformHelpers, g as getMode, c as setMode } from './index-7c9b1bca.js';\n\n// TODO(FW-2832): types\nclass Config {\n constructor() {\n this.m = new Map();\n }\n reset(configObj) {\n this.m = new Map(Object.entries(configObj));\n }\n get(key, fallback) {\n const value = this.m.get(key);\n return value !== undefined ? value : fallback;\n }\n getBoolean(key, fallback = false) {\n const val = this.m.get(key);\n if (val === undefined) {\n return fallback;\n }\n if (typeof val === 'string') {\n return val === 'true';\n }\n return !!val;\n }\n getNumber(key, fallback) {\n const val = parseFloat(this.m.get(key));\n return isNaN(val) ? (fallback !== undefined ? fallback : NaN) : val;\n }\n set(key, value) {\n this.m.set(key, value);\n }\n}\nconst config = /*@__PURE__*/ new Config();\nconst configFromSession = (win) => {\n try {\n const configStr = win.sessionStorage.getItem(IONIC_SESSION_KEY);\n return configStr !== null ? JSON.parse(configStr) : {};\n }\n catch (e) {\n return {};\n }\n};\nconst saveConfig = (win, c) => {\n try {\n win.sessionStorage.setItem(IONIC_SESSION_KEY, JSON.stringify(c));\n }\n catch (e) {\n return;\n }\n};\nconst configFromURL = (win) => {\n const configObj = {};\n win.location.search\n .slice(1)\n .split('&')\n .map((entry) => entry.split('='))\n .map(([key, value]) => [decodeURIComponent(key), decodeURIComponent(value)])\n .filter(([key]) => startsWith(key, IONIC_PREFIX))\n .map(([key, value]) => [key.slice(IONIC_PREFIX.length), value])\n .forEach(([key, value]) => {\n configObj[key] = value;\n });\n return configObj;\n};\nconst startsWith = (input, search) => {\n return input.substr(0, search.length) === search;\n};\nconst IONIC_PREFIX = 'ionic:';\nconst IONIC_SESSION_KEY = 'ionic-persist-config';\n\nconst getPlatforms = (win) => setupPlatforms(win);\nconst isPlatform = (winOrPlatform, platform) => {\n if (typeof winOrPlatform === 'string') {\n platform = winOrPlatform;\n winOrPlatform = undefined;\n }\n return getPlatforms(winOrPlatform).includes(platform);\n};\nconst setupPlatforms = (win = window) => {\n if (typeof win === 'undefined') {\n return [];\n }\n win.Ionic = win.Ionic || {};\n let platforms = win.Ionic.platforms;\n if (platforms == null) {\n platforms = win.Ionic.platforms = detectPlatforms(win);\n platforms.forEach((p) => win.document.documentElement.classList.add(`plt-${p}`));\n }\n return platforms;\n};\nconst detectPlatforms = (win) => {\n const customPlatformMethods = config.get('platform');\n return Object.keys(PLATFORMS_MAP).filter((p) => {\n const customMethod = customPlatformMethods === null || customPlatformMethods === void 0 ? void 0 : customPlatformMethods[p];\n return typeof customMethod === 'function' ? customMethod(win) : PLATFORMS_MAP[p](win);\n });\n};\nconst isMobileWeb = (win) => isMobile(win) && !isHybrid(win);\nconst isIpad = (win) => {\n // iOS 12 and below\n if (testUserAgent(win, /iPad/i)) {\n return true;\n }\n // iOS 13+\n if (testUserAgent(win, /Macintosh/i) && isMobile(win)) {\n return true;\n }\n return false;\n};\nconst isIphone = (win) => testUserAgent(win, /iPhone/i);\nconst isIOS = (win) => testUserAgent(win, /iPhone|iPod/i) || isIpad(win);\nconst isAndroid = (win) => testUserAgent(win, /android|sink/i);\nconst isAndroidTablet = (win) => {\n return isAndroid(win) && !testUserAgent(win, /mobile/i);\n};\nconst isPhablet = (win) => {\n const width = win.innerWidth;\n const height = win.innerHeight;\n const smallest = Math.min(width, height);\n const largest = Math.max(width, height);\n return smallest > 390 && smallest < 520 && largest > 620 && largest < 800;\n};\nconst isTablet = (win) => {\n const width = win.innerWidth;\n const height = win.innerHeight;\n const smallest = Math.min(width, height);\n const largest = Math.max(width, height);\n return isIpad(win) || isAndroidTablet(win) || (smallest > 460 && smallest < 820 && largest > 780 && largest < 1400);\n};\nconst isMobile = (win) => matchMedia(win, '(any-pointer:coarse)');\nconst isDesktop = (win) => !isMobile(win);\nconst isHybrid = (win) => isCordova(win) || isCapacitorNative(win);\nconst isCordova = (win) => !!(win['cordova'] || win['phonegap'] || win['PhoneGap']);\nconst isCapacitorNative = (win) => {\n const capacitor = win['Capacitor'];\n return !!(capacitor === null || capacitor === void 0 ? void 0 : capacitor.isNative);\n};\nconst isElectron = (win) => testUserAgent(win, /electron/i);\nconst isPWA = (win) => { var _a; return !!(((_a = win.matchMedia) === null || _a === void 0 ? void 0 : _a.call(win, '(display-mode: standalone)').matches) || win.navigator.standalone); };\nconst testUserAgent = (win, expr) => expr.test(win.navigator.userAgent);\nconst matchMedia = (win, query) => { var _a; return (_a = win.matchMedia) === null || _a === void 0 ? void 0 : _a.call(win, query).matches; };\nconst PLATFORMS_MAP = {\n ipad: isIpad,\n iphone: isIphone,\n ios: isIOS,\n android: isAndroid,\n phablet: isPhablet,\n tablet: isTablet,\n cordova: isCordova,\n capacitor: isCapacitorNative,\n electron: isElectron,\n pwa: isPWA,\n mobile: isMobile,\n mobileweb: isMobileWeb,\n desktop: isDesktop,\n hybrid: isHybrid,\n};\n\n// TODO(FW-2832): types\nlet defaultMode;\nconst getIonMode = (ref) => {\n return (ref && getMode(ref)) || defaultMode;\n};\nconst initialize = (userConfig = {}) => {\n if (typeof window === 'undefined') {\n return;\n }\n const doc = window.document;\n const win = window;\n const Ionic = (win.Ionic = win.Ionic || {});\n const platformHelpers = {};\n if (userConfig._ael) {\n platformHelpers.ael = userConfig._ael;\n }\n if (userConfig._rel) {\n platformHelpers.rel = userConfig._rel;\n }\n if (userConfig._ce) {\n platformHelpers.ce = userConfig._ce;\n }\n setPlatformHelpers(platformHelpers);\n // create the Ionic.config from raw config object (if it exists)\n // and convert Ionic.config into a ConfigApi that has a get() fn\n const configObj = Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, configFromSession(win)), { persistConfig: false }), Ionic.config), configFromURL(win)), userConfig);\n config.reset(configObj);\n if (config.getBoolean('persistConfig')) {\n saveConfig(win, configObj);\n }\n // Setup platforms\n setupPlatforms(win);\n // first see if the mode was set as an attribute on \n // which could have been set by the user, or by pre-rendering\n // otherwise get the mode via config settings, and fallback to md\n Ionic.config = config;\n Ionic.mode = defaultMode = config.get('mode', doc.documentElement.getAttribute('mode') || (isPlatform(win, 'ios') ? 'ios' : 'md'));\n config.set('mode', defaultMode);\n doc.documentElement.setAttribute('mode', defaultMode);\n doc.documentElement.classList.add(defaultMode);\n if (config.getBoolean('_testing')) {\n config.set('animated', false);\n }\n const isIonicElement = (elm) => { var _a; return (_a = elm.tagName) === null || _a === void 0 ? void 0 : _a.startsWith('ION-'); };\n const isAllowedIonicModeValue = (elmMode) => ['ios', 'md'].includes(elmMode);\n setMode((elm) => {\n while (elm) {\n const elmMode = elm.mode || elm.getAttribute('mode');\n if (elmMode) {\n if (isAllowedIonicModeValue(elmMode)) {\n return elmMode;\n }\n else if (isIonicElement(elm)) {\n console.warn('Invalid ionic mode: \"' + elmMode + '\", expected: \"ios\" or \"md\"');\n }\n }\n elm = elm.parentElement;\n }\n return defaultMode;\n });\n};\n\nexport { isPlatform as a, getIonMode as b, config as c, getPlatforms as g, initialize as i };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nimport { c as createAnimation } from './animation-8aa13916.js';\nimport { g as getIonPageElement } from './index-6a0ccabb.js';\nimport './index-7a14ecec.js';\nimport './helpers-3379ba19.js';\nimport './index-7c9b1bca.js';\n\nconst DURATION = 540;\n// TODO(FW-2832): types\nconst getClonedElement = (tagName) => {\n return document.querySelector(`${tagName}.ion-cloned-element`);\n};\nconst shadow = (el) => {\n return el.shadowRoot || el;\n};\nconst getLargeTitle = (refEl) => {\n const tabs = refEl.tagName === 'ION-TABS' ? refEl : refEl.querySelector('ion-tabs');\n const query = 'ion-content ion-header:not(.header-collapse-condense-inactive) ion-title.title-large';\n if (tabs != null) {\n const activeTab = tabs.querySelector('ion-tab:not(.tab-hidden), .ion-page:not(.ion-page-hidden)');\n return activeTab != null ? activeTab.querySelector(query) : null;\n }\n return refEl.querySelector(query);\n};\nconst getBackButton = (refEl, backDirection) => {\n const tabs = refEl.tagName === 'ION-TABS' ? refEl : refEl.querySelector('ion-tabs');\n let buttonsList = [];\n if (tabs != null) {\n const activeTab = tabs.querySelector('ion-tab:not(.tab-hidden), .ion-page:not(.ion-page-hidden)');\n if (activeTab != null) {\n buttonsList = activeTab.querySelectorAll('ion-buttons');\n }\n }\n else {\n buttonsList = refEl.querySelectorAll('ion-buttons');\n }\n for (const buttons of buttonsList) {\n const parentHeader = buttons.closest('ion-header');\n const activeHeader = parentHeader && !parentHeader.classList.contains('header-collapse-condense-inactive');\n const backButton = buttons.querySelector('ion-back-button');\n const buttonsCollapse = buttons.classList.contains('buttons-collapse');\n const startSlot = buttons.slot === 'start' || buttons.slot === '';\n if (backButton !== null && startSlot && ((buttonsCollapse && activeHeader && backDirection) || !buttonsCollapse)) {\n return backButton;\n }\n }\n return null;\n};\nconst createLargeTitleTransition = (rootAnimation, rtl, backDirection, enteringEl, leavingEl) => {\n const enteringBackButton = getBackButton(enteringEl, backDirection);\n const leavingLargeTitle = getLargeTitle(leavingEl);\n const enteringLargeTitle = getLargeTitle(enteringEl);\n const leavingBackButton = getBackButton(leavingEl, backDirection);\n const shouldAnimationForward = enteringBackButton !== null && leavingLargeTitle !== null && !backDirection;\n const shouldAnimationBackward = enteringLargeTitle !== null && leavingBackButton !== null && backDirection;\n if (shouldAnimationForward) {\n const leavingLargeTitleBox = leavingLargeTitle.getBoundingClientRect();\n const enteringBackButtonBox = enteringBackButton.getBoundingClientRect();\n const enteringBackButtonTextEl = shadow(enteringBackButton).querySelector('.button-text');\n const enteringBackButtonTextBox = enteringBackButtonTextEl.getBoundingClientRect();\n const leavingLargeTitleTextEl = shadow(leavingLargeTitle).querySelector('.toolbar-title');\n const leavingLargeTitleTextBox = leavingLargeTitleTextEl.getBoundingClientRect();\n animateLargeTitle(rootAnimation, rtl, backDirection, leavingLargeTitle, leavingLargeTitleBox, leavingLargeTitleTextBox, enteringBackButtonTextEl, enteringBackButtonTextBox);\n animateBackButton(rootAnimation, rtl, backDirection, enteringBackButton, enteringBackButtonBox, enteringBackButtonTextEl, enteringBackButtonTextBox, leavingLargeTitle, leavingLargeTitleTextBox);\n }\n else if (shouldAnimationBackward) {\n const enteringLargeTitleBox = enteringLargeTitle.getBoundingClientRect();\n const leavingBackButtonBox = leavingBackButton.getBoundingClientRect();\n const leavingBackButtonTextEl = shadow(leavingBackButton).querySelector('.button-text');\n const leavingBackButtonTextBox = leavingBackButtonTextEl.getBoundingClientRect();\n const enteringLargeTitleTextEl = shadow(enteringLargeTitle).querySelector('.toolbar-title');\n const enteringLargeTitleTextBox = enteringLargeTitleTextEl.getBoundingClientRect();\n animateLargeTitle(rootAnimation, rtl, backDirection, enteringLargeTitle, enteringLargeTitleBox, enteringLargeTitleTextBox, leavingBackButtonTextEl, leavingBackButtonTextBox);\n animateBackButton(rootAnimation, rtl, backDirection, leavingBackButton, leavingBackButtonBox, leavingBackButtonTextEl, leavingBackButtonTextBox, enteringLargeTitle, enteringLargeTitleTextBox);\n }\n return {\n forward: shouldAnimationForward,\n backward: shouldAnimationBackward,\n };\n};\nconst animateBackButton = (rootAnimation, rtl, backDirection, backButtonEl, backButtonBox, backButtonTextEl, backButtonTextBox, largeTitleEl, largeTitleTextBox) => {\n var _a, _b;\n const BACK_BUTTON_START_OFFSET = rtl ? `calc(100% - ${backButtonBox.right + 4}px)` : `${backButtonBox.left - 4}px`;\n const TEXT_ORIGIN_X = rtl ? 'right' : 'left';\n const ICON_ORIGIN_X = rtl ? 'left' : 'right';\n const CONTAINER_ORIGIN_X = rtl ? 'right' : 'left';\n /**\n * When the title and back button texts match\n * then they should overlap during the page transition.\n * If the texts do not match up then the back button text scale adjusts\n * to not perfectly match the large title text otherwise the\n * proportions will be incorrect.\n * When the texts match we scale both the width and height to account for\n * font weight differences between the title and back button.\n */\n const doTitleAndButtonTextsMatch = ((_a = backButtonTextEl.textContent) === null || _a === void 0 ? void 0 : _a.trim()) === ((_b = largeTitleEl.textContent) === null || _b === void 0 ? void 0 : _b.trim());\n const WIDTH_SCALE = largeTitleTextBox.width / backButtonTextBox.width;\n /**\n * We subtract an offset to account for slight sizing/padding\n * differences between the title and the back button.\n */\n const HEIGHT_SCALE = (largeTitleTextBox.height - LARGE_TITLE_SIZE_OFFSET) / backButtonTextBox.height;\n const TEXT_START_SCALE = doTitleAndButtonTextsMatch\n ? `scale(${WIDTH_SCALE}, ${HEIGHT_SCALE})`\n : `scale(${HEIGHT_SCALE})`;\n const TEXT_END_SCALE = 'scale(1)';\n const backButtonIconEl = shadow(backButtonEl).querySelector('ion-icon');\n const backButtonIconBox = backButtonIconEl.getBoundingClientRect();\n /**\n * We need to offset the container by the icon dimensions\n * so that the back button text aligns with the large title\n * text. Otherwise, the back button icon will align with the\n * large title text but the back button text will not.\n */\n const CONTAINER_START_TRANSLATE_X = rtl\n ? `${backButtonIconBox.width / 2 - (backButtonIconBox.right - backButtonBox.right)}px`\n : `${backButtonBox.left - backButtonIconBox.width / 2}px`;\n const CONTAINER_END_TRANSLATE_X = rtl ? `-${window.innerWidth - backButtonBox.right}px` : `${backButtonBox.left}px`;\n /**\n * Back button container should be\n * aligned to the top of the title container\n * so the texts overlap as the back button\n * text begins to fade in.\n */\n const CONTAINER_START_TRANSLATE_Y = `${largeTitleTextBox.top}px`;\n /**\n * The cloned back button should align exactly with the\n * real back button on the entering page otherwise there will\n * be a layout shift.\n */\n const CONTAINER_END_TRANSLATE_Y = `${backButtonBox.top}px`;\n /**\n * In the forward direction, the cloned back button\n * container should translate from over the large title\n * to over the back button. In the backward direction,\n * it should translate from over the back button to over\n * the large title.\n */\n const FORWARD_CONTAINER_KEYFRAMES = [\n { offset: 0, transform: `translate3d(${CONTAINER_START_TRANSLATE_X}, ${CONTAINER_START_TRANSLATE_Y}, 0)` },\n { offset: 1, transform: `translate3d(${CONTAINER_END_TRANSLATE_X}, ${CONTAINER_END_TRANSLATE_Y}, 0)` },\n ];\n const BACKWARD_CONTAINER_KEYFRAMES = [\n { offset: 0, transform: `translate3d(${CONTAINER_END_TRANSLATE_X}, ${CONTAINER_END_TRANSLATE_Y}, 0)` },\n { offset: 1, transform: `translate3d(${CONTAINER_START_TRANSLATE_X}, ${CONTAINER_START_TRANSLATE_Y}, 0)` },\n ];\n const CONTAINER_KEYFRAMES = backDirection ? BACKWARD_CONTAINER_KEYFRAMES : FORWARD_CONTAINER_KEYFRAMES;\n /**\n * In the forward direction, the text in the cloned back button\n * should start to be (roughly) the size of the large title\n * and then scale down to be the size of the actual back button.\n * The text should also translate, but that translate is handled\n * by the container keyframes.\n */\n const FORWARD_TEXT_KEYFRAMES = [\n { offset: 0, opacity: 0, transform: TEXT_START_SCALE },\n { offset: 1, opacity: 1, transform: TEXT_END_SCALE },\n ];\n const BACKWARD_TEXT_KEYFRAMES = [\n { offset: 0, opacity: 1, transform: TEXT_END_SCALE },\n { offset: 1, opacity: 0, transform: TEXT_START_SCALE },\n ];\n const TEXT_KEYFRAMES = backDirection ? BACKWARD_TEXT_KEYFRAMES : FORWARD_TEXT_KEYFRAMES;\n /**\n * The icon should scale in/out in the second\n * half of the animation. The icon should also\n * translate, but that translate is handled by the\n * container keyframes.\n */\n const FORWARD_ICON_KEYFRAMES = [\n { offset: 0, opacity: 0, transform: 'scale(0.6)' },\n { offset: 0.6, opacity: 0, transform: 'scale(0.6)' },\n { offset: 1, opacity: 1, transform: 'scale(1)' },\n ];\n const BACKWARD_ICON_KEYFRAMES = [\n { offset: 0, opacity: 1, transform: 'scale(1)' },\n { offset: 0.2, opacity: 0, transform: 'scale(0.6)' },\n { offset: 1, opacity: 0, transform: 'scale(0.6)' },\n ];\n const ICON_KEYFRAMES = backDirection ? BACKWARD_ICON_KEYFRAMES : FORWARD_ICON_KEYFRAMES;\n const enteringBackButtonTextAnimation = createAnimation();\n const enteringBackButtonIconAnimation = createAnimation();\n const enteringBackButtonAnimation = createAnimation();\n const clonedBackButtonEl = getClonedElement('ion-back-button');\n const clonedBackButtonTextEl = shadow(clonedBackButtonEl).querySelector('.button-text');\n const clonedBackButtonIconEl = shadow(clonedBackButtonEl).querySelector('ion-icon');\n clonedBackButtonEl.text = backButtonEl.text;\n clonedBackButtonEl.mode = backButtonEl.mode;\n clonedBackButtonEl.icon = backButtonEl.icon;\n clonedBackButtonEl.color = backButtonEl.color;\n clonedBackButtonEl.disabled = backButtonEl.disabled;\n clonedBackButtonEl.style.setProperty('display', 'block');\n clonedBackButtonEl.style.setProperty('position', 'fixed');\n enteringBackButtonIconAnimation.addElement(clonedBackButtonIconEl);\n enteringBackButtonTextAnimation.addElement(clonedBackButtonTextEl);\n enteringBackButtonAnimation.addElement(clonedBackButtonEl);\n enteringBackButtonAnimation\n .beforeStyles({\n position: 'absolute',\n top: '0px',\n [CONTAINER_ORIGIN_X]: '0px',\n })\n .keyframes(CONTAINER_KEYFRAMES);\n enteringBackButtonTextAnimation\n .beforeStyles({\n 'transform-origin': `${TEXT_ORIGIN_X} top`,\n })\n .beforeAddWrite(() => {\n backButtonEl.style.setProperty('display', 'none');\n clonedBackButtonEl.style.setProperty(TEXT_ORIGIN_X, BACK_BUTTON_START_OFFSET);\n })\n .afterAddWrite(() => {\n backButtonEl.style.setProperty('display', '');\n clonedBackButtonEl.style.setProperty('display', 'none');\n clonedBackButtonEl.style.removeProperty(TEXT_ORIGIN_X);\n })\n .keyframes(TEXT_KEYFRAMES);\n enteringBackButtonIconAnimation\n .beforeStyles({\n 'transform-origin': `${ICON_ORIGIN_X} center`,\n })\n .keyframes(ICON_KEYFRAMES);\n rootAnimation.addAnimation([\n enteringBackButtonTextAnimation,\n enteringBackButtonIconAnimation,\n enteringBackButtonAnimation,\n ]);\n};\nconst animateLargeTitle = (rootAnimation, rtl, backDirection, largeTitleEl, largeTitleBox, largeTitleTextBox, backButtonTextEl, backButtonTextBox) => {\n var _a, _b;\n /**\n * The horizontal transform origin for the large title\n */\n const ORIGIN_X = rtl ? 'right' : 'left';\n const TITLE_START_OFFSET = rtl ? `calc(100% - ${largeTitleBox.right}px)` : `${largeTitleBox.left}px`;\n /**\n * The cloned large should align exactly with the\n * real large title on the leaving page otherwise there will\n * be a layout shift.\n */\n const START_TRANSLATE_X = '0px';\n const START_TRANSLATE_Y = `${largeTitleBox.top}px`;\n /**\n * How much to offset the large title translation by.\n * This accounts for differences in sizing between the large\n * title and the back button due to padding and font weight.\n */\n const LARGE_TITLE_TRANSLATION_OFFSET = 8;\n /**\n * The scaled title should (roughly) overlap the back button.\n * This ensures that the back button and title overlap during\n * the animation. Note that since both elements either fade in\n * or fade out over the course of the animation, neither element\n * will be fully visible on top of the other. As a result, the overlap\n * does not need to be perfect, so approximate values are acceptable here.\n */\n const END_TRANSLATE_X = rtl\n ? `-${window.innerWidth - backButtonTextBox.right - LARGE_TITLE_TRANSLATION_OFFSET}px`\n : `${backButtonTextBox.x - LARGE_TITLE_TRANSLATION_OFFSET}px`;\n /**\n * The top of the scaled large title\n * should match with the top of the\n * back button text element.\n * We subtract 2px to account for the top padding\n * on the large title element.\n */\n const LARGE_TITLE_TOP_PADDING = 2;\n const END_TRANSLATE_Y = `${backButtonTextBox.y - LARGE_TITLE_TOP_PADDING}px`;\n /**\n * In the forward direction, the large title should start at its\n * normal size and then scale down to be (roughly) the size of the\n * back button on the other view. In the backward direction, the\n * large title should start at (roughly) the size of the back button\n * and then scale up to its original size.\n *\n * Note that since both elements either fade in\n * or fade out over the course of the animation, neither element\n * will be fully visible on top of the other. As a result, the overlap\n * does not need to be perfect, so approximate values are acceptable here.\n */\n /**\n * When the title and back button texts match\n * then they should overlap during the page transition.\n * If the texts do not match up then the large title text scale adjusts\n * to not perfectly match the back button text otherwise the\n * proportions will be incorrect.\n * When the texts match we scale both the width and height to account for\n * font weight differences between the title and back button.\n */\n const doTitleAndButtonTextsMatch = ((_a = backButtonTextEl.textContent) === null || _a === void 0 ? void 0 : _a.trim()) === ((_b = largeTitleEl.textContent) === null || _b === void 0 ? void 0 : _b.trim());\n const WIDTH_SCALE = backButtonTextBox.width / largeTitleTextBox.width;\n const HEIGHT_SCALE = backButtonTextBox.height / (largeTitleTextBox.height - LARGE_TITLE_SIZE_OFFSET);\n const START_SCALE = 'scale(1)';\n const END_SCALE = doTitleAndButtonTextsMatch ? `scale(${WIDTH_SCALE}, ${HEIGHT_SCALE})` : `scale(${HEIGHT_SCALE})`;\n const BACKWARDS_KEYFRAMES = [\n { offset: 0, opacity: 0, transform: `translate3d(${END_TRANSLATE_X}, ${END_TRANSLATE_Y}, 0) ${END_SCALE}` },\n { offset: 0.1, opacity: 0 },\n { offset: 1, opacity: 1, transform: `translate3d(${START_TRANSLATE_X}, ${START_TRANSLATE_Y}, 0) ${START_SCALE}` },\n ];\n const FORWARDS_KEYFRAMES = [\n {\n offset: 0,\n opacity: 0.99,\n transform: `translate3d(${START_TRANSLATE_X}, ${START_TRANSLATE_Y}, 0) ${START_SCALE}`,\n },\n { offset: 0.6, opacity: 0 },\n { offset: 1, opacity: 0, transform: `translate3d(${END_TRANSLATE_X}, ${END_TRANSLATE_Y}, 0) ${END_SCALE}` },\n ];\n const KEYFRAMES = backDirection ? BACKWARDS_KEYFRAMES : FORWARDS_KEYFRAMES;\n const clonedTitleEl = getClonedElement('ion-title');\n const clonedLargeTitleAnimation = createAnimation();\n clonedTitleEl.innerText = largeTitleEl.innerText;\n clonedTitleEl.size = largeTitleEl.size;\n clonedTitleEl.color = largeTitleEl.color;\n clonedLargeTitleAnimation.addElement(clonedTitleEl);\n clonedLargeTitleAnimation\n .beforeStyles({\n 'transform-origin': `${ORIGIN_X} top`,\n /**\n * Since font size changes will cause\n * the dimension of the large title to change\n * we need to set the cloned title height\n * equal to that of the original large title height.\n */\n height: `${largeTitleBox.height}px`,\n display: '',\n position: 'relative',\n [ORIGIN_X]: TITLE_START_OFFSET,\n })\n .beforeAddWrite(() => {\n largeTitleEl.style.setProperty('opacity', '0');\n })\n .afterAddWrite(() => {\n largeTitleEl.style.setProperty('opacity', '');\n clonedTitleEl.style.setProperty('display', 'none');\n })\n .keyframes(KEYFRAMES);\n rootAnimation.addAnimation(clonedLargeTitleAnimation);\n};\nconst iosTransitionAnimation = (navEl, opts) => {\n var _a;\n try {\n const EASING = 'cubic-bezier(0.32,0.72,0,1)';\n const OPACITY = 'opacity';\n const TRANSFORM = 'transform';\n const CENTER = '0%';\n const OFF_OPACITY = 0.8;\n const isRTL = navEl.ownerDocument.dir === 'rtl';\n const OFF_RIGHT = isRTL ? '-99.5%' : '99.5%';\n const OFF_LEFT = isRTL ? '33%' : '-33%';\n const enteringEl = opts.enteringEl;\n const leavingEl = opts.leavingEl;\n const backDirection = opts.direction === 'back';\n const contentEl = enteringEl.querySelector(':scope > ion-content');\n const headerEls = enteringEl.querySelectorAll(':scope > ion-header > *:not(ion-toolbar), :scope > ion-footer > *');\n const enteringToolBarEls = enteringEl.querySelectorAll(':scope > ion-header > ion-toolbar');\n const rootAnimation = createAnimation();\n const enteringContentAnimation = createAnimation();\n rootAnimation\n .addElement(enteringEl)\n .duration(((_a = opts.duration) !== null && _a !== void 0 ? _a : 0) || DURATION)\n .easing(opts.easing || EASING)\n .fill('both')\n .beforeRemoveClass('ion-page-invisible');\n // eslint-disable-next-line @typescript-eslint/prefer-optional-chain\n if (leavingEl && navEl !== null && navEl !== undefined) {\n const navDecorAnimation = createAnimation();\n navDecorAnimation.addElement(navEl);\n rootAnimation.addAnimation(navDecorAnimation);\n }\n if (!contentEl && enteringToolBarEls.length === 0 && headerEls.length === 0) {\n enteringContentAnimation.addElement(enteringEl.querySelector(':scope > .ion-page, :scope > ion-nav, :scope > ion-tabs')); // REVIEW\n }\n else {\n enteringContentAnimation.addElement(contentEl); // REVIEW\n enteringContentAnimation.addElement(headerEls);\n }\n rootAnimation.addAnimation(enteringContentAnimation);\n if (backDirection) {\n enteringContentAnimation\n .beforeClearStyles([OPACITY])\n .fromTo('transform', `translateX(${OFF_LEFT})`, `translateX(${CENTER})`)\n .fromTo(OPACITY, OFF_OPACITY, 1);\n }\n else {\n // entering content, forward direction\n enteringContentAnimation\n .beforeClearStyles([OPACITY])\n .fromTo('transform', `translateX(${OFF_RIGHT})`, `translateX(${CENTER})`);\n }\n if (contentEl) {\n const enteringTransitionEffectEl = shadow(contentEl).querySelector('.transition-effect');\n if (enteringTransitionEffectEl) {\n const enteringTransitionCoverEl = enteringTransitionEffectEl.querySelector('.transition-cover');\n const enteringTransitionShadowEl = enteringTransitionEffectEl.querySelector('.transition-shadow');\n const enteringTransitionEffect = createAnimation();\n const enteringTransitionCover = createAnimation();\n const enteringTransitionShadow = createAnimation();\n enteringTransitionEffect\n .addElement(enteringTransitionEffectEl)\n .beforeStyles({ opacity: '1', display: 'block' })\n .afterStyles({ opacity: '', display: '' });\n enteringTransitionCover\n .addElement(enteringTransitionCoverEl) // REVIEW\n .beforeClearStyles([OPACITY])\n .fromTo(OPACITY, 0, 0.1);\n enteringTransitionShadow\n .addElement(enteringTransitionShadowEl) // REVIEW\n .beforeClearStyles([OPACITY])\n .fromTo(OPACITY, 0.03, 0.7);\n enteringTransitionEffect.addAnimation([enteringTransitionCover, enteringTransitionShadow]);\n enteringContentAnimation.addAnimation([enteringTransitionEffect]);\n }\n }\n const enteringContentHasLargeTitle = enteringEl.querySelector('ion-header.header-collapse-condense');\n const { forward, backward } = createLargeTitleTransition(rootAnimation, isRTL, backDirection, enteringEl, leavingEl);\n enteringToolBarEls.forEach((enteringToolBarEl) => {\n const enteringToolBar = createAnimation();\n enteringToolBar.addElement(enteringToolBarEl);\n rootAnimation.addAnimation(enteringToolBar);\n const enteringTitle = createAnimation();\n enteringTitle.addElement(enteringToolBarEl.querySelector('ion-title')); // REVIEW\n const enteringToolBarButtons = createAnimation();\n const buttons = Array.from(enteringToolBarEl.querySelectorAll('ion-buttons,[menuToggle]'));\n const parentHeader = enteringToolBarEl.closest('ion-header');\n const inactiveHeader = parentHeader === null || parentHeader === void 0 ? void 0 : parentHeader.classList.contains('header-collapse-condense-inactive');\n let buttonsToAnimate;\n if (backDirection) {\n buttonsToAnimate = buttons.filter((button) => {\n const isCollapseButton = button.classList.contains('buttons-collapse');\n return (isCollapseButton && !inactiveHeader) || !isCollapseButton;\n });\n }\n else {\n buttonsToAnimate = buttons.filter((button) => !button.classList.contains('buttons-collapse'));\n }\n enteringToolBarButtons.addElement(buttonsToAnimate);\n const enteringToolBarItems = createAnimation();\n enteringToolBarItems.addElement(enteringToolBarEl.querySelectorAll(':scope > *:not(ion-title):not(ion-buttons):not([menuToggle])'));\n const enteringToolBarBg = createAnimation();\n enteringToolBarBg.addElement(shadow(enteringToolBarEl).querySelector('.toolbar-background')); // REVIEW\n const enteringBackButton = createAnimation();\n const backButtonEl = enteringToolBarEl.querySelector('ion-back-button');\n if (backButtonEl) {\n enteringBackButton.addElement(backButtonEl);\n }\n enteringToolBar.addAnimation([\n enteringTitle,\n enteringToolBarButtons,\n enteringToolBarItems,\n enteringToolBarBg,\n enteringBackButton,\n ]);\n enteringToolBarButtons.fromTo(OPACITY, 0.01, 1);\n enteringToolBarItems.fromTo(OPACITY, 0.01, 1);\n if (backDirection) {\n if (!inactiveHeader) {\n enteringTitle\n .fromTo('transform', `translateX(${OFF_LEFT})`, `translateX(${CENTER})`)\n .fromTo(OPACITY, 0.01, 1);\n }\n enteringToolBarItems.fromTo('transform', `translateX(${OFF_LEFT})`, `translateX(${CENTER})`);\n // back direction, entering page has a back button\n enteringBackButton.fromTo(OPACITY, 0.01, 1);\n }\n else {\n // entering toolbar, forward direction\n if (!enteringContentHasLargeTitle) {\n enteringTitle\n .fromTo('transform', `translateX(${OFF_RIGHT})`, `translateX(${CENTER})`)\n .fromTo(OPACITY, 0.01, 1);\n }\n enteringToolBarItems.fromTo('transform', `translateX(${OFF_RIGHT})`, `translateX(${CENTER})`);\n enteringToolBarBg.beforeClearStyles([OPACITY, 'transform']);\n const translucentHeader = parentHeader === null || parentHeader === void 0 ? void 0 : parentHeader.translucent;\n if (!translucentHeader) {\n enteringToolBarBg.fromTo(OPACITY, 0.01, 'var(--opacity)');\n }\n else {\n enteringToolBarBg.fromTo('transform', isRTL ? 'translateX(-100%)' : 'translateX(100%)', 'translateX(0px)');\n }\n // forward direction, entering page has a back button\n if (!forward) {\n enteringBackButton.fromTo(OPACITY, 0.01, 1);\n }\n if (backButtonEl && !forward) {\n const enteringBackBtnText = createAnimation();\n enteringBackBtnText\n .addElement(shadow(backButtonEl).querySelector('.button-text')) // REVIEW\n .fromTo(`transform`, isRTL ? 'translateX(-100px)' : 'translateX(100px)', 'translateX(0px)');\n enteringToolBar.addAnimation(enteringBackBtnText);\n }\n }\n });\n // setup leaving view\n if (leavingEl) {\n const leavingContent = createAnimation();\n const leavingContentEl = leavingEl.querySelector(':scope > ion-content');\n const leavingToolBarEls = leavingEl.querySelectorAll(':scope > ion-header > ion-toolbar');\n const leavingHeaderEls = leavingEl.querySelectorAll(':scope > ion-header > *:not(ion-toolbar), :scope > ion-footer > *');\n if (!leavingContentEl && leavingToolBarEls.length === 0 && leavingHeaderEls.length === 0) {\n leavingContent.addElement(leavingEl.querySelector(':scope > .ion-page, :scope > ion-nav, :scope > ion-tabs')); // REVIEW\n }\n else {\n leavingContent.addElement(leavingContentEl); // REVIEW\n leavingContent.addElement(leavingHeaderEls);\n }\n rootAnimation.addAnimation(leavingContent);\n if (backDirection) {\n // leaving content, back direction\n leavingContent\n .beforeClearStyles([OPACITY])\n .fromTo('transform', `translateX(${CENTER})`, isRTL ? 'translateX(-100%)' : 'translateX(100%)');\n const leavingPage = getIonPageElement(leavingEl);\n rootAnimation.afterAddWrite(() => {\n if (rootAnimation.getDirection() === 'normal') {\n leavingPage.style.setProperty('display', 'none');\n }\n });\n }\n else {\n // leaving content, forward direction\n leavingContent\n .fromTo('transform', `translateX(${CENTER})`, `translateX(${OFF_LEFT})`)\n .fromTo(OPACITY, 1, OFF_OPACITY);\n }\n if (leavingContentEl) {\n const leavingTransitionEffectEl = shadow(leavingContentEl).querySelector('.transition-effect');\n if (leavingTransitionEffectEl) {\n const leavingTransitionCoverEl = leavingTransitionEffectEl.querySelector('.transition-cover');\n const leavingTransitionShadowEl = leavingTransitionEffectEl.querySelector('.transition-shadow');\n const leavingTransitionEffect = createAnimation();\n const leavingTransitionCover = createAnimation();\n const leavingTransitionShadow = createAnimation();\n leavingTransitionEffect\n .addElement(leavingTransitionEffectEl)\n .beforeStyles({ opacity: '1', display: 'block' })\n .afterStyles({ opacity: '', display: '' });\n leavingTransitionCover\n .addElement(leavingTransitionCoverEl) // REVIEW\n .beforeClearStyles([OPACITY])\n .fromTo(OPACITY, 0.1, 0);\n leavingTransitionShadow\n .addElement(leavingTransitionShadowEl) // REVIEW\n .beforeClearStyles([OPACITY])\n .fromTo(OPACITY, 0.7, 0.03);\n leavingTransitionEffect.addAnimation([leavingTransitionCover, leavingTransitionShadow]);\n leavingContent.addAnimation([leavingTransitionEffect]);\n }\n }\n leavingToolBarEls.forEach((leavingToolBarEl) => {\n const leavingToolBar = createAnimation();\n leavingToolBar.addElement(leavingToolBarEl);\n const leavingTitle = createAnimation();\n leavingTitle.addElement(leavingToolBarEl.querySelector('ion-title')); // REVIEW\n const leavingToolBarButtons = createAnimation();\n const buttons = leavingToolBarEl.querySelectorAll('ion-buttons,[menuToggle]');\n const parentHeader = leavingToolBarEl.closest('ion-header');\n const inactiveHeader = parentHeader === null || parentHeader === void 0 ? void 0 : parentHeader.classList.contains('header-collapse-condense-inactive');\n const buttonsToAnimate = Array.from(buttons).filter((button) => {\n const isCollapseButton = button.classList.contains('buttons-collapse');\n return (isCollapseButton && !inactiveHeader) || !isCollapseButton;\n });\n leavingToolBarButtons.addElement(buttonsToAnimate);\n const leavingToolBarItems = createAnimation();\n const leavingToolBarItemEls = leavingToolBarEl.querySelectorAll(':scope > *:not(ion-title):not(ion-buttons):not([menuToggle])');\n if (leavingToolBarItemEls.length > 0) {\n leavingToolBarItems.addElement(leavingToolBarItemEls);\n }\n const leavingToolBarBg = createAnimation();\n leavingToolBarBg.addElement(shadow(leavingToolBarEl).querySelector('.toolbar-background')); // REVIEW\n const leavingBackButton = createAnimation();\n const backButtonEl = leavingToolBarEl.querySelector('ion-back-button');\n if (backButtonEl) {\n leavingBackButton.addElement(backButtonEl);\n }\n leavingToolBar.addAnimation([\n leavingTitle,\n leavingToolBarButtons,\n leavingToolBarItems,\n leavingBackButton,\n leavingToolBarBg,\n ]);\n rootAnimation.addAnimation(leavingToolBar);\n // fade out leaving toolbar items\n leavingBackButton.fromTo(OPACITY, 0.99, 0);\n leavingToolBarButtons.fromTo(OPACITY, 0.99, 0);\n leavingToolBarItems.fromTo(OPACITY, 0.99, 0);\n if (backDirection) {\n if (!inactiveHeader) {\n // leaving toolbar, back direction\n leavingTitle\n .fromTo('transform', `translateX(${CENTER})`, isRTL ? 'translateX(-100%)' : 'translateX(100%)')\n .fromTo(OPACITY, 0.99, 0);\n }\n leavingToolBarItems.fromTo('transform', `translateX(${CENTER})`, isRTL ? 'translateX(-100%)' : 'translateX(100%)');\n leavingToolBarBg.beforeClearStyles([OPACITY, 'transform']);\n // leaving toolbar, back direction, and there's no entering toolbar\n // should just slide out, no fading out\n const translucentHeader = parentHeader === null || parentHeader === void 0 ? void 0 : parentHeader.translucent;\n if (!translucentHeader) {\n leavingToolBarBg.fromTo(OPACITY, 'var(--opacity)', 0);\n }\n else {\n leavingToolBarBg.fromTo('transform', 'translateX(0px)', isRTL ? 'translateX(-100%)' : 'translateX(100%)');\n }\n if (backButtonEl && !backward) {\n const leavingBackBtnText = createAnimation();\n leavingBackBtnText\n .addElement(shadow(backButtonEl).querySelector('.button-text')) // REVIEW\n .fromTo('transform', `translateX(${CENTER})`, `translateX(${(isRTL ? -124 : 124) + 'px'})`);\n leavingToolBar.addAnimation(leavingBackBtnText);\n }\n }\n else {\n // leaving toolbar, forward direction\n if (!inactiveHeader) {\n leavingTitle\n .fromTo('transform', `translateX(${CENTER})`, `translateX(${OFF_LEFT})`)\n .fromTo(OPACITY, 0.99, 0)\n .afterClearStyles([TRANSFORM, OPACITY]);\n }\n leavingToolBarItems\n .fromTo('transform', `translateX(${CENTER})`, `translateX(${OFF_LEFT})`)\n .afterClearStyles([TRANSFORM, OPACITY]);\n leavingBackButton.afterClearStyles([OPACITY]);\n leavingTitle.afterClearStyles([OPACITY]);\n leavingToolBarButtons.afterClearStyles([OPACITY]);\n }\n });\n }\n return rootAnimation;\n }\n catch (err) {\n throw err;\n }\n};\n/**\n * The scale of the back button during the animation\n * is computed based on the scale of the large title\n * and vice versa. However, we need to account for slight\n * variations in the size of the large title due to\n * padding and font weight. This value should be used to subtract\n * a small amount from the large title height when computing scales\n * to get more accurate scale results.\n */\nconst LARGE_TITLE_SIZE_OFFSET = 10;\n\nexport { iosTransitionAnimation, shadow };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nimport { c as createAnimation } from './animation-8aa13916.js';\nimport { g as getIonPageElement } from './index-6a0ccabb.js';\nimport './index-7a14ecec.js';\nimport './helpers-3379ba19.js';\nimport './index-7c9b1bca.js';\n\nconst mdTransitionAnimation = (_, opts) => {\n var _a, _b, _c;\n const OFF_BOTTOM = '40px';\n const CENTER = '0px';\n const backDirection = opts.direction === 'back';\n const enteringEl = opts.enteringEl;\n const leavingEl = opts.leavingEl;\n const ionPageElement = getIonPageElement(enteringEl);\n const enteringToolbarEle = ionPageElement.querySelector('ion-toolbar');\n const rootTransition = createAnimation();\n rootTransition.addElement(ionPageElement).fill('both').beforeRemoveClass('ion-page-invisible');\n // animate the component itself\n if (backDirection) {\n rootTransition.duration(((_a = opts.duration) !== null && _a !== void 0 ? _a : 0) || 200).easing('cubic-bezier(0.47,0,0.745,0.715)');\n }\n else {\n rootTransition\n .duration(((_b = opts.duration) !== null && _b !== void 0 ? _b : 0) || 280)\n .easing('cubic-bezier(0.36,0.66,0.04,1)')\n .fromTo('transform', `translateY(${OFF_BOTTOM})`, `translateY(${CENTER})`)\n .fromTo('opacity', 0.01, 1);\n }\n // Animate toolbar if it's there\n if (enteringToolbarEle) {\n const enteringToolBar = createAnimation();\n enteringToolBar.addElement(enteringToolbarEle);\n rootTransition.addAnimation(enteringToolBar);\n }\n // setup leaving view\n if (leavingEl && backDirection) {\n // leaving content\n rootTransition.duration(((_c = opts.duration) !== null && _c !== void 0 ? _c : 0) || 200).easing('cubic-bezier(0.47,0,0.745,0.715)');\n const leavingPage = createAnimation();\n leavingPage\n .addElement(getIonPageElement(leavingEl))\n .onFinish((currentStep) => {\n if (currentStep === 1 && leavingPage.elements.length > 0) {\n leavingPage.elements[0].style.setProperty('display', 'none');\n }\n })\n .fromTo('transform', `translateY(${CENTER})`, `translateY(${OFF_BOTTOM})`)\n .fromTo('opacity', 1, 0);\n rootTransition.addAnimation(leavingPage);\n }\n return rootTransition;\n};\n\nexport { mdTransitionAnimation };\n","/*!\n * (C) Ionic http://ionicframework.com - MIT License\n */\nimport { d as doc } from './index-7a14ecec.js';\nimport { b as getIonMode, c as config } from './ionic-global-40e42e7f.js';\nimport { C as CoreDelegate } from './framework-delegate-aa433dea.js';\nimport { OVERLAY_BACK_BUTTON_PRIORITY } from './hardware-back-button-39299f84.js';\nimport { c as componentOnReady, f as focusElement, a as addEventListener, b as removeEventListener, g as getElementRoot } from './helpers-3379ba19.js';\nimport { p as printIonWarning } from './index-595d62c9.js';\n\nlet lastOverlayIndex = 0;\nlet lastId = 0;\nconst activeAnimations = new WeakMap();\nconst createController = (tagName) => {\n return {\n create(options) {\n return createOverlay(tagName, options);\n },\n dismiss(data, role, id) {\n return dismissOverlay(document, data, role, tagName, id);\n },\n async getTop() {\n return getPresentedOverlay(document, tagName);\n },\n };\n};\nconst alertController = /*@__PURE__*/ createController('ion-alert');\nconst actionSheetController = /*@__PURE__*/ createController('ion-action-sheet');\nconst loadingController = /*@__PURE__*/ createController('ion-loading');\nconst modalController = /*@__PURE__*/ createController('ion-modal');\nconst pickerController = /*@__PURE__*/ createController('ion-picker');\nconst popoverController = /*@__PURE__*/ createController('ion-popover');\nconst toastController = /*@__PURE__*/ createController('ion-toast');\n/**\n * Prepares the overlay element to be presented.\n */\nconst prepareOverlay = (el) => {\n if (typeof document !== 'undefined') {\n /**\n * Adds a single instance of event listeners for application behaviors:\n *\n * - Escape Key behavior to dismiss an overlay\n * - Trapping focus within an overlay\n * - Back button behavior to dismiss an overlay\n *\n * This only occurs when the first overlay is created.\n */\n connectListeners(document);\n }\n const overlayIndex = lastOverlayIndex++;\n /**\n * overlayIndex is used in the overlay components to set a zIndex.\n * This ensures that the most recently presented overlay will be\n * on top.\n */\n el.overlayIndex = overlayIndex;\n};\n/**\n * Assigns an incrementing id to an overlay element, that does not\n * already have an id assigned to it.\n *\n * Used to track unique instances of an overlay element.\n */\nconst setOverlayId = (el) => {\n if (!el.hasAttribute('id')) {\n el.id = `ion-overlay-${++lastId}`;\n }\n return el.id;\n};\nconst createOverlay = (tagName, opts) => {\n // eslint-disable-next-line @typescript-eslint/prefer-optional-chain\n if (typeof window !== 'undefined' && typeof window.customElements !== 'undefined') {\n return window.customElements.whenDefined(tagName).then(() => {\n const element = document.createElement(tagName);\n element.classList.add('overlay-hidden');\n /**\n * Convert the passed in overlay options into props\n * that get passed down into the new overlay.\n */\n Object.assign(element, Object.assign(Object.assign({}, opts), { hasController: true }));\n // append the overlay element to the document body\n getAppRoot(document).appendChild(element);\n return new Promise((resolve) => componentOnReady(element, resolve));\n });\n }\n return Promise.resolve();\n};\n/**\n * This query string selects elements that\n * are eligible to receive focus. We select\n * interactive elements that meet the following\n * criteria:\n * 1. Element does not have a negative tabindex\n * 2. Element does not have `hidden`\n * 3. Element does not have `disabled` for non-Ionic components.\n * 4. Element does not have `disabled` or `disabled=\"true\"` for Ionic components.\n * Note: We need this distinction because `disabled=\"false\"` is\n * valid usage for the disabled property on ion-button.\n */\nconst focusableQueryString = '[tabindex]:not([tabindex^=\"-\"]):not([hidden]):not([disabled]), input:not([type=hidden]):not([tabindex^=\"-\"]):not([hidden]):not([disabled]), textarea:not([tabindex^=\"-\"]):not([hidden]):not([disabled]), button:not([tabindex^=\"-\"]):not([hidden]):not([disabled]), select:not([tabindex^=\"-\"]):not([hidden]):not([disabled]), .ion-focusable:not([tabindex^=\"-\"]):not([hidden]):not([disabled]), .ion-focusable[disabled=\"false\"]:not([tabindex^=\"-\"]):not([hidden])';\nconst focusFirstDescendant = (ref, overlay) => {\n let firstInput = ref.querySelector(focusableQueryString);\n const shadowRoot = firstInput === null || firstInput === void 0 ? void 0 : firstInput.shadowRoot;\n if (shadowRoot) {\n // If there are no inner focusable elements, just focus the host element.\n firstInput = shadowRoot.querySelector(focusableQueryString) || firstInput;\n }\n if (firstInput) {\n focusElement(firstInput);\n }\n else {\n // Focus overlay instead of letting focus escape\n overlay.focus();\n }\n};\nconst isOverlayHidden = (overlay) => overlay.classList.contains('overlay-hidden');\nconst focusLastDescendant = (ref, overlay) => {\n const inputs = Array.from(ref.querySelectorAll(focusableQueryString));\n let lastInput = inputs.length > 0 ? inputs[inputs.length - 1] : null;\n const shadowRoot = lastInput === null || lastInput === void 0 ? void 0 : lastInput.shadowRoot;\n if (shadowRoot) {\n // If there are no inner focusable elements, just focus the host element.\n lastInput = shadowRoot.querySelector(focusableQueryString) || lastInput;\n }\n if (lastInput) {\n lastInput.focus();\n }\n else {\n // Focus overlay instead of letting focus escape\n overlay.focus();\n }\n};\n/**\n * Traps keyboard focus inside of overlay components.\n * Based on https://w3c.github.io/aria-practices/examples/dialog-modal/alertdialog.html\n * This includes the following components: Action Sheet, Alert, Loading, Modal,\n * Picker, and Popover.\n * Should NOT include: Toast\n */\nconst trapKeyboardFocus = (ev, doc) => {\n const lastOverlay = getPresentedOverlay(doc, 'ion-alert,ion-action-sheet,ion-loading,ion-modal,ion-picker,ion-popover');\n const target = ev.target;\n /**\n * If no active overlay, ignore this event.\n *\n * If this component uses the shadow dom,\n * this global listener is pointless\n * since it will not catch the focus\n * traps as they are inside the shadow root.\n * We need to add a listener to the shadow root\n * itself to ensure the focus trap works.\n */\n if (!lastOverlay || !target) {\n return;\n }\n /**\n * If the ion-disable-focus-trap class\n * is present on an overlay, then this component\n * instance has opted out of focus trapping.\n * An example of this is when the sheet modal\n * has a backdrop that is disabled. The content\n * behind the sheet should be focusable until\n * the backdrop is enabled.\n */\n if (lastOverlay.classList.contains('ion-disable-focus-trap')) {\n return;\n }\n const trapScopedFocus = () => {\n /**\n * If we are focusing the overlay, clear\n * the last focused element so that hitting\n * tab activates the first focusable element\n * in the overlay wrapper.\n */\n if (lastOverlay === target) {\n lastOverlay.lastFocus = undefined;\n /**\n * Otherwise, we must be focusing an element\n * inside of the overlay. The two possible options\n * here are an input/button/etc or the ion-focus-trap\n * element. The focus trap element is used to prevent\n * the keyboard focus from leaving the overlay when\n * using Tab or screen assistants.\n */\n }\n else {\n /**\n * We do not want to focus the traps, so get the overlay\n * wrapper element as the traps live outside of the wrapper.\n */\n const overlayRoot = getElementRoot(lastOverlay);\n if (!overlayRoot.contains(target)) {\n return;\n }\n const overlayWrapper = overlayRoot.querySelector('.ion-overlay-wrapper');\n if (!overlayWrapper) {\n return;\n }\n /**\n * If the target is inside the wrapper, let the browser\n * focus as normal and keep a log of the last focused element.\n * Additionally, if the backdrop was tapped we should not\n * move focus back inside the wrapper as that could cause\n * an interactive elements focus state to activate.\n */\n if (overlayWrapper.contains(target) || target === overlayRoot.querySelector('ion-backdrop')) {\n lastOverlay.lastFocus = target;\n }\n else {\n /**\n * Otherwise, we must have focused one of the focus traps.\n * We need to wrap the focus to either the first element\n * or the last element.\n */\n /**\n * Once we call `focusFirstDescendant` and focus the first\n * descendant, another focus event will fire which will\n * cause `lastOverlay.lastFocus` to be updated before\n * we can run the code after that. We will cache the value\n * here to avoid that.\n */\n const lastFocus = lastOverlay.lastFocus;\n // Focus the first element in the overlay wrapper\n focusFirstDescendant(overlayWrapper, lastOverlay);\n /**\n * If the cached last focused element is the\n * same as the active element, then we need\n * to wrap focus to the last descendant. This happens\n * when the first descendant is focused, and the user\n * presses Shift + Tab. The previous line will focus\n * the same descendant again (the first one), causing\n * last focus to equal the active element.\n */\n if (lastFocus === doc.activeElement) {\n focusLastDescendant(overlayWrapper, lastOverlay);\n }\n lastOverlay.lastFocus = doc.activeElement;\n }\n }\n };\n const trapShadowFocus = () => {\n /**\n * If the target is inside the wrapper, let the browser\n * focus as normal and keep a log of the last focused element.\n */\n if (lastOverlay.contains(target)) {\n lastOverlay.lastFocus = target;\n }\n else {\n /**\n * Otherwise, we are about to have focus\n * go out of the overlay. We need to wrap\n * the focus to either the first element\n * or the last element.\n */\n /**\n * Once we call `focusFirstDescendant` and focus the first\n * descendant, another focus event will fire which will\n * cause `lastOverlay.lastFocus` to be updated before\n * we can run the code after that. We will cache the value\n * here to avoid that.\n */\n const lastFocus = lastOverlay.lastFocus;\n // Focus the first element in the overlay wrapper\n focusFirstDescendant(lastOverlay, lastOverlay);\n /**\n * If the cached last focused element is the\n * same as the active element, then we need\n * to wrap focus to the last descendant. This happens\n * when the first descendant is focused, and the user\n * presses Shift + Tab. The previous line will focus\n * the same descendant again (the first one), causing\n * last focus to equal the active element.\n */\n if (lastFocus === doc.activeElement) {\n focusLastDescendant(lastOverlay, lastOverlay);\n }\n lastOverlay.lastFocus = doc.activeElement;\n }\n };\n if (lastOverlay.shadowRoot) {\n trapShadowFocus();\n }\n else {\n trapScopedFocus();\n }\n};\nconst connectListeners = (doc) => {\n if (lastOverlayIndex === 0) {\n lastOverlayIndex = 1;\n doc.addEventListener('focus', (ev) => {\n trapKeyboardFocus(ev, doc);\n }, true);\n // handle back-button click\n doc.addEventListener('ionBackButton', (ev) => {\n const lastOverlay = getPresentedOverlay(doc);\n if (lastOverlay === null || lastOverlay === void 0 ? void 0 : lastOverlay.backdropDismiss) {\n ev.detail.register(OVERLAY_BACK_BUTTON_PRIORITY, () => {\n return lastOverlay.dismiss(undefined, BACKDROP);\n });\n }\n });\n // handle ESC to close overlay\n doc.addEventListener('keydown', (ev) => {\n if (ev.key === 'Escape') {\n const lastOverlay = getPresentedOverlay(doc);\n if (lastOverlay === null || lastOverlay === void 0 ? void 0 : lastOverlay.backdropDismiss) {\n lastOverlay.dismiss(undefined, BACKDROP);\n }\n }\n });\n }\n};\nconst dismissOverlay = (doc, data, role, overlayTag, id) => {\n const overlay = getPresentedOverlay(doc, overlayTag, id);\n if (!overlay) {\n return Promise.reject('overlay does not exist');\n }\n return overlay.dismiss(data, role);\n};\n/**\n * Returns a list of all overlays in the DOM even if they are not presented.\n */\nconst getOverlays = (doc, selector) => {\n if (selector === undefined) {\n selector = 'ion-alert,ion-action-sheet,ion-loading,ion-modal,ion-picker,ion-popover,ion-toast';\n }\n return Array.from(doc.querySelectorAll(selector)).filter((c) => c.overlayIndex > 0);\n};\n/**\n * Returns a list of all presented overlays.\n * Inline overlays can exist in the DOM but not be presented,\n * so there are times when we want to exclude those.\n * @param doc The document to find the element within.\n * @param overlayTag The selector for the overlay, defaults to Ionic overlay components.\n */\nconst getPresentedOverlays = (doc, overlayTag) => {\n return getOverlays(doc, overlayTag).filter((o) => !isOverlayHidden(o));\n};\n/**\n * Returns a presented overlay element.\n * @param doc The document to find the element within.\n * @param overlayTag The selector for the overlay, defaults to Ionic overlay components.\n * @param id The unique identifier for the overlay instance.\n * @returns The overlay element or `undefined` if no overlay element is found.\n */\nconst getPresentedOverlay = (doc, overlayTag, id) => {\n const overlays = getPresentedOverlays(doc, overlayTag);\n return id === undefined ? overlays[overlays.length - 1] : overlays.find((o) => o.id === id);\n};\n/**\n * When an overlay is presented, the main\n * focus is the overlay not the page content.\n * We need to remove the page content from the\n * accessibility tree otherwise when\n * users use \"read screen from top\" gestures with\n * TalkBack and VoiceOver, the screen reader will begin\n * to read the content underneath the overlay.\n *\n * We need a container where all page components\n * exist that is separate from where the overlays\n * are added in the DOM. For most apps, this element\n * is the top most ion-router-outlet. In the event\n * that devs are not using a router,\n * they will need to add the \"ion-view-container-root\"\n * id to the element that contains all of their views.\n *\n * TODO: If Framework supports having multiple top\n * level router outlets we would need to update this.\n * Example: One outlet for side menu and one outlet\n * for main content.\n */\nconst setRootAriaHidden = (hidden = false) => {\n const root = getAppRoot(document);\n const viewContainer = root.querySelector('ion-router-outlet, ion-nav, #ion-view-container-root');\n if (!viewContainer) {\n return;\n }\n if (hidden) {\n viewContainer.setAttribute('aria-hidden', 'true');\n }\n else {\n viewContainer.removeAttribute('aria-hidden');\n }\n};\nconst present = async (overlay, name, iosEnterAnimation, mdEnterAnimation, opts) => {\n var _a, _b;\n if (overlay.presented) {\n return;\n }\n setRootAriaHidden(true);\n overlay.presented = true;\n overlay.willPresent.emit();\n (_a = overlay.willPresentShorthand) === null || _a === void 0 ? void 0 : _a.emit();\n const mode = getIonMode(overlay);\n // get the user's animation fn if one was provided\n const animationBuilder = overlay.enterAnimation\n ? overlay.enterAnimation\n : config.get(name, mode === 'ios' ? iosEnterAnimation : mdEnterAnimation);\n const completed = await overlayAnimation(overlay, animationBuilder, overlay.el, opts);\n if (completed) {\n overlay.didPresent.emit();\n (_b = overlay.didPresentShorthand) === null || _b === void 0 ? void 0 : _b.emit();\n }\n /**\n * When an overlay that steals focus\n * is dismissed, focus should be returned\n * to the element that was focused\n * prior to the overlay opening. Toast\n * does not steal focus and is excluded\n * from returning focus as a result.\n */\n if (overlay.el.tagName !== 'ION-TOAST') {\n focusPreviousElementOnDismiss(overlay.el);\n }\n /**\n * If the focused element is already\n * inside the overlay component then\n * focus should not be moved from that\n * to the overlay container.\n */\n if (overlay.keyboardClose && (document.activeElement === null || !overlay.el.contains(document.activeElement))) {\n overlay.el.focus();\n }\n};\n/**\n * When an overlay component is dismissed,\n * focus should be returned to the element\n * that presented the overlay. Otherwise\n * focus will be set on the body which\n * means that people using screen readers\n * or tabbing will need to re-navigate\n * to where they were before they\n * opened the overlay.\n */\nconst focusPreviousElementOnDismiss = async (overlayEl) => {\n let previousElement = document.activeElement;\n if (!previousElement) {\n return;\n }\n const shadowRoot = previousElement === null || previousElement === void 0 ? void 0 : previousElement.shadowRoot;\n if (shadowRoot) {\n // If there are no inner focusable elements, just focus the host element.\n previousElement = shadowRoot.querySelector(focusableQueryString) || previousElement;\n }\n await overlayEl.onDidDismiss();\n previousElement.focus();\n};\nconst dismiss = async (overlay, data, role, name, iosLeaveAnimation, mdLeaveAnimation, opts) => {\n var _a, _b;\n if (!overlay.presented) {\n return false;\n }\n /**\n * If this is the last visible overlay then\n * we want to re-add the root to the accessibility tree.\n */\n if (doc !== undefined && getPresentedOverlays(doc).length === 1) {\n setRootAriaHidden(false);\n }\n overlay.presented = false;\n try {\n // Overlay contents should not be clickable during dismiss\n overlay.el.style.setProperty('pointer-events', 'none');\n overlay.willDismiss.emit({ data, role });\n (_a = overlay.willDismissShorthand) === null || _a === void 0 ? void 0 : _a.emit({ data, role });\n const mode = getIonMode(overlay);\n const animationBuilder = overlay.leaveAnimation\n ? overlay.leaveAnimation\n : config.get(name, mode === 'ios' ? iosLeaveAnimation : mdLeaveAnimation);\n // If dismissed via gesture, no need to play leaving animation again\n if (role !== GESTURE) {\n await overlayAnimation(overlay, animationBuilder, overlay.el, opts);\n }\n overlay.didDismiss.emit({ data, role });\n (_b = overlay.didDismissShorthand) === null || _b === void 0 ? void 0 : _b.emit({ data, role });\n activeAnimations.delete(overlay);\n /**\n * Make overlay hidden again in case it is being reused.\n * We can safely remove pointer-events: none as\n * overlay-hidden will set display: none.\n */\n overlay.el.classList.add('overlay-hidden');\n overlay.el.style.removeProperty('pointer-events');\n /**\n * Clear any focus trapping references\n * when the overlay is dismissed.\n */\n if (overlay.el.lastFocus !== undefined) {\n overlay.el.lastFocus = undefined;\n }\n }\n catch (err) {\n console.error(err);\n }\n overlay.el.remove();\n return true;\n};\nconst getAppRoot = (doc) => {\n return doc.querySelector('ion-app') || doc.body;\n};\nconst overlayAnimation = async (overlay, animationBuilder, baseEl, opts) => {\n // Make overlay visible in case it's hidden\n baseEl.classList.remove('overlay-hidden');\n const aniRoot = overlay.el;\n const animation = animationBuilder(aniRoot, opts);\n if (!overlay.animated || !config.getBoolean('animated', true)) {\n animation.duration(0);\n }\n if (overlay.keyboardClose) {\n animation.beforeAddWrite(() => {\n const activeElement = baseEl.ownerDocument.activeElement;\n if (activeElement === null || activeElement === void 0 ? void 0 : activeElement.matches('input,ion-input, ion-textarea')) {\n activeElement.blur();\n }\n });\n }\n const activeAni = activeAnimations.get(overlay) || [];\n activeAnimations.set(overlay, [...activeAni, animation]);\n await animation.play();\n return true;\n};\nconst eventMethod = (element, eventName) => {\n let resolve;\n const promise = new Promise((r) => (resolve = r));\n onceEvent(element, eventName, (event) => {\n resolve(event.detail);\n });\n return promise;\n};\nconst onceEvent = (element, eventName, callback) => {\n const handler = (ev) => {\n removeEventListener(element, eventName, handler);\n callback(ev);\n };\n addEventListener(element, eventName, handler);\n};\nconst isCancel = (role) => {\n return role === 'cancel' || role === BACKDROP;\n};\nconst defaultGate = (h) => h();\n/**\n * Calls a developer provided method while avoiding\n * Angular Zones. Since the handler is provided by\n * the developer, we should throw any errors\n * received so that developer-provided bug\n * tracking software can log it.\n */\nconst safeCall = (handler, arg) => {\n if (typeof handler === 'function') {\n const jmp = config.get('_zoneGate', defaultGate);\n return jmp(() => {\n try {\n return handler(arg);\n }\n catch (e) {\n throw e;\n }\n });\n }\n return undefined;\n};\nconst BACKDROP = 'backdrop';\nconst GESTURE = 'gesture';\n/**\n * Creates a delegate controller.\n *\n * Requires that the component has the following properties:\n * - `el: HTMLElement`\n * - `hasController: boolean`\n * - `delegate?: FrameworkDelegate`\n *\n * @param ref The component class instance.\n */\nconst createDelegateController = (ref) => {\n let inline = false;\n let workingDelegate;\n const coreDelegate = CoreDelegate();\n /**\n * Determines whether or not an overlay is being used\n * inline or via a controller/JS and returns the correct delegate.\n * By default, subsequent calls to getDelegate will use\n * a cached version of the delegate.\n * This is useful for calling dismiss after present,\n * so that the correct delegate is given.\n * @param force `true` to force the non-cached version of the delegate.\n * @returns The delegate to use and whether or not the overlay is inline.\n */\n const getDelegate = (force = false) => {\n if (workingDelegate && !force) {\n return {\n delegate: workingDelegate,\n inline,\n };\n }\n const { el, hasController, delegate } = ref;\n /**\n * If using overlay inline\n * we potentially need to use the coreDelegate\n * so that this works in vanilla JS apps.\n * If a developer has presented this component\n * via a controller, then we can assume\n * the component is already in the\n * correct place.\n */\n const parentEl = el.parentNode;\n inline = parentEl !== null && !hasController;\n workingDelegate = inline ? delegate || coreDelegate : delegate;\n return { inline, delegate: workingDelegate };\n };\n /**\n * Attaches a component in the DOM. Teleports the component\n * to the root of the app.\n * @param component The component to optionally construct and append to the element.\n */\n const attachViewToDom = async (component) => {\n const { delegate } = getDelegate(true);\n if (delegate) {\n return await delegate.attachViewToDom(ref.el, component);\n }\n const { hasController } = ref;\n if (hasController && component !== undefined) {\n throw new Error('framework delegate is missing');\n }\n return null;\n };\n /**\n * Moves a component back to its original location in the DOM.\n */\n const removeViewFromDom = () => {\n const { delegate } = getDelegate();\n if (delegate && ref.el !== undefined) {\n delegate.removeViewFromDom(ref.el.parentElement, ref.el);\n }\n };\n return {\n attachViewToDom,\n removeViewFromDom,\n };\n};\n/**\n * Constructs a trigger interaction for an overlay.\n * Presents an overlay when the trigger is clicked.\n *\n * Usage:\n * ```ts\n * triggerController = createTriggerController();\n * triggerController.addClickListener(el, trigger);\n * ```\n */\nconst createTriggerController = () => {\n let destroyTriggerInteraction;\n /**\n * Removes the click listener from the trigger element.\n */\n const removeClickListener = () => {\n if (destroyTriggerInteraction) {\n destroyTriggerInteraction();\n destroyTriggerInteraction = undefined;\n }\n };\n /**\n * Adds a click listener to the trigger element.\n * Presents the overlay when the trigger is clicked.\n * @param el The overlay element.\n * @param trigger The ID of the element to add a click listener to.\n */\n const addClickListener = (el, trigger) => {\n removeClickListener();\n const triggerEl = trigger !== undefined ? document.getElementById(trigger) : null;\n if (!triggerEl) {\n printIonWarning(`A trigger element with the ID \"${trigger}\" was not found in the DOM. The trigger element must be in the DOM when the \"trigger\" property is set on an overlay component.`, el);\n return;\n }\n const configureTriggerInteraction = (targetEl, overlayEl) => {\n const openOverlay = () => {\n overlayEl.present();\n };\n targetEl.addEventListener('click', openOverlay);\n return () => {\n targetEl.removeEventListener('click', openOverlay);\n };\n };\n destroyTriggerInteraction = configureTriggerInteraction(triggerEl, el);\n };\n return {\n addClickListener,\n removeClickListener,\n };\n};\n\nexport { BACKDROP as B, GESTURE as G, alertController as a, actionSheetController as b, popoverController as c, createDelegateController as d, createTriggerController as e, present as f, dismiss as g, eventMethod as h, isCancel as i, prepareOverlay as j, setOverlayId as k, loadingController as l, modalController as m, activeAnimations as n, focusFirstDescendant as o, pickerController as p, getPresentedOverlay as q, safeCall as s, toastController as t };\n","import LocalForage from 'localforage';\n/** @hidden */\nexport const Drivers = {\n SecureStorage: 'ionicSecureStorage',\n IndexedDB: LocalForage.INDEXEDDB,\n LocalStorage: LocalForage.LOCALSTORAGE\n};\nconst defaultConfig = {\n name: '_ionicstorage',\n storeName: '_ionickv',\n dbKey: '_ionickey',\n driverOrder: [\n Drivers.SecureStorage,\n Drivers.IndexedDB,\n Drivers.LocalStorage\n ]\n};\nexport class Storage {\n /**\n * Create a new Storage instance using the order of drivers and any additional config\n * options to pass to LocalForage.\n *\n * Possible default driverOrder options are: ['indexeddb', 'localstorage'] and the\n * default is that exact ordering.\n *\n * When using Ionic Secure Storage (enterprise only), use ['ionicSecureStorage', 'indexeddb', 'localstorage'] to ensure\n * Secure Storage is used when available, or fall back to IndexedDB or LocalStorage on the web.\n */\n constructor(config = defaultConfig) {\n this._db = null;\n this._secureStorageDriver = null;\n const actualConfig = Object.assign({}, defaultConfig, config || {});\n this._config = actualConfig;\n }\n async create() {\n const db = LocalForage.createInstance(this._config);\n this._db = db;\n await db.setDriver(this._config.driverOrder || []);\n return this;\n }\n /**\n * Define a new Driver. Must be called before\n * initializing the database. Example:\n *\n * await storage.defineDriver(myDriver);\n * await storage.create();\n */\n async defineDriver(driver) {\n if (driver._driver === Drivers.SecureStorage) {\n this._secureStorageDriver = driver;\n }\n return LocalForage.defineDriver(driver);\n }\n /**\n * Get the name of the driver being used.\n * @returns Name of the driver\n */\n get driver() {\n var _a;\n return ((_a = this._db) === null || _a === void 0 ? void 0 : _a.driver()) || null;\n }\n assertDb() {\n if (!this._db) {\n throw new Error('Database not created. Must call create() first');\n }\n return this._db;\n }\n /**\n * Get the value associated with the given key.\n * @param key the key to identify this value\n * @returns Returns a promise with the value of the given key\n */\n get(key) {\n const db = this.assertDb();\n return db.getItem(key);\n }\n /**\n * Set the value for the given key.\n * @param key the key to identify this value\n * @param value the value for this key\n * @returns Returns a promise that resolves when the key and value are set\n */\n set(key, value) {\n const db = this.assertDb();\n return db.setItem(key, value);\n }\n /**\n * Remove any value associated with this key.\n * @param key the key to identify this value\n * @returns Returns a promise that resolves when the value is removed\n */\n remove(key) {\n const db = this.assertDb();\n return db.removeItem(key);\n }\n /**\n * Clear the entire key value store. WARNING: HOT!\n * @returns Returns a promise that resolves when the store is cleared\n */\n clear() {\n const db = this.assertDb();\n return db.clear();\n }\n /**\n * @returns Returns a promise that resolves with the number of keys stored.\n */\n length() {\n const db = this.assertDb();\n return db.length();\n }\n /**\n * @returns Returns a promise that resolves with the keys in the store.\n */\n keys() {\n const db = this.assertDb();\n return db.keys();\n }\n /**\n * Iterate through each key,value pair.\n * @param iteratorCallback a callback of the form (value, key, iterationNumber)\n * @returns Returns a promise that resolves when the iteration has finished.\n */\n forEach(iteratorCallback) {\n const db = this.assertDb();\n return db.iterate(iteratorCallback);\n }\n setEncryptionKey(key) {\n var _a;\n if (!this._secureStorageDriver) {\n throw new Error('@ionic-enterprise/secure-storage not installed. Encryption support not available');\n }\n else {\n (_a = this._secureStorageDriver) === null || _a === void 0 ? void 0 : _a.setEncryptionKey(key);\n }\n }\n}\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 // @ts-expect-error \"npm\" is injected by rollup during build process\n return \"npm\";\n}\n\nexport { getSDKSource, isBrowserBundle };\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 * 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/explicit-module-boundary-types, @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 * @returns possibly required module\n */\nfunction loadModule(moduleName) {\n let mod;\n\n try {\n mod = dynamicRequire(module, moduleName);\n } catch (e) {\n // no-empty\n }\n\n try {\n const { cwd } = dynamicRequire(module, 'process');\n mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) ;\n } catch (e) {\n // no-empty\n }\n\n return mod;\n}\n\nexport { dynamicRequire, isNodeEnv, loadModule };\n","import { isNodeEnv, dynamicRequire } from './node.js';\nimport { getGlobalObject } from './worldwide.js';\n\n// eslint-disable-next-line deprecation/deprecation\nconst WINDOW = getGlobalObject();\n\n/**\n * An object that can return the current timestamp in seconds since the UNIX epoch.\n */\n\n/**\n * A TimestampSource implementation for environments that do not support the Performance Web API natively.\n *\n * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier\n * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It\n * is more obvious to explain \"why does my span have negative duration\" than \"why my spans have zero duration\".\n */\nconst dateTimestampSource = {\n nowSeconds: () => Date.now() / 1000,\n};\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 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 getBrowserPerformance() {\n const { performance } = WINDOW;\n if (!performance || !performance.now) {\n return undefined;\n }\n\n // Replace performance.timeOrigin with our own timeOrigin based on Date.now().\n //\n // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin +\n // performance.now() gives a date arbitrarily in the past.\n //\n // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is\n // undefined.\n //\n // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to\n // interact with data coming out of performance entries.\n //\n // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that\n // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes\n // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have\n // observed skews that can be as long as days, weeks or months.\n //\n // See https://github.com/getsentry/sentry-javascript/issues/2590.\n //\n // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload\n // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation\n // transactions of long-lived web pages.\n const timeOrigin = Date.now() - performance.now();\n\n return {\n now: () => performance.now(),\n timeOrigin,\n };\n}\n\n/**\n * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't\n * implement the API.\n */\nfunction getNodePerformance() {\n try {\n const perfHooks = dynamicRequire(module, 'perf_hooks') ;\n return perfHooks.performance;\n } catch (_) {\n return undefined;\n }\n}\n\n/**\n * The Performance API implementation for the current platform, if available.\n */\nconst platformPerformance = isNodeEnv() ? getNodePerformance() : getBrowserPerformance();\n\nconst timestampSource =\n platformPerformance === undefined\n ? dateTimestampSource\n : {\n nowSeconds: () => (platformPerformance.timeOrigin + platformPerformance.now()) / 1000,\n };\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nconst dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource);\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 * See `usingPerformanceAPI` to test whether the Performance API is used.\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 = timestampSource.nowSeconds.bind(timestampSource);\n\n/**\n * Re-exported with an old name for backwards-compatibility.\n * TODO (v8): Remove this\n *\n * @deprecated Use `timestampInSeconds` instead.\n */\nconst timestampWithMs = timestampInSeconds;\n\n/**\n * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps.\n */\nconst usingPerformanceAPI = platformPerformance !== undefined;\n\n/**\n * Internal helper to store what is the source of browserPerformanceTimeOrigin below. For debugging only.\n */\nlet _browserPerformanceTimeOriginMode;\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 */\nconst browserPerformanceTimeOrigin = (() => {\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 } = WINDOW;\n if (!performance || !performance.now) {\n _browserPerformanceTimeOriginMode = 'none';\n return undefined;\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 && 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 _browserPerformanceTimeOriginMode = 'timeOrigin';\n return performance.timeOrigin;\n } else {\n _browserPerformanceTimeOriginMode = 'navigationStart';\n return navigationStart;\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n _browserPerformanceTimeOriginMode = 'dateNow';\n return dateNow;\n})();\n\nexport { _browserPerformanceTimeOriginMode, browserPerformanceTimeOrigin, dateTimestampInSeconds, timestampInSeconds, timestampWithMs, usingPerformanceAPI };\n","/** Internal global with common properties and Sentry extensions */\n\n// The code below for 'isGlobalObj' and 'GLOBAL_OBJ' was copied from core-js before modification\n// https://github.com/zloirock/core-js/blob/1b944df55282cdc99c90db5f49eb0b6eda2cc0a3/packages/core-js/internals/global.js\n// core-js has the following licence:\n//\n// Copyright (c) 2014-2022 Denis Pushkarev\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\n/** Returns 'obj' if it's the global object, otherwise returns undefined */\nfunction isGlobalObj(obj) {\n return obj && obj.Math == Math ? obj : undefined;\n}\n\n/** Get's the global object for the current JavaScript runtime */\nconst GLOBAL_OBJ =\n (typeof globalThis == 'object' && isGlobalObj(globalThis)) ||\n // eslint-disable-next-line no-restricted-globals\n (typeof window == 'object' && isGlobalObj(window)) ||\n (typeof self == 'object' && isGlobalObj(self)) ||\n (typeof global == 'object' && isGlobalObj(global)) ||\n (function () {\n return this;\n })() ||\n {};\n\n/**\n * @deprecated Use GLOBAL_OBJ instead or WINDOW from @sentry/browser. This will be removed in v8\n */\nfunction getGlobalObject() {\n return GLOBAL_OBJ ;\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nfunction getGlobalSingleton(name, creator, obj) {\n const gbl = (obj || GLOBAL_OBJ) ;\n const __SENTRY__ = (gbl.__SENTRY__ = gbl.__SENTRY__ || {});\n const singleton = __SENTRY__[name] || (__SENTRY__[name] = creator());\n return singleton;\n}\n\nexport { GLOBAL_OBJ, getGlobalObject, getGlobalSingleton };\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nvar base64 = require('base64-js')\nvar ieee754 = require('ieee754')\nvar customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nvar K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n var arr = new Uint8Array(1)\n var proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n var buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n var valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n var b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(\n value[Symbol.toPrimitive]('string'), encodingOrOffset, length\n )\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n var length = byteLength(string, encoding) | 0\n var buf = createBuffer(length)\n\n var actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n var buf = createBuffer(length)\n for (var i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n var copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n var buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n var len = checked(obj.length) | 0\n var buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n Buffer.from(buf).copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n var len = string.length\n var mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return ''\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n var strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (var i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n var limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n var len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nvar hexSliceLookupTable = (function () {\n var alphabet = '0123456789abcdef'\n var table = new Array(256)\n for (var i = 0; i < 16; ++i) {\n var i16 = i * 16\n for (var j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar callBind = require('./');\n\nvar $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));\n\nmodule.exports = function callBoundIntrinsic(name, allowMissing) {\n\tvar intrinsic = GetIntrinsic(name, !!allowMissing);\n\tif (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {\n\t\treturn callBind(intrinsic);\n\t}\n\treturn intrinsic;\n};\n","'use strict';\n\nvar bind = require('function-bind');\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $apply = GetIntrinsic('%Function.prototype.apply%');\nvar $call = GetIntrinsic('%Function.prototype.call%');\nvar $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);\n\nvar $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);\nvar $defineProperty = GetIntrinsic('%Object.defineProperty%', true);\nvar $max = GetIntrinsic('%Math.max%');\n\nif ($defineProperty) {\n\ttry {\n\t\t$defineProperty({}, 'a', { value: 1 });\n\t} catch (e) {\n\t\t// IE 8 has a broken defineProperty\n\t\t$defineProperty = null;\n\t}\n}\n\nmodule.exports = function callBind(originalFunction) {\n\tvar func = $reflectApply(bind, $call, arguments);\n\tif ($gOPD && $defineProperty) {\n\t\tvar desc = $gOPD(func, 'length');\n\t\tif (desc.configurable) {\n\t\t\t// original length, plus the receiver, minus any additional arguments (after the receiver)\n\t\t\t$defineProperty(\n\t\t\t\tfunc,\n\t\t\t\t'length',\n\t\t\t\t{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }\n\t\t\t);\n\t\t}\n\t}\n\treturn func;\n};\n\nvar applyBind = function applyBind() {\n\treturn $reflectApply(bind, $apply, arguments);\n};\n\nif ($defineProperty) {\n\t$defineProperty(module.exports, 'apply', { value: applyBind });\n} else {\n\tmodule.exports.apply = applyBind;\n}\n","export const semver = /^[v^~<>=]*?(\\d+)(?:\\.([x*]|\\d+)(?:\\.([x*]|\\d+)(?:\\.([x*]|\\d+))?(?:-([\\da-z\\-]+(?:\\.[\\da-z\\-]+)*))?(?:\\+[\\da-z\\-]+(?:\\.[\\da-z\\-]+)*)?)?)?$/i;\nexport const validateAndParse = (version) => {\n if (typeof version !== 'string') {\n throw new TypeError('Invalid argument expected string');\n }\n const match = version.match(semver);\n if (!match) {\n throw new Error(`Invalid argument not valid semver ('${version}' received)`);\n }\n match.shift();\n return match;\n};\nconst isWildcard = (s) => s === '*' || s === 'x' || s === 'X';\nconst tryParse = (v) => {\n const n = parseInt(v, 10);\n return isNaN(n) ? v : n;\n};\nconst forceType = (a, b) => typeof a !== typeof b ? [String(a), String(b)] : [a, b];\nconst compareStrings = (a, b) => {\n if (isWildcard(a) || isWildcard(b))\n return 0;\n const [ap, bp] = forceType(tryParse(a), tryParse(b));\n if (ap > bp)\n return 1;\n if (ap < bp)\n return -1;\n return 0;\n};\nexport const compareSegments = (a, b) => {\n for (let i = 0; i < Math.max(a.length, b.length); i++) {\n const r = compareStrings(a[i] || '0', b[i] || '0');\n if (r !== 0)\n return r;\n }\n return 0;\n};\n","import { compareSegments, validateAndParse } from './utils';\n/**\n * Compare [semver](https://semver.org/) version strings to find greater, equal or lesser.\n * This library supports the full semver specification, including comparing versions with different number of digits like `1.0.0`, `1.0`, `1`, and pre-release versions like `1.0.0-alpha`.\n * @param v1 - First version to compare\n * @param v2 - Second version to compare\n * @returns Numeric value compatible with the [Array.sort(fn) interface](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters).\n */\nexport const compareVersions = (v1, v2) => {\n // validate input and split into segments\n const n1 = validateAndParse(v1);\n const n2 = validateAndParse(v2);\n // pop off the patch\n const p1 = n1.pop();\n const p2 = n2.pop();\n // validate numbers\n const r = compareSegments(n1, n2);\n if (r !== 0)\n return r;\n // validate pre-release\n if (p1 && p2) {\n return compareSegments(p1.split('.'), p2.split('.'));\n }\n else if (p1 || p2) {\n return p1 ? -1 : 1;\n }\n return 0;\n};\n","import copy from 'fast-copy';\nimport qs from 'qs';\nimport isString from 'lodash.isstring';\nimport pThrottle from 'p-throttle';\nimport isPlainObject from 'lodash.isplainobject';\n\nfunction _iterableToArrayLimit(arr, i) {\n var _i = null == arr ? null : \"undefined\" != typeof Symbol && arr[Symbol.iterator] || arr[\"@@iterator\"];\n if (null != _i) {\n var _s,\n _e,\n _x,\n _r,\n _arr = [],\n _n = !0,\n _d = !1;\n try {\n if (_x = (_i = _i.call(arr)).next, 0 === i) {\n if (Object(_i) !== _i) return;\n _n = !1;\n } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);\n } catch (err) {\n _d = !0, _e = err;\n } finally {\n try {\n if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;\n } finally {\n if (_d) throw _e;\n }\n }\n return _arr;\n }\n}\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n enumerableOnly && (symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n })), keys.push.apply(keys, symbols);\n }\n return keys;\n}\nfunction _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = null != arguments[i] ? arguments[i] : {};\n i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n return target;\n}\nfunction _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n return _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && \"function\" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n }, _typeof(obj);\n}\nfunction _wrapRegExp() {\n _wrapRegExp = function (re, groups) {\n return new BabelRegExp(re, void 0, groups);\n };\n var _super = RegExp.prototype,\n _groups = new WeakMap();\n function BabelRegExp(re, flags, groups) {\n var _this = new RegExp(re, flags);\n return _groups.set(_this, groups || _groups.get(re)), _setPrototypeOf(_this, BabelRegExp.prototype);\n }\n function buildGroups(result, re) {\n var g = _groups.get(re);\n return Object.keys(g).reduce(function (groups, name) {\n var i = g[name];\n if (\"number\" == typeof i) groups[name] = result[i];else {\n for (var k = 0; void 0 === result[i[k]] && k + 1 < i.length;) k++;\n groups[name] = result[i[k]];\n }\n return groups;\n }, Object.create(null));\n }\n return _inherits(BabelRegExp, RegExp), BabelRegExp.prototype.exec = function (str) {\n var result = _super.exec.call(this, str);\n if (result) {\n result.groups = buildGroups(result, this);\n var indices = result.indices;\n indices && (indices.groups = buildGroups(indices, this));\n }\n return result;\n }, BabelRegExp.prototype[Symbol.replace] = function (str, substitution) {\n if (\"string\" == typeof substitution) {\n var groups = _groups.get(this);\n return _super[Symbol.replace].call(this, str, substitution.replace(/\\$<([^>]+)>/g, function (_, name) {\n var group = groups[name];\n return \"$\" + (Array.isArray(group) ? group.join(\"$\") : group);\n }));\n }\n if (\"function\" == typeof substitution) {\n var _this = this;\n return _super[Symbol.replace].call(this, str, function () {\n var args = arguments;\n return \"object\" != typeof args[args.length - 1] && (args = [].slice.call(args)).push(buildGroups(args, _this)), substitution.apply(this, args);\n });\n }\n return _super[Symbol.replace].call(this, str, substitution);\n }, _wrapRegExp.apply(this, arguments);\n}\nfunction _defineProperty(obj, key, value) {\n key = _toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n Object.defineProperty(subClass, \"prototype\", {\n writable: false\n });\n if (superClass) _setPrototypeOf(subClass, superClass);\n}\nfunction _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n}\nfunction _slicedToArray(arr, i) {\n return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();\n}\nfunction _arrayWithHoles(arr) {\n if (Array.isArray(arr)) return arr;\n}\nfunction _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n}\nfunction _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n return arr2;\n}\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction _createForOfIteratorHelper(o, allowArrayLike) {\n var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"];\n if (!it) {\n if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") {\n if (it) o = it;\n var i = 0;\n var F = function () {};\n return {\n s: F,\n n: function () {\n if (i >= o.length) return {\n done: true\n };\n return {\n done: false,\n value: o[i++]\n };\n },\n e: function (e) {\n throw e;\n },\n f: F\n };\n }\n throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n }\n var normalCompletion = true,\n didErr = false,\n err;\n return {\n s: function () {\n it = it.call(o);\n },\n n: function () {\n var step = it.next();\n normalCompletion = step.done;\n return step;\n },\n e: function (e) {\n didErr = true;\n err = e;\n },\n f: function () {\n try {\n if (!normalCompletion && it.return != null) it.return();\n } finally {\n if (didErr) throw err;\n }\n }\n };\n}\nfunction _toPrimitive(input, hint) {\n if (typeof input !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (typeof res !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n}\nfunction _toPropertyKey(arg) {\n var key = _toPrimitive(arg, \"string\");\n return typeof key === \"symbol\" ? key : String(key);\n}\n\nfunction isNode() {\n /**\n * Polyfills of 'process' might set process.browser === true\n *\n * See:\n * https://github.com/webpack/node-libs-browser/blob/master/mock/process.js#L8\n * https://github.com/defunctzombie/node-process/blob/master/browser.js#L156\n **/\n return typeof process !== 'undefined' && !process.browser;\n}\nfunction isReactNative() {\n return typeof window !== 'undefined' && 'navigator' in window && 'product' in window.navigator && window.navigator.product === 'ReactNative';\n}\nfunction getNodeVersion() {\n return process.versions && process.versions.node ? \"v\".concat(process.versions.node) : process.version;\n}\nfunction getWindow() {\n return window;\n}\nfunction noop() {\n return undefined;\n}\n\nvar PERCENTAGE_REGEX = /*#__PURE__*/_wrapRegExp(/(\\d+)(%)/, {\n value: 1\n});\nfunction calculateLimit(type) {\n var max = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 7;\n var limit = max;\n if (PERCENTAGE_REGEX.test(type)) {\n var _type$match;\n var groups = (_type$match = type.match(PERCENTAGE_REGEX)) === null || _type$match === void 0 ? void 0 : _type$match.groups;\n if (groups && groups.value) {\n var percentage = parseInt(groups.value) / 100;\n limit = Math.round(max * percentage);\n }\n }\n return Math.min(30, Math.max(1, limit));\n}\nfunction createThrottle(limit, logger) {\n logger('info', \"Throttle request to \".concat(limit, \"/s\"));\n return pThrottle({\n limit: limit,\n interval: 1000,\n strict: false\n });\n}\nvar rateLimitThrottle = (function (axiosInstance) {\n var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'auto';\n var _axiosInstance$defaul = axiosInstance.defaults.logHandler,\n logHandler = _axiosInstance$defaul === void 0 ? noop : _axiosInstance$defaul;\n var limit = isString(type) ? calculateLimit(type) : calculateLimit('auto', type);\n var throttle = createThrottle(limit, logHandler);\n var isCalculated = false;\n var requestInterceptorId = axiosInstance.interceptors.request.use(function (config) {\n return throttle(function () {\n return config;\n })();\n }, function (error) {\n return Promise.reject(error);\n });\n var responseInterceptorId = axiosInstance.interceptors.response.use(function (response) {\n if (!isCalculated && isString(type) && (type === 'auto' || PERCENTAGE_REGEX.test(type)) && response.headers && response.headers['x-contentful-ratelimit-second-limit']) {\n var rawLimit = parseInt(response.headers['x-contentful-ratelimit-second-limit']);\n var nextLimit = calculateLimit(type, rawLimit);\n if (nextLimit !== limit) {\n if (requestInterceptorId) {\n axiosInstance.interceptors.request.eject(requestInterceptorId);\n }\n limit = nextLimit;\n throttle = createThrottle(nextLimit, logHandler);\n requestInterceptorId = axiosInstance.interceptors.request.use(function (config) {\n return throttle(function () {\n return config;\n })();\n }, function (error) {\n return Promise.reject(error);\n });\n }\n isCalculated = true;\n }\n return response;\n }, function (error) {\n return Promise.reject(error);\n });\n return function () {\n axiosInstance.interceptors.request.eject(requestInterceptorId);\n axiosInstance.interceptors.response.eject(responseInterceptorId);\n };\n});\n\nvar delay = function delay(ms) {\n return new Promise(function (resolve) {\n setTimeout(resolve, ms);\n });\n};\nvar defaultWait = function defaultWait(attempts) {\n return Math.pow(Math.SQRT2, attempts);\n};\nfunction rateLimit(instance) {\n var maxRetry = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 5;\n var _instance$defaults = instance.defaults,\n _instance$defaults$re = _instance$defaults.responseLogger,\n responseLogger = _instance$defaults$re === void 0 ? noop : _instance$defaults$re,\n _instance$defaults$re2 = _instance$defaults.requestLogger,\n requestLogger = _instance$defaults$re2 === void 0 ? noop : _instance$defaults$re2;\n instance.interceptors.request.use(function (config) {\n requestLogger(config);\n return config;\n }, function (error) {\n requestLogger(error);\n return Promise.reject(error);\n });\n instance.interceptors.response.use(function (response) {\n // we don't need to do anything here\n responseLogger(response);\n return response;\n }, function (error) {\n var response = error.response;\n var config = error.config;\n responseLogger(error);\n // Do not retry if it is disabled or no request config exists (not an axios error)\n if (!config || !instance.defaults.retryOnError) {\n return Promise.reject(error);\n }\n\n // Retried already for max attempts\n var doneAttempts = config.attempts || 1;\n if (doneAttempts > maxRetry) {\n error.attempts = config.attempts;\n return Promise.reject(error);\n }\n var retryErrorType = null;\n var wait = defaultWait(doneAttempts);\n\n // Errors without response did not receive anything from the server\n if (!response) {\n retryErrorType = 'Connection';\n } else if (response.status >= 500 && response.status < 600) {\n // 5** errors are server related\n retryErrorType = \"Server \".concat(response.status);\n } else if (response.status === 429) {\n // 429 errors are exceeded rate limit exceptions\n retryErrorType = 'Rate limit';\n // all headers are lowercased by axios https://github.com/mzabriskie/axios/issues/413\n if (response.headers && error.response.headers['x-contentful-ratelimit-reset']) {\n wait = response.headers['x-contentful-ratelimit-reset'];\n }\n }\n if (retryErrorType) {\n // convert to ms and add jitter\n wait = Math.floor(wait * 1000 + Math.random() * 200 + 500);\n instance.defaults.logHandler('warning', \"\".concat(retryErrorType, \" error occurred. Waiting for \").concat(wait, \" ms before retrying...\"));\n\n // increase attempts counter\n config.attempts = doneAttempts + 1;\n\n /* Somehow between the interceptor and retrying the request the httpAgent/httpsAgent gets transformed from an Agent-like object\n to a regular object, causing failures on retries after rate limits. Removing these properties here fixes the error, but retry\n requests still use the original http/httpsAgent property */\n delete config.httpAgent;\n delete config.httpsAgent;\n return delay(wait).then(function () {\n return instance(config);\n });\n }\n return Promise.reject(error);\n });\n}\n\nfunction asyncToken(instance, getToken) {\n instance.interceptors.request.use(function (config) {\n return getToken().then(function (accessToken) {\n config.headers = _objectSpread2(_objectSpread2({}, config.headers), {}, {\n Authorization: \"Bearer \".concat(accessToken)\n });\n return config;\n });\n });\n}\n\n// Matches 'sub.host:port' or 'host:port' and extracts hostname and port\n// Also enforces toplevel domain specified, no spaces and no protocol\nvar HOST_REGEX = /^(?!\\w+:\\/\\/)([^\\s:]+\\.?[^\\s:]+)(?::(\\d+))?(?!:)$/;\n\n/**\n * Create pre configured axios instance\n * @private\n * @param {AxiosStatic} axios - Axios library\n * @param {CreateHttpClientParams} options - Initialization parameters for the HTTP client\n * @return {ContentfulAxiosInstance} Initialized axios instance\n */\nfunction createHttpClient(axios, options) {\n var defaultConfig = {\n insecure: false,\n retryOnError: true,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n logHandler: function logHandler(level, data) {\n if (level === 'error' && data) {\n var title = [data.name, data.message].filter(function (a) {\n return a;\n }).join(' - ');\n console.error(\"[error] \".concat(title));\n console.error(data);\n return;\n }\n console.log(\"[\".concat(level, \"] \").concat(data));\n },\n // Passed to axios\n headers: {},\n httpAgent: false,\n httpsAgent: false,\n timeout: 30000,\n throttle: 0,\n proxy: false,\n basePath: '',\n adapter: undefined,\n maxContentLength: 1073741824,\n // 1GB\n maxBodyLength: 1073741824 // 1GB\n };\n\n var config = _objectSpread2(_objectSpread2({}, defaultConfig), options);\n if (!config.accessToken) {\n var missingAccessTokenError = new TypeError('Expected parameter accessToken');\n config.logHandler('error', missingAccessTokenError);\n throw missingAccessTokenError;\n }\n\n // Construct axios baseURL option\n var protocol = config.insecure ? 'http' : 'https';\n var space = config.space ? \"\".concat(config.space, \"/\") : '';\n var hostname = config.defaultHostname;\n var port = config.insecure ? 80 : 443;\n if (config.host && HOST_REGEX.test(config.host)) {\n var parsed = config.host.split(':');\n if (parsed.length === 2) {\n var _parsed = _slicedToArray(parsed, 2);\n hostname = _parsed[0];\n port = _parsed[1];\n } else {\n hostname = parsed[0];\n }\n }\n\n // Ensure that basePath does start but not end with a slash\n if (config.basePath) {\n config.basePath = \"/\".concat(config.basePath.split('/').filter(Boolean).join('/'));\n }\n var baseURL = options.baseURL || \"\".concat(protocol, \"://\").concat(hostname, \":\").concat(port).concat(config.basePath, \"/spaces/\").concat(space);\n if (!config.headers.Authorization && typeof config.accessToken !== 'function') {\n config.headers.Authorization = 'Bearer ' + config.accessToken;\n }\n var axiosOptions = {\n // Axios\n baseURL: baseURL,\n headers: config.headers,\n httpAgent: config.httpAgent,\n httpsAgent: config.httpsAgent,\n paramsSerializer: qs.stringify,\n proxy: config.proxy,\n timeout: config.timeout,\n adapter: config.adapter,\n maxContentLength: config.maxContentLength,\n maxBodyLength: config.maxBodyLength,\n // Contentful\n logHandler: config.logHandler,\n responseLogger: config.responseLogger,\n requestLogger: config.requestLogger,\n retryOnError: config.retryOnError\n };\n var instance = axios.create(axiosOptions);\n instance.httpClientParams = options;\n\n /**\n * Creates a new axios instance with the same default base parameters as the\n * current one, and with any overrides passed to the newParams object\n * This is useful as the SDKs use dependency injection to get the axios library\n * and the version of the library comes from different places depending\n * on whether it's a browser build or a node.js build.\n * @private\n * @param {CreateHttpClientParams} httpClientParams - Initialization parameters for the HTTP client\n * @return {ContentfulAxiosInstance} Initialized axios instance\n */\n instance.cloneWithNewParams = function (newParams) {\n return createHttpClient(axios, _objectSpread2(_objectSpread2({}, copy(options)), newParams));\n };\n\n /**\n * Apply interceptors.\n * Please note that the order of interceptors is important\n */\n\n if (config.onBeforeRequest) {\n instance.interceptors.request.use(config.onBeforeRequest);\n }\n if (typeof config.accessToken === 'function') {\n asyncToken(instance, config.accessToken);\n }\n if (config.throttle) {\n rateLimitThrottle(instance, config.throttle);\n }\n rateLimit(instance, config.retryLimit);\n if (config.onError) {\n instance.interceptors.response.use(function (response) {\n return response;\n }, config.onError);\n }\n return instance;\n}\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/**\n * Creates request parameters configuration by parsing an existing query object\n * @private\n * @param {Object} query\n * @return {Object} Config object with `params` property, ready to be used in axios\n */\nfunction createRequestConfig(_ref) {\n var query = _ref.query;\n var config = {};\n delete query.resolveLinks;\n config.params = copy(query);\n return config;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction enforceObjPath(obj, path) {\n if (!(path in obj)) {\n var err = new Error();\n err.name = 'PropertyMissing';\n err.message = \"Required property \".concat(path, \" missing from:\\n\\n\").concat(JSON.stringify(obj), \"\\n\\n\");\n throw err;\n }\n return true;\n}\n\n// copied from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze\n\nfunction deepFreeze(object) {\n var propNames = Object.getOwnPropertyNames(object);\n var _iterator = _createForOfIteratorHelper(propNames),\n _step;\n try {\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n var name = _step.value;\n var value = object[name];\n if (value && _typeof(value) === 'object') {\n deepFreeze(value);\n }\n }\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n return Object.freeze(object);\n}\nfunction freezeSys(obj) {\n deepFreeze(obj.sys || {});\n return obj;\n}\n\nfunction getBrowserOS() {\n var win = getWindow();\n if (!win) {\n return null;\n }\n var userAgent = win.navigator.userAgent;\n // TODO: platform is deprecated.\n var platform = win.navigator.platform;\n var macosPlatforms = ['Macintosh', 'MacIntel', 'MacPPC', 'Mac68K'];\n var windowsPlatforms = ['Win32', 'Win64', 'Windows', 'WinCE'];\n var iosPlatforms = ['iPhone', 'iPad', 'iPod'];\n if (macosPlatforms.indexOf(platform) !== -1) {\n return 'macOS';\n } else if (iosPlatforms.indexOf(platform) !== -1) {\n return 'iOS';\n } else if (windowsPlatforms.indexOf(platform) !== -1) {\n return 'Windows';\n } else if (/Android/.test(userAgent)) {\n return 'Android';\n } else if (/Linux/.test(platform)) {\n return 'Linux';\n }\n return null;\n}\nfunction getNodeOS() {\n var platform = process.platform || 'linux';\n var version = process.version || '0.0.0';\n var platformMap = {\n android: 'Android',\n aix: 'Linux',\n darwin: 'macOS',\n freebsd: 'Linux',\n linux: 'Linux',\n openbsd: 'Linux',\n sunos: 'Linux',\n win32: 'Windows'\n };\n if (platform in platformMap) {\n return \"\".concat(platformMap[platform] || 'Linux', \"/\").concat(version);\n }\n return null;\n}\nfunction getUserAgentHeader(sdk, application, integration, feature) {\n var headerParts = [];\n if (application) {\n headerParts.push(\"app \".concat(application));\n }\n if (integration) {\n headerParts.push(\"integration \".concat(integration));\n }\n if (feature) {\n headerParts.push('feature ' + feature);\n }\n headerParts.push(\"sdk \".concat(sdk));\n var platform = null;\n try {\n if (isReactNative()) {\n platform = getBrowserOS();\n headerParts.push('platform ReactNative');\n } else if (isNode()) {\n platform = getNodeOS();\n headerParts.push(\"platform node.js/\".concat(getNodeVersion()));\n } else {\n platform = getBrowserOS();\n headerParts.push('platform browser');\n }\n } catch (e) {\n platform = null;\n }\n if (platform) {\n headerParts.push(\"os \".concat(platform));\n }\n return \"\".concat(headerParts.filter(function (item) {\n return item !== '';\n }).join('; '), \";\");\n}\n\n/**\n * Mixes in a method to return just a plain object with no additional methods\n * @private\n * @param data - Any plain JSON response returned from the API\n * @return Enhanced object with toPlainObject method\n */\nfunction toPlainObject(data) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-expect-error\n return Object.defineProperty(data, 'toPlainObject', {\n enumerable: false,\n configurable: false,\n writable: false,\n value: function value() {\n return copy(this);\n }\n });\n}\n\n/**\n * Handles errors received from the server. Parses the error into a more useful\n * format, places it in an exception and throws it.\n * See https://www.contentful.com/developers/docs/references/errors/\n * for more details on the data received on the errorResponse.data property\n * and the expected error codes.\n * @private\n */\nfunction errorHandler(errorResponse) {\n var config = errorResponse.config,\n response = errorResponse.response;\n var errorName;\n\n // Obscure the Management token\n if (config && config.headers && config.headers['Authorization']) {\n var token = \"...\".concat(config.headers['Authorization'].toString().substr(-5));\n config.headers['Authorization'] = \"Bearer \".concat(token);\n }\n if (!isPlainObject(response) || !isPlainObject(config)) {\n throw errorResponse;\n }\n var data = response === null || response === void 0 ? void 0 : response.data;\n var errorData = {\n status: response === null || response === void 0 ? void 0 : response.status,\n statusText: response === null || response === void 0 ? void 0 : response.statusText,\n message: '',\n details: {}\n };\n if (isPlainObject(config)) {\n errorData.request = {\n url: config.url,\n headers: config.headers,\n method: config.method,\n payloadData: config.data\n };\n }\n if (data && isPlainObject(data)) {\n if ('requestId' in data) {\n errorData.requestId = data.requestId || 'UNKNOWN';\n }\n if ('message' in data) {\n errorData.message = data.message || '';\n }\n if ('details' in data) {\n errorData.details = data.details || {};\n }\n if ('sys' in data) {\n if ('id' in data.sys) {\n errorName = data.sys.id;\n }\n }\n }\n var error = new Error();\n error.name = errorName && errorName !== 'Unknown' ? errorName : \"\".concat(response === null || response === void 0 ? void 0 : response.status, \" \").concat(response === null || response === void 0 ? void 0 : response.statusText);\n try {\n error.message = JSON.stringify(errorData, null, ' ');\n } catch (_unused) {\n var _errorData$message;\n error.message = (_errorData$message = errorData === null || errorData === void 0 ? void 0 : errorData.message) !== null && _errorData$message !== void 0 ? _errorData$message : '';\n }\n throw error;\n}\n\nexport { createHttpClient, createRequestConfig, enforceObjPath, errorHandler, freezeSys, getUserAgentHeader, toPlainObject };\n","import { toPlainObject, freezeSys } from 'contentful-sdk-core';\n\n/**\n * @memberof Entities\n * @typedef Space\n * @prop {Object} sys - System metadata\n * @prop {string} sys.id - Space id\n * @prop {string} sys.type - Entity type\n * @prop {string} name - Space name\n * @prop {Array} locales - Array with locale codes\n * @prop {function(): Object} toPlainObject() - Returns this Space as a plain JS object\n */\n\n/**\n * @private\n * @param {Object} data - API response for a Space\n * @return {Space}\n */\nexport function wrapSpace(data) {\n return freezeSys(toPlainObject(data));\n}","import jsonStringifySafe from 'json-stringify-safe';\nexport default function mixinStringifySafe(data) {\n return Object.defineProperty(data, 'stringifySafe', {\n enumerable: false,\n configurable: false,\n writable: false,\n value: function () {\n let serializer = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n let indent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n return jsonStringifySafe(this, serializer, indent, (key, value) => {\n return {\n sys: {\n type: 'Link',\n linkType: 'Entry',\n id: value.sys.id,\n circular: true\n }\n };\n });\n }\n });\n}","var _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 _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"]) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); } }; }();\n\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\nimport copy from 'fast-copy';\n\nvar UNRESOLVED_LINK = {}; // unique object to avoid polyfill bloat using Symbol()\n\n/**\n * isLink Function\n * Checks if the object has sys.type \"Link\"\n * @param object\n */\nvar isLink = function isLink(object) {\n return object && object.sys && object.sys.type === 'Link';\n};\n\n/**\n * isResourceLink Function\n * Checks if the object has sys.type \"ResourceLink\"\n * @param object\n */\nvar isResourceLink = function isResourceLink(object) {\n return object && object.sys && object.sys.type === 'ResourceLink';\n};\n\n/**\n * Creates a key with spaceId and a key without for entityMap\n *\n * @param {*} sys\n * @param {String} sys.type\n * @param {String} sys.id\n * @param {*} sys.space\n * @param {*} sys.space.sys\n * @param {String} sys.space.id\n * @return {string[]}\n */\nvar makeEntityMapKeys = function makeEntityMapKeys(sys) {\n if (sys.space && sys.environment) {\n return [sys.type + '!' + sys.id, sys.space.sys.id + '!' + sys.environment.sys.id + '!' + sys.type + '!' + sys.id];\n }\n\n return [sys.type + '!' + sys.id];\n};\n\n/**\n * Looks up in entityMap\n *\n * @param entityMap\n * @param {*} linkData\n * @param {String} linkData.type\n * @param {String} linkData.linkType\n * @param {String} linkData.id\n * @param {String} linkData.urn\n * @return {String}\n */\nvar lookupInEntityMap = function lookupInEntityMap(entityMap, linkData) {\n var entryId = linkData.entryId,\n linkType = linkData.linkType,\n spaceId = linkData.spaceId,\n environmentId = linkData.environmentId;\n\n\n if (spaceId && environmentId) {\n return entityMap.get(spaceId + '!' + environmentId + '!' + linkType + '!' + entryId);\n }\n\n return entityMap.get(linkType + '!' + entryId);\n};\n\nvar getIdsFromUrn = function getIdsFromUrn(urn) {\n var regExp = /.*:spaces\\/([^/]+)(?:\\/environments\\/([^/]+))?\\/entries\\/([^/]+)$/;\n\n if (!regExp.test(urn)) {\n return undefined;\n }\n\n var _urn$match = urn.match(regExp),\n _urn$match2 = _slicedToArray(_urn$match, 4),\n _ = _urn$match2[0],\n spaceId = _urn$match2[1],\n _urn$match2$ = _urn$match2[2],\n environmentId = _urn$match2$ === undefined ? 'master' : _urn$match2$,\n entryId = _urn$match2[3];\n\n return { spaceId: spaceId, environmentId: environmentId, entryId: entryId };\n};\n\n/**\n * getResolvedLink Function\n *\n * @param entityMap\n * @param link\n * @return {undefined}\n */\nvar getResolvedLink = function getResolvedLink(entityMap, link) {\n var _link$sys = link.sys,\n type = _link$sys.type,\n linkType = _link$sys.linkType;\n\n if (type === 'ResourceLink') {\n var urn = link.sys.urn;\n\n var _getIdsFromUrn = getIdsFromUrn(urn),\n spaceId = _getIdsFromUrn.spaceId,\n environmentId = _getIdsFromUrn.environmentId,\n _entryId = _getIdsFromUrn.entryId;\n\n var extractedLinkType = linkType.split(':')[1];\n\n return lookupInEntityMap(entityMap, {\n linkType: extractedLinkType,\n entryId: _entryId,\n spaceId: spaceId,\n environmentId: environmentId\n }) || UNRESOLVED_LINK;\n }\n\n var entryId = link.sys.id;\n\n return lookupInEntityMap(entityMap, { linkType: linkType, entryId: entryId }) || UNRESOLVED_LINK;\n};\n\n/**\n * cleanUpLinks Function\n * - Removes unresolvable links from Arrays and Objects\n *\n * @param {Object[]|Object} input\n */\nvar cleanUpLinks = function cleanUpLinks(input) {\n if (Array.isArray(input)) {\n return input.filter(function (val) {\n return val !== UNRESOLVED_LINK;\n });\n }\n for (var key in input) {\n if (input[key] === UNRESOLVED_LINK) {\n delete input[key];\n }\n }\n return input;\n};\n\n/**\n * walkMutate Function\n * @param input\n * @param predicate\n * @param mutator\n * @param removeUnresolved\n * @return {*}\n */\nvar walkMutate = function walkMutate(input, predicate, mutator, removeUnresolved) {\n if (predicate(input)) {\n return mutator(input);\n }\n\n if (input && (typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object') {\n for (var key in input) {\n // eslint-disable-next-line no-prototype-builtins\n if (input.hasOwnProperty(key)) {\n input[key] = walkMutate(input[key], predicate, mutator, removeUnresolved);\n }\n }\n if (removeUnresolved) {\n input = cleanUpLinks(input);\n }\n }\n return input;\n};\n\nvar normalizeLink = function normalizeLink(entityMap, link, removeUnresolved) {\n var resolvedLink = getResolvedLink(entityMap, link);\n if (resolvedLink === UNRESOLVED_LINK) {\n return removeUnresolved ? resolvedLink : link;\n }\n return resolvedLink;\n};\n\nvar makeEntryObject = function makeEntryObject(item, itemEntryPoints) {\n if (!Array.isArray(itemEntryPoints)) {\n return item;\n }\n\n var entryPoints = Object.keys(item).filter(function (ownKey) {\n return itemEntryPoints.indexOf(ownKey) !== -1;\n });\n\n return entryPoints.reduce(function (entryObj, entryPoint) {\n entryObj[entryPoint] = item[entryPoint];\n return entryObj;\n }, {});\n};\n\n/**\n * resolveResponse Function\n * Resolves contentful response to normalized form.\n * @param {Object} response Contentful response\n * @param {{removeUnresolved: Boolean, itemEntryPoints: Array}|{}} options\n * @param {Boolean} options.removeUnresolved - Remove unresolved links default:false\n * @param {Array} options.itemEntryPoints - Resolve links only in those item properties\n * @return {Object}\n */\nvar resolveResponse = function resolveResponse(response, options) {\n options = options || {};\n if (!response.items) {\n return [];\n }\n var responseClone = copy(response);\n var allIncludes = Object.keys(responseClone.includes || {}).reduce(function (all, type) {\n return [].concat(_toConsumableArray(all), _toConsumableArray(response.includes[type]));\n }, []);\n\n var allEntries = [].concat(_toConsumableArray(responseClone.items), _toConsumableArray(allIncludes)).filter(function (entity) {\n return Boolean(entity.sys);\n });\n\n var entityMap = new Map(allEntries.reduce(function (acc, entity) {\n var entries = makeEntityMapKeys(entity.sys).map(function (key) {\n return [key, entity];\n });\n acc.push.apply(acc, _toConsumableArray(entries));\n return acc;\n }, []));\n\n allEntries.forEach(function (item) {\n var entryObject = makeEntryObject(item, options.itemEntryPoints);\n\n Object.assign(item, walkMutate(entryObject, function (x) {\n return isLink(x) || isResourceLink(x);\n }, function (link) {\n return normalizeLink(entityMap, link, options.removeUnresolved);\n }, options.removeUnresolved));\n });\n\n return responseClone.items;\n};\n\nexport default resolveResponse;","import copy from 'fast-copy';\nimport { toPlainObject, freezeSys } from 'contentful-sdk-core';\nimport mixinStringifySafe from '../mixins/stringify-safe';\nimport resolveResponse from 'contentful-resolve-response';\n\n/**\n * Types of fields found in an Entry\n * @namespace EntryFields\n */\n\n/**\n * @memberof EntryFields\n * @typedef Symbol\n * @type string\n */\n\n/**\n * @memberof EntryFields\n * @typedef Text\n * @type string\n */\n\n/**\n * @memberof EntryFields\n * @typedef Integer\n * @type number\n */\n\n/**\n * @memberof EntryFields\n * @typedef Number\n * @type number\n */\n\n/**\n * @memberof EntryFields\n * @typedef Date\n * @type string\n */\n\n/**\n * @memberof EntryFields\n * @typedef Boolean\n * @type boolean\n */\n\n/**\n * @memberof EntryFields\n * @typedef Location\n * @prop {string} lat - latitude\n * @prop {string} lon - longitude\n */\n\n/**\n * A Field in an Entry can have one of the following types that can be defined in Contentful. See Field Types for more details.\n * @memberof Entities\n * @typedef Field\n * @type EntryFields.Symbol | EntryFields.Text | EntryFields.Integer | EntryFields.Number | EntryFields.Date | EntryFields.Boolean | EntryFields.Location | Entities.Link | Entities.ResourceLink | Array | Object\n */\n\n/**\n * @memberof Entities\n * @typedef Entry\n * @prop {Entities.Sys} sys - Standard system metadata with additional entry specific properties\n * @prop {Entities.Link} sys.contentType - Content Type used by this Entry\n * @prop {string=} sys.locale - If present, indicates the locale which this entry uses\n * @prop {Object} fields - Object with content for each field\n * @prop {function(): Object} toPlainObject() - Returns this Entry as a plain JS object\n */\n\n/**\n * @private\n * @param {Object} data - Raw entry data\n * @return {Entry} Wrapped entry data\n */\nexport function wrapEntry(data) {\n return freezeSys(toPlainObject(copy(data)));\n}\n\n/**\n * @memberof Entities\n * @typedef EntryCollection\n * @prop {number} total\n * @prop {number} skip\n * @prop {number} limit\n * @prop {Array} items\n * @prop {Array=} errors - Array of errors that might occur when retrieving entries.\n * @prop {Object=} includes - Object with arrays of includes for Entries and Assets. This will be present if resolveLinks is on, and any linked entries or assets exist. Those links will be resolved in the Entries present in the items array, but they are also present here in raw form.\n * @prop {function(): Object} toPlainObject() - Returns this Entry collection as a plain JS object\n * @prop {function(?function=, space=): Object} stringifySafe(replacer,space) - Stringifies the entry collection, accounting for circular references. Circular references will be replaced with just a Link object, with a circular property set to true. See MDN and json-stringify-safe for more details on the arguments this method can take.\n */\n\n/**\n * Data is also mixed in with link getters if links exist and includes were requested\n * @private\n * @param {Object} data - Raw entry collection data\n * @param {Object} options - wrapper options\n * @return {EntryCollection} Wrapped entry collection data\n */\nexport function wrapEntryCollection(data, _ref) {\n let {\n resolveLinks,\n removeUnresolved\n } = _ref;\n const wrappedData = mixinStringifySafe(toPlainObject(copy(data)));\n if (resolveLinks) {\n wrappedData.items = resolveResponse(wrappedData, {\n removeUnresolved,\n itemEntryPoints: ['fields']\n });\n }\n return freezeSys(wrappedData);\n}","import copy from 'fast-copy';\nimport { toPlainObject, freezeSys } from 'contentful-sdk-core';\n\n/**\n * @memberof Entities\n * @typedef Asset\n * @prop {Entities.Sys} sys - Standard system metadata with additional entry specific properties\n * @prop {string=} sys.locale - If present, indicates the locale which this asset uses\n * @prop {Object} fields - Object with content for each field\n * @prop {string} fields.title - Title for this asset\n * @prop {string} fields.description - Description for this asset\n * @prop {Object} fields.file - File object for this asset\n * @prop {string} fields.file.fileName - Name for the file\n * @prop {string} fields.file.contentType - Mime type for the file\n * @prop {string} fields.file.url - Url where the file is available at.\n * @prop {Object} fields.file.details - Details for the file, depending on file type (example: image size in bytes, etc)\n * @prop {function(): Object} toPlainObject() - Returns this Asset as a plain JS object\n */\n\n/**\n * @private\n * @param {Object} data - Raw asset data\n * @return {Asset} Wrapped asset data\n */\nexport function wrapAsset(data) {\n return freezeSys(toPlainObject(copy(data)));\n}\n\n/**\n * @memberof Entities\n * @typedef AssetCollection\n * @prop {number} total\n * @prop {number} skip\n * @prop {number} limit\n * @prop {Array} items\n * @prop {function(): Object} toPlainObject() - Returns this Asset collection as a plain JS object\n */\n\n/**\n * @private\n * @param {Object} data - Raw asset collection data\n * @return {AssetCollection} Wrapped asset collection data\n */\nexport function wrapAssetCollection(data) {\n return freezeSys(toPlainObject(copy(data)));\n}","import copy from 'fast-copy';\nimport { toPlainObject, freezeSys } from 'contentful-sdk-core';\n\n/**\n * @memberof Entities\n * @typedef AssetKey\n * @prop {string} policy - The asset key's policy\n * @prop {string} secret - The secret for creating a signing token\n * @prop {function(): Object} toPlainObject() - Returns this AssetKey as a plain JS object\n */\n\n/**\n * @private\n * @param {Object} data - Raw asset key data\n * @return {Asset} Wrapped asset key data\n */\nexport function wrapAssetKey(data) {\n return freezeSys(toPlainObject(copy(data)));\n}","import copy from 'fast-copy';\nimport { toPlainObject, freezeSys } from 'contentful-sdk-core';\n\n/**\n * @memberof Entities\n * @typedef ContentType\n * @prop {Entities.Sys} sys - System metadata\n * @prop {string} name\n * @prop {string} description\n * @prop {string} displayField - Field used as the main display field for Entries\n * @prop {string} Array - All the fields contained in this Content Type\n * @prop {function(): Object} toPlainObject() - Returns this Content Type as a plain JS object\n */\n\n/**\n * @private\n * @param {Object} data - Raw content type data\n * @return {ContentType} Wrapped content type data\n */\nexport function wrapContentType(data) {\n return freezeSys(toPlainObject(copy(data)));\n}\n\n/**\n * @memberof Entities\n * @typedef ContentTypeCollection\n * @prop {number} total\n * @prop {number} skip\n * @prop {number} limit\n * @prop {Array} items\n * @prop {function(): Object} toPlainObject() - Returns this Content Type collection as a plain JS object\n */\n\n/**\n * @private\n * @param {Object} data - Raw content type collection data\n * @return {ContentTypeCollection} Wrapped content type collection data\n */\nexport function wrapContentTypeCollection(data) {\n return freezeSys(toPlainObject(copy(data)));\n}","import copy from 'fast-copy';\nimport { toPlainObject, freezeSys } from 'contentful-sdk-core';\n\n/**\n * @memberof Entities\n * @typedef Locale\n * @prop {Entities.Sys} sys - Standard system metadata with additional entry specific properties\n * @prop {string} name - locale name (example: English)\n * @prop {string} code - locale code (example: en-US)\n * @prop {string} fallbackCode - the locale code to fallback to when there is not content for the current locale\n * @prop {boolean} default - If this is the default locale\n * @prop {boolean} optional - If the locale needs to be filled in on entries or not\n * @prop {function(): Object} toPlainObject() - Returns this Locale as a plain JS object\n */\n\n/**\n * @private\n * @param {Object} data - Raw locale data\n * @return {Locale} Wrapped locale data\n */\nexport function wrapLocale(data) {\n return freezeSys(toPlainObject(copy(data)));\n}\n\n/**\n * @memberof Entities\n * @typedef LocaleCollection\n * @prop {number} total\n * @prop {number} skip\n * @prop {number} limit\n * @prop {Array} items\n * @prop {function(): Object} toPlainObject() - Returns this Locale collection as a plain JS object\n */\n\n/**\n * @private\n * @param {Object} data - Raw locale collection data\n * @return {LocaleCollection} Wrapped locale collection data\n */\nexport function wrapLocaleCollection(data) {\n return freezeSys(toPlainObject(copy(data)));\n}","import copy from 'fast-copy';\nimport { toPlainObject, freezeSys } from 'contentful-sdk-core';\n\n/**\n * @memberof Entities\n * @typedef Tag\n * @prop {Entities.Sys} sys - Standard system metadata with additional entry specific properties\n * @prop {string} name - Tag name\n * @prop {function(): Object} toPlainObject() - Returns this tag as a plain JS object\n */\n\n/**\n * @private\n * @param {Object} data - Raw tag data\n * @return {Tag} Wrapped tag data\n */\nexport function wrapTag(data) {\n return freezeSys(toPlainObject(copy(data)));\n}\n\n/**\n * @memberof Entities\n * @typedef TagCollection\n * @prop {number} total\n * @prop {number} skip\n * @prop {number} limit\n * @prop {Array} items\n * @prop {function(): Object} toPlainObject() - Returns this Tag collection as a plain JS object\n */\n\n/**\n * @private\n * @param {Object} data - Raw tag collection data\n * @return {TagCollection} Wrapped tag collection data\n */\nexport function wrapTagCollection(data) {\n return freezeSys(toPlainObject(copy(data)));\n}","import * as space from './space';\nimport * as entry from './entry';\nimport * as asset from './asset';\nimport * as assetKey from './asset-key';\nimport * as contentType from './content-type';\nimport * as locale from './locale';\nimport * as tag from './tag';\nexport default {\n space,\n entry,\n asset,\n assetKey,\n contentType,\n locale,\n tag\n};","function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/**\n * See Synchronization for more information.\n * @namespace Sync\n */\nimport { createRequestConfig, freezeSys, toPlainObject } from 'contentful-sdk-core';\nimport resolveResponse from 'contentful-resolve-response';\nimport mixinStringifySafe from './mixins/stringify-safe';\n\n/**\n * @memberof Sync\n * @typedef SyncCollection\n * @prop {Array} entries - All existing entries on first sync. New and updated entries on subsequent syncs.\n * @prop {Array} assets - All existing assets on first sync. New and updated assets on subsequent syncs.\n * @prop {Array} deletedEntries - List of deleted Entries since last sync\n * @prop {Array} deletedAssets - List of deleted Assets since last sync\n * @prop {string} nextSyncToken - Token to be sent to the next sync call\n * @prop {function(): Object} toPlainObject() - Returns this Sync collection as a plain JS object\n * @prop {function(?function=, space=): Object} stringifySafe(replacer,space) - Stringifies the Sync collection, accounting for circular references. Circular references will be replaced with just a Link object, with a circular property set to true. See MDN and json-stringify-safe for more details on the arguments this method can take.\n */\n\n/**\n * Deleted Entries are the same as Entries, but only appear on the sync API.\n * @memberof Sync\n * @typedef DeletedEntry\n * @type Entities.Entry\n */\n\n/**\n * Deleted Assets are the same as Assets, but only appear on the sync API.\n * @memberof Sync\n * @typedef DeletedAsset\n * @type Entities.Asset\n */\n\n/**\n * This module retrieves all the available pages for a sync operation\n * @private\n * @param {Object} http - HTTP client\n * @param {Object} query - Query object\n * @param {Object} options - Sync options object\n * @param {boolean} [options.resolveLinks = true] - If links should be resolved\n * @param {boolean} [options.removeUnresolved = false] - If unresolvable links should get removed\n * @param {boolean} [options.paginate = true] - If further sync pages should automatically be crawled\n * @return {Promise}\n */\nexport default async function pagedSync(http, query) {\n let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n if (!query || !query.initial && !query.nextSyncToken && !query.nextPageToken) {\n throw new Error('Please provide one of `initial`, `nextSyncToken` or `nextPageToken` parameters for syncing');\n }\n if (query && query.content_type && !query.type) {\n query.type = 'Entry';\n } else if (query && query.content_type && query.type && query.type !== 'Entry') {\n throw new Error('When using the `content_type` filter your `type` parameter cannot be different from `Entry`.');\n }\n const defaultOptions = {\n resolveLinks: true,\n removeUnresolved: false,\n paginate: true\n };\n const {\n resolveLinks,\n removeUnresolved,\n paginate\n } = _objectSpread(_objectSpread({}, defaultOptions), options);\n const syncOptions = {\n paginate\n };\n const response = await getSyncPage(http, [], query, syncOptions);\n // clones response.items used in includes because we don't want these to be mutated\n if (resolveLinks) {\n response.items = resolveResponse(response, {\n removeUnresolved,\n itemEntryPoints: ['fields']\n });\n }\n // maps response items again after getters are attached\n const mappedResponseItems = mapResponseItems(response.items);\n if (response.nextSyncToken) {\n mappedResponseItems.nextSyncToken = response.nextSyncToken;\n }\n if (response.nextPageToken) {\n mappedResponseItems.nextPageToken = response.nextPageToken;\n }\n return freezeSys(mixinStringifySafe(toPlainObject(mappedResponseItems)));\n}\n\n/**\n * @private\n * @param {Array} items\n * @return {Object} Entities mapped to an object for each entity type\n */\nfunction mapResponseItems(items) {\n const reducer = type => {\n return (accumulated, item) => {\n if (item.sys.type === type) {\n accumulated.push(toPlainObject(item));\n }\n return accumulated;\n };\n };\n return {\n entries: items.reduce(reducer('Entry'), []),\n assets: items.reduce(reducer('Asset'), []),\n deletedEntries: items.reduce(reducer('DeletedEntry'), []),\n deletedAssets: items.reduce(reducer('DeletedAsset'), [])\n };\n}\n\n/**\n * If the response contains a nextPageUrl, extracts the sync token to get the\n * next page and calls itself again with that token.\n * Otherwise, if the response contains a nextSyncUrl, extracts the sync token\n * and returns it.\n * On each call of this function, any retrieved items are collected in the\n * supplied items array, which gets returned in the end\n * @private\n * @param {Object} http\n * @param {Array} items\n * @param {Object} query\n * @param {Object} options - Sync page options object\n * @param {boolean} [options.paginate = true] - If further sync pages should automatically be crawled\n * @return {Promise<{items: Array, nextSyncToken: string}>}\n */\nasync function getSyncPage(http, items, query, _ref) {\n let {\n paginate\n } = _ref;\n if (query.nextSyncToken) {\n query.sync_token = query.nextSyncToken;\n delete query.nextSyncToken;\n }\n if (query.nextPageToken) {\n query.sync_token = query.nextPageToken;\n delete query.nextPageToken;\n }\n if (query.sync_token) {\n delete query.initial;\n delete query.type;\n delete query.content_type;\n delete query.limit;\n }\n const response = await http.get('sync', createRequestConfig({\n query: query\n }));\n const data = response.data || {};\n items = items.concat(data.items || []);\n if (data.nextPageUrl) {\n if (paginate) {\n delete query.initial;\n query.sync_token = getToken(data.nextPageUrl);\n return getSyncPage(http, items, query, {\n paginate\n });\n }\n return {\n items: items,\n nextPageToken: getToken(data.nextPageUrl)\n };\n } else if (data.nextSyncUrl) {\n return {\n items: items,\n nextSyncToken: getToken(data.nextSyncUrl)\n };\n } else {\n return {\n items: []\n };\n }\n}\n\n/**\n * Extracts token out of an url\n * @private\n */\nfunction getToken(url) {\n const urlParts = url.split('?');\n return urlParts.length > 0 ? urlParts[1].replace('sync_token=', '') : '';\n}","function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/*\n* sdk relies heavily on sys metadata\n* so we cannot omit the sys property on sdk level entirely\n* and we have to ensure that at least `id` and `type` are present\n* */\n\nexport default function normalizeSelect(query) {\n if (!query.select) {\n return query;\n }\n\n // The selection of fields for the query is limited\n // Get the different parts that are listed for selection\n const allSelects = Array.isArray(query.select) ? query.select : query.select.split(',').map(q => q.trim());\n // Move the parts into a set for easy access and deduplication\n const selectedSet = new Set(allSelects);\n\n // If we already select all of `sys` we can just return\n // since we're anyway fetching everything that is needed\n if (selectedSet.has('sys')) {\n return query;\n }\n\n // We don't select `sys` so we need to ensure the minimum set\n selectedSet.add('sys.id');\n selectedSet.add('sys.type');\n\n // Reassign the normalized sys properties\n return _objectSpread(_objectSpread({}, query), {}, {\n select: [...selectedSet].join(',')\n });\n}","export class ValidationError extends Error {\n constructor(name, message) {\n super(`Invalid \"${name}\" provided, ` + message);\n this.name = 'ValidationError';\n }\n}\nexport default function validateTimestamp(name, timestamp, options) {\n options = options || {};\n if (typeof timestamp !== 'number') {\n throw new ValidationError(name, `only numeric values are allowed for timestamps, provided type was \"${typeof timestamp}\"`);\n }\n if (options.maximum && timestamp > options.maximum) {\n throw new ValidationError(name, `value (${timestamp}) cannot be further in the future than expected maximum (${options.maximum})`);\n }\n if (options.now && timestamp < options.now) {\n throw new ValidationError(name, `value (${timestamp}) cannot be in the past, current time was ${options.now}`);\n }\n}","function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/**\n * Contentful Delivery API Client. Contains methods which allow access to the\n * different kinds of entities present in Contentful (Entries, Assets, etc).\n * @namespace ContentfulClientAPI\n * @see Entities\n */\n\n/**\n * The different kinds of top level entities you can find in Contentful\n * @namespace Entities\n */\n\n/**\n * System metadata. See Common Resource Attributes for more details.\n * @memberof Entities\n * @typedef Sys\n * @prop {string} type\n * @prop {string} id\n * @prop {Entities.Link} space\n * @prop {string} createdAt\n * @prop {string} updatedAt\n * @prop {number} revision\n */\n\n/**\n * Link to another entity. See Links for more details.\n * @memberof Entities\n * @typedef Link\n * @prop {string} type - type of this entity. Always link.\n * @prop {string} id\n * @prop {string} linkType - type of this link. If defined, either Entry or Asset\n */\n\n/**\n * Link to another entity in a different space.\n * @memberof Entities\n * @typedef ResourceLink\n * @prop {string} type - type of this entity. Always ResourceLink.\n * @prop {string} urn\n * @prop {string} linkType - type of this link. Always Contentful:Entry\n */\n\n/**\n * @memberof ContentfulClientAPI\n * @typedef {Object} ClientAPI\n * @prop {function} getSpace\n * @prop {function} getContentType\n * @prop {function} getTag\n * @prop {function} getTags\n * @prop {function} getContentTypes\n * @prop {function} getEntry\n * @prop {function} getEntries\n * @prop {function} getAsset\n * @prop {function} getAssets\n * @prop {function} createAssetKey\n * @prop {function} parseEntries\n * @prop {function} sync\n */\n\nimport { createRequestConfig, errorHandler } from 'contentful-sdk-core';\nimport entities from './entities';\nimport pagedSync from './paged-sync';\nimport normalizeSelect from './utils/normalize-select';\nimport validateTimestamp from './utils/validate-timestamp';\nconst ASSET_KEY_MAX_LIFETIME = 48 * 60 * 60;\n\n/**\n * Creates API object with methods to access functionality from Contentful's\n * Delivery API\n * @private\n * @param {Object} params - API initialization params\n * @prop {Object} http - HTTP client instance\n * @prop {Object} entities - Object with wrapper methods for each kind of entity\n * @prop {Function} getGlobalOptions - Link resolver preconfigured with global setting\n * @return {ClientAPI}\n */\nexport default function createContentfulApi(_ref) {\n let {\n http,\n getGlobalOptions\n } = _ref;\n const {\n wrapSpace\n } = entities.space;\n const {\n wrapContentType,\n wrapContentTypeCollection\n } = entities.contentType;\n const {\n wrapEntry,\n wrapEntryCollection\n } = entities.entry;\n const {\n wrapAsset,\n wrapAssetCollection\n } = entities.asset;\n const {\n wrapTag,\n wrapTagCollection\n } = entities.tag;\n const {\n wrapAssetKey\n } = entities.assetKey;\n const {\n wrapLocaleCollection\n } = entities.locale;\n const notFoundError = id => {\n const error = new Error('The resource could not be found.');\n error.sys = {\n type: 'Error',\n id: 'NotFound'\n };\n error.details = {\n type: 'Entry',\n id: id,\n environment: getGlobalOptions().environment,\n space: getGlobalOptions().space\n };\n return error;\n };\n\n /**\n * Gets the Space which the client is currently configured to use\n * @memberof ContentfulClientAPI\n * @return {Promise} Promise for a Space\n * @example\n * const contentful = require('contentful')\n *\n * const client = contentful.createClient({\n * space: '',\n * accessToken: ''\n * })\n * // returns the space object with the above \n * const space = await client.getSpace()\n * console.log(space)\n */\n async function getSpace() {\n switchToSpace(http);\n try {\n const response = await http.get('/');\n return wrapSpace(response.data);\n } catch (error) {\n errorHandler(error);\n }\n }\n\n /**\n * Gets a Content Type\n * @memberof ContentfulClientAPI\n * @param {string} id\n * @return {Promise} Promise for a Content Type\n * @example\n * const contentful = require('contentful')\n *\n * const client = contentful.createClient({\n * space: '',\n * accessToken: ''\n * })\n *\n * const contentType = await client.getContentType('')\n * console.log(contentType)\n */\n async function getContentType(id) {\n switchToEnvironment(http);\n try {\n const response = await http.get(`content_types/${id}`);\n return wrapContentType(response.data);\n } catch (error) {\n errorHandler(error);\n }\n }\n\n /**\n * Gets a collection of Content Types\n * @memberof ContentfulClientAPI\n * @param {Object=} query - Object with search parameters. Check the JS SDK tutorial and the REST API reference for more details.\n * @return {Promise} Promise for a collection of Content Types\n * @example\n * const contentful = require('contentful')\n *\n * const client = contentful.createClient({\n * space: '',\n * accessToken: ''\n * })\n *\n * const response = await client.getContentTypes()\n * console.log(response.items)\n */\n async function getContentTypes() {\n let query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n switchToEnvironment(http);\n try {\n const response = await http.get('content_types', createRequestConfig({\n query: query\n }));\n return wrapContentTypeCollection(response.data);\n } catch (error) {\n errorHandler(error);\n }\n }\n\n /**\n * Gets an Entry\n * @memberof ContentfulClientAPI\n * @param {string} id\n * @param {Object=} query - Object with search parameters. In this method it's only useful for `locale`.\n * @return {Promise} Promise for an Entry\n * @example\n * const contentful = require('contentful')\n *\n * const client = contentful.createClient({\n * space: '',\n * accessToken: ''\n * })\n *\n * const entry = await client.getEntry('')\n * console.log(entry)\n */\n async function getEntry(id) {\n let query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n if (!id) {\n throw notFoundError(id);\n }\n try {\n const response = await this.getEntries(_objectSpread({\n 'sys.id': id\n }, query));\n if (response.items.length > 0) {\n return wrapEntry(response.items[0]);\n } else {\n throw notFoundError(id);\n }\n } catch (error) {\n errorHandler(error);\n }\n }\n\n /**\n * Gets a collection of Entries\n * @memberof ContentfulClientAPI\n * @param {Object=} query - Object with search parameters. Check the JS SDK tutorial and the REST API reference for more details.\n * @return {Promise} Promise for a collection of Entries\n * @example\n * const contentful = require('contentful')\n *\n * const client = contentful.createClient({\n * space: '',\n * accessToken: ''\n * })\n *\n * const response = await client.getEntries()\n * console.log(response.items)\n */\n async function getEntries() {\n let query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n switchToEnvironment(http);\n const {\n resolveLinks,\n removeUnresolved\n } = getGlobalOptions(query);\n query = normalizeSelect(query);\n try {\n const response = await http.get('entries', createRequestConfig({\n query: query\n }));\n return wrapEntryCollection(response.data, {\n resolveLinks,\n removeUnresolved\n });\n } catch (error) {\n errorHandler(error);\n }\n }\n /**\n * Gets an Asset\n * @memberof ContentfulClientAPI\n * @param {string} id\n * @param {Object=} query - Object with search parameters. In this method it's only useful for `locale`.\n * @return {Promise} Promise for an Asset\n * @example\n * const contentful = require('contentful')\n *\n * const client = contentful.createClient({\n * space: '',\n * accessToken: ''\n * })\n *\n * const asset = await client.getAsset('')\n * console.log(asset)\n */\n async function getAsset(id) {\n let query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n switchToEnvironment(http);\n query = normalizeSelect(query);\n try {\n const response = await http.get(`assets/${id}`, createRequestConfig({\n query: query\n }));\n return wrapAsset(response.data);\n } catch (error) {\n errorHandler(error);\n }\n }\n\n /**\n * Gets a collection of Assets\n * @memberof ContentfulClientAPI\n * @param {Object=} query - Object with search parameters. Check the JS SDK tutorial and the REST API reference for more details.\n * @return {Promise} Promise for a collection of Assets\n * @example\n * const contentful = require('contentful')\n *\n * const client = contentful.createClient({\n * space: '',\n * accessToken: ''\n * })\n *\n * const response = await client.getAssets()\n * console.log(response.items)\n */\n async function getAssets() {\n let query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n switchToEnvironment(http);\n query = normalizeSelect(query);\n try {\n const response = await http.get('assets', createRequestConfig({\n query: query\n }));\n return wrapAssetCollection(response.data);\n } catch (error) {\n errorHandler(error);\n }\n }\n\n /**\n * Gets a Tag\n * @memberof ContentfulClientAPI\n * @param {string} id\n * @return {Promise} Promise for a Tag\n * @example\n * const contentful = require('contentful')\n *\n * const client = contentful.createClient({\n * space: '',\n * accessToken: ''\n * })\n *\n * const tag = await client.getTag('')\n * console.log(tag)\n */\n async function getTag(id) {\n switchToEnvironment(http);\n try {\n const response = await http.get(`tags/${id}`);\n return wrapTag(response.data);\n } catch (error) {\n errorHandler(error);\n }\n }\n\n /**\n * Gets a collection of Tags\n * @memberof ContentfulClientAPI\n * @param {Object=} query - Object with search parameters.\n * @return {Promise} Promise for a collection of Tags\n * @example\n * const contentful = require('contentful')\n *\n * const client = contentful.createClient({\n * space: '',\n * accessToken: ''\n * })\n *\n * const response = await client.getTags()\n * console.log(response.items)\n */\n async function getTags() {\n let query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n switchToEnvironment(http);\n query = normalizeSelect(query);\n try {\n const response = await http.get('tags', createRequestConfig({\n query: query\n }));\n return wrapTagCollection(response.data);\n } catch (error) {\n errorHandler(error);\n }\n }\n\n /**\n * Creates an asset key for signing asset URLs (Embargoed Assets)\n * @memberof ContentfulClientAPI\n * @param {number} expiresAt - UNIX timestamp in the future, maximum of 48h from now\n * @return {Promise} Promise for an AssetKey\n * @example\n * const contentful = require('contentful')\n *\n * const client = contentful.createClient({\n * space: '',\n * accessToken: ''\n * })\n *\n * const assetKey = await client.getAssetKey()\n * console.log(assetKey)\n */\n async function createAssetKey(expiresAt) {\n switchToEnvironment(http);\n try {\n const now = Math.floor(Date.now() / 1000);\n const currentMaxLifetime = now + ASSET_KEY_MAX_LIFETIME;\n validateTimestamp('expiresAt', expiresAt, {\n maximum: currentMaxLifetime,\n now\n });\n const params = {\n expiresAt\n };\n const response = await http.post('asset_keys', params);\n return wrapAssetKey(response.data);\n } catch (error) {\n errorHandler(error);\n }\n }\n\n /**\n * Gets a collection of Locale\n * @memberof ContentfulClientAPI\n * @param {Object=} query - Object with search parameters. Check the JS SDK tutorial and the REST API reference for more details.\n * @return {Promise} Promise for a collection of Locale\n * @example\n * const contentful = require('contentful')\n *\n * const client = contentful.createClient({\n * space: '',\n * accessToken: ''\n * })\n *\n * const response = await client.getLocales()\n * console.log(response.items)\n */\n async function getLocales() {\n let query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n switchToEnvironment(http);\n try {\n const response = await http.get('locales', createRequestConfig({\n query: query\n }));\n return wrapLocaleCollection(response.data);\n } catch (error) {\n errorHandler(error);\n }\n }\n\n /**\n * Synchronizes either all the content or only new content since last sync\n * See Synchronization for more information.\n * Important note: The the sync api endpoint does not support include or link resolution.\n * However contentful.js is doing link resolution client side if you only make an initial sync.\n * For the delta sync (using nextSyncToken) it is not possible since the sdk wont have access to all the data to make such an operation.\n * @memberof ContentfulClientAPI\n * @param {Object} query - Query object for the sync call. One of initial or nextSyncToken always needs to be specified, but not both.\n * @param {boolean?} query.initial - Indicates if this is the first sync. Use it if you don't have a sync token.\n * @param {string?} query.nextSyncToken - The token you got the last time you used this method. Ensures you only get changed content.\n * @param {string=} query.type - Filter by this type (all (default), Entry, Asset, Deletion, DeletedAsset or DeletedEntry)\n * @param {string=} query.content_type - Filter by this content type id\n * @param {boolean=} query.resolveLinks - When true, links to other Entries or Assets are resolved. Default: true.\n * @param {Object} options\n * @param {boolean=} [options.paginate = true] - Set to false to disable pagination\n * @return {Promise} Promise for the collection resulting of a sync operation\n * @example\n * const contentful = require('contentful')\n *\n * const client = contentful.createClient({\n * space: '',\n * accessToken: ''\n * })\n *\n * const response = await client.sync({\n * initial: true\n * })\n * console.log({\n * entries: response.entries,\n * assets: response.assets,\n * nextSyncToken: response.nextSyncToken\n * })\n */\n async function sync() {\n let query = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n paginate: true\n };\n const {\n resolveLinks,\n removeUnresolved\n } = getGlobalOptions(query);\n switchToEnvironment(http);\n return pagedSync(http, query, _objectSpread({\n resolveLinks,\n removeUnresolved\n }, options));\n }\n\n /**\n * Parse raw json data into collection of entry objects.Links will be resolved also\n * @memberof ContentfulClientAPI\n * @param {Object} raw json data\n * @example\n * let data = {items: [\n * {\n * sys: {type: 'Entry', locale: 'en-US'},\n * fields: {\n * animal: {sys: {type: 'Link', linkType: 'Animal', id: 'oink'}},\n * anotheranimal: {sys: {type: 'Link', linkType: 'Animal', id: 'middle-parrot'}}\n * }\n * }\n * ],\n * includes: {\n * Animal: [\n * {\n * sys: {type: 'Animal', id: 'oink', locale: 'en-US'},\n * fields: {\n * name: 'Pig',\n * friend: {sys: {type: 'Link', linkType: 'Animal', id: 'groundhog'}}\n * }\n * }\n * ]\n * }\n * }\n * console.log( data.items[0].fields.foo ); // undefined\n * let parsedData = client.parseEntries(data);\n * console.log( parsedData.items[0].fields.foo ); // foo\n */\n function parseEntries(data) {\n const {\n resolveLinks,\n removeUnresolved\n } = getGlobalOptions({});\n return wrapEntryCollection(data, {\n resolveLinks,\n removeUnresolved\n });\n }\n\n /*\n * Switches BaseURL to use /environments path\n * */\n function switchToEnvironment(http) {\n http.defaults.baseURL = getGlobalOptions().environmentBaseUrl;\n }\n\n /*\n * Switches BaseURL to use /spaces path\n * */\n function switchToSpace(http) {\n http.defaults.baseURL = getGlobalOptions().spaceBaseUrl;\n }\n return {\n getSpace,\n getContentType,\n getContentTypes,\n getEntry,\n getEntries,\n getAsset,\n getAssets,\n getTag,\n getTags,\n createAssetKey,\n getLocales,\n parseEntries,\n sync\n };\n}","function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }\nfunction _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\nfunction _toPropertyKey(arg) { var key = _toPrimitive(arg, \"string\"); return typeof key === \"symbol\" ? key : String(key); }\nfunction _toPrimitive(input, hint) { if (typeof input !== \"object\" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || \"default\"); if (typeof res !== \"object\") return res; throw new TypeError(\"@@toPrimitive must return a primitive value.\"); } return (hint === \"string\" ? String : Number)(input); }\n/**\n * Contentful Delivery API SDK. Allows you to create instances of a client\n * with access to the Contentful Content Delivery API.\n * @namespace contentful\n * @see ContentfulClientAPI\n */\n\nimport axios from 'axios';\nimport { createHttpClient, getUserAgentHeader } from 'contentful-sdk-core';\nimport createContentfulApi from './create-contentful-api';\nimport createGlobalOptions from './create-global-options';\n\n/**\n * Create a client instance\n * @func\n * @name createClient\n * @memberof contentful\n * @param {Object} params - Client initialization parameters\n * @prop {string} params.space - Space ID\n * @prop {string} params.accessToken - Contentful CDA Access Token\n * @prop {string} [params.environment=\"master\"] - Contentful Environment ID\n * @prop {boolean=} params.insecure - Requests will be made over http instead of the default https (default: true)\n * @prop {string=} params.host - API host (default: cdn.contentful.com). Also usable with preview.contentful.com.\n * @prop {string=} params.basePath - Path appended to the host to support gateways/proxies with custom urls.\n * @prop {Object=} params.httpAgent - Optional Node.js HTTP agent for proxying (see Node.js docs and https-proxy-agent)\n * @prop {Object=} params.httpsAgent - Optional Node.js HTTP agent for proxying (see Node.js docs and https-proxy-agent)\n * @prop {Object=} params.proxy - Optional Axios proxy (see axios docs )\n * @prop {Object=} params.headers - Optional additional headers\n * @prop {function=} params.adapter - Optional axios request adapter (see axios docs )\n * @prop {boolean=?} params.resolveLinks - If we should resolve links between entries (default: true)\n * @prop {boolean=?} params.removeUnresolved - If we should remove links to entries which could not be resolved (default: false)\n * @prop {boolean=?} params.retryOnError - If we should retry on errors and 429 rate limit exceptions (default: true)\n * @prop {function=} params.logHandler - A log handler function to process given log messages & errors. Receives the log level (error, warning & info) and the actual log data (Error object or string). (The default can be found at: https://github.com/contentful/contentful-sdk-core/blob/master/src/create-http-client.ts)\n * @prop {string=?} params.application - Application name and version e.g myApp/version\n * @prop {string=?} params.integration - Integration name and version e.g react/version\n * @prop {number=} params.timeout in milliseconds - connection timeout (default:30000)\n * @prop {number=} params.retryLimit - Optional number of retries before failure. Default is 5\n * @returns {ContentfulClientAPI.ClientAPI}\n * @example\n * const contentful = require('contentful')\n * const client = contentful.createClient({\n * accessToken: 'myAccessToken',\n * space: 'mySpaceId'\n * })\n */\n\nexport function createClient(params) {\n if (!params.accessToken) {\n throw new TypeError('Expected parameter accessToken');\n }\n if (!params.space) {\n throw new TypeError('Expected parameter space');\n }\n const defaultConfig = {\n resolveLinks: true,\n removeUnresolved: false,\n defaultHostname: 'cdn.contentful.com',\n environment: 'master'\n };\n const config = _objectSpread(_objectSpread({}, defaultConfig), params);\n const userAgentHeader = getUserAgentHeader(`contentful.js/${\"9.3.5\"}`, config.application, config.integration);\n config.headers = _objectSpread(_objectSpread({}, config.headers), {}, {\n 'Content-Type': 'application/vnd.contentful.delivery.v1+json',\n 'X-Contentful-User-Agent': userAgentHeader\n });\n const http = createHttpClient(axios, config);\n const getGlobalOptions = createGlobalOptions({\n resolveLinks: config.resolveLinks,\n environment: config.environment,\n removeUnresolved: config.removeUnresolved,\n spaceBaseUrl: http.defaults.baseURL,\n environmentBaseUrl: `${http.defaults.baseURL}environments/${config.environment}`\n });\n // Append environment to baseURL\n http.defaults.baseURL = getGlobalOptions().environmentBaseUrl;\n return createContentfulApi({\n http,\n getGlobalOptions\n });\n}","/**\n * Link resolution can be set globally, or it can be turned off for the methods\n * which make use of it. The local setting always overrides the global setting.\n * @private\n * @param {boolean} globalSetting - Global library setting for link resolution\n * @returns {function} Link resolver method preconfigured with global setting\n */\nexport default function createGlobalOptions(globalSettings) {\n /**\n * Link resolver method\n * @param {Object} query - regular query object used for collection endpoints\n */\n return function getGlobalOptions(query) {\n return Object.assign({}, globalSettings, query);\n };\n}","module.exports = require('./lib/axios');","'use strict';\n\nvar utils = require('./../utils');\nvar settle = require('./../core/settle');\nvar cookies = require('./../helpers/cookies');\nvar buildURL = require('./../helpers/buildURL');\nvar buildFullPath = require('../core/buildFullPath');\nvar parseHeaders = require('./../helpers/parseHeaders');\nvar isURLSameOrigin = require('./../helpers/isURLSameOrigin');\nvar transitionalDefaults = require('../defaults/transitional');\nvar AxiosError = require('../core/AxiosError');\nvar CanceledError = require('../cancel/CanceledError');\nvar parseProtocol = require('../helpers/parseProtocol');\n\nmodule.exports = function xhrAdapter(config) {\n return new Promise(function dispatchXhrRequest(resolve, reject) {\n var requestData = config.data;\n var requestHeaders = config.headers;\n var responseType = config.responseType;\n var onCanceled;\n function done() {\n if (config.cancelToken) {\n config.cancelToken.unsubscribe(onCanceled);\n }\n\n if (config.signal) {\n config.signal.removeEventListener('abort', onCanceled);\n }\n }\n\n if (utils.isFormData(requestData) && utils.isStandardBrowserEnv()) {\n delete requestHeaders['Content-Type']; // Let the browser set it\n }\n\n var request = new XMLHttpRequest();\n\n // HTTP basic authentication\n if (config.auth) {\n var username = config.auth.username || '';\n var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : '';\n requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);\n }\n\n var fullPath = buildFullPath(config.baseURL, config.url);\n\n request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true);\n\n // Set the request timeout in MS\n request.timeout = config.timeout;\n\n function onloadend() {\n if (!request) {\n return;\n }\n // Prepare the response\n var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;\n var responseData = !responseType || responseType === 'text' || responseType === 'json' ?\n request.responseText : request.response;\n var response = {\n data: responseData,\n status: request.status,\n statusText: request.statusText,\n headers: responseHeaders,\n config: config,\n request: request\n };\n\n settle(function _resolve(value) {\n resolve(value);\n done();\n }, function _reject(err) {\n reject(err);\n done();\n }, response);\n\n // Clean up request\n request = null;\n }\n\n if ('onloadend' in request) {\n // Use onloadend if available\n request.onloadend = onloadend;\n } else {\n // Listen for ready state to emulate onloadend\n request.onreadystatechange = function handleLoad() {\n if (!request || request.readyState !== 4) {\n return;\n }\n\n // The request errored out and we didn't get a response, this will be\n // handled by onerror instead\n // With one exception: request that using file: protocol, most browsers\n // will return status as 0 even though it's a successful request\n if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {\n return;\n }\n // readystate handler is calling before onerror or ontimeout handlers,\n // so we should call onloadend on the next 'tick'\n setTimeout(onloadend);\n };\n }\n\n // Handle browser request cancellation (as opposed to a manual cancellation)\n request.onabort = function handleAbort() {\n if (!request) {\n return;\n }\n\n reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle low level network errors\n request.onerror = function handleError() {\n // Real errors are hidden from us by the browser\n // onerror should only fire if it's a network error\n reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request, request));\n\n // Clean up request\n request = null;\n };\n\n // Handle timeout\n request.ontimeout = function handleTimeout() {\n var timeoutErrorMessage = config.timeout ? 'timeout of ' + config.timeout + 'ms exceeded' : 'timeout exceeded';\n var transitional = config.transitional || transitionalDefaults;\n if (config.timeoutErrorMessage) {\n timeoutErrorMessage = config.timeoutErrorMessage;\n }\n reject(new AxiosError(\n timeoutErrorMessage,\n transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED,\n config,\n request));\n\n // Clean up request\n request = null;\n };\n\n // Add xsrf header\n // This is only done if running in a standard browser environment.\n // Specifically not if we're in a web worker, or react-native.\n if (utils.isStandardBrowserEnv()) {\n // Add xsrf header\n var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ?\n cookies.read(config.xsrfCookieName) :\n undefined;\n\n if (xsrfValue) {\n requestHeaders[config.xsrfHeaderName] = xsrfValue;\n }\n }\n\n // Add headers to the request\n if ('setRequestHeader' in request) {\n utils.forEach(requestHeaders, function setRequestHeader(val, key) {\n if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {\n // Remove Content-Type if data is undefined\n delete requestHeaders[key];\n } else {\n // Otherwise add header to the request\n request.setRequestHeader(key, val);\n }\n });\n }\n\n // Add withCredentials to request if needed\n if (!utils.isUndefined(config.withCredentials)) {\n request.withCredentials = !!config.withCredentials;\n }\n\n // Add responseType to request if needed\n if (responseType && responseType !== 'json') {\n request.responseType = config.responseType;\n }\n\n // Handle progress if needed\n if (typeof config.onDownloadProgress === 'function') {\n request.addEventListener('progress', config.onDownloadProgress);\n }\n\n // Not all browsers support upload events\n if (typeof config.onUploadProgress === 'function' && request.upload) {\n request.upload.addEventListener('progress', config.onUploadProgress);\n }\n\n if (config.cancelToken || config.signal) {\n // Handle cancellation\n // eslint-disable-next-line func-names\n onCanceled = function(cancel) {\n if (!request) {\n return;\n }\n reject(!cancel || (cancel && cancel.type) ? new CanceledError() : cancel);\n request.abort();\n request = null;\n };\n\n config.cancelToken && config.cancelToken.subscribe(onCanceled);\n if (config.signal) {\n config.signal.aborted ? onCanceled() : config.signal.addEventListener('abort', onCanceled);\n }\n }\n\n if (!requestData) {\n requestData = null;\n }\n\n var protocol = parseProtocol(fullPath);\n\n if (protocol && [ 'http', 'https', 'file' ].indexOf(protocol) === -1) {\n reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config));\n return;\n }\n\n\n // Send the request\n request.send(requestData);\n });\n};\n","'use strict';\n\nvar utils = require('./utils');\nvar bind = require('./helpers/bind');\nvar Axios = require('./core/Axios');\nvar mergeConfig = require('./core/mergeConfig');\nvar defaults = require('./defaults');\n\n/**\n * Create an instance of Axios\n *\n * @param {Object} defaultConfig The default config for the instance\n * @return {Axios} A new instance of Axios\n */\nfunction createInstance(defaultConfig) {\n var context = new Axios(defaultConfig);\n var instance = bind(Axios.prototype.request, context);\n\n // Copy axios.prototype to instance\n utils.extend(instance, Axios.prototype, context);\n\n // Copy context to instance\n utils.extend(instance, context);\n\n // Factory for creating new instances\n instance.create = function create(instanceConfig) {\n return createInstance(mergeConfig(defaultConfig, instanceConfig));\n };\n\n return instance;\n}\n\n// Create the default instance to be exported\nvar axios = createInstance(defaults);\n\n// Expose Axios class to allow class inheritance\naxios.Axios = Axios;\n\n// Expose Cancel & CancelToken\naxios.CanceledError = require('./cancel/CanceledError');\naxios.CancelToken = require('./cancel/CancelToken');\naxios.isCancel = require('./cancel/isCancel');\naxios.VERSION = require('./env/data').version;\naxios.toFormData = require('./helpers/toFormData');\n\n// Expose AxiosError class\naxios.AxiosError = require('../lib/core/AxiosError');\n\n// alias for CanceledError for backward compatibility\naxios.Cancel = axios.CanceledError;\n\n// Expose all/spread\naxios.all = function all(promises) {\n return Promise.all(promises);\n};\naxios.spread = require('./helpers/spread');\n\n// Expose isAxiosError\naxios.isAxiosError = require('./helpers/isAxiosError');\n\nmodule.exports = axios;\n\n// Allow use of default import syntax in TypeScript\nmodule.exports.default = axios;\n","'use strict';\n\nvar CanceledError = require('./CanceledError');\n\n/**\n * A `CancelToken` is an object that can be used to request cancellation of an operation.\n *\n * @class\n * @param {Function} executor The executor function.\n */\nfunction CancelToken(executor) {\n if (typeof executor !== 'function') {\n throw new TypeError('executor must be a function.');\n }\n\n var resolvePromise;\n\n this.promise = new Promise(function promiseExecutor(resolve) {\n resolvePromise = resolve;\n });\n\n var token = this;\n\n // eslint-disable-next-line func-names\n this.promise.then(function(cancel) {\n if (!token._listeners) return;\n\n var i;\n var l = token._listeners.length;\n\n for (i = 0; i < l; i++) {\n token._listeners[i](cancel);\n }\n token._listeners = null;\n });\n\n // eslint-disable-next-line func-names\n this.promise.then = function(onfulfilled) {\n var _resolve;\n // eslint-disable-next-line func-names\n var promise = new Promise(function(resolve) {\n token.subscribe(resolve);\n _resolve = resolve;\n }).then(onfulfilled);\n\n promise.cancel = function reject() {\n token.unsubscribe(_resolve);\n };\n\n return promise;\n };\n\n executor(function cancel(message) {\n if (token.reason) {\n // Cancellation has already been requested\n return;\n }\n\n token.reason = new CanceledError(message);\n resolvePromise(token.reason);\n });\n}\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n */\nCancelToken.prototype.throwIfRequested = function throwIfRequested() {\n if (this.reason) {\n throw this.reason;\n }\n};\n\n/**\n * Subscribe to the cancel signal\n */\n\nCancelToken.prototype.subscribe = function subscribe(listener) {\n if (this.reason) {\n listener(this.reason);\n return;\n }\n\n if (this._listeners) {\n this._listeners.push(listener);\n } else {\n this._listeners = [listener];\n }\n};\n\n/**\n * Unsubscribe from the cancel signal\n */\n\nCancelToken.prototype.unsubscribe = function unsubscribe(listener) {\n if (!this._listeners) {\n return;\n }\n var index = this._listeners.indexOf(listener);\n if (index !== -1) {\n this._listeners.splice(index, 1);\n }\n};\n\n/**\n * Returns an object that contains a new `CancelToken` and a function that, when called,\n * cancels the `CancelToken`.\n */\nCancelToken.source = function source() {\n var cancel;\n var token = new CancelToken(function executor(c) {\n cancel = c;\n });\n return {\n token: token,\n cancel: cancel\n };\n};\n\nmodule.exports = CancelToken;\n","'use strict';\n\nvar AxiosError = require('../core/AxiosError');\nvar utils = require('../utils');\n\n/**\n * A `CanceledError` is an object that is thrown when an operation is canceled.\n *\n * @class\n * @param {string=} message The message.\n */\nfunction CanceledError(message) {\n // eslint-disable-next-line no-eq-null,eqeqeq\n AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED);\n this.name = 'CanceledError';\n}\n\nutils.inherits(CanceledError, AxiosError, {\n __CANCEL__: true\n});\n\nmodule.exports = CanceledError;\n","'use strict';\n\nmodule.exports = function isCancel(value) {\n return !!(value && value.__CANCEL__);\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar buildURL = require('../helpers/buildURL');\nvar InterceptorManager = require('./InterceptorManager');\nvar dispatchRequest = require('./dispatchRequest');\nvar mergeConfig = require('./mergeConfig');\nvar buildFullPath = require('./buildFullPath');\nvar validator = require('../helpers/validator');\n\nvar validators = validator.validators;\n/**\n * Create a new instance of Axios\n *\n * @param {Object} instanceConfig The default config for the instance\n */\nfunction Axios(instanceConfig) {\n this.defaults = instanceConfig;\n this.interceptors = {\n request: new InterceptorManager(),\n response: new InterceptorManager()\n };\n}\n\n/**\n * Dispatch a request\n *\n * @param {Object} config The config specific for this request (merged with this.defaults)\n */\nAxios.prototype.request = function request(configOrUrl, config) {\n /*eslint no-param-reassign:0*/\n // Allow for axios('example/url'[, config]) a la fetch API\n if (typeof configOrUrl === 'string') {\n config = config || {};\n config.url = configOrUrl;\n } else {\n config = configOrUrl || {};\n }\n\n config = mergeConfig(this.defaults, config);\n\n // Set config.method\n if (config.method) {\n config.method = config.method.toLowerCase();\n } else if (this.defaults.method) {\n config.method = this.defaults.method.toLowerCase();\n } else {\n config.method = 'get';\n }\n\n var transitional = config.transitional;\n\n if (transitional !== undefined) {\n validator.assertOptions(transitional, {\n silentJSONParsing: validators.transitional(validators.boolean),\n forcedJSONParsing: validators.transitional(validators.boolean),\n clarifyTimeoutError: validators.transitional(validators.boolean)\n }, false);\n }\n\n // filter out skipped interceptors\n var requestInterceptorChain = [];\n var synchronousRequestInterceptors = true;\n this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {\n if (typeof interceptor.runWhen === 'function' && interceptor.runWhen(config) === false) {\n return;\n }\n\n synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous;\n\n requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected);\n });\n\n var responseInterceptorChain = [];\n this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {\n responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected);\n });\n\n var promise;\n\n if (!synchronousRequestInterceptors) {\n var chain = [dispatchRequest, undefined];\n\n Array.prototype.unshift.apply(chain, requestInterceptorChain);\n chain = chain.concat(responseInterceptorChain);\n\n promise = Promise.resolve(config);\n while (chain.length) {\n promise = promise.then(chain.shift(), chain.shift());\n }\n\n return promise;\n }\n\n\n var newConfig = config;\n while (requestInterceptorChain.length) {\n var onFulfilled = requestInterceptorChain.shift();\n var onRejected = requestInterceptorChain.shift();\n try {\n newConfig = onFulfilled(newConfig);\n } catch (error) {\n onRejected(error);\n break;\n }\n }\n\n try {\n promise = dispatchRequest(newConfig);\n } catch (error) {\n return Promise.reject(error);\n }\n\n while (responseInterceptorChain.length) {\n promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift());\n }\n\n return promise;\n};\n\nAxios.prototype.getUri = function getUri(config) {\n config = mergeConfig(this.defaults, config);\n var fullPath = buildFullPath(config.baseURL, config.url);\n return buildURL(fullPath, config.params, config.paramsSerializer);\n};\n\n// Provide aliases for supported request methods\nutils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {\n /*eslint func-names:0*/\n Axios.prototype[method] = function(url, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n url: url,\n data: (config || {}).data\n }));\n };\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n /*eslint func-names:0*/\n\n function generateHTTPMethod(isForm) {\n return function httpMethod(url, data, config) {\n return this.request(mergeConfig(config || {}, {\n method: method,\n headers: isForm ? {\n 'Content-Type': 'multipart/form-data'\n } : {},\n url: url,\n data: data\n }));\n };\n }\n\n Axios.prototype[method] = generateHTTPMethod();\n\n Axios.prototype[method + 'Form'] = generateHTTPMethod(true);\n});\n\nmodule.exports = Axios;\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Create an Error with the specified message, config, error code, request and response.\n *\n * @param {string} message The error message.\n * @param {string} [code] The error code (for example, 'ECONNABORTED').\n * @param {Object} [config] The config.\n * @param {Object} [request] The request.\n * @param {Object} [response] The response.\n * @returns {Error} The created error.\n */\nfunction AxiosError(message, code, config, request, response) {\n Error.call(this);\n this.message = message;\n this.name = 'AxiosError';\n code && (this.code = code);\n config && (this.config = config);\n request && (this.request = request);\n response && (this.response = response);\n}\n\nutils.inherits(AxiosError, Error, {\n toJSON: function toJSON() {\n return {\n // Standard\n message: this.message,\n name: this.name,\n // Microsoft\n description: this.description,\n number: this.number,\n // Mozilla\n fileName: this.fileName,\n lineNumber: this.lineNumber,\n columnNumber: this.columnNumber,\n stack: this.stack,\n // Axios\n config: this.config,\n code: this.code,\n status: this.response && this.response.status ? this.response.status : null\n };\n }\n});\n\nvar prototype = AxiosError.prototype;\nvar descriptors = {};\n\n[\n 'ERR_BAD_OPTION_VALUE',\n 'ERR_BAD_OPTION',\n 'ECONNABORTED',\n 'ETIMEDOUT',\n 'ERR_NETWORK',\n 'ERR_FR_TOO_MANY_REDIRECTS',\n 'ERR_DEPRECATED',\n 'ERR_BAD_RESPONSE',\n 'ERR_BAD_REQUEST',\n 'ERR_CANCELED'\n// eslint-disable-next-line func-names\n].forEach(function(code) {\n descriptors[code] = {value: code};\n});\n\nObject.defineProperties(AxiosError, descriptors);\nObject.defineProperty(prototype, 'isAxiosError', {value: true});\n\n// eslint-disable-next-line func-names\nAxiosError.from = function(error, code, config, request, response, customProps) {\n var axiosError = Object.create(prototype);\n\n utils.toFlatObject(error, axiosError, function filter(obj) {\n return obj !== Error.prototype;\n });\n\n AxiosError.call(axiosError, error.message, code, config, request, response);\n\n axiosError.name = error.name;\n\n customProps && Object.assign(axiosError, customProps);\n\n return axiosError;\n};\n\nmodule.exports = AxiosError;\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction InterceptorManager() {\n this.handlers = [];\n}\n\n/**\n * Add a new interceptor to the stack\n *\n * @param {Function} fulfilled The function to handle `then` for a `Promise`\n * @param {Function} rejected The function to handle `reject` for a `Promise`\n *\n * @return {Number} An ID used to remove interceptor later\n */\nInterceptorManager.prototype.use = function use(fulfilled, rejected, options) {\n this.handlers.push({\n fulfilled: fulfilled,\n rejected: rejected,\n synchronous: options ? options.synchronous : false,\n runWhen: options ? options.runWhen : null\n });\n return this.handlers.length - 1;\n};\n\n/**\n * Remove an interceptor from the stack\n *\n * @param {Number} id The ID that was returned by `use`\n */\nInterceptorManager.prototype.eject = function eject(id) {\n if (this.handlers[id]) {\n this.handlers[id] = null;\n }\n};\n\n/**\n * Iterate over all the registered interceptors\n *\n * This method is particularly useful for skipping over any\n * interceptors that may have become `null` calling `eject`.\n *\n * @param {Function} fn The function to call for each interceptor\n */\nInterceptorManager.prototype.forEach = function forEach(fn) {\n utils.forEach(this.handlers, function forEachHandler(h) {\n if (h !== null) {\n fn(h);\n }\n });\n};\n\nmodule.exports = InterceptorManager;\n","'use strict';\n\nvar isAbsoluteURL = require('../helpers/isAbsoluteURL');\nvar combineURLs = require('../helpers/combineURLs');\n\n/**\n * Creates a new URL by combining the baseURL with the requestedURL,\n * only when the requestedURL is not already an absolute URL.\n * If the requestURL is absolute, this function returns the requestedURL untouched.\n *\n * @param {string} baseURL The base URL\n * @param {string} requestedURL Absolute or relative URL to combine\n * @returns {string} The combined full path\n */\nmodule.exports = function buildFullPath(baseURL, requestedURL) {\n if (baseURL && !isAbsoluteURL(requestedURL)) {\n return combineURLs(baseURL, requestedURL);\n }\n return requestedURL;\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar transformData = require('./transformData');\nvar isCancel = require('../cancel/isCancel');\nvar defaults = require('../defaults');\nvar CanceledError = require('../cancel/CanceledError');\n\n/**\n * Throws a `CanceledError` if cancellation has been requested.\n */\nfunction throwIfCancellationRequested(config) {\n if (config.cancelToken) {\n config.cancelToken.throwIfRequested();\n }\n\n if (config.signal && config.signal.aborted) {\n throw new CanceledError();\n }\n}\n\n/**\n * Dispatch a request to the server using the configured adapter.\n *\n * @param {object} config The config that is to be used for the request\n * @returns {Promise} The Promise to be fulfilled\n */\nmodule.exports = function dispatchRequest(config) {\n throwIfCancellationRequested(config);\n\n // Ensure headers exist\n config.headers = config.headers || {};\n\n // Transform request data\n config.data = transformData.call(\n config,\n config.data,\n config.headers,\n config.transformRequest\n );\n\n // Flatten headers\n config.headers = utils.merge(\n config.headers.common || {},\n config.headers[config.method] || {},\n config.headers\n );\n\n utils.forEach(\n ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],\n function cleanHeaderConfig(method) {\n delete config.headers[method];\n }\n );\n\n var adapter = config.adapter || defaults.adapter;\n\n return adapter(config).then(function onAdapterResolution(response) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n response.data = transformData.call(\n config,\n response.data,\n response.headers,\n config.transformResponse\n );\n\n return response;\n }, function onAdapterRejection(reason) {\n if (!isCancel(reason)) {\n throwIfCancellationRequested(config);\n\n // Transform response data\n if (reason && reason.response) {\n reason.response.data = transformData.call(\n config,\n reason.response.data,\n reason.response.headers,\n config.transformResponse\n );\n }\n }\n\n return Promise.reject(reason);\n });\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Config-specific merge-function which creates a new config-object\n * by merging two configuration objects together.\n *\n * @param {Object} config1\n * @param {Object} config2\n * @returns {Object} New object resulting from merging config2 to config1\n */\nmodule.exports = function mergeConfig(config1, config2) {\n // eslint-disable-next-line no-param-reassign\n config2 = config2 || {};\n var config = {};\n\n function getMergedValue(target, source) {\n if (utils.isPlainObject(target) && utils.isPlainObject(source)) {\n return utils.merge(target, source);\n } else if (utils.isPlainObject(source)) {\n return utils.merge({}, source);\n } else if (utils.isArray(source)) {\n return source.slice();\n }\n return source;\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDeepProperties(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(config1[prop], config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function valueFromConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(undefined, config2[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function defaultToConfig2(prop) {\n if (!utils.isUndefined(config2[prop])) {\n return getMergedValue(undefined, config2[prop]);\n } else if (!utils.isUndefined(config1[prop])) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n // eslint-disable-next-line consistent-return\n function mergeDirectKeys(prop) {\n if (prop in config2) {\n return getMergedValue(config1[prop], config2[prop]);\n } else if (prop in config1) {\n return getMergedValue(undefined, config1[prop]);\n }\n }\n\n var mergeMap = {\n 'url': valueFromConfig2,\n 'method': valueFromConfig2,\n 'data': valueFromConfig2,\n 'baseURL': defaultToConfig2,\n 'transformRequest': defaultToConfig2,\n 'transformResponse': defaultToConfig2,\n 'paramsSerializer': defaultToConfig2,\n 'timeout': defaultToConfig2,\n 'timeoutMessage': defaultToConfig2,\n 'withCredentials': defaultToConfig2,\n 'adapter': defaultToConfig2,\n 'responseType': defaultToConfig2,\n 'xsrfCookieName': defaultToConfig2,\n 'xsrfHeaderName': defaultToConfig2,\n 'onUploadProgress': defaultToConfig2,\n 'onDownloadProgress': defaultToConfig2,\n 'decompress': defaultToConfig2,\n 'maxContentLength': defaultToConfig2,\n 'maxBodyLength': defaultToConfig2,\n 'beforeRedirect': defaultToConfig2,\n 'transport': defaultToConfig2,\n 'httpAgent': defaultToConfig2,\n 'httpsAgent': defaultToConfig2,\n 'cancelToken': defaultToConfig2,\n 'socketPath': defaultToConfig2,\n 'responseEncoding': defaultToConfig2,\n 'validateStatus': mergeDirectKeys\n };\n\n utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) {\n var merge = mergeMap[prop] || mergeDeepProperties;\n var configValue = merge(prop);\n (utils.isUndefined(configValue) && merge !== mergeDirectKeys) || (config[prop] = configValue);\n });\n\n return config;\n};\n","'use strict';\n\nvar AxiosError = require('./AxiosError');\n\n/**\n * Resolve or reject a Promise based on response status.\n *\n * @param {Function} resolve A function that resolves the promise.\n * @param {Function} reject A function that rejects the promise.\n * @param {object} response The response.\n */\nmodule.exports = function settle(resolve, reject, response) {\n var validateStatus = response.config.validateStatus;\n if (!response.status || !validateStatus || validateStatus(response.status)) {\n resolve(response);\n } else {\n reject(new AxiosError(\n 'Request failed with status code ' + response.status,\n [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4],\n response.config,\n response.request,\n response\n ));\n }\n};\n","'use strict';\n\nvar utils = require('./../utils');\nvar defaults = require('../defaults');\n\n/**\n * Transform the data for a request or a response\n *\n * @param {Object|String} data The data to be transformed\n * @param {Array} headers The headers for the request or response\n * @param {Array|Function} fns A single function or Array of functions\n * @returns {*} The resulting transformed data\n */\nmodule.exports = function transformData(data, headers, fns) {\n var context = this || defaults;\n /*eslint no-param-reassign:0*/\n utils.forEach(fns, function transform(fn) {\n data = fn.call(context, data, headers);\n });\n\n return data;\n};\n","'use strict';\n\nvar utils = require('../utils');\nvar normalizeHeaderName = require('../helpers/normalizeHeaderName');\nvar AxiosError = require('../core/AxiosError');\nvar transitionalDefaults = require('./transitional');\nvar toFormData = require('../helpers/toFormData');\n\nvar DEFAULT_CONTENT_TYPE = {\n 'Content-Type': 'application/x-www-form-urlencoded'\n};\n\nfunction setContentTypeIfUnset(headers, value) {\n if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {\n headers['Content-Type'] = value;\n }\n}\n\nfunction getDefaultAdapter() {\n var adapter;\n if (typeof XMLHttpRequest !== 'undefined') {\n // For browsers use XHR adapter\n adapter = require('../adapters/xhr');\n } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') {\n // For node use HTTP adapter\n adapter = require('../adapters/http');\n }\n return adapter;\n}\n\nfunction stringifySafely(rawValue, parser, encoder) {\n if (utils.isString(rawValue)) {\n try {\n (parser || JSON.parse)(rawValue);\n return utils.trim(rawValue);\n } catch (e) {\n if (e.name !== 'SyntaxError') {\n throw e;\n }\n }\n }\n\n return (encoder || JSON.stringify)(rawValue);\n}\n\nvar defaults = {\n\n transitional: transitionalDefaults,\n\n adapter: getDefaultAdapter(),\n\n transformRequest: [function transformRequest(data, headers) {\n normalizeHeaderName(headers, 'Accept');\n normalizeHeaderName(headers, 'Content-Type');\n\n if (utils.isFormData(data) ||\n utils.isArrayBuffer(data) ||\n utils.isBuffer(data) ||\n utils.isStream(data) ||\n utils.isFile(data) ||\n utils.isBlob(data)\n ) {\n return data;\n }\n if (utils.isArrayBufferView(data)) {\n return data.buffer;\n }\n if (utils.isURLSearchParams(data)) {\n setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');\n return data.toString();\n }\n\n var isObjectPayload = utils.isObject(data);\n var contentType = headers && headers['Content-Type'];\n\n var isFileList;\n\n if ((isFileList = utils.isFileList(data)) || (isObjectPayload && contentType === 'multipart/form-data')) {\n var _FormData = this.env && this.env.FormData;\n return toFormData(isFileList ? {'files[]': data} : data, _FormData && new _FormData());\n } else if (isObjectPayload || contentType === 'application/json') {\n setContentTypeIfUnset(headers, 'application/json');\n return stringifySafely(data);\n }\n\n return data;\n }],\n\n transformResponse: [function transformResponse(data) {\n var transitional = this.transitional || defaults.transitional;\n var silentJSONParsing = transitional && transitional.silentJSONParsing;\n var forcedJSONParsing = transitional && transitional.forcedJSONParsing;\n var strictJSONParsing = !silentJSONParsing && this.responseType === 'json';\n\n if (strictJSONParsing || (forcedJSONParsing && utils.isString(data) && data.length)) {\n try {\n return JSON.parse(data);\n } catch (e) {\n if (strictJSONParsing) {\n if (e.name === 'SyntaxError') {\n throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response);\n }\n throw e;\n }\n }\n }\n\n return data;\n }],\n\n /**\n * A timeout in milliseconds to abort a request. If set to 0 (default) a\n * timeout is not created.\n */\n timeout: 0,\n\n xsrfCookieName: 'XSRF-TOKEN',\n xsrfHeaderName: 'X-XSRF-TOKEN',\n\n maxContentLength: -1,\n maxBodyLength: -1,\n\n env: {\n FormData: require('./env/FormData')\n },\n\n validateStatus: function validateStatus(status) {\n return status >= 200 && status < 300;\n },\n\n headers: {\n common: {\n 'Accept': 'application/json, text/plain, */*'\n }\n }\n};\n\nutils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {\n defaults.headers[method] = {};\n});\n\nutils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {\n defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);\n});\n\nmodule.exports = defaults;\n","'use strict';\n\nmodule.exports = {\n silentJSONParsing: true,\n forcedJSONParsing: true,\n clarifyTimeoutError: false\n};\n","module.exports = {\n \"version\": \"0.27.2\"\n};","'use strict';\n\nmodule.exports = function bind(fn, thisArg) {\n return function wrap() {\n var args = new Array(arguments.length);\n for (var i = 0; i < args.length; i++) {\n args[i] = arguments[i];\n }\n return fn.apply(thisArg, args);\n };\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nfunction encode(val) {\n return encodeURIComponent(val).\n replace(/%3A/gi, ':').\n replace(/%24/g, '$').\n replace(/%2C/gi, ',').\n replace(/%20/g, '+').\n replace(/%5B/gi, '[').\n replace(/%5D/gi, ']');\n}\n\n/**\n * Build a URL by appending params to the end\n *\n * @param {string} url The base of the url (e.g., http://www.google.com)\n * @param {object} [params] The params to be appended\n * @returns {string} The formatted url\n */\nmodule.exports = function buildURL(url, params, paramsSerializer) {\n /*eslint no-param-reassign:0*/\n if (!params) {\n return url;\n }\n\n var serializedParams;\n if (paramsSerializer) {\n serializedParams = paramsSerializer(params);\n } else if (utils.isURLSearchParams(params)) {\n serializedParams = params.toString();\n } else {\n var parts = [];\n\n utils.forEach(params, function serialize(val, key) {\n if (val === null || typeof val === 'undefined') {\n return;\n }\n\n if (utils.isArray(val)) {\n key = key + '[]';\n } else {\n val = [val];\n }\n\n utils.forEach(val, function parseValue(v) {\n if (utils.isDate(v)) {\n v = v.toISOString();\n } else if (utils.isObject(v)) {\n v = JSON.stringify(v);\n }\n parts.push(encode(key) + '=' + encode(v));\n });\n });\n\n serializedParams = parts.join('&');\n }\n\n if (serializedParams) {\n var hashmarkIndex = url.indexOf('#');\n if (hashmarkIndex !== -1) {\n url = url.slice(0, hashmarkIndex);\n }\n\n url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;\n }\n\n return url;\n};\n","'use strict';\n\n/**\n * Creates a new URL by combining the specified URLs\n *\n * @param {string} baseURL The base URL\n * @param {string} relativeURL The relative URL\n * @returns {string} The combined URL\n */\nmodule.exports = function combineURLs(baseURL, relativeURL) {\n return relativeURL\n ? baseURL.replace(/\\/+$/, '') + '/' + relativeURL.replace(/^\\/+/, '')\n : baseURL;\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs support document.cookie\n (function standardBrowserEnv() {\n return {\n write: function write(name, value, expires, path, domain, secure) {\n var cookie = [];\n cookie.push(name + '=' + encodeURIComponent(value));\n\n if (utils.isNumber(expires)) {\n cookie.push('expires=' + new Date(expires).toGMTString());\n }\n\n if (utils.isString(path)) {\n cookie.push('path=' + path);\n }\n\n if (utils.isString(domain)) {\n cookie.push('domain=' + domain);\n }\n\n if (secure === true) {\n cookie.push('secure');\n }\n\n document.cookie = cookie.join('; ');\n },\n\n read: function read(name) {\n var match = document.cookie.match(new RegExp('(^|;\\\\s*)(' + name + ')=([^;]*)'));\n return (match ? decodeURIComponent(match[3]) : null);\n },\n\n remove: function remove(name) {\n this.write(name, '', Date.now() - 86400000);\n }\n };\n })() :\n\n // Non standard browser env (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return {\n write: function write() {},\n read: function read() { return null; },\n remove: function remove() {}\n };\n })()\n);\n","'use strict';\n\n/**\n * Determines whether the specified URL is absolute\n *\n * @param {string} url The URL to test\n * @returns {boolean} True if the specified URL is absolute, otherwise false\n */\nmodule.exports = function isAbsoluteURL(url) {\n // A URL is considered absolute if it begins with \"://\" or \"//\" (protocol-relative URL).\n // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed\n // by any combination of letters, digits, plus, period, or hyphen.\n return /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(url);\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\n/**\n * Determines whether the payload is an error thrown by Axios\n *\n * @param {*} payload The value to test\n * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false\n */\nmodule.exports = function isAxiosError(payload) {\n return utils.isObject(payload) && (payload.isAxiosError === true);\n};\n","'use strict';\n\nvar utils = require('./../utils');\n\nmodule.exports = (\n utils.isStandardBrowserEnv() ?\n\n // Standard browser envs have full support of the APIs needed to test\n // whether the request URL is of the same origin as current location.\n (function standardBrowserEnv() {\n var msie = /(msie|trident)/i.test(navigator.userAgent);\n var urlParsingNode = document.createElement('a');\n var originURL;\n\n /**\n * Parse a URL to discover it's components\n *\n * @param {String} url The URL to be parsed\n * @returns {Object}\n */\n function resolveURL(url) {\n var href = url;\n\n if (msie) {\n // IE needs attribute set twice to normalize properties\n urlParsingNode.setAttribute('href', href);\n href = urlParsingNode.href;\n }\n\n urlParsingNode.setAttribute('href', href);\n\n // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n return {\n href: urlParsingNode.href,\n protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n host: urlParsingNode.host,\n search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n hostname: urlParsingNode.hostname,\n port: urlParsingNode.port,\n pathname: (urlParsingNode.pathname.charAt(0) === '/') ?\n urlParsingNode.pathname :\n '/' + urlParsingNode.pathname\n };\n }\n\n originURL = resolveURL(window.location.href);\n\n /**\n * Determine if a URL shares the same origin as the current location\n *\n * @param {String} requestURL The URL to test\n * @returns {boolean} True if URL shares the same origin, otherwise false\n */\n return function isURLSameOrigin(requestURL) {\n var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;\n return (parsed.protocol === originURL.protocol &&\n parsed.host === originURL.host);\n };\n })() :\n\n // Non standard browser envs (web workers, react-native) lack needed support.\n (function nonStandardBrowserEnv() {\n return function isURLSameOrigin() {\n return true;\n };\n })()\n);\n","'use strict';\n\nvar utils = require('../utils');\n\nmodule.exports = function normalizeHeaderName(headers, normalizedName) {\n utils.forEach(headers, function processHeader(value, name) {\n if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {\n headers[normalizedName] = value;\n delete headers[name];\n }\n });\n};\n","// eslint-disable-next-line strict\nmodule.exports = null;\n","'use strict';\n\nvar utils = require('./../utils');\n\n// Headers whose duplicates are ignored by node\n// c.f. https://nodejs.org/api/http.html#http_message_headers\nvar ignoreDuplicateOf = [\n 'age', 'authorization', 'content-length', 'content-type', 'etag',\n 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',\n 'last-modified', 'location', 'max-forwards', 'proxy-authorization',\n 'referer', 'retry-after', 'user-agent'\n];\n\n/**\n * Parse headers into an object\n *\n * ```\n * Date: Wed, 27 Aug 2014 08:58:49 GMT\n * Content-Type: application/json\n * Connection: keep-alive\n * Transfer-Encoding: chunked\n * ```\n *\n * @param {String} headers Headers needing to be parsed\n * @returns {Object} Headers parsed into an object\n */\nmodule.exports = function parseHeaders(headers) {\n var parsed = {};\n var key;\n var val;\n var i;\n\n if (!headers) { return parsed; }\n\n utils.forEach(headers.split('\\n'), function parser(line) {\n i = line.indexOf(':');\n key = utils.trim(line.substr(0, i)).toLowerCase();\n val = utils.trim(line.substr(i + 1));\n\n if (key) {\n if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {\n return;\n }\n if (key === 'set-cookie') {\n parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);\n } else {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n }\n });\n\n return parsed;\n};\n","'use strict';\n\nmodule.exports = function parseProtocol(url) {\n var match = /^([-+\\w]{1,25})(:?\\/\\/|:)/.exec(url);\n return match && match[1] || '';\n};\n","'use strict';\n\n/**\n * Syntactic sugar for invoking a function and expanding an array for arguments.\n *\n * Common use case would be to use `Function.prototype.apply`.\n *\n * ```js\n * function f(x, y, z) {}\n * var args = [1, 2, 3];\n * f.apply(null, args);\n * ```\n *\n * With `spread` this example can be re-written.\n *\n * ```js\n * spread(function(x, y, z) {})([1, 2, 3]);\n * ```\n *\n * @param {Function} callback\n * @returns {Function}\n */\nmodule.exports = function spread(callback) {\n return function wrap(arr) {\n return callback.apply(null, arr);\n };\n};\n","'use strict';\n\nvar utils = require('../utils');\n\n/**\n * Convert a data object to FormData\n * @param {Object} obj\n * @param {?Object} [formData]\n * @returns {Object}\n **/\n\nfunction toFormData(obj, formData) {\n // eslint-disable-next-line no-param-reassign\n formData = formData || new FormData();\n\n var stack = [];\n\n function convertValue(value) {\n if (value === null) return '';\n\n if (utils.isDate(value)) {\n return value.toISOString();\n }\n\n if (utils.isArrayBuffer(value) || utils.isTypedArray(value)) {\n return typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value);\n }\n\n return value;\n }\n\n function build(data, parentKey) {\n if (utils.isPlainObject(data) || utils.isArray(data)) {\n if (stack.indexOf(data) !== -1) {\n throw Error('Circular reference detected in ' + parentKey);\n }\n\n stack.push(data);\n\n utils.forEach(data, function each(value, key) {\n if (utils.isUndefined(value)) return;\n var fullKey = parentKey ? parentKey + '.' + key : key;\n var arr;\n\n if (value && !parentKey && typeof value === 'object') {\n if (utils.endsWith(key, '{}')) {\n // eslint-disable-next-line no-param-reassign\n value = JSON.stringify(value);\n } else if (utils.endsWith(key, '[]') && (arr = utils.toArray(value))) {\n // eslint-disable-next-line func-names\n arr.forEach(function(el) {\n !utils.isUndefined(el) && formData.append(fullKey, convertValue(el));\n });\n return;\n }\n }\n\n build(value, fullKey);\n });\n\n stack.pop();\n } else {\n formData.append(parentKey, convertValue(data));\n }\n }\n\n build(obj);\n\n return formData;\n}\n\nmodule.exports = toFormData;\n","'use strict';\n\nvar VERSION = require('../env/data').version;\nvar AxiosError = require('../core/AxiosError');\n\nvar validators = {};\n\n// eslint-disable-next-line func-names\n['object', 'boolean', 'number', 'function', 'string', 'symbol'].forEach(function(type, i) {\n validators[type] = function validator(thing) {\n return typeof thing === type || 'a' + (i < 1 ? 'n ' : ' ') + type;\n };\n});\n\nvar deprecatedWarnings = {};\n\n/**\n * Transitional option validator\n * @param {function|boolean?} validator - set to false if the transitional option has been removed\n * @param {string?} version - deprecated version / removed since version\n * @param {string?} message - some message with additional info\n * @returns {function}\n */\nvalidators.transitional = function transitional(validator, version, message) {\n function formatMessage(opt, desc) {\n return '[Axios v' + VERSION + '] Transitional option \\'' + opt + '\\'' + desc + (message ? '. ' + message : '');\n }\n\n // eslint-disable-next-line func-names\n return function(value, opt, opts) {\n if (validator === false) {\n throw new AxiosError(\n formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')),\n AxiosError.ERR_DEPRECATED\n );\n }\n\n if (version && !deprecatedWarnings[opt]) {\n deprecatedWarnings[opt] = true;\n // eslint-disable-next-line no-console\n console.warn(\n formatMessage(\n opt,\n ' has been deprecated since v' + version + ' and will be removed in the near future'\n )\n );\n }\n\n return validator ? validator(value, opt, opts) : true;\n };\n};\n\n/**\n * Assert object's properties type\n * @param {object} options\n * @param {object} schema\n * @param {boolean?} allowUnknown\n */\n\nfunction assertOptions(options, schema, allowUnknown) {\n if (typeof options !== 'object') {\n throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE);\n }\n var keys = Object.keys(options);\n var i = keys.length;\n while (i-- > 0) {\n var opt = keys[i];\n var validator = schema[opt];\n if (validator) {\n var value = options[opt];\n var result = value === undefined || validator(value, opt, options);\n if (result !== true) {\n throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE);\n }\n continue;\n }\n if (allowUnknown !== true) {\n throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION);\n }\n }\n}\n\nmodule.exports = {\n assertOptions: assertOptions,\n validators: validators\n};\n","'use strict';\n\nvar bind = require('./helpers/bind');\n\n// utils is a library of generic helper functions non-specific to axios\n\nvar toString = Object.prototype.toString;\n\n// eslint-disable-next-line func-names\nvar kindOf = (function(cache) {\n // eslint-disable-next-line func-names\n return function(thing) {\n var str = toString.call(thing);\n return cache[str] || (cache[str] = str.slice(8, -1).toLowerCase());\n };\n})(Object.create(null));\n\nfunction kindOfTest(type) {\n type = type.toLowerCase();\n return function isKindOf(thing) {\n return kindOf(thing) === type;\n };\n}\n\n/**\n * Determine if a value is an Array\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Array, otherwise false\n */\nfunction isArray(val) {\n return Array.isArray(val);\n}\n\n/**\n * Determine if a value is undefined\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if the value is undefined, otherwise false\n */\nfunction isUndefined(val) {\n return typeof val === 'undefined';\n}\n\n/**\n * Determine if a value is a Buffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Buffer, otherwise false\n */\nfunction isBuffer(val) {\n return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor)\n && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val);\n}\n\n/**\n * Determine if a value is an ArrayBuffer\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an ArrayBuffer, otherwise false\n */\nvar isArrayBuffer = kindOfTest('ArrayBuffer');\n\n\n/**\n * Determine if a value is a view on an ArrayBuffer\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false\n */\nfunction isArrayBufferView(val) {\n var result;\n if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {\n result = ArrayBuffer.isView(val);\n } else {\n result = (val) && (val.buffer) && (isArrayBuffer(val.buffer));\n }\n return result;\n}\n\n/**\n * Determine if a value is a String\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a String, otherwise false\n */\nfunction isString(val) {\n return typeof val === 'string';\n}\n\n/**\n * Determine if a value is a Number\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Number, otherwise false\n */\nfunction isNumber(val) {\n return typeof val === 'number';\n}\n\n/**\n * Determine if a value is an Object\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is an Object, otherwise false\n */\nfunction isObject(val) {\n return val !== null && typeof val === 'object';\n}\n\n/**\n * Determine if a value is a plain Object\n *\n * @param {Object} val The value to test\n * @return {boolean} True if value is a plain Object, otherwise false\n */\nfunction isPlainObject(val) {\n if (kindOf(val) !== 'object') {\n return false;\n }\n\n var prototype = Object.getPrototypeOf(val);\n return prototype === null || prototype === Object.prototype;\n}\n\n/**\n * Determine if a value is a Date\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Date, otherwise false\n */\nvar isDate = kindOfTest('Date');\n\n/**\n * Determine if a value is a File\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nvar isFile = kindOfTest('File');\n\n/**\n * Determine if a value is a Blob\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Blob, otherwise false\n */\nvar isBlob = kindOfTest('Blob');\n\n/**\n * Determine if a value is a FileList\n *\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a File, otherwise false\n */\nvar isFileList = kindOfTest('FileList');\n\n/**\n * Determine if a value is a Function\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Function, otherwise false\n */\nfunction isFunction(val) {\n return toString.call(val) === '[object Function]';\n}\n\n/**\n * Determine if a value is a Stream\n *\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a Stream, otherwise false\n */\nfunction isStream(val) {\n return isObject(val) && isFunction(val.pipe);\n}\n\n/**\n * Determine if a value is a FormData\n *\n * @param {Object} thing The value to test\n * @returns {boolean} True if value is an FormData, otherwise false\n */\nfunction isFormData(thing) {\n var pattern = '[object FormData]';\n return thing && (\n (typeof FormData === 'function' && thing instanceof FormData) ||\n toString.call(thing) === pattern ||\n (isFunction(thing.toString) && thing.toString() === pattern)\n );\n}\n\n/**\n * Determine if a value is a URLSearchParams object\n * @function\n * @param {Object} val The value to test\n * @returns {boolean} True if value is a URLSearchParams object, otherwise false\n */\nvar isURLSearchParams = kindOfTest('URLSearchParams');\n\n/**\n * Trim excess whitespace off the beginning and end of a string\n *\n * @param {String} str The String to trim\n * @returns {String} The String freed of excess whitespace\n */\nfunction trim(str) {\n return str.trim ? str.trim() : str.replace(/^\\s+|\\s+$/g, '');\n}\n\n/**\n * Determine if we're running in a standard browser environment\n *\n * This allows axios to run in a web worker, and react-native.\n * Both environments support XMLHttpRequest, but not fully standard globals.\n *\n * web workers:\n * typeof window -> undefined\n * typeof document -> undefined\n *\n * react-native:\n * navigator.product -> 'ReactNative'\n * nativescript\n * navigator.product -> 'NativeScript' or 'NS'\n */\nfunction isStandardBrowserEnv() {\n if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' ||\n navigator.product === 'NativeScript' ||\n navigator.product === 'NS')) {\n return false;\n }\n return (\n typeof window !== 'undefined' &&\n typeof document !== 'undefined'\n );\n}\n\n/**\n * Iterate over an Array or an Object invoking a function for each item.\n *\n * If `obj` is an Array callback will be called passing\n * the value, index, and complete array for each item.\n *\n * If 'obj' is an Object callback will be called passing\n * the value, key, and complete object for each property.\n *\n * @param {Object|Array} obj The object to iterate\n * @param {Function} fn The callback to invoke for each item\n */\nfunction forEach(obj, fn) {\n // Don't bother if no value provided\n if (obj === null || typeof obj === 'undefined') {\n return;\n }\n\n // Force an array if not already something iterable\n if (typeof obj !== 'object') {\n /*eslint no-param-reassign:0*/\n obj = [obj];\n }\n\n if (isArray(obj)) {\n // Iterate over array values\n for (var i = 0, l = obj.length; i < l; i++) {\n fn.call(null, obj[i], i, obj);\n }\n } else {\n // Iterate over object keys\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn.call(null, obj[key], key, obj);\n }\n }\n }\n}\n\n/**\n * Accepts varargs expecting each argument to be an object, then\n * immutably merges the properties of each object and returns result.\n *\n * When multiple objects contain the same key the later object in\n * the arguments list will take precedence.\n *\n * Example:\n *\n * ```js\n * var result = merge({foo: 123}, {foo: 456});\n * console.log(result.foo); // outputs 456\n * ```\n *\n * @param {Object} obj1 Object to merge\n * @returns {Object} Result of all merge properties\n */\nfunction merge(/* obj1, obj2, obj3, ... */) {\n var result = {};\n function assignValue(val, key) {\n if (isPlainObject(result[key]) && isPlainObject(val)) {\n result[key] = merge(result[key], val);\n } else if (isPlainObject(val)) {\n result[key] = merge({}, val);\n } else if (isArray(val)) {\n result[key] = val.slice();\n } else {\n result[key] = val;\n }\n }\n\n for (var i = 0, l = arguments.length; i < l; i++) {\n forEach(arguments[i], assignValue);\n }\n return result;\n}\n\n/**\n * Extends object a by mutably adding to it the properties of object b.\n *\n * @param {Object} a The object to be extended\n * @param {Object} b The object to copy properties from\n * @param {Object} thisArg The object to bind function to\n * @return {Object} The resulting value of object a\n */\nfunction extend(a, b, thisArg) {\n forEach(b, function assignValue(val, key) {\n if (thisArg && typeof val === 'function') {\n a[key] = bind(val, thisArg);\n } else {\n a[key] = val;\n }\n });\n return a;\n}\n\n/**\n * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)\n *\n * @param {string} content with BOM\n * @return {string} content value without BOM\n */\nfunction stripBOM(content) {\n if (content.charCodeAt(0) === 0xFEFF) {\n content = content.slice(1);\n }\n return content;\n}\n\n/**\n * Inherit the prototype methods from one constructor into another\n * @param {function} constructor\n * @param {function} superConstructor\n * @param {object} [props]\n * @param {object} [descriptors]\n */\n\nfunction inherits(constructor, superConstructor, props, descriptors) {\n constructor.prototype = Object.create(superConstructor.prototype, descriptors);\n constructor.prototype.constructor = constructor;\n props && Object.assign(constructor.prototype, props);\n}\n\n/**\n * Resolve object with deep prototype chain to a flat object\n * @param {Object} sourceObj source object\n * @param {Object} [destObj]\n * @param {Function} [filter]\n * @returns {Object}\n */\n\nfunction toFlatObject(sourceObj, destObj, filter) {\n var props;\n var i;\n var prop;\n var merged = {};\n\n destObj = destObj || {};\n\n do {\n props = Object.getOwnPropertyNames(sourceObj);\n i = props.length;\n while (i-- > 0) {\n prop = props[i];\n if (!merged[prop]) {\n destObj[prop] = sourceObj[prop];\n merged[prop] = true;\n }\n }\n sourceObj = Object.getPrototypeOf(sourceObj);\n } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype);\n\n return destObj;\n}\n\n/*\n * determines whether a string ends with the characters of a specified string\n * @param {String} str\n * @param {String} searchString\n * @param {Number} [position= 0]\n * @returns {boolean}\n */\nfunction endsWith(str, searchString, position) {\n str = String(str);\n if (position === undefined || position > str.length) {\n position = str.length;\n }\n position -= searchString.length;\n var lastIndex = str.indexOf(searchString, position);\n return lastIndex !== -1 && lastIndex === position;\n}\n\n\n/**\n * Returns new array from array like object\n * @param {*} [thing]\n * @returns {Array}\n */\nfunction toArray(thing) {\n if (!thing) return null;\n var i = thing.length;\n if (isUndefined(i)) return null;\n var arr = new Array(i);\n while (i-- > 0) {\n arr[i] = thing[i];\n }\n return arr;\n}\n\n// eslint-disable-next-line func-names\nvar isTypedArray = (function(TypedArray) {\n // eslint-disable-next-line func-names\n return function(thing) {\n return TypedArray && thing instanceof TypedArray;\n };\n})(typeof Uint8Array !== 'undefined' && Object.getPrototypeOf(Uint8Array));\n\nmodule.exports = {\n isArray: isArray,\n isArrayBuffer: isArrayBuffer,\n isBuffer: isBuffer,\n isFormData: isFormData,\n isArrayBufferView: isArrayBufferView,\n isString: isString,\n isNumber: isNumber,\n isObject: isObject,\n isPlainObject: isPlainObject,\n isUndefined: isUndefined,\n isDate: isDate,\n isFile: isFile,\n isBlob: isBlob,\n isFunction: isFunction,\n isStream: isStream,\n isURLSearchParams: isURLSearchParams,\n isStandardBrowserEnv: isStandardBrowserEnv,\n forEach: forEach,\n merge: merge,\n extend: extend,\n trim: trim,\n stripBOM: stripBOM,\n inherits: inherits,\n toFlatObject: toFlatObject,\n kindOf: kindOf,\n kindOfTest: kindOfTest,\n endsWith: endsWith,\n toArray: toArray,\n isTypedArray: isTypedArray,\n isFileList: isFileList\n};\n","'use strict';\n\nvar isMergeableObject = function isMergeableObject(value) {\n\treturn isNonNullObject(value)\n\t\t&& !isSpecial(value)\n};\n\nfunction isNonNullObject(value) {\n\treturn !!value && typeof value === 'object'\n}\n\nfunction isSpecial(value) {\n\tvar stringValue = Object.prototype.toString.call(value);\n\n\treturn stringValue === '[object RegExp]'\n\t\t|| stringValue === '[object Date]'\n\t\t|| isReactElement(value)\n}\n\n// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25\nvar canUseSymbol = typeof Symbol === 'function' && Symbol.for;\nvar REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;\n\nfunction isReactElement(value) {\n\treturn value.$$typeof === REACT_ELEMENT_TYPE\n}\n\nfunction emptyTarget(val) {\n\treturn Array.isArray(val) ? [] : {}\n}\n\nfunction cloneUnlessOtherwiseSpecified(value, options) {\n\treturn (options.clone !== false && options.isMergeableObject(value))\n\t\t? deepmerge(emptyTarget(value), value, options)\n\t\t: value\n}\n\nfunction defaultArrayMerge(target, source, options) {\n\treturn target.concat(source).map(function(element) {\n\t\treturn cloneUnlessOtherwiseSpecified(element, options)\n\t})\n}\n\nfunction getMergeFunction(key, options) {\n\tif (!options.customMerge) {\n\t\treturn deepmerge\n\t}\n\tvar customMerge = options.customMerge(key);\n\treturn typeof customMerge === 'function' ? customMerge : deepmerge\n}\n\nfunction getEnumerableOwnPropertySymbols(target) {\n\treturn Object.getOwnPropertySymbols\n\t\t? Object.getOwnPropertySymbols(target).filter(function(symbol) {\n\t\t\treturn Object.propertyIsEnumerable.call(target, symbol)\n\t\t})\n\t\t: []\n}\n\nfunction getKeys(target) {\n\treturn Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))\n}\n\nfunction propertyIsOnObject(object, property) {\n\ttry {\n\t\treturn property in object\n\t} catch(_) {\n\t\treturn false\n\t}\n}\n\n// Protects from prototype poisoning and unexpected merging up the prototype chain.\nfunction propertyIsUnsafe(target, key) {\n\treturn propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,\n\t\t&& !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,\n\t\t\t&& Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.\n}\n\nfunction mergeObject(target, source, options) {\n\tvar destination = {};\n\tif (options.isMergeableObject(target)) {\n\t\tgetKeys(target).forEach(function(key) {\n\t\t\tdestination[key] = cloneUnlessOtherwiseSpecified(target[key], options);\n\t\t});\n\t}\n\tgetKeys(source).forEach(function(key) {\n\t\tif (propertyIsUnsafe(target, key)) {\n\t\t\treturn\n\t\t}\n\n\t\tif (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {\n\t\t\tdestination[key] = getMergeFunction(key, options)(target[key], source[key], options);\n\t\t} else {\n\t\t\tdestination[key] = cloneUnlessOtherwiseSpecified(source[key], options);\n\t\t}\n\t});\n\treturn destination\n}\n\nfunction deepmerge(target, source, options) {\n\toptions = options || {};\n\toptions.arrayMerge = options.arrayMerge || defaultArrayMerge;\n\toptions.isMergeableObject = options.isMergeableObject || isMergeableObject;\n\t// cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()\n\t// implementations can use it. The caller may not replace it.\n\toptions.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;\n\n\tvar sourceIsArray = Array.isArray(source);\n\tvar targetIsArray = Array.isArray(target);\n\tvar sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;\n\n\tif (!sourceAndTargetTypesMatch) {\n\t\treturn cloneUnlessOtherwiseSpecified(source, options)\n\t} else if (sourceIsArray) {\n\t\treturn options.arrayMerge(target, source, options)\n\t} else {\n\t\treturn mergeObject(target, source, options)\n\t}\n}\n\ndeepmerge.all = function deepmergeAll(array, options) {\n\tif (!Array.isArray(array)) {\n\t\tthrow new Error('first argument should be an array')\n\t}\n\n\treturn array.reduce(function(prev, next) {\n\t\treturn deepmerge(prev, next, options)\n\t}, {})\n};\n\nvar deepmerge_1 = deepmerge;\n\nmodule.exports = deepmerge_1;\n","\n/**\n * Expose `Emitter`.\n */\n\nmodule.exports = Emitter;\n\n/**\n * Initialize a new `Emitter`.\n *\n * @api public\n */\n\nfunction Emitter(obj) {\n if (obj) return mixin(obj);\n};\n\n/**\n * Mixin the emitter properties.\n *\n * @param {Object} obj\n * @return {Object}\n * @api private\n */\n\nfunction mixin(obj) {\n for (var key in Emitter.prototype) {\n obj[key] = Emitter.prototype[key];\n }\n return obj;\n}\n\n/**\n * Listen on the given `event` with `fn`.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.on =\nEmitter.prototype.addEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n (this._callbacks[event] = this._callbacks[event] || [])\n .push(fn);\n return this;\n};\n\n/**\n * Adds an `event` listener that will be invoked a single\n * time then automatically removed.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.once = function(event, fn){\n var self = this;\n this._callbacks = this._callbacks || {};\n\n function on() {\n self.off(event, on);\n fn.apply(this, arguments);\n }\n\n on.fn = fn;\n this.on(event, on);\n return this;\n};\n\n/**\n * Remove the given callback for `event` or all\n * registered callbacks.\n *\n * @param {String} event\n * @param {Function} fn\n * @return {Emitter}\n * @api public\n */\n\nEmitter.prototype.off =\nEmitter.prototype.removeListener =\nEmitter.prototype.removeAllListeners =\nEmitter.prototype.removeEventListener = function(event, fn){\n this._callbacks = this._callbacks || {};\n\n // all\n if (0 == arguments.length) {\n this._callbacks = {};\n return this;\n }\n\n // specific event\n var callbacks = this._callbacks[event];\n if (!callbacks) return this;\n\n // remove all handlers\n if (1 == arguments.length) {\n delete this._callbacks[event];\n return this;\n }\n\n // remove specific handler\n var cb;\n for (var i = 0; i < callbacks.length; i++) {\n cb = callbacks[i];\n if (cb === fn || cb.fn === fn) {\n callbacks.splice(i, 1);\n break;\n }\n }\n return this;\n};\n\n/**\n * Emit `event` with the given args.\n *\n * @param {String} event\n * @param {Mixed} ...\n * @return {Emitter}\n */\n\nEmitter.prototype.emit = function(event){\n this._callbacks = this._callbacks || {};\n var args = [].slice.call(arguments, 1)\n , callbacks = this._callbacks[event];\n\n if (callbacks) {\n callbacks = callbacks.slice(0);\n for (var i = 0, len = callbacks.length; i < len; ++i) {\n callbacks[i].apply(this, args);\n }\n }\n\n return this;\n};\n\n/**\n * Return array of callbacks for `event`.\n *\n * @param {String} event\n * @return {Array}\n * @api public\n */\n\nEmitter.prototype.listeners = function(event){\n this._callbacks = this._callbacks || {};\n return this._callbacks[event] || [];\n};\n\n/**\n * Check if this emitter has `event` handlers.\n *\n * @param {String} event\n * @return {Boolean}\n * @api public\n */\n\nEmitter.prototype.hasListeners = function(event){\n return !! this.listeners(event).length;\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// 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 permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global[\"fast-copy\"] = factory());\n})(this, (function () { 'use strict';\n\n var toStringFunction = Function.prototype.toString;\n var create = Object.create, defineProperty = Object.defineProperty, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getOwnPropertyNames = Object.getOwnPropertyNames, getOwnPropertySymbols = Object.getOwnPropertySymbols, getPrototypeOf$1 = Object.getPrototypeOf;\n var _a = Object.prototype, hasOwnProperty = _a.hasOwnProperty, propertyIsEnumerable = _a.propertyIsEnumerable;\n var SYMBOL_PROPERTIES = typeof getOwnPropertySymbols === 'function';\n var WEAK_MAP = typeof WeakMap === 'function';\n /**\n * @function createCache\n *\n * @description\n * get a new cache object to prevent circular references\n *\n * @returns the new cache object\n */\n var createCache = (function () {\n if (WEAK_MAP) {\n return function () { return new WeakMap(); };\n }\n var Cache = /** @class */ (function () {\n function Cache() {\n this._keys = [];\n this._values = [];\n }\n Cache.prototype.has = function (key) {\n return !!~this._keys.indexOf(key);\n };\n Cache.prototype.get = function (key) {\n return this._values[this._keys.indexOf(key)];\n };\n Cache.prototype.set = function (key, value) {\n this._keys.push(key);\n this._values.push(value);\n };\n return Cache;\n }());\n return function () { return new Cache(); };\n })();\n /**\n * @function getCleanClone\n *\n * @description\n * get an empty version of the object with the same prototype it has\n *\n * @param object the object to build a clean clone from\n * @param realm the realm the object resides in\n * @returns the empty cloned object\n */\n var getCleanClone = function (object, realm) {\n var prototype = object.__proto__ || getPrototypeOf$1(object);\n if (!prototype) {\n return create(null);\n }\n var Constructor = prototype.constructor;\n if (Constructor === realm.Object) {\n return prototype === realm.Object.prototype ? {} : create(prototype);\n }\n if (~toStringFunction.call(Constructor).indexOf('[native code]')) {\n try {\n return new Constructor();\n }\n catch (_a) { }\n }\n return create(prototype);\n };\n /**\n * @function getObjectCloneLoose\n *\n * @description\n * get a copy of the object based on loose rules, meaning all enumerable keys\n * and symbols are copied, but property descriptors are not considered\n *\n * @param object the object to clone\n * @param realm the realm the object resides in\n * @param handleCopy the function that handles copying the object\n * @returns the copied object\n */\n var getObjectCloneLoose = function (object, realm, handleCopy, cache) {\n var clone = getCleanClone(object, realm);\n // set in the cache immediately to be able to reuse the object recursively\n cache.set(object, clone);\n for (var key in object) {\n if (hasOwnProperty.call(object, key)) {\n clone[key] = handleCopy(object[key], cache);\n }\n }\n if (SYMBOL_PROPERTIES) {\n var symbols = getOwnPropertySymbols(object);\n for (var index = 0, length_1 = symbols.length, symbol = void 0; index < length_1; ++index) {\n symbol = symbols[index];\n if (propertyIsEnumerable.call(object, symbol)) {\n clone[symbol] = handleCopy(object[symbol], cache);\n }\n }\n }\n return clone;\n };\n /**\n * @function getObjectCloneStrict\n *\n * @description\n * get a copy of the object based on strict rules, meaning all keys and symbols\n * are copied based on the original property descriptors\n *\n * @param object the object to clone\n * @param realm the realm the object resides in\n * @param handleCopy the function that handles copying the object\n * @returns the copied object\n */\n var getObjectCloneStrict = function (object, realm, handleCopy, cache) {\n var clone = getCleanClone(object, realm);\n // set in the cache immediately to be able to reuse the object recursively\n cache.set(object, clone);\n var properties = SYMBOL_PROPERTIES\n ? getOwnPropertyNames(object).concat(getOwnPropertySymbols(object))\n : getOwnPropertyNames(object);\n for (var index = 0, length_2 = properties.length, property = void 0, descriptor = void 0; index < length_2; ++index) {\n property = properties[index];\n if (property !== 'callee' && property !== 'caller') {\n descriptor = getOwnPropertyDescriptor(object, property);\n if (descriptor) {\n // Only clone the value if actually a value, not a getter / setter.\n if (!descriptor.get && !descriptor.set) {\n descriptor.value = handleCopy(object[property], cache);\n }\n try {\n defineProperty(clone, property, descriptor);\n }\n catch (error) {\n // Tee above can fail on node in edge cases, so fall back to the loose assignment.\n clone[property] = descriptor.value;\n }\n }\n else {\n // In extra edge cases where the property descriptor cannot be retrived, fall back to\n // the loose assignment.\n clone[property] = handleCopy(object[property], cache);\n }\n }\n }\n return clone;\n };\n /**\n * @function getRegExpFlags\n *\n * @description\n * get the flags to apply to the copied regexp\n *\n * @param regExp the regexp to get the flags of\n * @returns the flags for the regexp\n */\n var getRegExpFlags = function (regExp) {\n var flags = '';\n if (regExp.global) {\n flags += 'g';\n }\n if (regExp.ignoreCase) {\n flags += 'i';\n }\n if (regExp.multiline) {\n flags += 'm';\n }\n if (regExp.unicode) {\n flags += 'u';\n }\n if (regExp.sticky) {\n flags += 'y';\n }\n return flags;\n };\n\n // utils\n var isArray = Array.isArray;\n var getPrototypeOf = Object.getPrototypeOf;\n var GLOBAL_THIS = (function () {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n if (console && console.error) {\n console.error('Unable to locate global object, returning \"this\".');\n }\n return this;\n })();\n /**\n * @function copy\n *\n * @description\n * copy an value deeply as much as possible\n *\n * If `strict` is applied, then all properties (including non-enumerable ones)\n * are copied with their original property descriptors on both objects and arrays.\n *\n * The value is compared to the global constructors in the `realm` provided,\n * and the native constructor is always used to ensure that extensions of native\n * objects (allows in ES2015+) are maintained.\n *\n * @param value the value to copy\n * @param [options] the options for copying with\n * @param [options.isStrict] should the copy be strict\n * @param [options.realm] the realm (this) value the value is copied from\n * @returns the copied value\n */\n function copy(value, options) {\n // manually coalesced instead of default parameters for performance\n var isStrict = !!(options && options.isStrict);\n var realm = (options && options.realm) || GLOBAL_THIS;\n var getObjectClone = isStrict ? getObjectCloneStrict : getObjectCloneLoose;\n /**\n * @function handleCopy\n *\n * @description\n * copy the value recursively based on its type\n *\n * @param value the value to copy\n * @returns the copied value\n */\n var handleCopy = function (value, cache) {\n if (!value || typeof value !== 'object') {\n return value;\n }\n if (cache.has(value)) {\n return cache.get(value);\n }\n var prototype = value.__proto__ || getPrototypeOf(value);\n var Constructor = prototype && prototype.constructor;\n // plain objects\n if (!Constructor || Constructor === realm.Object) {\n return getObjectClone(value, realm, handleCopy, cache);\n }\n var clone;\n // arrays\n if (isArray(value)) {\n // if strict, include non-standard properties\n if (isStrict) {\n return getObjectCloneStrict(value, realm, handleCopy, cache);\n }\n clone = new Constructor();\n cache.set(value, clone);\n for (var index = 0, length_1 = value.length; index < length_1; ++index) {\n clone[index] = handleCopy(value[index], cache);\n }\n return clone;\n }\n // dates\n if (value instanceof realm.Date) {\n return new Constructor(value.getTime());\n }\n // regexps\n if (value instanceof realm.RegExp) {\n clone = new Constructor(value.source, value.flags || getRegExpFlags(value));\n clone.lastIndex = value.lastIndex;\n return clone;\n }\n // maps\n if (realm.Map && value instanceof realm.Map) {\n clone = new Constructor();\n cache.set(value, clone);\n value.forEach(function (value, key) {\n clone.set(key, handleCopy(value, cache));\n });\n return clone;\n }\n // sets\n if (realm.Set && value instanceof realm.Set) {\n clone = new Constructor();\n cache.set(value, clone);\n value.forEach(function (value) {\n clone.add(handleCopy(value, cache));\n });\n return clone;\n }\n // blobs\n if (realm.Blob && value instanceof realm.Blob) {\n return value.slice(0, value.size, value.type);\n }\n // buffers (node-only)\n if (realm.Buffer && realm.Buffer.isBuffer(value)) {\n clone = realm.Buffer.allocUnsafe\n ? realm.Buffer.allocUnsafe(value.length)\n : new Constructor(value.length);\n cache.set(value, clone);\n value.copy(clone);\n return clone;\n }\n // arraybuffers / dataviews\n if (realm.ArrayBuffer) {\n // dataviews\n if (realm.ArrayBuffer.isView(value)) {\n clone = new Constructor(value.buffer.slice(0));\n cache.set(value, clone);\n return clone;\n }\n // arraybuffers\n if (value instanceof realm.ArrayBuffer) {\n clone = value.slice(0);\n cache.set(value, clone);\n return clone;\n }\n }\n // if the value cannot / should not be cloned, don't\n if (\n // promise-like\n typeof value.then === 'function' ||\n // errors\n value instanceof Error ||\n // weakmaps\n (realm.WeakMap && value instanceof realm.WeakMap) ||\n // weaksets\n (realm.WeakSet && value instanceof realm.WeakSet)) {\n return value;\n }\n // assume anything left is a custom constructor\n return getObjectClone(value, realm, handleCopy, cache);\n };\n return handleCopy(value, createCache());\n }\n // Adding reference to allow usage in CommonJS libraries compiled using TSC, which\n // expects there to be a default property on the exported value. See\n // [#37](https://github.com/planttheidea/fast-copy/issues/37) for details.\n copy.default = copy;\n /**\n * @function strictCopy\n *\n * @description\n * copy the value with `strict` option pre-applied\n *\n * @param value the value to copy\n * @param [options] the options for copying with\n * @param [options.realm] the realm (this) value the value is copied from\n * @returns the copied value\n */\n copy.strict = function strictCopy(value, options) {\n return copy(value, {\n isStrict: true,\n realm: options ? options.realm : void 0,\n });\n };\n\n return copy;\n\n}));\n","'use strict';\n\n/* eslint no-invalid-this: 1 */\n\nvar ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';\nvar slice = Array.prototype.slice;\nvar toStr = Object.prototype.toString;\nvar funcType = '[object Function]';\n\nmodule.exports = function bind(that) {\n var target = this;\n if (typeof target !== 'function' || toStr.call(target) !== funcType) {\n throw new TypeError(ERROR_MESSAGE + target);\n }\n var args = slice.call(arguments, 1);\n\n var bound;\n var binder = function () {\n if (this instanceof bound) {\n var result = target.apply(\n this,\n args.concat(slice.call(arguments))\n );\n if (Object(result) === result) {\n return result;\n }\n return this;\n } else {\n return target.apply(\n that,\n args.concat(slice.call(arguments))\n );\n }\n };\n\n var boundLength = Math.max(0, target.length - args.length);\n var boundArgs = [];\n for (var i = 0; i < boundLength; i++) {\n boundArgs.push('$' + i);\n }\n\n bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);\n\n if (target.prototype) {\n var Empty = function Empty() {};\n Empty.prototype = target.prototype;\n bound.prototype = new Empty();\n Empty.prototype = null;\n }\n\n return bound;\n};\n","'use strict';\n\nvar implementation = require('./implementation');\n\nmodule.exports = Function.prototype.bind || implementation;\n","'use strict';\n\nvar undefined;\n\nvar $SyntaxError = SyntaxError;\nvar $Function = Function;\nvar $TypeError = TypeError;\n\n// eslint-disable-next-line consistent-return\nvar getEvalledConstructor = function (expressionSyntax) {\n\ttry {\n\t\treturn $Function('\"use strict\"; return (' + expressionSyntax + ').constructor;')();\n\t} catch (e) {}\n};\n\nvar $gOPD = Object.getOwnPropertyDescriptor;\nif ($gOPD) {\n\ttry {\n\t\t$gOPD({}, '');\n\t} catch (e) {\n\t\t$gOPD = null; // this is IE 8, which has a broken gOPD\n\t}\n}\n\nvar throwTypeError = function () {\n\tthrow new $TypeError();\n};\nvar ThrowTypeError = $gOPD\n\t? (function () {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties\n\t\t\targuments.callee; // IE 8 does not throw here\n\t\t\treturn throwTypeError;\n\t\t} catch (calleeThrows) {\n\t\t\ttry {\n\t\t\t\t// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')\n\t\t\t\treturn $gOPD(arguments, 'callee').get;\n\t\t\t} catch (gOPDthrows) {\n\t\t\t\treturn throwTypeError;\n\t\t\t}\n\t\t}\n\t}())\n\t: throwTypeError;\n\nvar hasSymbols = require('has-symbols')();\nvar hasProto = require('has-proto')();\n\nvar getProto = Object.getPrototypeOf || (\n\thasProto\n\t\t? function (x) { return x.__proto__; } // eslint-disable-line no-proto\n\t\t: null\n);\n\nvar needsEval = {};\n\nvar TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array);\n\nvar INTRINSICS = {\n\t'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,\n\t'%Array%': Array,\n\t'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,\n\t'%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined,\n\t'%AsyncFromSyncIteratorPrototype%': undefined,\n\t'%AsyncFunction%': needsEval,\n\t'%AsyncGenerator%': needsEval,\n\t'%AsyncGeneratorFunction%': needsEval,\n\t'%AsyncIteratorPrototype%': needsEval,\n\t'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,\n\t'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,\n\t'%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array,\n\t'%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array,\n\t'%Boolean%': Boolean,\n\t'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,\n\t'%Date%': Date,\n\t'%decodeURI%': decodeURI,\n\t'%decodeURIComponent%': decodeURIComponent,\n\t'%encodeURI%': encodeURI,\n\t'%encodeURIComponent%': encodeURIComponent,\n\t'%Error%': Error,\n\t'%eval%': eval, // eslint-disable-line no-eval\n\t'%EvalError%': EvalError,\n\t'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,\n\t'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,\n\t'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,\n\t'%Function%': $Function,\n\t'%GeneratorFunction%': needsEval,\n\t'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,\n\t'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,\n\t'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,\n\t'%isFinite%': isFinite,\n\t'%isNaN%': isNaN,\n\t'%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined,\n\t'%JSON%': typeof JSON === 'object' ? JSON : undefined,\n\t'%Map%': typeof Map === 'undefined' ? undefined : Map,\n\t'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()),\n\t'%Math%': Math,\n\t'%Number%': Number,\n\t'%Object%': Object,\n\t'%parseFloat%': parseFloat,\n\t'%parseInt%': parseInt,\n\t'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,\n\t'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,\n\t'%RangeError%': RangeError,\n\t'%ReferenceError%': ReferenceError,\n\t'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,\n\t'%RegExp%': RegExp,\n\t'%Set%': typeof Set === 'undefined' ? undefined : Set,\n\t'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()),\n\t'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,\n\t'%String%': String,\n\t'%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined,\n\t'%Symbol%': hasSymbols ? Symbol : undefined,\n\t'%SyntaxError%': $SyntaxError,\n\t'%ThrowTypeError%': ThrowTypeError,\n\t'%TypedArray%': TypedArray,\n\t'%TypeError%': $TypeError,\n\t'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,\n\t'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,\n\t'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,\n\t'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,\n\t'%URIError%': URIError,\n\t'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,\n\t'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,\n\t'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet\n};\n\nif (getProto) {\n\ttry {\n\t\tnull.error; // eslint-disable-line no-unused-expressions\n\t} catch (e) {\n\t\t// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229\n\t\tvar errorProto = getProto(getProto(e));\n\t\tINTRINSICS['%Error.prototype%'] = errorProto;\n\t}\n}\n\nvar doEval = function doEval(name) {\n\tvar value;\n\tif (name === '%AsyncFunction%') {\n\t\tvalue = getEvalledConstructor('async function () {}');\n\t} else if (name === '%GeneratorFunction%') {\n\t\tvalue = getEvalledConstructor('function* () {}');\n\t} else if (name === '%AsyncGeneratorFunction%') {\n\t\tvalue = getEvalledConstructor('async function* () {}');\n\t} else if (name === '%AsyncGenerator%') {\n\t\tvar fn = doEval('%AsyncGeneratorFunction%');\n\t\tif (fn) {\n\t\t\tvalue = fn.prototype;\n\t\t}\n\t} else if (name === '%AsyncIteratorPrototype%') {\n\t\tvar gen = doEval('%AsyncGenerator%');\n\t\tif (gen && getProto) {\n\t\t\tvalue = getProto(gen.prototype);\n\t\t}\n\t}\n\n\tINTRINSICS[name] = value;\n\n\treturn value;\n};\n\nvar LEGACY_ALIASES = {\n\t'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],\n\t'%ArrayPrototype%': ['Array', 'prototype'],\n\t'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],\n\t'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],\n\t'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],\n\t'%ArrayProto_values%': ['Array', 'prototype', 'values'],\n\t'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],\n\t'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],\n\t'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],\n\t'%BooleanPrototype%': ['Boolean', 'prototype'],\n\t'%DataViewPrototype%': ['DataView', 'prototype'],\n\t'%DatePrototype%': ['Date', 'prototype'],\n\t'%ErrorPrototype%': ['Error', 'prototype'],\n\t'%EvalErrorPrototype%': ['EvalError', 'prototype'],\n\t'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],\n\t'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],\n\t'%FunctionPrototype%': ['Function', 'prototype'],\n\t'%Generator%': ['GeneratorFunction', 'prototype'],\n\t'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],\n\t'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],\n\t'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],\n\t'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],\n\t'%JSONParse%': ['JSON', 'parse'],\n\t'%JSONStringify%': ['JSON', 'stringify'],\n\t'%MapPrototype%': ['Map', 'prototype'],\n\t'%NumberPrototype%': ['Number', 'prototype'],\n\t'%ObjectPrototype%': ['Object', 'prototype'],\n\t'%ObjProto_toString%': ['Object', 'prototype', 'toString'],\n\t'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],\n\t'%PromisePrototype%': ['Promise', 'prototype'],\n\t'%PromiseProto_then%': ['Promise', 'prototype', 'then'],\n\t'%Promise_all%': ['Promise', 'all'],\n\t'%Promise_reject%': ['Promise', 'reject'],\n\t'%Promise_resolve%': ['Promise', 'resolve'],\n\t'%RangeErrorPrototype%': ['RangeError', 'prototype'],\n\t'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],\n\t'%RegExpPrototype%': ['RegExp', 'prototype'],\n\t'%SetPrototype%': ['Set', 'prototype'],\n\t'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],\n\t'%StringPrototype%': ['String', 'prototype'],\n\t'%SymbolPrototype%': ['Symbol', 'prototype'],\n\t'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],\n\t'%TypedArrayPrototype%': ['TypedArray', 'prototype'],\n\t'%TypeErrorPrototype%': ['TypeError', 'prototype'],\n\t'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],\n\t'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],\n\t'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],\n\t'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],\n\t'%URIErrorPrototype%': ['URIError', 'prototype'],\n\t'%WeakMapPrototype%': ['WeakMap', 'prototype'],\n\t'%WeakSetPrototype%': ['WeakSet', 'prototype']\n};\n\nvar bind = require('function-bind');\nvar hasOwn = require('has');\nvar $concat = bind.call(Function.call, Array.prototype.concat);\nvar $spliceApply = bind.call(Function.apply, Array.prototype.splice);\nvar $replace = bind.call(Function.call, String.prototype.replace);\nvar $strSlice = bind.call(Function.call, String.prototype.slice);\nvar $exec = bind.call(Function.call, RegExp.prototype.exec);\n\n/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */\nvar rePropName = /[^%.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|%$))/g;\nvar reEscapeChar = /\\\\(\\\\)?/g; /** Used to match backslashes in property paths. */\nvar stringToPath = function stringToPath(string) {\n\tvar first = $strSlice(string, 0, 1);\n\tvar last = $strSlice(string, -1);\n\tif (first === '%' && last !== '%') {\n\t\tthrow new $SyntaxError('invalid intrinsic syntax, expected closing `%`');\n\t} else if (last === '%' && first !== '%') {\n\t\tthrow new $SyntaxError('invalid intrinsic syntax, expected opening `%`');\n\t}\n\tvar result = [];\n\t$replace(string, rePropName, function (match, number, quote, subString) {\n\t\tresult[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;\n\t});\n\treturn result;\n};\n/* end adaptation */\n\nvar getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {\n\tvar intrinsicName = name;\n\tvar alias;\n\tif (hasOwn(LEGACY_ALIASES, intrinsicName)) {\n\t\talias = LEGACY_ALIASES[intrinsicName];\n\t\tintrinsicName = '%' + alias[0] + '%';\n\t}\n\n\tif (hasOwn(INTRINSICS, intrinsicName)) {\n\t\tvar value = INTRINSICS[intrinsicName];\n\t\tif (value === needsEval) {\n\t\t\tvalue = doEval(intrinsicName);\n\t\t}\n\t\tif (typeof value === 'undefined' && !allowMissing) {\n\t\t\tthrow new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');\n\t\t}\n\n\t\treturn {\n\t\t\talias: alias,\n\t\t\tname: intrinsicName,\n\t\t\tvalue: value\n\t\t};\n\t}\n\n\tthrow new $SyntaxError('intrinsic ' + name + ' does not exist!');\n};\n\nmodule.exports = function GetIntrinsic(name, allowMissing) {\n\tif (typeof name !== 'string' || name.length === 0) {\n\t\tthrow new $TypeError('intrinsic name must be a non-empty string');\n\t}\n\tif (arguments.length > 1 && typeof allowMissing !== 'boolean') {\n\t\tthrow new $TypeError('\"allowMissing\" argument must be a boolean');\n\t}\n\n\tif ($exec(/^%?[^%]*%?$/, name) === null) {\n\t\tthrow new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');\n\t}\n\tvar parts = stringToPath(name);\n\tvar intrinsicBaseName = parts.length > 0 ? parts[0] : '';\n\n\tvar intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);\n\tvar intrinsicRealName = intrinsic.name;\n\tvar value = intrinsic.value;\n\tvar skipFurtherCaching = false;\n\n\tvar alias = intrinsic.alias;\n\tif (alias) {\n\t\tintrinsicBaseName = alias[0];\n\t\t$spliceApply(parts, $concat([0, 1], alias));\n\t}\n\n\tfor (var i = 1, isOwn = true; i < parts.length; i += 1) {\n\t\tvar part = parts[i];\n\t\tvar first = $strSlice(part, 0, 1);\n\t\tvar last = $strSlice(part, -1);\n\t\tif (\n\t\t\t(\n\t\t\t\t(first === '\"' || first === \"'\" || first === '`')\n\t\t\t\t|| (last === '\"' || last === \"'\" || last === '`')\n\t\t\t)\n\t\t\t&& first !== last\n\t\t) {\n\t\t\tthrow new $SyntaxError('property names with quotes must have matching quotes');\n\t\t}\n\t\tif (part === 'constructor' || !isOwn) {\n\t\t\tskipFurtherCaching = true;\n\t\t}\n\n\t\tintrinsicBaseName += '.' + part;\n\t\tintrinsicRealName = '%' + intrinsicBaseName + '%';\n\n\t\tif (hasOwn(INTRINSICS, intrinsicRealName)) {\n\t\t\tvalue = INTRINSICS[intrinsicRealName];\n\t\t} else if (value != null) {\n\t\t\tif (!(part in value)) {\n\t\t\t\tif (!allowMissing) {\n\t\t\t\t\tthrow new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');\n\t\t\t\t}\n\t\t\t\treturn void undefined;\n\t\t\t}\n\t\t\tif ($gOPD && (i + 1) >= parts.length) {\n\t\t\t\tvar desc = $gOPD(value, part);\n\t\t\t\tisOwn = !!desc;\n\n\t\t\t\t// By convention, when a data property is converted to an accessor\n\t\t\t\t// property to emulate a data property that does not suffer from\n\t\t\t\t// the override mistake, that accessor's getter is marked with\n\t\t\t\t// an `originalValue` property. Here, when we detect this, we\n\t\t\t\t// uphold the illusion by pretending to see that original data\n\t\t\t\t// property, i.e., returning the value rather than the getter\n\t\t\t\t// itself.\n\t\t\t\tif (isOwn && 'get' in desc && !('originalValue' in desc.get)) {\n\t\t\t\t\tvalue = desc.get;\n\t\t\t\t} else {\n\t\t\t\t\tvalue = value[part];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tisOwn = hasOwn(value, part);\n\t\t\t\tvalue = value[part];\n\t\t\t}\n\n\t\t\tif (isOwn && !skipFurtherCaching) {\n\t\t\t\tINTRINSICS[intrinsicRealName] = value;\n\t\t\t}\n\t\t}\n\t}\n\treturn value;\n};\n","'use strict';\n\nvar test = {\n\tfoo: {}\n};\n\nvar $Object = Object;\n\nmodule.exports = function hasProto() {\n\treturn { __proto__: test }.foo === test.foo && !({ __proto__: null } instanceof $Object);\n};\n","'use strict';\n\nvar origSymbol = typeof Symbol !== 'undefined' && Symbol;\nvar hasSymbolSham = require('./shams');\n\nmodule.exports = function hasNativeSymbols() {\n\tif (typeof origSymbol !== 'function') { return false; }\n\tif (typeof Symbol !== 'function') { return false; }\n\tif (typeof origSymbol('foo') !== 'symbol') { return false; }\n\tif (typeof Symbol('bar') !== 'symbol') { return false; }\n\n\treturn hasSymbolSham();\n};\n","'use strict';\n\n/* eslint complexity: [2, 18], max-statements: [2, 33] */\nmodule.exports = function hasSymbols() {\n\tif (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }\n\tif (typeof Symbol.iterator === 'symbol') { return true; }\n\n\tvar obj = {};\n\tvar sym = Symbol('test');\n\tvar symObj = Object(sym);\n\tif (typeof sym === 'string') { return false; }\n\n\tif (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }\n\tif (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }\n\n\t// temp disabled per https://github.com/ljharb/object.assign/issues/17\n\t// if (sym instanceof Symbol) { return false; }\n\t// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4\n\t// if (!(symObj instanceof Symbol)) { return false; }\n\n\t// if (typeof Symbol.prototype.toString !== 'function') { return false; }\n\t// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }\n\n\tvar symVal = 42;\n\tobj[sym] = symVal;\n\tfor (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop\n\tif (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }\n\n\tif (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }\n\n\tvar syms = Object.getOwnPropertySymbols(obj);\n\tif (syms.length !== 1 || syms[0] !== sym) { return false; }\n\n\tif (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }\n\n\tif (typeof Object.getOwnPropertyDescriptor === 'function') {\n\t\tvar descriptor = Object.getOwnPropertyDescriptor(obj, sym);\n\t\tif (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }\n\t}\n\n\treturn true;\n};\n","'use strict';\n\nvar bind = require('function-bind');\n\nmodule.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","exports = module.exports = stringify\nexports.getSerialize = serializer\n\nfunction stringify(obj, replacer, spaces, cycleReplacer) {\n return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)\n}\n\nfunction serializer(replacer, cycleReplacer) {\n var stack = [], keys = []\n\n if (cycleReplacer == null) cycleReplacer = function(key, value) {\n if (stack[0] === value) return \"[Circular ~]\"\n return \"[Circular ~.\" + keys.slice(0, stack.indexOf(value)).join(\".\") + \"]\"\n }\n\n return function(key, value) {\n if (stack.length > 0) {\n var thisPos = stack.indexOf(this)\n ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)\n ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)\n if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)\n }\n else stack.push(value)\n\n return replacer == null ? value : replacer.call(this, key, value)\n }\n}\n","/*!\n localForage -- Offline Storage, Improved\n Version 1.10.0\n https://localforage.github.io/localForage\n (c) 2013-2017 Mozilla, Apache License 2.0\n*/\n(function(f){if(typeof exports===\"object\"&&typeof module!==\"undefined\"){module.exports=f()}else if(typeof define===\"function\"&&define.amd){define([],f)}else{var g;if(typeof window!==\"undefined\"){g=window}else if(typeof global!==\"undefined\"){g=global}else if(typeof self!==\"undefined\"){g=self}else{g=this}g.localforage = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw (f.code=\"MODULE_NOT_FOUND\", f)}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o element; its readystatechange event will be fired asynchronously once it is inserted\n // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.\n var scriptEl = global.document.createElement('script');\n scriptEl.onreadystatechange = function () {\n nextTick();\n\n scriptEl.onreadystatechange = null;\n scriptEl.parentNode.removeChild(scriptEl);\n scriptEl = null;\n };\n global.document.documentElement.appendChild(scriptEl);\n };\n } else {\n scheduleDrain = function () {\n setTimeout(nextTick, 0);\n };\n }\n}\n\nvar draining;\nvar queue = [];\n//named nextTick for less confusing stack traces\nfunction nextTick() {\n draining = true;\n var i, oldQueue;\n var len = queue.length;\n while (len) {\n oldQueue = queue;\n queue = [];\n i = -1;\n while (++i < len) {\n oldQueue[i]();\n }\n len = queue.length;\n }\n draining = false;\n}\n\nmodule.exports = immediate;\nfunction immediate(task) {\n if (queue.push(task) === 1 && !draining) {\n scheduleDrain();\n }\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{}],2:[function(_dereq_,module,exports){\n'use strict';\nvar immediate = _dereq_(1);\n\n/* istanbul ignore next */\nfunction INTERNAL() {}\n\nvar handlers = {};\n\nvar REJECTED = ['REJECTED'];\nvar FULFILLED = ['FULFILLED'];\nvar PENDING = ['PENDING'];\n\nmodule.exports = Promise;\n\nfunction Promise(resolver) {\n if (typeof resolver !== 'function') {\n throw new TypeError('resolver must be a function');\n }\n this.state = PENDING;\n this.queue = [];\n this.outcome = void 0;\n if (resolver !== INTERNAL) {\n safelyResolveThenable(this, resolver);\n }\n}\n\nPromise.prototype[\"catch\"] = function (onRejected) {\n return this.then(null, onRejected);\n};\nPromise.prototype.then = function (onFulfilled, onRejected) {\n if (typeof onFulfilled !== 'function' && this.state === FULFILLED ||\n typeof onRejected !== 'function' && this.state === REJECTED) {\n return this;\n }\n var promise = new this.constructor(INTERNAL);\n if (this.state !== PENDING) {\n var resolver = this.state === FULFILLED ? onFulfilled : onRejected;\n unwrap(promise, resolver, this.outcome);\n } else {\n this.queue.push(new QueueItem(promise, onFulfilled, onRejected));\n }\n\n return promise;\n};\nfunction QueueItem(promise, onFulfilled, onRejected) {\n this.promise = promise;\n if (typeof onFulfilled === 'function') {\n this.onFulfilled = onFulfilled;\n this.callFulfilled = this.otherCallFulfilled;\n }\n if (typeof onRejected === 'function') {\n this.onRejected = onRejected;\n this.callRejected = this.otherCallRejected;\n }\n}\nQueueItem.prototype.callFulfilled = function (value) {\n handlers.resolve(this.promise, value);\n};\nQueueItem.prototype.otherCallFulfilled = function (value) {\n unwrap(this.promise, this.onFulfilled, value);\n};\nQueueItem.prototype.callRejected = function (value) {\n handlers.reject(this.promise, value);\n};\nQueueItem.prototype.otherCallRejected = function (value) {\n unwrap(this.promise, this.onRejected, value);\n};\n\nfunction unwrap(promise, func, value) {\n immediate(function () {\n var returnValue;\n try {\n returnValue = func(value);\n } catch (e) {\n return handlers.reject(promise, e);\n }\n if (returnValue === promise) {\n handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));\n } else {\n handlers.resolve(promise, returnValue);\n }\n });\n}\n\nhandlers.resolve = function (self, value) {\n var result = tryCatch(getThen, value);\n if (result.status === 'error') {\n return handlers.reject(self, result.value);\n }\n var thenable = result.value;\n\n if (thenable) {\n safelyResolveThenable(self, thenable);\n } else {\n self.state = FULFILLED;\n self.outcome = value;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callFulfilled(value);\n }\n }\n return self;\n};\nhandlers.reject = function (self, error) {\n self.state = REJECTED;\n self.outcome = error;\n var i = -1;\n var len = self.queue.length;\n while (++i < len) {\n self.queue[i].callRejected(error);\n }\n return self;\n};\n\nfunction getThen(obj) {\n // Make sure we only access the accessor once as required by the spec\n var then = obj && obj.then;\n if (obj && (typeof obj === 'object' || typeof obj === 'function') && typeof then === 'function') {\n return function appyThen() {\n then.apply(obj, arguments);\n };\n }\n}\n\nfunction safelyResolveThenable(self, thenable) {\n // Either fulfill, reject or reject with error\n var called = false;\n function onError(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.reject(self, value);\n }\n\n function onSuccess(value) {\n if (called) {\n return;\n }\n called = true;\n handlers.resolve(self, value);\n }\n\n function tryToUnwrap() {\n thenable(onSuccess, onError);\n }\n\n var result = tryCatch(tryToUnwrap);\n if (result.status === 'error') {\n onError(result.value);\n }\n}\n\nfunction tryCatch(func, value) {\n var out = {};\n try {\n out.value = func(value);\n out.status = 'success';\n } catch (e) {\n out.status = 'error';\n out.value = e;\n }\n return out;\n}\n\nPromise.resolve = resolve;\nfunction resolve(value) {\n if (value instanceof this) {\n return value;\n }\n return handlers.resolve(new this(INTERNAL), value);\n}\n\nPromise.reject = reject;\nfunction reject(reason) {\n var promise = new this(INTERNAL);\n return handlers.reject(promise, reason);\n}\n\nPromise.all = all;\nfunction all(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var values = new Array(len);\n var resolved = 0;\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n allResolver(iterable[i], i);\n }\n return promise;\n function allResolver(value, i) {\n self.resolve(value).then(resolveFromAll, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n function resolveFromAll(outValue) {\n values[i] = outValue;\n if (++resolved === len && !called) {\n called = true;\n handlers.resolve(promise, values);\n }\n }\n }\n}\n\nPromise.race = race;\nfunction race(iterable) {\n var self = this;\n if (Object.prototype.toString.call(iterable) !== '[object Array]') {\n return this.reject(new TypeError('must be an array'));\n }\n\n var len = iterable.length;\n var called = false;\n if (!len) {\n return this.resolve([]);\n }\n\n var i = -1;\n var promise = new this(INTERNAL);\n\n while (++i < len) {\n resolver(iterable[i]);\n }\n return promise;\n function resolver(value) {\n self.resolve(value).then(function (response) {\n if (!called) {\n called = true;\n handlers.resolve(promise, response);\n }\n }, function (error) {\n if (!called) {\n called = true;\n handlers.reject(promise, error);\n }\n });\n }\n}\n\n},{\"1\":1}],3:[function(_dereq_,module,exports){\n(function (global){\n'use strict';\nif (typeof global.Promise !== 'function') {\n global.Promise = _dereq_(2);\n}\n\n}).call(this,typeof global !== \"undefined\" ? global : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : {})\n},{\"2\":2}],4:[function(_dereq_,module,exports){\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\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction getIDB() {\n /* global indexedDB,webkitIndexedDB,mozIndexedDB,OIndexedDB,msIndexedDB */\n try {\n if (typeof indexedDB !== 'undefined') {\n return indexedDB;\n }\n if (typeof webkitIndexedDB !== 'undefined') {\n return webkitIndexedDB;\n }\n if (typeof mozIndexedDB !== 'undefined') {\n return mozIndexedDB;\n }\n if (typeof OIndexedDB !== 'undefined') {\n return OIndexedDB;\n }\n if (typeof msIndexedDB !== 'undefined') {\n return msIndexedDB;\n }\n } catch (e) {\n return;\n }\n}\n\nvar idb = getIDB();\n\nfunction isIndexedDBValid() {\n try {\n // Initialize IndexedDB; fall back to vendor-prefixed versions\n // if needed.\n if (!idb || !idb.open) {\n return false;\n }\n // We mimic PouchDB here;\n //\n // We test for openDatabase because IE Mobile identifies itself\n // as Safari. Oh the lulz...\n var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);\n\n var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;\n\n // Safari <10.1 does not meet our requirements for IDB support\n // (see: https://github.com/pouchdb/pouchdb/issues/5572).\n // Safari 10.1 shipped with fetch, we can use that to detect it.\n // Note: this creates issues with `window.fetch` polyfills and\n // overrides; see:\n // https://github.com/localForage/localForage/issues/856\n return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&\n // some outdated implementations of IDB that appear on Samsung\n // and HTC Android devices <4.4 are missing IDBKeyRange\n // See: https://github.com/mozilla/localForage/issues/128\n // See: https://github.com/mozilla/localForage/issues/272\n typeof IDBKeyRange !== 'undefined';\n } catch (e) {\n return false;\n }\n}\n\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\n// Abstracts constructing a Blob object, so it also works in older\n// browsers that don't support the native Blob constructor. (i.e.\n// old QtWebKit versions, at least).\nfunction createBlob(parts, properties) {\n /* global BlobBuilder,MSBlobBuilder,MozBlobBuilder,WebKitBlobBuilder */\n parts = parts || [];\n properties = properties || {};\n try {\n return new Blob(parts, properties);\n } catch (e) {\n if (e.name !== 'TypeError') {\n throw e;\n }\n var Builder = typeof BlobBuilder !== 'undefined' ? BlobBuilder : typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder : WebKitBlobBuilder;\n var builder = new Builder();\n for (var i = 0; i < parts.length; i += 1) {\n builder.append(parts[i]);\n }\n return builder.getBlob(properties.type);\n }\n}\n\n// This is CommonJS because lie is an external dependency, so Rollup\n// can just ignore it.\nif (typeof Promise === 'undefined') {\n // In the \"nopromises\" build this will just throw if you don't have\n // a global promise object, but it would throw anyway later.\n _dereq_(3);\n}\nvar Promise$1 = Promise;\n\nfunction executeCallback(promise, callback) {\n if (callback) {\n promise.then(function (result) {\n callback(null, result);\n }, function (error) {\n callback(error);\n });\n }\n}\n\nfunction executeTwoCallbacks(promise, callback, errorCallback) {\n if (typeof callback === 'function') {\n promise.then(callback);\n }\n\n if (typeof errorCallback === 'function') {\n promise[\"catch\"](errorCallback);\n }\n}\n\nfunction normalizeKey(key) {\n // Cast the key to a string, as that's all we can set as a key.\n if (typeof key !== 'string') {\n console.warn(key + ' used as a key, but it is not a string.');\n key = String(key);\n }\n\n return key;\n}\n\nfunction getCallback() {\n if (arguments.length && typeof arguments[arguments.length - 1] === 'function') {\n return arguments[arguments.length - 1];\n }\n}\n\n// Some code originally from async_storage.js in\n// [Gaia](https://github.com/mozilla-b2g/gaia).\n\nvar DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';\nvar supportsBlobs = void 0;\nvar dbContexts = {};\nvar toString = Object.prototype.toString;\n\n// Transaction Modes\nvar READ_ONLY = 'readonly';\nvar READ_WRITE = 'readwrite';\n\n// Transform a binary string to an array buffer, because otherwise\n// weird stuff happens when you try to work with the binary string directly.\n// It is known.\n// From http://stackoverflow.com/questions/14967647/ (continues on next line)\n// encode-decode-image-with-base64-breaks-image (2013-04-21)\nfunction _binStringToArrayBuffer(bin) {\n var length = bin.length;\n var buf = new ArrayBuffer(length);\n var arr = new Uint8Array(buf);\n for (var i = 0; i < length; i++) {\n arr[i] = bin.charCodeAt(i);\n }\n return buf;\n}\n\n//\n// Blobs are not supported in all versions of IndexedDB, notably\n// Chrome <37 and Android <5. In those versions, storing a blob will throw.\n//\n// Various other blob bugs exist in Chrome v37-42 (inclusive).\n// Detecting them is expensive and confusing to users, and Chrome 37-42\n// is at very low usage worldwide, so we do a hacky userAgent check instead.\n//\n// content-type bug: https://code.google.com/p/chromium/issues/detail?id=408120\n// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916\n// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836\n//\n// Code borrowed from PouchDB. See:\n// https://github.com/pouchdb/pouchdb/blob/master/packages/node_modules/pouchdb-adapter-idb/src/blobSupport.js\n//\nfunction _checkBlobSupportWithoutCaching(idb) {\n return new Promise$1(function (resolve) {\n var txn = idb.transaction(DETECT_BLOB_SUPPORT_STORE, READ_WRITE);\n var blob = createBlob(['']);\n txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');\n\n txn.onabort = function (e) {\n // If the transaction aborts now its due to not being able to\n // write to the database, likely due to the disk being full\n e.preventDefault();\n e.stopPropagation();\n resolve(false);\n };\n\n txn.oncomplete = function () {\n var matchedChrome = navigator.userAgent.match(/Chrome\\/(\\d+)/);\n var matchedEdge = navigator.userAgent.match(/Edge\\//);\n // MS Edge pretends to be Chrome 42:\n // https://msdn.microsoft.com/en-us/library/hh869301%28v=vs.85%29.aspx\n resolve(matchedEdge || !matchedChrome || parseInt(matchedChrome[1], 10) >= 43);\n };\n })[\"catch\"](function () {\n return false; // error, so assume unsupported\n });\n}\n\nfunction _checkBlobSupport(idb) {\n if (typeof supportsBlobs === 'boolean') {\n return Promise$1.resolve(supportsBlobs);\n }\n return _checkBlobSupportWithoutCaching(idb).then(function (value) {\n supportsBlobs = value;\n return supportsBlobs;\n });\n}\n\nfunction _deferReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Create a deferred object representing the current database operation.\n var deferredOperation = {};\n\n deferredOperation.promise = new Promise$1(function (resolve, reject) {\n deferredOperation.resolve = resolve;\n deferredOperation.reject = reject;\n });\n\n // Enqueue the deferred operation.\n dbContext.deferredOperations.push(deferredOperation);\n\n // Chain its promise to the database readiness.\n if (!dbContext.dbReady) {\n dbContext.dbReady = deferredOperation.promise;\n } else {\n dbContext.dbReady = dbContext.dbReady.then(function () {\n return deferredOperation.promise;\n });\n }\n}\n\nfunction _advanceReadiness(dbInfo) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Resolve its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.resolve();\n return deferredOperation.promise;\n }\n}\n\nfunction _rejectReadiness(dbInfo, err) {\n var dbContext = dbContexts[dbInfo.name];\n\n // Dequeue a deferred operation.\n var deferredOperation = dbContext.deferredOperations.pop();\n\n // Reject its promise (which is part of the database readiness\n // chain of promises).\n if (deferredOperation) {\n deferredOperation.reject(err);\n return deferredOperation.promise;\n }\n}\n\nfunction _getConnection(dbInfo, upgradeNeeded) {\n return new Promise$1(function (resolve, reject) {\n dbContexts[dbInfo.name] = dbContexts[dbInfo.name] || createDbContext();\n\n if (dbInfo.db) {\n if (upgradeNeeded) {\n _deferReadiness(dbInfo);\n dbInfo.db.close();\n } else {\n return resolve(dbInfo.db);\n }\n }\n\n var dbArgs = [dbInfo.name];\n\n if (upgradeNeeded) {\n dbArgs.push(dbInfo.version);\n }\n\n var openreq = idb.open.apply(idb, dbArgs);\n\n if (upgradeNeeded) {\n openreq.onupgradeneeded = function (e) {\n var db = openreq.result;\n try {\n db.createObjectStore(dbInfo.storeName);\n if (e.oldVersion <= 1) {\n // Added when support for blob shims was added\n db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);\n }\n } catch (ex) {\n if (ex.name === 'ConstraintError') {\n console.warn('The database \"' + dbInfo.name + '\"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage \"' + dbInfo.storeName + '\" already exists.');\n } else {\n throw ex;\n }\n }\n };\n }\n\n openreq.onerror = function (e) {\n e.preventDefault();\n reject(openreq.error);\n };\n\n openreq.onsuccess = function () {\n var db = openreq.result;\n db.onversionchange = function (e) {\n // Triggered when the database is modified (e.g. adding an objectStore) or\n // deleted (even when initiated by other sessions in different tabs).\n // Closing the connection here prevents those operations from being blocked.\n // If the database is accessed again later by this instance, the connection\n // will be reopened or the database recreated as needed.\n e.target.close();\n };\n resolve(db);\n _advanceReadiness(dbInfo);\n };\n });\n}\n\nfunction _getOriginalConnection(dbInfo) {\n return _getConnection(dbInfo, false);\n}\n\nfunction _getUpgradedConnection(dbInfo) {\n return _getConnection(dbInfo, true);\n}\n\nfunction _isUpgradeNeeded(dbInfo, defaultVersion) {\n if (!dbInfo.db) {\n return true;\n }\n\n var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName);\n var isDowngrade = dbInfo.version < dbInfo.db.version;\n var isUpgrade = dbInfo.version > dbInfo.db.version;\n\n if (isDowngrade) {\n // If the version is not the default one\n // then warn for impossible downgrade.\n if (dbInfo.version !== defaultVersion) {\n console.warn('The database \"' + dbInfo.name + '\"' + \" can't be downgraded from version \" + dbInfo.db.version + ' to version ' + dbInfo.version + '.');\n }\n // Align the versions to prevent errors.\n dbInfo.version = dbInfo.db.version;\n }\n\n if (isUpgrade || isNewStore) {\n // If the store is new then increment the version (if needed).\n // This will trigger an \"upgradeneeded\" event which is required\n // for creating a store.\n if (isNewStore) {\n var incVersion = dbInfo.db.version + 1;\n if (incVersion > dbInfo.version) {\n dbInfo.version = incVersion;\n }\n }\n\n return true;\n }\n\n return false;\n}\n\n// encode a blob for indexeddb engines that don't support blobs\nfunction _encodeBlob(blob) {\n return new Promise$1(function (resolve, reject) {\n var reader = new FileReader();\n reader.onerror = reject;\n reader.onloadend = function (e) {\n var base64 = btoa(e.target.result || '');\n resolve({\n __local_forage_encoded_blob: true,\n data: base64,\n type: blob.type\n });\n };\n reader.readAsBinaryString(blob);\n });\n}\n\n// decode an encoded blob\nfunction _decodeBlob(encodedBlob) {\n var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));\n return createBlob([arrayBuff], { type: encodedBlob.type });\n}\n\n// is this one of our fancy encoded blobs?\nfunction _isEncodedBlob(value) {\n return value && value.__local_forage_encoded_blob;\n}\n\n// Specialize the default `ready()` function by making it dependent\n// on the current database operations. Thus, the driver will be actually\n// ready when it's been initialized (default) *and* there are no pending\n// operations on the database (initiated by some other instances).\nfunction _fullyReady(callback) {\n var self = this;\n\n var promise = self._initReady().then(function () {\n var dbContext = dbContexts[self._dbInfo.name];\n\n if (dbContext && dbContext.dbReady) {\n return dbContext.dbReady;\n }\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n}\n\n// Try to establish a new db connection to replace the\n// current one which is broken (i.e. experiencing\n// InvalidStateError while creating a transaction).\nfunction _tryReconnect(dbInfo) {\n _deferReadiness(dbInfo);\n\n var dbContext = dbContexts[dbInfo.name];\n var forages = dbContext.forages;\n\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n if (forage._dbInfo.db) {\n forage._dbInfo.db.close();\n forage._dbInfo.db = null;\n }\n }\n dbInfo.db = null;\n\n return _getOriginalConnection(dbInfo).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n // store the latest db reference\n // in case the db was upgraded\n dbInfo.db = dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n })[\"catch\"](function (err) {\n _rejectReadiness(dbInfo, err);\n throw err;\n });\n}\n\n// FF doesn't like Promises (micro-tasks) and IDDB store operations,\n// so we have to do it with callbacks\nfunction createTransaction(dbInfo, mode, callback, retries) {\n if (retries === undefined) {\n retries = 1;\n }\n\n try {\n var tx = dbInfo.db.transaction(dbInfo.storeName, mode);\n callback(null, tx);\n } catch (err) {\n if (retries > 0 && (!dbInfo.db || err.name === 'InvalidStateError' || err.name === 'NotFoundError')) {\n return Promise$1.resolve().then(function () {\n if (!dbInfo.db || err.name === 'NotFoundError' && !dbInfo.db.objectStoreNames.contains(dbInfo.storeName) && dbInfo.version <= dbInfo.db.version) {\n // increase the db version, to create the new ObjectStore\n if (dbInfo.db) {\n dbInfo.version = dbInfo.db.version + 1;\n }\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n }).then(function () {\n return _tryReconnect(dbInfo).then(function () {\n createTransaction(dbInfo, mode, callback, retries - 1);\n });\n })[\"catch\"](callback);\n }\n\n callback(err);\n }\n}\n\nfunction createDbContext() {\n return {\n // Running localForages sharing a database.\n forages: [],\n // Shared database.\n db: null,\n // Database readiness (promise).\n dbReady: null,\n // Deferred operations on the database.\n deferredOperations: []\n };\n}\n\n// Open the IndexedDB database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n // Get the current context of the database;\n var dbContext = dbContexts[dbInfo.name];\n\n // ...or create a new context.\n if (!dbContext) {\n dbContext = createDbContext();\n // Register the new context in the global container.\n dbContexts[dbInfo.name] = dbContext;\n }\n\n // Register itself as a running localForage in the current context.\n dbContext.forages.push(self);\n\n // Replace the default `ready()` function with the specialized one.\n if (!self._initReady) {\n self._initReady = self.ready;\n self.ready = _fullyReady;\n }\n\n // Create an array of initialization states of the related localForages.\n var initPromises = [];\n\n function ignoreErrors() {\n // Don't handle errors here,\n // just makes sure related localForages aren't pending.\n return Promise$1.resolve();\n }\n\n for (var j = 0; j < dbContext.forages.length; j++) {\n var forage = dbContext.forages[j];\n if (forage !== self) {\n // Don't wait for itself...\n initPromises.push(forage._initReady()[\"catch\"](ignoreErrors));\n }\n }\n\n // Take a snapshot of the related localForages.\n var forages = dbContext.forages.slice(0);\n\n // Initialize the connection process only when\n // all the related localForages aren't pending.\n return Promise$1.all(initPromises).then(function () {\n dbInfo.db = dbContext.db;\n // Get the connection or open a new one without upgrade.\n return _getOriginalConnection(dbInfo);\n }).then(function (db) {\n dbInfo.db = db;\n if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) {\n // Reopen the database for upgrading.\n return _getUpgradedConnection(dbInfo);\n }\n return db;\n }).then(function (db) {\n dbInfo.db = dbContext.db = db;\n self._dbInfo = dbInfo;\n // Share the final connection amongst related localForages.\n for (var k = 0; k < forages.length; k++) {\n var forage = forages[k];\n if (forage !== self) {\n // Self is already up-to-date.\n forage._dbInfo.db = dbInfo.db;\n forage._dbInfo.version = dbInfo.version;\n }\n }\n });\n}\n\nfunction getItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.get(key);\n\n req.onsuccess = function () {\n var value = req.result;\n if (value === undefined) {\n value = null;\n }\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n resolve(value);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items stored in database.\nfunction iterate(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openCursor();\n var iterationNumber = 1;\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (cursor) {\n var value = cursor.value;\n if (_isEncodedBlob(value)) {\n value = _decodeBlob(value);\n }\n var result = iterator(value, cursor.key, iterationNumber++);\n\n // when the iterator callback returns any\n // (non-`undefined`) value, then we stop\n // the iteration immediately\n if (result !== void 0) {\n resolve(result);\n } else {\n cursor[\"continue\"]();\n }\n } else {\n resolve();\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n\n return promise;\n}\n\nfunction setItem(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n var dbInfo;\n self.ready().then(function () {\n dbInfo = self._dbInfo;\n if (toString.call(value) === '[object Blob]') {\n return _checkBlobSupport(dbInfo.db).then(function (blobSupport) {\n if (blobSupport) {\n return value;\n }\n return _encodeBlob(value);\n });\n }\n return value;\n }).then(function (value) {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n\n // The reason we don't _save_ null is because IE 10 does\n // not support saving the `null` type in IndexedDB. How\n // ironic, given the bug below!\n // See: https://github.com/mozilla/localForage/issues/161\n if (value === null) {\n value = undefined;\n }\n\n var req = store.put(value, key);\n\n transaction.oncomplete = function () {\n // Cast to undefined so the value passed to\n // callback/promise is the same as what one would get out\n // of `getItem()` later. This leads to some weirdness\n // (setItem('foo', undefined) will return `null`), but\n // it's not my fault localStorage is our baseline and that\n // it's weird.\n if (value === undefined) {\n value = null;\n }\n\n resolve(value);\n };\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction removeItem(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n // We use a Grunt task to make this safe for IE and some\n // versions of Android (including those used by Cordova).\n // Normally IE won't like `.delete()` and will insist on\n // using `['delete']()`, but we have a build step that\n // fixes this for us now.\n var req = store[\"delete\"](key);\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onerror = function () {\n reject(req.error);\n };\n\n // The request will be also be aborted if we've exceeded our storage\n // space.\n transaction.onabort = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction clear(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_WRITE, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.clear();\n\n transaction.oncomplete = function () {\n resolve();\n };\n\n transaction.onabort = transaction.onerror = function () {\n var err = req.error ? req.error : req.transaction.error;\n reject(err);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction length(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.count();\n\n req.onsuccess = function () {\n resolve(req.result);\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction key(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n if (n < 0) {\n resolve(null);\n\n return;\n }\n\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var advanced = false;\n var req = store.openKeyCursor();\n\n req.onsuccess = function () {\n var cursor = req.result;\n if (!cursor) {\n // this means there weren't enough keys\n resolve(null);\n\n return;\n }\n\n if (n === 0) {\n // We have the first key, return it if that's what they\n // wanted.\n resolve(cursor.key);\n } else {\n if (!advanced) {\n // Otherwise, ask the cursor to skip ahead n\n // records.\n advanced = true;\n cursor.advance(n);\n } else {\n // When we get here, we've got the nth key.\n resolve(cursor.key);\n }\n }\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n createTransaction(self._dbInfo, READ_ONLY, function (err, transaction) {\n if (err) {\n return reject(err);\n }\n\n try {\n var store = transaction.objectStore(self._dbInfo.storeName);\n var req = store.openKeyCursor();\n var keys = [];\n\n req.onsuccess = function () {\n var cursor = req.result;\n\n if (!cursor) {\n resolve(keys);\n return;\n }\n\n keys.push(cursor.key);\n cursor[\"continue\"]();\n };\n\n req.onerror = function () {\n reject(req.error);\n };\n } catch (e) {\n reject(e);\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n var isCurrentDb = options.name === currentConfig.name && self._dbInfo.db;\n\n var dbPromise = isCurrentDb ? Promise$1.resolve(self._dbInfo.db) : _getOriginalConnection(options).then(function (db) {\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n forages[i]._dbInfo.db = db;\n }\n return db;\n });\n\n if (!options.storeName) {\n promise = dbPromise.then(function (db) {\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n }\n\n var dropDBPromise = new Promise$1(function (resolve, reject) {\n var req = idb.deleteDatabase(options.name);\n\n req.onerror = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n reject(req.error);\n };\n\n req.onblocked = function () {\n // Closing all open connections in onversionchange handler should prevent this situation, but if\n // we do get here, it just means the request remains pending - eventually it will succeed or error\n console.warn('dropInstance blocked for database \"' + options.name + '\" until all open connections are closed');\n };\n\n req.onsuccess = function () {\n var db = req.result;\n if (db) {\n db.close();\n }\n resolve(db);\n };\n });\n\n return dropDBPromise.then(function (db) {\n dbContext.db = db;\n for (var i = 0; i < forages.length; i++) {\n var _forage = forages[i];\n _advanceReadiness(_forage._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n } else {\n promise = dbPromise.then(function (db) {\n if (!db.objectStoreNames.contains(options.storeName)) {\n return;\n }\n\n var newVersion = db.version + 1;\n\n _deferReadiness(options);\n\n var dbContext = dbContexts[options.name];\n var forages = dbContext.forages;\n\n db.close();\n for (var i = 0; i < forages.length; i++) {\n var forage = forages[i];\n forage._dbInfo.db = null;\n forage._dbInfo.version = newVersion;\n }\n\n var dropObjectPromise = new Promise$1(function (resolve, reject) {\n var req = idb.open(options.name, newVersion);\n\n req.onerror = function (err) {\n var db = req.result;\n db.close();\n reject(err);\n };\n\n req.onupgradeneeded = function () {\n var db = req.result;\n db.deleteObjectStore(options.storeName);\n };\n\n req.onsuccess = function () {\n var db = req.result;\n db.close();\n resolve(db);\n };\n });\n\n return dropObjectPromise.then(function (db) {\n dbContext.db = db;\n for (var j = 0; j < forages.length; j++) {\n var _forage2 = forages[j];\n _forage2._dbInfo.db = db;\n _advanceReadiness(_forage2._dbInfo);\n }\n })[\"catch\"](function (err) {\n (_rejectReadiness(options, err) || Promise$1.resolve())[\"catch\"](function () {});\n throw err;\n });\n });\n }\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar asyncStorage = {\n _driver: 'asyncStorage',\n _initStorage: _initStorage,\n _support: isIndexedDBValid(),\n iterate: iterate,\n getItem: getItem,\n setItem: setItem,\n removeItem: removeItem,\n clear: clear,\n length: length,\n key: key,\n keys: keys,\n dropInstance: dropInstance\n};\n\nfunction isWebSQLValid() {\n return typeof openDatabase === 'function';\n}\n\n// Sadly, the best way to save binary data in WebSQL/localStorage is serializing\n// it to Base64, so this is how we store it to prevent very strange errors with less\n// verbose ways of binary <-> string data storage.\nvar BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\nvar BLOB_TYPE_PREFIX = '~~local_forage_type~';\nvar BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;\n\nvar SERIALIZED_MARKER = '__lfsc__:';\nvar SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;\n\n// OMG the serializations!\nvar TYPE_ARRAYBUFFER = 'arbf';\nvar TYPE_BLOB = 'blob';\nvar TYPE_INT8ARRAY = 'si08';\nvar TYPE_UINT8ARRAY = 'ui08';\nvar TYPE_UINT8CLAMPEDARRAY = 'uic8';\nvar TYPE_INT16ARRAY = 'si16';\nvar TYPE_INT32ARRAY = 'si32';\nvar TYPE_UINT16ARRAY = 'ur16';\nvar TYPE_UINT32ARRAY = 'ui32';\nvar TYPE_FLOAT32ARRAY = 'fl32';\nvar TYPE_FLOAT64ARRAY = 'fl64';\nvar TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length;\n\nvar toString$1 = Object.prototype.toString;\n\nfunction stringToBuffer(serializedString) {\n // Fill the string into a ArrayBuffer.\n var bufferLength = serializedString.length * 0.75;\n var len = serializedString.length;\n var i;\n var p = 0;\n var encoded1, encoded2, encoded3, encoded4;\n\n if (serializedString[serializedString.length - 1] === '=') {\n bufferLength--;\n if (serializedString[serializedString.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n var buffer = new ArrayBuffer(bufferLength);\n var bytes = new Uint8Array(buffer);\n\n for (i = 0; i < len; i += 4) {\n encoded1 = BASE_CHARS.indexOf(serializedString[i]);\n encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]);\n encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]);\n encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]);\n\n /*jslint bitwise: true */\n bytes[p++] = encoded1 << 2 | encoded2 >> 4;\n bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2;\n bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63;\n }\n return buffer;\n}\n\n// Converts a buffer to a string to store, serialized, in the backend\n// storage library.\nfunction bufferToString(buffer) {\n // base64-arraybuffer\n var bytes = new Uint8Array(buffer);\n var base64String = '';\n var i;\n\n for (i = 0; i < bytes.length; i += 3) {\n /*jslint bitwise: true */\n base64String += BASE_CHARS[bytes[i] >> 2];\n base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4];\n base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6];\n base64String += BASE_CHARS[bytes[i + 2] & 63];\n }\n\n if (bytes.length % 3 === 2) {\n base64String = base64String.substring(0, base64String.length - 1) + '=';\n } else if (bytes.length % 3 === 1) {\n base64String = base64String.substring(0, base64String.length - 2) + '==';\n }\n\n return base64String;\n}\n\n// Serialize a value, afterwards executing a callback (which usually\n// instructs the `setItem()` callback/promise to be executed). This is how\n// we store binary data with localStorage.\nfunction serialize(value, callback) {\n var valueType = '';\n if (value) {\n valueType = toString$1.call(value);\n }\n\n // Cannot use `value instanceof ArrayBuffer` or such here, as these\n // checks fail when running the tests using casper.js...\n //\n // TODO: See why those tests fail and use a better solution.\n if (value && (valueType === '[object ArrayBuffer]' || value.buffer && toString$1.call(value.buffer) === '[object ArrayBuffer]')) {\n // Convert binary arrays to a string and prefix the string with\n // a special marker.\n var buffer;\n var marker = SERIALIZED_MARKER;\n\n if (value instanceof ArrayBuffer) {\n buffer = value;\n marker += TYPE_ARRAYBUFFER;\n } else {\n buffer = value.buffer;\n\n if (valueType === '[object Int8Array]') {\n marker += TYPE_INT8ARRAY;\n } else if (valueType === '[object Uint8Array]') {\n marker += TYPE_UINT8ARRAY;\n } else if (valueType === '[object Uint8ClampedArray]') {\n marker += TYPE_UINT8CLAMPEDARRAY;\n } else if (valueType === '[object Int16Array]') {\n marker += TYPE_INT16ARRAY;\n } else if (valueType === '[object Uint16Array]') {\n marker += TYPE_UINT16ARRAY;\n } else if (valueType === '[object Int32Array]') {\n marker += TYPE_INT32ARRAY;\n } else if (valueType === '[object Uint32Array]') {\n marker += TYPE_UINT32ARRAY;\n } else if (valueType === '[object Float32Array]') {\n marker += TYPE_FLOAT32ARRAY;\n } else if (valueType === '[object Float64Array]') {\n marker += TYPE_FLOAT64ARRAY;\n } else {\n callback(new Error('Failed to get type for BinaryArray'));\n }\n }\n\n callback(marker + bufferToString(buffer));\n } else if (valueType === '[object Blob]') {\n // Conver the blob to a binaryArray and then to a string.\n var fileReader = new FileReader();\n\n fileReader.onload = function () {\n // Backwards-compatible prefix for the blob type.\n var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result);\n\n callback(SERIALIZED_MARKER + TYPE_BLOB + str);\n };\n\n fileReader.readAsArrayBuffer(value);\n } else {\n try {\n callback(JSON.stringify(value));\n } catch (e) {\n console.error(\"Couldn't convert value into a JSON string: \", value);\n\n callback(null, e);\n }\n }\n}\n\n// Deserialize data we've inserted into a value column/field. We place\n// special markers into our strings to mark them as encoded; this isn't\n// as nice as a meta field, but it's the only sane thing we can do whilst\n// keeping localStorage support intact.\n//\n// Oftentimes this will just deserialize JSON content, but if we have a\n// special marker (SERIALIZED_MARKER, defined above), we will extract\n// some kind of arraybuffer/binary data/typed array out of the string.\nfunction deserialize(value) {\n // If we haven't marked this string as being specially serialized (i.e.\n // something other than serialized JSON), we can just return it and be\n // done with it.\n if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {\n return JSON.parse(value);\n }\n\n // The following code deals with deserializing some kind of Blob or\n // TypedArray. First we separate out the type of data we're dealing\n // with from the data itself.\n var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);\n var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH);\n\n var blobType;\n // Backwards-compatible blob type serialization strategy.\n // DBs created with older versions of localForage will simply not have the blob type.\n if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {\n var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);\n blobType = matcher[1];\n serializedString = serializedString.substring(matcher[0].length);\n }\n var buffer = stringToBuffer(serializedString);\n\n // Return the right type based on the code/type set during\n // serialization.\n switch (type) {\n case TYPE_ARRAYBUFFER:\n return buffer;\n case TYPE_BLOB:\n return createBlob([buffer], { type: blobType });\n case TYPE_INT8ARRAY:\n return new Int8Array(buffer);\n case TYPE_UINT8ARRAY:\n return new Uint8Array(buffer);\n case TYPE_UINT8CLAMPEDARRAY:\n return new Uint8ClampedArray(buffer);\n case TYPE_INT16ARRAY:\n return new Int16Array(buffer);\n case TYPE_UINT16ARRAY:\n return new Uint16Array(buffer);\n case TYPE_INT32ARRAY:\n return new Int32Array(buffer);\n case TYPE_UINT32ARRAY:\n return new Uint32Array(buffer);\n case TYPE_FLOAT32ARRAY:\n return new Float32Array(buffer);\n case TYPE_FLOAT64ARRAY:\n return new Float64Array(buffer);\n default:\n throw new Error('Unkown type: ' + type);\n }\n}\n\nvar localforageSerializer = {\n serialize: serialize,\n deserialize: deserialize,\n stringToBuffer: stringToBuffer,\n bufferToString: bufferToString\n};\n\n/*\n * Includes code from:\n *\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n\nfunction createDbTable(t, dbInfo, callback, errorCallback) {\n t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' ' + '(id INTEGER PRIMARY KEY, key unique, value)', [], callback, errorCallback);\n}\n\n// Open the WebSQL database (automatically creates one if one didn't\n// previously exist), using any options set in the config.\nfunction _initStorage$1(options) {\n var self = this;\n var dbInfo = {\n db: null\n };\n\n if (options) {\n for (var i in options) {\n dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i];\n }\n }\n\n var dbInfoPromise = new Promise$1(function (resolve, reject) {\n // Open the database; the openDatabase API will automatically\n // create it for us if it doesn't exist.\n try {\n dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size);\n } catch (e) {\n return reject(e);\n }\n\n // Create our key/value table if it doesn't exist.\n dbInfo.db.transaction(function (t) {\n createDbTable(t, dbInfo, function () {\n self._dbInfo = dbInfo;\n resolve();\n }, function (t, error) {\n reject(error);\n });\n }, reject);\n });\n\n dbInfo.serializer = localforageSerializer;\n return dbInfoPromise;\n}\n\nfunction tryExecuteSql(t, dbInfo, sqlStatement, args, callback, errorCallback) {\n t.executeSql(sqlStatement, args, callback, function (t, error) {\n if (error.code === error.SYNTAX_ERR) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name = ?\", [dbInfo.storeName], function (t, results) {\n if (!results.rows.length) {\n // if the table is missing (was deleted)\n // re-create it table and retry\n createDbTable(t, dbInfo, function () {\n t.executeSql(sqlStatement, args, callback, errorCallback);\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n } else {\n errorCallback(t, error);\n }\n }, errorCallback);\n}\n\nfunction getItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).value : null;\n\n // Check to see if this is serialized content we need to\n // unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction iterate$1(iterator, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT * FROM ' + dbInfo.storeName, [], function (t, results) {\n var rows = results.rows;\n var length = rows.length;\n\n for (var i = 0; i < length; i++) {\n var item = rows.item(i);\n var result = item.value;\n\n // Check to see if this is serialized content\n // we need to unpack.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n result = iterator(result, item.key, i + 1);\n\n // void(0) prevents problems with redefinition\n // of `undefined`.\n if (result !== void 0) {\n resolve(result);\n return;\n }\n }\n\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction _setItem(key, value, callback, retriesLeft) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n // The localStorage API doesn't return undefined values in an\n // \"expected\" way, so undefined is always cast to null in all\n // drivers. See: https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'INSERT OR REPLACE INTO ' + dbInfo.storeName + ' ' + '(key, value) VALUES (?, ?)', [key, value], function () {\n resolve(originalValue);\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n // The transaction failed; check\n // to see if it's a quota error.\n if (sqlError.code === sqlError.QUOTA_ERR) {\n // We reject the callback outright for now, but\n // it's worth trying to re-run the transaction.\n // Even if the user accepts the prompt to use\n // more storage on Safari, this error will\n // be called.\n //\n // Try to re-run the transaction.\n if (retriesLeft > 0) {\n resolve(_setItem.apply(self, [key, originalValue, callback, retriesLeft - 1]));\n return;\n }\n reject(sqlError);\n }\n });\n }\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction setItem$1(key, value, callback) {\n return _setItem.apply(this, [key, value, callback, 1]);\n}\n\nfunction removeItem$1(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Deletes every item in the table.\n// TODO: Find out if this resets the AUTO_INCREMENT number.\nfunction clear$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'DELETE FROM ' + dbInfo.storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Does a simple `COUNT(key)` to get the number of items stored in\n// localForage.\nfunction length$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n // Ahhh, SQL makes this one soooooo easy.\n tryExecuteSql(t, dbInfo, 'SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) {\n var result = results.rows.item(0).c;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Return the key located at key index X; essentially gets the key from a\n// `WHERE id = ?`. This is the most efficient way I can think to implement\n// this rarely-used (in my experience) part of the API, but it can seem\n// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so\n// the ID of each key will change every time it's updated. Perhaps a stored\n// procedure for the `setItem()` SQL would solve this problem?\n// TODO: Don't change ID on `setItem()`.\nfunction key$1(n, callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) {\n var result = results.rows.length ? results.rows.item(0).key : null;\n resolve(result);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$1(callback) {\n var self = this;\n\n var promise = new Promise$1(function (resolve, reject) {\n self.ready().then(function () {\n var dbInfo = self._dbInfo;\n dbInfo.db.transaction(function (t) {\n tryExecuteSql(t, dbInfo, 'SELECT key FROM ' + dbInfo.storeName, [], function (t, results) {\n var keys = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n keys.push(results.rows.item(i).key);\n }\n\n resolve(keys);\n }, function (t, error) {\n reject(error);\n });\n });\n })[\"catch\"](reject);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// https://www.w3.org/TR/webdatabase/#databases\n// > There is no way to enumerate or delete the databases available for an origin from this API.\nfunction getAllStoreNames(db) {\n return new Promise$1(function (resolve, reject) {\n db.transaction(function (t) {\n t.executeSql('SELECT name FROM sqlite_master ' + \"WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'\", [], function (t, results) {\n var storeNames = [];\n\n for (var i = 0; i < results.rows.length; i++) {\n storeNames.push(results.rows.item(i).name);\n }\n\n resolve({\n db: db,\n storeNames: storeNames\n });\n }, function (t, error) {\n reject(error);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n}\n\nfunction dropInstance$1(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n var currentConfig = this.config();\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n var db;\n if (options.name === currentConfig.name) {\n // use the db reference of the current instance\n db = self._dbInfo.db;\n } else {\n db = openDatabase(options.name, '', '', 0);\n }\n\n if (!options.storeName) {\n // drop all database tables\n resolve(getAllStoreNames(db));\n } else {\n resolve({\n db: db,\n storeNames: [options.storeName]\n });\n }\n }).then(function (operationInfo) {\n return new Promise$1(function (resolve, reject) {\n operationInfo.db.transaction(function (t) {\n function dropTable(storeName) {\n return new Promise$1(function (resolve, reject) {\n t.executeSql('DROP TABLE IF EXISTS ' + storeName, [], function () {\n resolve();\n }, function (t, error) {\n reject(error);\n });\n });\n }\n\n var operations = [];\n for (var i = 0, len = operationInfo.storeNames.length; i < len; i++) {\n operations.push(dropTable(operationInfo.storeNames[i]));\n }\n\n Promise$1.all(operations).then(function () {\n resolve();\n })[\"catch\"](function (e) {\n reject(e);\n });\n }, function (sqlError) {\n reject(sqlError);\n });\n });\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar webSQLStorage = {\n _driver: 'webSQLStorage',\n _initStorage: _initStorage$1,\n _support: isWebSQLValid(),\n iterate: iterate$1,\n getItem: getItem$1,\n setItem: setItem$1,\n removeItem: removeItem$1,\n clear: clear$1,\n length: length$1,\n key: key$1,\n keys: keys$1,\n dropInstance: dropInstance$1\n};\n\nfunction isLocalStorageValid() {\n try {\n return typeof localStorage !== 'undefined' && 'setItem' in localStorage &&\n // in IE8 typeof localStorage.setItem === 'object'\n !!localStorage.setItem;\n } catch (e) {\n return false;\n }\n}\n\nfunction _getKeyPrefix(options, defaultConfig) {\n var keyPrefix = options.name + '/';\n\n if (options.storeName !== defaultConfig.storeName) {\n keyPrefix += options.storeName + '/';\n }\n return keyPrefix;\n}\n\n// Check if localStorage throws when saving an item\nfunction checkIfLocalStorageThrows() {\n var localStorageTestKey = '_localforage_support_test';\n\n try {\n localStorage.setItem(localStorageTestKey, true);\n localStorage.removeItem(localStorageTestKey);\n\n return false;\n } catch (e) {\n return true;\n }\n}\n\n// Check if localStorage is usable and allows to save an item\n// This method checks if localStorage is usable in Safari Private Browsing\n// mode, or in any other case where the available quota for localStorage\n// is 0 and there wasn't any saved items yet.\nfunction _isLocalStorageUsable() {\n return !checkIfLocalStorageThrows() || localStorage.length > 0;\n}\n\n// Config the localStorage backend, using options set in the config.\nfunction _initStorage$2(options) {\n var self = this;\n var dbInfo = {};\n if (options) {\n for (var i in options) {\n dbInfo[i] = options[i];\n }\n }\n\n dbInfo.keyPrefix = _getKeyPrefix(options, self._defaultConfig);\n\n if (!_isLocalStorageUsable()) {\n return Promise$1.reject();\n }\n\n self._dbInfo = dbInfo;\n dbInfo.serializer = localforageSerializer;\n\n return Promise$1.resolve();\n}\n\n// Remove all keys from the datastore, effectively destroying all data in\n// the app's key/value store!\nfunction clear$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var keyPrefix = self._dbInfo.keyPrefix;\n\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Retrieve an item from the store. Unlike the original async_storage\n// library in Gaia, we don't modify return values at all. If a key's value\n// is `undefined`, we pass that value to the callback function.\nfunction getItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result = localStorage.getItem(dbInfo.keyPrefix + key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the key\n // is likely undefined and we'll pass it straight to the\n // callback.\n if (result) {\n result = dbInfo.serializer.deserialize(result);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Iterate over all items in the store.\nfunction iterate$2(iterator, callback) {\n var self = this;\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var keyPrefix = dbInfo.keyPrefix;\n var keyPrefixLength = keyPrefix.length;\n var length = localStorage.length;\n\n // We use a dedicated iterator instead of the `i` variable below\n // so other keys we fetch in localStorage aren't counted in\n // the `iterationNumber` argument passed to the `iterate()`\n // callback.\n //\n // See: github.com/mozilla/localForage/pull/435#discussion_r38061530\n var iterationNumber = 1;\n\n for (var i = 0; i < length; i++) {\n var key = localStorage.key(i);\n if (key.indexOf(keyPrefix) !== 0) {\n continue;\n }\n var value = localStorage.getItem(key);\n\n // If a result was found, parse it from the serialized\n // string into a JS object. If result isn't truthy, the\n // key is likely undefined and we'll pass it straight\n // to the iterator.\n if (value) {\n value = dbInfo.serializer.deserialize(value);\n }\n\n value = iterator(value, key.substring(keyPrefixLength), iterationNumber++);\n\n if (value !== void 0) {\n return value;\n }\n }\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Same as localStorage's key() method, except takes a callback.\nfunction key$2(n, callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var result;\n try {\n result = localStorage.key(n);\n } catch (error) {\n result = null;\n }\n\n // Remove the prefix from the key, if a key is found.\n if (result) {\n result = result.substring(dbInfo.keyPrefix.length);\n }\n\n return result;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction keys$2(callback) {\n var self = this;\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n var length = localStorage.length;\n var keys = [];\n\n for (var i = 0; i < length; i++) {\n var itemKey = localStorage.key(i);\n if (itemKey.indexOf(dbInfo.keyPrefix) === 0) {\n keys.push(itemKey.substring(dbInfo.keyPrefix.length));\n }\n }\n\n return keys;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Supply the number of keys in the datastore to the callback function.\nfunction length$2(callback) {\n var self = this;\n var promise = self.keys().then(function (keys) {\n return keys.length;\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Remove an item from the store, nice and simple.\nfunction removeItem$2(key, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n var dbInfo = self._dbInfo;\n localStorage.removeItem(dbInfo.keyPrefix + key);\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\n// Set a key's value and run an optional callback once the value is set.\n// Unlike Gaia's implementation, the callback function is passed the value,\n// in case you want to operate on that value only after you're sure it\n// saved, or something like that.\nfunction setItem$2(key, value, callback) {\n var self = this;\n\n key = normalizeKey(key);\n\n var promise = self.ready().then(function () {\n // Convert undefined values to null.\n // https://github.com/mozilla/localForage/pull/42\n if (value === undefined) {\n value = null;\n }\n\n // Save the original value to pass to the callback.\n var originalValue = value;\n\n return new Promise$1(function (resolve, reject) {\n var dbInfo = self._dbInfo;\n dbInfo.serializer.serialize(value, function (value, error) {\n if (error) {\n reject(error);\n } else {\n try {\n localStorage.setItem(dbInfo.keyPrefix + key, value);\n resolve(originalValue);\n } catch (e) {\n // localStorage capacity exceeded.\n // TODO: Make this a specific error/event.\n if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {\n reject(e);\n }\n reject(e);\n }\n }\n });\n });\n });\n\n executeCallback(promise, callback);\n return promise;\n}\n\nfunction dropInstance$2(options, callback) {\n callback = getCallback.apply(this, arguments);\n\n options = typeof options !== 'function' && options || {};\n if (!options.name) {\n var currentConfig = this.config();\n options.name = options.name || currentConfig.name;\n options.storeName = options.storeName || currentConfig.storeName;\n }\n\n var self = this;\n var promise;\n if (!options.name) {\n promise = Promise$1.reject('Invalid arguments');\n } else {\n promise = new Promise$1(function (resolve) {\n if (!options.storeName) {\n resolve(options.name + '/');\n } else {\n resolve(_getKeyPrefix(options, self._defaultConfig));\n }\n }).then(function (keyPrefix) {\n for (var i = localStorage.length - 1; i >= 0; i--) {\n var key = localStorage.key(i);\n\n if (key.indexOf(keyPrefix) === 0) {\n localStorage.removeItem(key);\n }\n }\n });\n }\n\n executeCallback(promise, callback);\n return promise;\n}\n\nvar localStorageWrapper = {\n _driver: 'localStorageWrapper',\n _initStorage: _initStorage$2,\n _support: isLocalStorageValid(),\n iterate: iterate$2,\n getItem: getItem$2,\n setItem: setItem$2,\n removeItem: removeItem$2,\n clear: clear$2,\n length: length$2,\n key: key$2,\n keys: keys$2,\n dropInstance: dropInstance$2\n};\n\nvar sameValue = function sameValue(x, y) {\n return x === y || typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y);\n};\n\nvar includes = function includes(array, searchElement) {\n var len = array.length;\n var i = 0;\n while (i < len) {\n if (sameValue(array[i], searchElement)) {\n return true;\n }\n i++;\n }\n\n return false;\n};\n\nvar isArray = Array.isArray || function (arg) {\n return Object.prototype.toString.call(arg) === '[object Array]';\n};\n\n// Drivers are stored here when `defineDriver()` is called.\n// They are shared across all instances of localForage.\nvar DefinedDrivers = {};\n\nvar DriverSupport = {};\n\nvar DefaultDrivers = {\n INDEXEDDB: asyncStorage,\n WEBSQL: webSQLStorage,\n LOCALSTORAGE: localStorageWrapper\n};\n\nvar DefaultDriverOrder = [DefaultDrivers.INDEXEDDB._driver, DefaultDrivers.WEBSQL._driver, DefaultDrivers.LOCALSTORAGE._driver];\n\nvar OptionalDriverMethods = ['dropInstance'];\n\nvar LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem'].concat(OptionalDriverMethods);\n\nvar DefaultConfig = {\n description: '',\n driver: DefaultDriverOrder.slice(),\n name: 'localforage',\n // Default DB size is _JUST UNDER_ 5MB, as it's the highest size\n // we can use without a prompt.\n size: 4980736,\n storeName: 'keyvaluepairs',\n version: 1.0\n};\n\nfunction callWhenReady(localForageInstance, libraryMethod) {\n localForageInstance[libraryMethod] = function () {\n var _args = arguments;\n return localForageInstance.ready().then(function () {\n return localForageInstance[libraryMethod].apply(localForageInstance, _args);\n });\n };\n}\n\nfunction extend() {\n for (var i = 1; i < arguments.length; i++) {\n var arg = arguments[i];\n\n if (arg) {\n for (var _key in arg) {\n if (arg.hasOwnProperty(_key)) {\n if (isArray(arg[_key])) {\n arguments[0][_key] = arg[_key].slice();\n } else {\n arguments[0][_key] = arg[_key];\n }\n }\n }\n }\n }\n\n return arguments[0];\n}\n\nvar LocalForage = function () {\n function LocalForage(options) {\n _classCallCheck(this, LocalForage);\n\n for (var driverTypeKey in DefaultDrivers) {\n if (DefaultDrivers.hasOwnProperty(driverTypeKey)) {\n var driver = DefaultDrivers[driverTypeKey];\n var driverName = driver._driver;\n this[driverTypeKey] = driverName;\n\n if (!DefinedDrivers[driverName]) {\n // we don't need to wait for the promise,\n // since the default drivers can be defined\n // in a blocking manner\n this.defineDriver(driver);\n }\n }\n }\n\n this._defaultConfig = extend({}, DefaultConfig);\n this._config = extend({}, this._defaultConfig, options);\n this._driverSet = null;\n this._initDriver = null;\n this._ready = false;\n this._dbInfo = null;\n\n this._wrapLibraryMethodsWithReady();\n this.setDriver(this._config.driver)[\"catch\"](function () {});\n }\n\n // Set any config values for localForage; can be called anytime before\n // the first API call (e.g. `getItem`, `setItem`).\n // We loop through options so we don't overwrite existing config\n // values.\n\n\n LocalForage.prototype.config = function config(options) {\n // If the options argument is an object, we use it to set values.\n // Otherwise, we return either a specified config value or all\n // config values.\n if ((typeof options === 'undefined' ? 'undefined' : _typeof(options)) === 'object') {\n // If localforage is ready and fully initialized, we can't set\n // any new configuration values. Instead, we return an error.\n if (this._ready) {\n return new Error(\"Can't call config() after localforage \" + 'has been used.');\n }\n\n for (var i in options) {\n if (i === 'storeName') {\n options[i] = options[i].replace(/\\W/g, '_');\n }\n\n if (i === 'version' && typeof options[i] !== 'number') {\n return new Error('Database version must be a number.');\n }\n\n this._config[i] = options[i];\n }\n\n // after all config options are set and\n // the driver option is used, try setting it\n if ('driver' in options && options.driver) {\n return this.setDriver(this._config.driver);\n }\n\n return true;\n } else if (typeof options === 'string') {\n return this._config[options];\n } else {\n return this._config;\n }\n };\n\n // Used to define a custom driver, shared across all instances of\n // localForage.\n\n\n LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) {\n var promise = new Promise$1(function (resolve, reject) {\n try {\n var driverName = driverObject._driver;\n var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver');\n\n // A driver name should be defined and not overlap with the\n // library-defined, default drivers.\n if (!driverObject._driver) {\n reject(complianceError);\n return;\n }\n\n var driverMethods = LibraryMethods.concat('_initStorage');\n for (var i = 0, len = driverMethods.length; i < len; i++) {\n var driverMethodName = driverMethods[i];\n\n // when the property is there,\n // it should be a method even when optional\n var isRequired = !includes(OptionalDriverMethods, driverMethodName);\n if ((isRequired || driverObject[driverMethodName]) && typeof driverObject[driverMethodName] !== 'function') {\n reject(complianceError);\n return;\n }\n }\n\n var configureMissingMethods = function configureMissingMethods() {\n var methodNotImplementedFactory = function methodNotImplementedFactory(methodName) {\n return function () {\n var error = new Error('Method ' + methodName + ' is not implemented by the current driver');\n var promise = Promise$1.reject(error);\n executeCallback(promise, arguments[arguments.length - 1]);\n return promise;\n };\n };\n\n for (var _i = 0, _len = OptionalDriverMethods.length; _i < _len; _i++) {\n var optionalDriverMethod = OptionalDriverMethods[_i];\n if (!driverObject[optionalDriverMethod]) {\n driverObject[optionalDriverMethod] = methodNotImplementedFactory(optionalDriverMethod);\n }\n }\n };\n\n configureMissingMethods();\n\n var setDriverSupport = function setDriverSupport(support) {\n if (DefinedDrivers[driverName]) {\n console.info('Redefining LocalForage driver: ' + driverName);\n }\n DefinedDrivers[driverName] = driverObject;\n DriverSupport[driverName] = support;\n // don't use a then, so that we can define\n // drivers that have simple _support methods\n // in a blocking manner\n resolve();\n };\n\n if ('_support' in driverObject) {\n if (driverObject._support && typeof driverObject._support === 'function') {\n driverObject._support().then(setDriverSupport, reject);\n } else {\n setDriverSupport(!!driverObject._support);\n }\n } else {\n setDriverSupport(true);\n }\n } catch (e) {\n reject(e);\n }\n });\n\n executeTwoCallbacks(promise, callback, errorCallback);\n return promise;\n };\n\n LocalForage.prototype.driver = function driver() {\n return this._driver || null;\n };\n\n LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) {\n var getDriverPromise = DefinedDrivers[driverName] ? Promise$1.resolve(DefinedDrivers[driverName]) : Promise$1.reject(new Error('Driver not found.'));\n\n executeTwoCallbacks(getDriverPromise, callback, errorCallback);\n return getDriverPromise;\n };\n\n LocalForage.prototype.getSerializer = function getSerializer(callback) {\n var serializerPromise = Promise$1.resolve(localforageSerializer);\n executeTwoCallbacks(serializerPromise, callback);\n return serializerPromise;\n };\n\n LocalForage.prototype.ready = function ready(callback) {\n var self = this;\n\n var promise = self._driverSet.then(function () {\n if (self._ready === null) {\n self._ready = self._initDriver();\n }\n\n return self._ready;\n });\n\n executeTwoCallbacks(promise, callback, callback);\n return promise;\n };\n\n LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) {\n var self = this;\n\n if (!isArray(drivers)) {\n drivers = [drivers];\n }\n\n var supportedDrivers = this._getSupportedDrivers(drivers);\n\n function setDriverToConfig() {\n self._config.driver = self.driver();\n }\n\n function extendSelfWithDriver(driver) {\n self._extend(driver);\n setDriverToConfig();\n\n self._ready = self._initStorage(self._config);\n return self._ready;\n }\n\n function initDriver(supportedDrivers) {\n return function () {\n var currentDriverIndex = 0;\n\n function driverPromiseLoop() {\n while (currentDriverIndex < supportedDrivers.length) {\n var driverName = supportedDrivers[currentDriverIndex];\n currentDriverIndex++;\n\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(extendSelfWithDriver)[\"catch\"](driverPromiseLoop);\n }\n\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n }\n\n return driverPromiseLoop();\n };\n }\n\n // There might be a driver initialization in progress\n // so wait for it to finish in order to avoid a possible\n // race condition to set _dbInfo\n var oldDriverSetDone = this._driverSet !== null ? this._driverSet[\"catch\"](function () {\n return Promise$1.resolve();\n }) : Promise$1.resolve();\n\n this._driverSet = oldDriverSetDone.then(function () {\n var driverName = supportedDrivers[0];\n self._dbInfo = null;\n self._ready = null;\n\n return self.getDriver(driverName).then(function (driver) {\n self._driver = driver._driver;\n setDriverToConfig();\n self._wrapLibraryMethodsWithReady();\n self._initDriver = initDriver(supportedDrivers);\n });\n })[\"catch\"](function () {\n setDriverToConfig();\n var error = new Error('No available storage method found.');\n self._driverSet = Promise$1.reject(error);\n return self._driverSet;\n });\n\n executeTwoCallbacks(this._driverSet, callback, errorCallback);\n return this._driverSet;\n };\n\n LocalForage.prototype.supports = function supports(driverName) {\n return !!DriverSupport[driverName];\n };\n\n LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) {\n extend(this, libraryMethodsAndProperties);\n };\n\n LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) {\n var supportedDrivers = [];\n for (var i = 0, len = drivers.length; i < len; i++) {\n var driverName = drivers[i];\n if (this.supports(driverName)) {\n supportedDrivers.push(driverName);\n }\n }\n return supportedDrivers;\n };\n\n LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() {\n // Add a stub for each driver API method that delays the call to the\n // corresponding driver method until localForage is ready. These stubs\n // will be replaced by the driver methods as soon as the driver is\n // loaded, so there is no performance impact.\n for (var i = 0, len = LibraryMethods.length; i < len; i++) {\n callWhenReady(this, LibraryMethods[i]);\n }\n };\n\n LocalForage.prototype.createInstance = function createInstance(options) {\n return new LocalForage(options);\n };\n\n return LocalForage;\n}();\n\n// The actual localForage object that we expose as a module or via a\n// global. It's extended by pulling in one of our other libraries.\n\n\nvar localforage_js = new LocalForage();\n\nmodule.exports = localforage_js;\n\n},{\"3\":3}]},{},[4])(4)\n});\n","/**\n * lodash (Custom Build) \n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright jQuery Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/**\n * Checks if `value` is a host object in IE < 9.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a host object, else `false`.\n */\nfunction isHostObject(value) {\n // Many host objects are `Object` objects that can coerce to strings\n // despite having improperly defined `toString` methods.\n var result = false;\n if (value != null && typeof value.toString != 'function') {\n try {\n result = !!(value + '');\n } catch (e) {}\n }\n return result;\n}\n\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\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 * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\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 && typeof value == 'object';\n}\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) ||\n objectToString.call(value) != objectTag || isHostObject(value)) {\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' &&\n Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString);\n}\n\nmodule.exports = isPlainObject;\n","/**\n * lodash 4.0.1 (Custom Build) \n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright 2012-2016 The Dojo Foundation \n * Based on Underscore.js 1.8.3 \n * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n * Available under MIT license \n */\n\n/** `Object#toString` result references. */\nvar stringTag = '[object String]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar objectToString = objectProto.toString;\n\n/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @type Function\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, 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\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 * @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 && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\nfunction isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag);\n}\n\nmodule.exports = isString;\n","var hasMap = typeof Map === 'function' && Map.prototype;\nvar mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;\nvar mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;\nvar mapForEach = hasMap && Map.prototype.forEach;\nvar hasSet = typeof Set === 'function' && Set.prototype;\nvar setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;\nvar setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;\nvar setForEach = hasSet && Set.prototype.forEach;\nvar hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;\nvar weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;\nvar hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;\nvar weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;\nvar hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype;\nvar weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null;\nvar booleanValueOf = Boolean.prototype.valueOf;\nvar objectToString = Object.prototype.toString;\nvar functionToString = Function.prototype.toString;\nvar $match = String.prototype.match;\nvar $slice = String.prototype.slice;\nvar $replace = String.prototype.replace;\nvar $toUpperCase = String.prototype.toUpperCase;\nvar $toLowerCase = String.prototype.toLowerCase;\nvar $test = RegExp.prototype.test;\nvar $concat = Array.prototype.concat;\nvar $join = Array.prototype.join;\nvar $arrSlice = Array.prototype.slice;\nvar $floor = Math.floor;\nvar bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;\nvar gOPS = Object.getOwnPropertySymbols;\nvar symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null;\nvar hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object';\n// ie, `has-tostringtag/shams\nvar toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol')\n ? Symbol.toStringTag\n : null;\nvar isEnumerable = Object.prototype.propertyIsEnumerable;\n\nvar gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || (\n [].__proto__ === Array.prototype // eslint-disable-line no-proto\n ? function (O) {\n return O.__proto__; // eslint-disable-line no-proto\n }\n : null\n);\n\nfunction addNumericSeparator(num, str) {\n if (\n num === Infinity\n || num === -Infinity\n || num !== num\n || (num && num > -1000 && num < 1000)\n || $test.call(/e/, str)\n ) {\n return str;\n }\n var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;\n if (typeof num === 'number') {\n var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num)\n if (int !== num) {\n var intStr = String(int);\n var dec = $slice.call(str, intStr.length + 1);\n return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, '');\n }\n }\n return $replace.call(str, sepRegex, '$&_');\n}\n\nvar utilInspect = require('./util.inspect');\nvar inspectCustom = utilInspect.custom;\nvar inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null;\n\nmodule.exports = function inspect_(obj, options, depth, seen) {\n var opts = options || {};\n\n if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {\n throw new TypeError('option \"quoteStyle\" must be \"single\" or \"double\"');\n }\n if (\n has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number'\n ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity\n : opts.maxStringLength !== null\n )\n ) {\n throw new TypeError('option \"maxStringLength\", if provided, must be a positive integer, Infinity, or `null`');\n }\n var customInspect = has(opts, 'customInspect') ? opts.customInspect : true;\n if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') {\n throw new TypeError('option \"customInspect\", if provided, must be `true`, `false`, or `\\'symbol\\'`');\n }\n\n if (\n has(opts, 'indent')\n && opts.indent !== null\n && opts.indent !== '\\t'\n && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0)\n ) {\n throw new TypeError('option \"indent\" must be \"\\\\t\", an integer > 0, or `null`');\n }\n if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') {\n throw new TypeError('option \"numericSeparator\", if provided, must be `true` or `false`');\n }\n var numericSeparator = opts.numericSeparator;\n\n if (typeof obj === 'undefined') {\n return 'undefined';\n }\n if (obj === null) {\n return 'null';\n }\n if (typeof obj === 'boolean') {\n return obj ? 'true' : 'false';\n }\n\n if (typeof obj === 'string') {\n return inspectString(obj, opts);\n }\n if (typeof obj === 'number') {\n if (obj === 0) {\n return Infinity / obj > 0 ? '0' : '-0';\n }\n var str = String(obj);\n return numericSeparator ? addNumericSeparator(obj, str) : str;\n }\n if (typeof obj === 'bigint') {\n var bigIntStr = String(obj) + 'n';\n return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr;\n }\n\n var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;\n if (typeof depth === 'undefined') { depth = 0; }\n if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {\n return isArray(obj) ? '[Array]' : '[Object]';\n }\n\n var indent = getIndent(opts, depth);\n\n if (typeof seen === 'undefined') {\n seen = [];\n } else if (indexOf(seen, obj) >= 0) {\n return '[Circular]';\n }\n\n function inspect(value, from, noIndent) {\n if (from) {\n seen = $arrSlice.call(seen);\n seen.push(from);\n }\n if (noIndent) {\n var newOpts = {\n depth: opts.depth\n };\n if (has(opts, 'quoteStyle')) {\n newOpts.quoteStyle = opts.quoteStyle;\n }\n return inspect_(value, newOpts, depth + 1, seen);\n }\n return inspect_(value, opts, depth + 1, seen);\n }\n\n if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable\n var name = nameOf(obj);\n var keys = arrObjKeys(obj, inspect);\n return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : '');\n }\n if (isSymbol(obj)) {\n var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\\(.*\\))_[^)]*$/, '$1') : symToString.call(obj);\n return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString;\n }\n if (isElement(obj)) {\n var s = '<' + $toLowerCase.call(String(obj.nodeName));\n var attrs = obj.attributes || [];\n for (var i = 0; i < attrs.length; i++) {\n s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);\n }\n s += '>';\n if (obj.childNodes && obj.childNodes.length) { s += '...'; }\n s += '';\n return s;\n }\n if (isArray(obj)) {\n if (obj.length === 0) { return '[]'; }\n var xs = arrObjKeys(obj, inspect);\n if (indent && !singleLineValues(xs)) {\n return '[' + indentedJoin(xs, indent) + ']';\n }\n return '[ ' + $join.call(xs, ', ') + ' ]';\n }\n if (isError(obj)) {\n var parts = arrObjKeys(obj, inspect);\n if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) {\n return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }';\n }\n if (parts.length === 0) { return '[' + String(obj) + ']'; }\n return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }';\n }\n if (typeof obj === 'object' && customInspect) {\n if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) {\n return utilInspect(obj, { depth: maxDepth - depth });\n } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') {\n return obj.inspect();\n }\n }\n if (isMap(obj)) {\n var mapParts = [];\n if (mapForEach) {\n mapForEach.call(obj, function (value, key) {\n mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj));\n });\n }\n return collectionOf('Map', mapSize.call(obj), mapParts, indent);\n }\n if (isSet(obj)) {\n var setParts = [];\n if (setForEach) {\n setForEach.call(obj, function (value) {\n setParts.push(inspect(value, obj));\n });\n }\n return collectionOf('Set', setSize.call(obj), setParts, indent);\n }\n if (isWeakMap(obj)) {\n return weakCollectionOf('WeakMap');\n }\n if (isWeakSet(obj)) {\n return weakCollectionOf('WeakSet');\n }\n if (isWeakRef(obj)) {\n return weakCollectionOf('WeakRef');\n }\n if (isNumber(obj)) {\n return markBoxed(inspect(Number(obj)));\n }\n if (isBigInt(obj)) {\n return markBoxed(inspect(bigIntValueOf.call(obj)));\n }\n if (isBoolean(obj)) {\n return markBoxed(booleanValueOf.call(obj));\n }\n if (isString(obj)) {\n return markBoxed(inspect(String(obj)));\n }\n if (!isDate(obj) && !isRegExp(obj)) {\n var ys = arrObjKeys(obj, inspect);\n var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object;\n var protoTag = obj instanceof Object ? '' : 'null prototype';\n var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : '';\n var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : '';\n var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : '');\n if (ys.length === 0) { return tag + '{}'; }\n if (indent) {\n return tag + '{' + indentedJoin(ys, indent) + '}';\n }\n return tag + '{ ' + $join.call(ys, ', ') + ' }';\n }\n return String(obj);\n};\n\nfunction wrapQuotes(s, defaultStyle, opts) {\n var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '\"' : \"'\";\n return quoteChar + s + quoteChar;\n}\n\nfunction quote(s) {\n return $replace.call(String(s), /\"/g, '"');\n}\n\nfunction isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\nfunction isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\nfunction isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\nfunction isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\nfunction isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\nfunction isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\nfunction isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); }\n\n// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives\nfunction isSymbol(obj) {\n if (hasShammedSymbols) {\n return obj && typeof obj === 'object' && obj instanceof Symbol;\n }\n if (typeof obj === 'symbol') {\n return true;\n }\n if (!obj || typeof obj !== 'object' || !symToString) {\n return false;\n }\n try {\n symToString.call(obj);\n return true;\n } catch (e) {}\n return false;\n}\n\nfunction isBigInt(obj) {\n if (!obj || typeof obj !== 'object' || !bigIntValueOf) {\n return false;\n }\n try {\n bigIntValueOf.call(obj);\n return true;\n } catch (e) {}\n return false;\n}\n\nvar hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; };\nfunction has(obj, key) {\n return hasOwn.call(obj, key);\n}\n\nfunction toStr(obj) {\n return objectToString.call(obj);\n}\n\nfunction nameOf(f) {\n if (f.name) { return f.name; }\n var m = $match.call(functionToString.call(f), /^function\\s*([\\w$]+)/);\n if (m) { return m[1]; }\n return null;\n}\n\nfunction indexOf(xs, x) {\n if (xs.indexOf) { return xs.indexOf(x); }\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) { return i; }\n }\n return -1;\n}\n\nfunction isMap(x) {\n if (!mapSize || !x || typeof x !== 'object') {\n return false;\n }\n try {\n mapSize.call(x);\n try {\n setSize.call(x);\n } catch (s) {\n return true;\n }\n return x instanceof Map; // core-js workaround, pre-v2.5.0\n } catch (e) {}\n return false;\n}\n\nfunction isWeakMap(x) {\n if (!weakMapHas || !x || typeof x !== 'object') {\n return false;\n }\n try {\n weakMapHas.call(x, weakMapHas);\n try {\n weakSetHas.call(x, weakSetHas);\n } catch (s) {\n return true;\n }\n return x instanceof WeakMap; // core-js workaround, pre-v2.5.0\n } catch (e) {}\n return false;\n}\n\nfunction isWeakRef(x) {\n if (!weakRefDeref || !x || typeof x !== 'object') {\n return false;\n }\n try {\n weakRefDeref.call(x);\n return true;\n } catch (e) {}\n return false;\n}\n\nfunction isSet(x) {\n if (!setSize || !x || typeof x !== 'object') {\n return false;\n }\n try {\n setSize.call(x);\n try {\n mapSize.call(x);\n } catch (m) {\n return true;\n }\n return x instanceof Set; // core-js workaround, pre-v2.5.0\n } catch (e) {}\n return false;\n}\n\nfunction isWeakSet(x) {\n if (!weakSetHas || !x || typeof x !== 'object') {\n return false;\n }\n try {\n weakSetHas.call(x, weakSetHas);\n try {\n weakMapHas.call(x, weakMapHas);\n } catch (s) {\n return true;\n }\n return x instanceof WeakSet; // core-js workaround, pre-v2.5.0\n } catch (e) {}\n return false;\n}\n\nfunction isElement(x) {\n if (!x || typeof x !== 'object') { return false; }\n if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {\n return true;\n }\n return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';\n}\n\nfunction inspectString(str, opts) {\n if (str.length > opts.maxStringLength) {\n var remaining = str.length - opts.maxStringLength;\n var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : '');\n return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer;\n }\n // eslint-disable-next-line no-control-regex\n var s = $replace.call($replace.call(str, /(['\\\\])/g, '\\\\$1'), /[\\x00-\\x1f]/g, lowbyte);\n return wrapQuotes(s, 'single', opts);\n}\n\nfunction lowbyte(c) {\n var n = c.charCodeAt(0);\n var x = {\n 8: 'b',\n 9: 't',\n 10: 'n',\n 12: 'f',\n 13: 'r'\n }[n];\n if (x) { return '\\\\' + x; }\n return '\\\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16));\n}\n\nfunction markBoxed(str) {\n return 'Object(' + str + ')';\n}\n\nfunction weakCollectionOf(type) {\n return type + ' { ? }';\n}\n\nfunction collectionOf(type, size, entries, indent) {\n var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', ');\n return type + ' (' + size + ') {' + joinedEntries + '}';\n}\n\nfunction singleLineValues(xs) {\n for (var i = 0; i < xs.length; i++) {\n if (indexOf(xs[i], '\\n') >= 0) {\n return false;\n }\n }\n return true;\n}\n\nfunction getIndent(opts, depth) {\n var baseIndent;\n if (opts.indent === '\\t') {\n baseIndent = '\\t';\n } else if (typeof opts.indent === 'number' && opts.indent > 0) {\n baseIndent = $join.call(Array(opts.indent + 1), ' ');\n } else {\n return null;\n }\n return {\n base: baseIndent,\n prev: $join.call(Array(depth + 1), baseIndent)\n };\n}\n\nfunction indentedJoin(xs, indent) {\n if (xs.length === 0) { return ''; }\n var lineJoiner = '\\n' + indent.prev + indent.base;\n return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\\n' + indent.prev;\n}\n\nfunction arrObjKeys(obj, inspect) {\n var isArr = isArray(obj);\n var xs = [];\n if (isArr) {\n xs.length = obj.length;\n for (var i = 0; i < obj.length; i++) {\n xs[i] = has(obj, i) ? inspect(obj[i], obj) : '';\n }\n }\n var syms = typeof gOPS === 'function' ? gOPS(obj) : [];\n var symMap;\n if (hasShammedSymbols) {\n symMap = {};\n for (var k = 0; k < syms.length; k++) {\n symMap['$' + syms[k]] = syms[k];\n }\n }\n\n for (var key in obj) { // eslint-disable-line no-restricted-syntax\n if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue\n if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue\n if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) {\n // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section\n continue; // eslint-disable-line no-restricted-syntax, no-continue\n } else if ($test.call(/[^\\w$]/, key)) {\n xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj));\n } else {\n xs.push(key + ': ' + inspect(obj[key], obj));\n }\n }\n if (typeof gOPS === 'function') {\n for (var j = 0; j < syms.length; j++) {\n if (isEnumerable.call(obj, syms[j])) {\n xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj));\n }\n }\n }\n return xs;\n}\n","'use strict';\n\nclass AbortError extends Error {\n\tconstructor() {\n\t\tsuper('Throttled function aborted');\n\t\tthis.name = 'AbortError';\n\t}\n}\n\nconst pThrottle = ({limit, interval, strict}) => {\n\tif (!Number.isFinite(limit)) {\n\t\tthrow new TypeError('Expected `limit` to be a finite number');\n\t}\n\n\tif (!Number.isFinite(interval)) {\n\t\tthrow new TypeError('Expected `interval` to be a finite number');\n\t}\n\n\tconst queue = new Map();\n\n\tlet currentTick = 0;\n\tlet activeCount = 0;\n\n\tfunction windowedDelay() {\n\t\tconst now = Date.now();\n\n\t\tif ((now - currentTick) > interval) {\n\t\t\tactiveCount = 1;\n\t\t\tcurrentTick = now;\n\t\t\treturn 0;\n\t\t}\n\n\t\tif (activeCount < limit) {\n\t\t\tactiveCount++;\n\t\t} else {\n\t\t\tcurrentTick += interval;\n\t\t\tactiveCount = 1;\n\t\t}\n\n\t\treturn currentTick - now;\n\t}\n\n\tconst strictTicks = [];\n\n\tfunction strictDelay() {\n\t\tconst now = Date.now();\n\n\t\tif (strictTicks.length < limit) {\n\t\t\tstrictTicks.push(now);\n\t\t\treturn 0;\n\t\t}\n\n\t\tconst earliestTime = strictTicks.shift() + interval;\n\n\t\tif (now >= earliestTime) {\n\t\t\tstrictTicks.push(now);\n\t\t\treturn 0;\n\t\t}\n\n\t\tstrictTicks.push(earliestTime);\n\t\treturn earliestTime - now;\n\t}\n\n\tconst getDelay = strict ? strictDelay : windowedDelay;\n\n\treturn function_ => {\n\t\tconst throttled = function (...args) {\n\t\t\tif (!throttled.isEnabled) {\n\t\t\t\treturn (async () => function_.apply(this, args))();\n\t\t\t}\n\n\t\t\tlet timeout;\n\t\t\treturn new Promise((resolve, reject) => {\n\t\t\t\tconst execute = () => {\n\t\t\t\t\tresolve(function_.apply(this, args));\n\t\t\t\t\tqueue.delete(timeout);\n\t\t\t\t};\n\n\t\t\t\ttimeout = setTimeout(execute, getDelay());\n\n\t\t\t\tqueue.set(timeout, reject);\n\t\t\t});\n\t\t};\n\n\t\tthrottled.abort = () => {\n\t\t\tfor (const timeout of queue.keys()) {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\tqueue.get(timeout)(new AbortError());\n\t\t\t}\n\n\t\t\tqueue.clear();\n\t\t\tstrictTicks.splice(0, strictTicks.length);\n\t\t};\n\n\t\tthrottled.isEnabled = true;\n\n\t\treturn throttled;\n\t};\n};\n\nmodule.exports = pThrottle;\nmodule.exports.AbortError = AbortError;\n","'use strict';\n\nvar replace = String.prototype.replace;\nvar percentTwenties = /%20/g;\n\nvar Format = {\n RFC1738: 'RFC1738',\n RFC3986: 'RFC3986'\n};\n\nmodule.exports = {\n 'default': Format.RFC3986,\n formatters: {\n RFC1738: function (value) {\n return replace.call(value, percentTwenties, '+');\n },\n RFC3986: function (value) {\n return String(value);\n }\n },\n RFC1738: Format.RFC1738,\n RFC3986: Format.RFC3986\n};\n","'use strict';\n\nvar stringify = require('./stringify');\nvar parse = require('./parse');\nvar formats = require('./formats');\n\nmodule.exports = {\n formats: formats,\n parse: parse,\n stringify: stringify\n};\n","'use strict';\n\nvar utils = require('./utils');\n\nvar has = Object.prototype.hasOwnProperty;\nvar isArray = Array.isArray;\n\nvar defaults = {\n allowDots: false,\n allowPrototypes: false,\n allowSparse: false,\n arrayLimit: 20,\n charset: 'utf-8',\n charsetSentinel: false,\n comma: false,\n decoder: utils.decode,\n delimiter: '&',\n depth: 5,\n ignoreQueryPrefix: false,\n interpretNumericEntities: false,\n parameterLimit: 1000,\n parseArrays: true,\n plainObjects: false,\n strictNullHandling: false\n};\n\nvar interpretNumericEntities = function (str) {\n return str.replace(/&#(\\d+);/g, function ($0, numberStr) {\n return String.fromCharCode(parseInt(numberStr, 10));\n });\n};\n\nvar parseArrayValue = function (val, options) {\n if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) {\n return val.split(',');\n }\n\n return val;\n};\n\n// This is what browsers will submit when the ✓ character occurs in an\n// application/x-www-form-urlencoded body and the encoding of the page containing\n// the form is iso-8859-1, or when the submitted form has an accept-charset\n// attribute of iso-8859-1. Presumably also with other charsets that do not contain\n// the ✓ character, such as us-ascii.\nvar isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓')\n\n// These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded.\nvar charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓')\n\nvar parseValues = function parseQueryStringValues(str, options) {\n var obj = {};\n var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\\?/, '') : str;\n var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;\n var parts = cleanStr.split(options.delimiter, limit);\n var skipIndex = -1; // Keep track of where the utf8 sentinel was found\n var i;\n\n var charset = options.charset;\n if (options.charsetSentinel) {\n for (i = 0; i < parts.length; ++i) {\n if (parts[i].indexOf('utf8=') === 0) {\n if (parts[i] === charsetSentinel) {\n charset = 'utf-8';\n } else if (parts[i] === isoSentinel) {\n charset = 'iso-8859-1';\n }\n skipIndex = i;\n i = parts.length; // The eslint settings do not allow break;\n }\n }\n }\n\n for (i = 0; i < parts.length; ++i) {\n if (i === skipIndex) {\n continue;\n }\n var part = parts[i];\n\n var bracketEqualsPos = part.indexOf(']=');\n var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;\n\n var key, val;\n if (pos === -1) {\n key = options.decoder(part, defaults.decoder, charset, 'key');\n val = options.strictNullHandling ? null : '';\n } else {\n key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key');\n val = utils.maybeMap(\n parseArrayValue(part.slice(pos + 1), options),\n function (encodedVal) {\n return options.decoder(encodedVal, defaults.decoder, charset, 'value');\n }\n );\n }\n\n if (val && options.interpretNumericEntities && charset === 'iso-8859-1') {\n val = interpretNumericEntities(val);\n }\n\n if (part.indexOf('[]=') > -1) {\n val = isArray(val) ? [val] : val;\n }\n\n if (has.call(obj, key)) {\n obj[key] = utils.combine(obj[key], val);\n } else {\n obj[key] = val;\n }\n }\n\n return obj;\n};\n\nvar parseObject = function (chain, val, options, valuesParsed) {\n var leaf = valuesParsed ? val : parseArrayValue(val, options);\n\n for (var i = chain.length - 1; i >= 0; --i) {\n var obj;\n var root = chain[i];\n\n if (root === '[]' && options.parseArrays) {\n obj = [].concat(leaf);\n } else {\n obj = options.plainObjects ? Object.create(null) : {};\n var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;\n var index = parseInt(cleanRoot, 10);\n if (!options.parseArrays && cleanRoot === '') {\n obj = { 0: leaf };\n } else if (\n !isNaN(index)\n && root !== cleanRoot\n && String(index) === cleanRoot\n && index >= 0\n && (options.parseArrays && index <= options.arrayLimit)\n ) {\n obj = [];\n obj[index] = leaf;\n } else if (cleanRoot !== '__proto__') {\n obj[cleanRoot] = leaf;\n }\n }\n\n leaf = obj;\n }\n\n return leaf;\n};\n\nvar parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) {\n if (!givenKey) {\n return;\n }\n\n // Transform dot notation to bracket notation\n var key = options.allowDots ? givenKey.replace(/\\.([^.[]+)/g, '[$1]') : givenKey;\n\n // The regex chunks\n\n var brackets = /(\\[[^[\\]]*])/;\n var child = /(\\[[^[\\]]*])/g;\n\n // Get the parent\n\n var segment = options.depth > 0 && brackets.exec(key);\n var parent = segment ? key.slice(0, segment.index) : key;\n\n // Stash the parent if it exists\n\n var keys = [];\n if (parent) {\n // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties\n if (!options.plainObjects && has.call(Object.prototype, parent)) {\n if (!options.allowPrototypes) {\n return;\n }\n }\n\n keys.push(parent);\n }\n\n // Loop through children appending to the array until we hit depth\n\n var i = 0;\n while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) {\n i += 1;\n if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {\n if (!options.allowPrototypes) {\n return;\n }\n }\n keys.push(segment[1]);\n }\n\n // If there's a remainder, just add whatever is left\n\n if (segment) {\n keys.push('[' + key.slice(segment.index) + ']');\n }\n\n return parseObject(keys, val, options, valuesParsed);\n};\n\nvar normalizeParseOptions = function normalizeParseOptions(opts) {\n if (!opts) {\n return defaults;\n }\n\n if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') {\n throw new TypeError('Decoder has to be a function.');\n }\n\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset;\n\n return {\n allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,\n allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes,\n allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse,\n arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit,\n charset: charset,\n charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma,\n decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder,\n delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter,\n // eslint-disable-next-line no-implicit-coercion, no-extra-parens\n depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth,\n ignoreQueryPrefix: opts.ignoreQueryPrefix === true,\n interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities,\n parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit,\n parseArrays: opts.parseArrays !== false,\n plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects,\n strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling\n };\n};\n\nmodule.exports = function (str, opts) {\n var options = normalizeParseOptions(opts);\n\n if (str === '' || str === null || typeof str === 'undefined') {\n return options.plainObjects ? Object.create(null) : {};\n }\n\n var tempObj = typeof str === 'string' ? parseValues(str, options) : str;\n var obj = options.plainObjects ? Object.create(null) : {};\n\n // Iterate over the keys and setup the new object\n\n var keys = Object.keys(tempObj);\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string');\n obj = utils.merge(obj, newObj, options);\n }\n\n if (options.allowSparse === true) {\n return obj;\n }\n\n return utils.compact(obj);\n};\n","'use strict';\n\nvar getSideChannel = require('side-channel');\nvar utils = require('./utils');\nvar formats = require('./formats');\nvar has = Object.prototype.hasOwnProperty;\n\nvar arrayPrefixGenerators = {\n brackets: function brackets(prefix) {\n return prefix + '[]';\n },\n comma: 'comma',\n indices: function indices(prefix, key) {\n return prefix + '[' + key + ']';\n },\n repeat: function repeat(prefix) {\n return prefix;\n }\n};\n\nvar isArray = Array.isArray;\nvar split = String.prototype.split;\nvar push = Array.prototype.push;\nvar pushToArray = function (arr, valueOrArray) {\n push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]);\n};\n\nvar toISO = Date.prototype.toISOString;\n\nvar defaultFormat = formats['default'];\nvar defaults = {\n addQueryPrefix: false,\n allowDots: false,\n charset: 'utf-8',\n charsetSentinel: false,\n delimiter: '&',\n encode: true,\n encoder: utils.encode,\n encodeValuesOnly: false,\n format: defaultFormat,\n formatter: formats.formatters[defaultFormat],\n // deprecated\n indices: false,\n serializeDate: function serializeDate(date) {\n return toISO.call(date);\n },\n skipNulls: false,\n strictNullHandling: false\n};\n\nvar isNonNullishPrimitive = function isNonNullishPrimitive(v) {\n return typeof v === 'string'\n || typeof v === 'number'\n || typeof v === 'boolean'\n || typeof v === 'symbol'\n || typeof v === 'bigint';\n};\n\nvar sentinel = {};\n\nvar stringify = function stringify(\n object,\n prefix,\n generateArrayPrefix,\n commaRoundTrip,\n strictNullHandling,\n skipNulls,\n encoder,\n filter,\n sort,\n allowDots,\n serializeDate,\n format,\n formatter,\n encodeValuesOnly,\n charset,\n sideChannel\n) {\n var obj = object;\n\n var tmpSc = sideChannel;\n var step = 0;\n var findFlag = false;\n while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) {\n // Where object last appeared in the ref tree\n var pos = tmpSc.get(object);\n step += 1;\n if (typeof pos !== 'undefined') {\n if (pos === step) {\n throw new RangeError('Cyclic object value');\n } else {\n findFlag = true; // Break while\n }\n }\n if (typeof tmpSc.get(sentinel) === 'undefined') {\n step = 0;\n }\n }\n\n if (typeof filter === 'function') {\n obj = filter(prefix, obj);\n } else if (obj instanceof Date) {\n obj = serializeDate(obj);\n } else if (generateArrayPrefix === 'comma' && isArray(obj)) {\n obj = utils.maybeMap(obj, function (value) {\n if (value instanceof Date) {\n return serializeDate(value);\n }\n return value;\n });\n }\n\n if (obj === null) {\n if (strictNullHandling) {\n return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix;\n }\n\n obj = '';\n }\n\n if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) {\n if (encoder) {\n var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format);\n if (generateArrayPrefix === 'comma' && encodeValuesOnly) {\n var valuesArray = split.call(String(obj), ',');\n var valuesJoined = '';\n for (var i = 0; i < valuesArray.length; ++i) {\n valuesJoined += (i === 0 ? '' : ',') + formatter(encoder(valuesArray[i], defaults.encoder, charset, 'value', format));\n }\n return [formatter(keyValue) + (commaRoundTrip && isArray(obj) && valuesArray.length === 1 ? '[]' : '') + '=' + valuesJoined];\n }\n return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))];\n }\n return [formatter(prefix) + '=' + formatter(String(obj))];\n }\n\n var values = [];\n\n if (typeof obj === 'undefined') {\n return values;\n }\n\n var objKeys;\n if (generateArrayPrefix === 'comma' && isArray(obj)) {\n // we need to join elements in\n objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];\n } else if (isArray(filter)) {\n objKeys = filter;\n } else {\n var keys = Object.keys(obj);\n objKeys = sort ? keys.sort(sort) : keys;\n }\n\n var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix;\n\n for (var j = 0; j < objKeys.length; ++j) {\n var key = objKeys[j];\n var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key];\n\n if (skipNulls && value === null) {\n continue;\n }\n\n var keyPrefix = isArray(obj)\n ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix\n : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']');\n\n sideChannel.set(object, step);\n var valueSideChannel = getSideChannel();\n valueSideChannel.set(sentinel, sideChannel);\n pushToArray(values, stringify(\n value,\n keyPrefix,\n generateArrayPrefix,\n commaRoundTrip,\n strictNullHandling,\n skipNulls,\n encoder,\n filter,\n sort,\n allowDots,\n serializeDate,\n format,\n formatter,\n encodeValuesOnly,\n charset,\n valueSideChannel\n ));\n }\n\n return values;\n};\n\nvar normalizeStringifyOptions = function normalizeStringifyOptions(opts) {\n if (!opts) {\n return defaults;\n }\n\n if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {\n throw new TypeError('Encoder has to be a function.');\n }\n\n var charset = opts.charset || defaults.charset;\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n\n var format = formats['default'];\n if (typeof opts.format !== 'undefined') {\n if (!has.call(formats.formatters, opts.format)) {\n throw new TypeError('Unknown format option provided.');\n }\n format = opts.format;\n }\n var formatter = formats.formatters[format];\n\n var filter = defaults.filter;\n if (typeof opts.filter === 'function' || isArray(opts.filter)) {\n filter = opts.filter;\n }\n\n return {\n addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,\n allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots,\n charset: charset,\n charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,\n encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,\n encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,\n encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,\n filter: filter,\n format: format,\n formatter: formatter,\n serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,\n skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,\n sort: typeof opts.sort === 'function' ? opts.sort : null,\n strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling\n };\n};\n\nmodule.exports = function (object, opts) {\n var obj = object;\n var options = normalizeStringifyOptions(opts);\n\n var objKeys;\n var filter;\n\n if (typeof options.filter === 'function') {\n filter = options.filter;\n obj = filter('', obj);\n } else if (isArray(options.filter)) {\n filter = options.filter;\n objKeys = filter;\n }\n\n var keys = [];\n\n if (typeof obj !== 'object' || obj === null) {\n return '';\n }\n\n var arrayFormat;\n if (opts && opts.arrayFormat in arrayPrefixGenerators) {\n arrayFormat = opts.arrayFormat;\n } else if (opts && 'indices' in opts) {\n arrayFormat = opts.indices ? 'indices' : 'repeat';\n } else {\n arrayFormat = 'indices';\n }\n\n var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];\n if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {\n throw new TypeError('`commaRoundTrip` must be a boolean, or absent');\n }\n var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip;\n\n if (!objKeys) {\n objKeys = Object.keys(obj);\n }\n\n if (options.sort) {\n objKeys.sort(options.sort);\n }\n\n var sideChannel = getSideChannel();\n for (var i = 0; i < objKeys.length; ++i) {\n var key = objKeys[i];\n\n if (options.skipNulls && obj[key] === null) {\n continue;\n }\n pushToArray(keys, stringify(\n obj[key],\n key,\n generateArrayPrefix,\n commaRoundTrip,\n options.strictNullHandling,\n options.skipNulls,\n options.encode ? options.encoder : null,\n options.filter,\n options.sort,\n options.allowDots,\n options.serializeDate,\n options.format,\n options.formatter,\n options.encodeValuesOnly,\n options.charset,\n sideChannel\n ));\n }\n\n var joined = keys.join(options.delimiter);\n var prefix = options.addQueryPrefix === true ? '?' : '';\n\n if (options.charsetSentinel) {\n if (options.charset === 'iso-8859-1') {\n // encodeURIComponent('✓'), the \"numeric entity\" representation of a checkmark\n prefix += 'utf8=%26%2310003%3B&';\n } else {\n // encodeURIComponent('✓')\n prefix += 'utf8=%E2%9C%93&';\n }\n }\n\n return joined.length > 0 ? prefix + joined : '';\n};\n","'use strict';\n\nvar formats = require('./formats');\n\nvar has = Object.prototype.hasOwnProperty;\nvar isArray = Array.isArray;\n\nvar hexTable = (function () {\n var array = [];\n for (var i = 0; i < 256; ++i) {\n array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());\n }\n\n return array;\n}());\n\nvar compactQueue = function compactQueue(queue) {\n while (queue.length > 1) {\n var item = queue.pop();\n var obj = item.obj[item.prop];\n\n if (isArray(obj)) {\n var compacted = [];\n\n for (var j = 0; j < obj.length; ++j) {\n if (typeof obj[j] !== 'undefined') {\n compacted.push(obj[j]);\n }\n }\n\n item.obj[item.prop] = compacted;\n }\n }\n};\n\nvar arrayToObject = function arrayToObject(source, options) {\n var obj = options && options.plainObjects ? Object.create(null) : {};\n for (var i = 0; i < source.length; ++i) {\n if (typeof source[i] !== 'undefined') {\n obj[i] = source[i];\n }\n }\n\n return obj;\n};\n\nvar merge = function merge(target, source, options) {\n /* eslint no-param-reassign: 0 */\n if (!source) {\n return target;\n }\n\n if (typeof source !== 'object') {\n if (isArray(target)) {\n target.push(source);\n } else if (target && typeof target === 'object') {\n if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) {\n target[source] = true;\n }\n } else {\n return [target, source];\n }\n\n return target;\n }\n\n if (!target || typeof target !== 'object') {\n return [target].concat(source);\n }\n\n var mergeTarget = target;\n if (isArray(target) && !isArray(source)) {\n mergeTarget = arrayToObject(target, options);\n }\n\n if (isArray(target) && isArray(source)) {\n source.forEach(function (item, i) {\n if (has.call(target, i)) {\n var targetItem = target[i];\n if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {\n target[i] = merge(targetItem, item, options);\n } else {\n target.push(item);\n }\n } else {\n target[i] = item;\n }\n });\n return target;\n }\n\n return Object.keys(source).reduce(function (acc, key) {\n var value = source[key];\n\n if (has.call(acc, key)) {\n acc[key] = merge(acc[key], value, options);\n } else {\n acc[key] = value;\n }\n return acc;\n }, mergeTarget);\n};\n\nvar assign = function assignSingleSource(target, source) {\n return Object.keys(source).reduce(function (acc, key) {\n acc[key] = source[key];\n return acc;\n }, target);\n};\n\nvar decode = function (str, decoder, charset) {\n var strWithoutPlus = str.replace(/\\+/g, ' ');\n if (charset === 'iso-8859-1') {\n // unescape never throws, no try...catch needed:\n return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);\n }\n // utf-8\n try {\n return decodeURIComponent(strWithoutPlus);\n } catch (e) {\n return strWithoutPlus;\n }\n};\n\nvar encode = function encode(str, defaultEncoder, charset, kind, format) {\n // This code was originally written by Brian White (mscdex) for the io.js core querystring library.\n // It has been adapted here for stricter adherence to RFC 3986\n if (str.length === 0) {\n return str;\n }\n\n var string = str;\n if (typeof str === 'symbol') {\n string = Symbol.prototype.toString.call(str);\n } else if (typeof str !== 'string') {\n string = String(str);\n }\n\n if (charset === 'iso-8859-1') {\n return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {\n return '%26%23' + parseInt($0.slice(2), 16) + '%3B';\n });\n }\n\n var out = '';\n for (var i = 0; i < string.length; ++i) {\n var c = string.charCodeAt(i);\n\n if (\n c === 0x2D // -\n || c === 0x2E // .\n || c === 0x5F // _\n || c === 0x7E // ~\n || (c >= 0x30 && c <= 0x39) // 0-9\n || (c >= 0x41 && c <= 0x5A) // a-z\n || (c >= 0x61 && c <= 0x7A) // A-Z\n || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( )\n ) {\n out += string.charAt(i);\n continue;\n }\n\n if (c < 0x80) {\n out = out + hexTable[c];\n continue;\n }\n\n if (c < 0x800) {\n out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);\n continue;\n }\n\n if (c < 0xD800 || c >= 0xE000) {\n out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);\n continue;\n }\n\n i += 1;\n c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));\n /* eslint operator-linebreak: [2, \"before\"] */\n out += hexTable[0xF0 | (c >> 18)]\n + hexTable[0x80 | ((c >> 12) & 0x3F)]\n + hexTable[0x80 | ((c >> 6) & 0x3F)]\n + hexTable[0x80 | (c & 0x3F)];\n }\n\n return out;\n};\n\nvar compact = function compact(value) {\n var queue = [{ obj: { o: value }, prop: 'o' }];\n var refs = [];\n\n for (var i = 0; i < queue.length; ++i) {\n var item = queue[i];\n var obj = item.obj[item.prop];\n\n var keys = Object.keys(obj);\n for (var j = 0; j < keys.length; ++j) {\n var key = keys[j];\n var val = obj[key];\n if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {\n queue.push({ obj: obj, prop: key });\n refs.push(val);\n }\n }\n }\n\n compactQueue(queue);\n\n return value;\n};\n\nvar isRegExp = function isRegExp(obj) {\n return Object.prototype.toString.call(obj) === '[object RegExp]';\n};\n\nvar isBuffer = function isBuffer(obj) {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n\n return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));\n};\n\nvar combine = function combine(a, b) {\n return [].concat(a, b);\n};\n\nvar maybeMap = function maybeMap(val, fn) {\n if (isArray(val)) {\n var mapped = [];\n for (var i = 0; i < val.length; i += 1) {\n mapped.push(fn(val[i]));\n }\n return mapped;\n }\n return fn(val);\n};\n\nmodule.exports = {\n arrayToObject: arrayToObject,\n assign: assign,\n combine: combine,\n compact: compact,\n decode: decode,\n encode: encode,\n isBuffer: isBuffer,\n isRegExp: isRegExp,\n maybeMap: maybeMap,\n merge: merge\n};\n","export function isNil(x){\n return x === undefined || x === null\n}\n","import { Subject } from './Subject';\nexport class BehaviorSubject extends Subject {\n constructor(_value) {\n super();\n this._value = _value;\n }\n get value() {\n return this.getValue();\n }\n _subscribe(subscriber) {\n const subscription = super._subscribe(subscriber);\n !subscription.closed && subscriber.next(this._value);\n return subscription;\n }\n getValue() {\n const { hasError, thrownError, _value } = this;\n if (hasError) {\n throw thrownError;\n }\n this._throwIfClosed();\n return _value;\n }\n next(value) {\n super.next((this._value = value));\n }\n}\n","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';\nexport class Observable {\n constructor(subscribe) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n lift(operator) {\n const observable = new Observable();\n observable.source = this;\n observable.operator = operator;\n return observable;\n }\n subscribe(observerOrNext, error, complete) {\n const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n errorContext(() => {\n const { operator, source } = this;\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 _trySubscribe(sink) {\n try {\n return this._subscribe(sink);\n }\n catch (err) {\n sink.error(err);\n }\n }\n forEach(next, promiseCtor) {\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor((resolve, reject) => {\n const subscriber = new SafeSubscriber({\n next: (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 _subscribe(subscriber) {\n var _a;\n return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);\n }\n [Symbol_observable]() {\n return this;\n }\n pipe(...operations) {\n return pipeFromArray(operations)(this);\n }\n toPromise(promiseCtor) {\n promiseCtor = getPromiseCtor(promiseCtor);\n return new promiseCtor((resolve, reject) => {\n let value;\n this.subscribe((x) => (value = x), (err) => reject(err), () => resolve(value));\n });\n }\n}\nObservable.create = (subscribe) => {\n return new Observable(subscribe);\n};\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","import { Subject } from './Subject';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\nexport class ReplaySubject extends Subject {\n constructor(_bufferSize = Infinity, _windowTime = Infinity, _timestampProvider = dateTimestampProvider) {\n super();\n this._bufferSize = _bufferSize;\n this._windowTime = _windowTime;\n this._timestampProvider = _timestampProvider;\n this._buffer = [];\n this._infiniteTimeWindow = true;\n this._infiniteTimeWindow = _windowTime === Infinity;\n this._bufferSize = Math.max(1, _bufferSize);\n this._windowTime = Math.max(1, _windowTime);\n }\n next(value) {\n const { isStopped, _buffer, _infiniteTimeWindow, _timestampProvider, _windowTime } = this;\n if (!isStopped) {\n _buffer.push(value);\n !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);\n }\n this._trimBuffer();\n super.next(value);\n }\n _subscribe(subscriber) {\n this._throwIfClosed();\n this._trimBuffer();\n const subscription = this._innerSubscribe(subscriber);\n const { _infiniteTimeWindow, _buffer } = this;\n const copy = _buffer.slice();\n for (let i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {\n subscriber.next(copy[i]);\n }\n this._checkFinalizedStatuses(subscriber);\n return subscription;\n }\n _trimBuffer() {\n const { _bufferSize, _timestampProvider, _buffer, _infiniteTimeWindow } = this;\n const adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;\n _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);\n if (!_infiniteTimeWindow) {\n const now = _timestampProvider.now();\n let last = 0;\n for (let i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) {\n last = i;\n }\n last && _buffer.splice(0, last + 1);\n }\n }\n}\n","import { createErrorClass } from './createErrorClass';\nexport const ObjectUnsubscribedError = createErrorClass((_super) => function ObjectUnsubscribedErrorImpl() {\n _super(this);\n this.name = 'ObjectUnsubscribedError';\n this.message = 'object unsubscribed';\n});\n","import { Observable } from './Observable';\nimport { Subscription, EMPTY_SUBSCRIPTION } from './Subscription';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { arrRemove } from './util/arrRemove';\nimport { errorContext } from './util/errorContext';\nexport class Subject extends Observable {\n constructor() {\n super();\n this.closed = false;\n this.currentObservers = null;\n this.observers = [];\n this.isStopped = false;\n this.hasError = false;\n this.thrownError = null;\n }\n lift(operator) {\n const subject = new AnonymousSubject(this, this);\n subject.operator = operator;\n return subject;\n }\n _throwIfClosed() {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n }\n next(value) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n if (!this.currentObservers) {\n this.currentObservers = Array.from(this.observers);\n }\n for (const observer of this.currentObservers) {\n observer.next(value);\n }\n }\n });\n }\n error(err) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.hasError = this.isStopped = true;\n this.thrownError = err;\n const { observers } = this;\n while (observers.length) {\n observers.shift().error(err);\n }\n }\n });\n }\n complete() {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.isStopped = true;\n const { observers } = this;\n while (observers.length) {\n observers.shift().complete();\n }\n }\n });\n }\n unsubscribe() {\n this.isStopped = this.closed = true;\n this.observers = this.currentObservers = null;\n }\n get observed() {\n var _a;\n return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;\n }\n _trySubscribe(subscriber) {\n this._throwIfClosed();\n return super._trySubscribe(subscriber);\n }\n _subscribe(subscriber) {\n this._throwIfClosed();\n this._checkFinalizedStatuses(subscriber);\n return this._innerSubscribe(subscriber);\n }\n _innerSubscribe(subscriber) {\n const { hasError, isStopped, observers } = this;\n if (hasError || isStopped) {\n return EMPTY_SUBSCRIPTION;\n }\n this.currentObservers = null;\n observers.push(subscriber);\n return new Subscription(() => {\n this.currentObservers = null;\n arrRemove(observers, subscriber);\n });\n }\n _checkFinalizedStatuses(subscriber) {\n const { hasError, thrownError, isStopped } = this;\n if (hasError) {\n subscriber.error(thrownError);\n }\n else if (isStopped) {\n subscriber.complete();\n }\n }\n asObservable() {\n const observable = new Observable();\n observable.source = this;\n return observable;\n }\n}\nSubject.create = (destination, source) => {\n return new AnonymousSubject(destination, source);\n};\nexport class AnonymousSubject extends Subject {\n constructor(destination, source) {\n super();\n this.destination = destination;\n this.source = source;\n }\n next(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 error(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 complete() {\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 _subscribe(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}\n","export const COMPLETE_NOTIFICATION = (() => createNotification('C', undefined, undefined))();\nexport function errorNotification(error) {\n return createNotification('E', undefined, error);\n}\nexport function nextNotification(value) {\n return createNotification('N', value, undefined);\n}\nexport function createNotification(kind, value, error) {\n return {\n kind,\n value,\n error,\n };\n}\n","import { 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';\nexport class Subscriber extends Subscription {\n constructor(destination) {\n super();\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 }\n static create(next, error, complete) {\n return new SafeSubscriber(next, error, complete);\n }\n next(value) {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n }\n else {\n this._next(value);\n }\n }\n error(err) {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n }\n else {\n this.isStopped = true;\n this._error(err);\n }\n }\n complete() {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n }\n else {\n this.isStopped = true;\n this._complete();\n }\n }\n unsubscribe() {\n if (!this.closed) {\n this.isStopped = true;\n super.unsubscribe();\n this.destination = null;\n }\n }\n _next(value) {\n this.destination.next(value);\n }\n _error(err) {\n try {\n this.destination.error(err);\n }\n finally {\n this.unsubscribe();\n }\n }\n _complete() {\n try {\n this.destination.complete();\n }\n finally {\n this.unsubscribe();\n }\n }\n}\nconst _bind = Function.prototype.bind;\nfunction bind(fn, thisArg) {\n return _bind.call(fn, thisArg);\n}\nclass ConsumerObserver {\n constructor(partialObserver) {\n this.partialObserver = partialObserver;\n }\n next(value) {\n const { partialObserver } = this;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n error(err) {\n const { partialObserver } = this;\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 complete() {\n const { partialObserver } = this;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n }\n catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n}\nexport class SafeSubscriber extends Subscriber {\n constructor(observerOrNext, error, complete) {\n super();\n let 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 let context;\n if (this && config.useDeprecatedNextContext) {\n context = Object.create(observerOrNext);\n context.unsubscribe = () => this.unsubscribe();\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context),\n error: observerOrNext.error && bind(observerOrNext.error, context),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context),\n };\n }\n else {\n partialObserver = observerOrNext;\n }\n }\n this.destination = new ConsumerObserver(partialObserver);\n }\n}\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 const { onStoppedNotification } = config;\n onStoppedNotification && timeoutProvider.setTimeout(() => onStoppedNotification(notification, subscriber));\n}\nexport const EMPTY_OBSERVER = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n","import { createErrorClass } from './createErrorClass';\nexport const UnsubscriptionError = createErrorClass((_super) => function UnsubscriptionErrorImpl(errors) {\n _super(this);\n this.message = errors\n ? `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}`\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n});\n","import { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { arrRemove } from './util/arrRemove';\nexport class Subscription {\n constructor(initialTeardown) {\n this.initialTeardown = initialTeardown;\n this.closed = false;\n this._parentage = null;\n this._finalizers = null;\n }\n unsubscribe() {\n let errors;\n if (!this.closed) {\n this.closed = true;\n const { _parentage } = this;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n for (const parent of _parentage) {\n parent.remove(this);\n }\n }\n else {\n _parentage.remove(this);\n }\n }\n const { initialTeardown: initialFinalizer } = this;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n }\n catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n const { _finalizers } = this;\n if (_finalizers) {\n this._finalizers = null;\n for (const finalizer of _finalizers) {\n try {\n execFinalizer(finalizer);\n }\n catch (err) {\n errors = errors !== null && errors !== void 0 ? errors : [];\n if (err instanceof UnsubscriptionError) {\n errors = [...errors, ...err.errors];\n }\n else {\n errors.push(err);\n }\n }\n }\n }\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n }\n add(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 _hasParent(parent) {\n const { _parentage } = this;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n }\n _addParent(parent) {\n const { _parentage } = this;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n }\n _removeParent(parent) {\n const { _parentage } = this;\n if (_parentage === parent) {\n this._parentage = null;\n }\n else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n }\n remove(teardown) {\n const { _finalizers } = this;\n _finalizers && arrRemove(_finalizers, teardown);\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n }\n}\nSubscription.EMPTY = (() => {\n const empty = new Subscription();\n empty.closed = true;\n return empty;\n})();\nexport const 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","export const config = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n","import { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { refCount as higherOrderRefCount } from '../operators/refCount';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { hasLift } from '../util/lift';\nexport class ConnectableObservable extends Observable {\n constructor(source, subjectFactory) {\n super();\n this.source = source;\n this.subjectFactory = subjectFactory;\n this._subject = null;\n this._refCount = 0;\n this._connection = null;\n if (hasLift(source)) {\n this.lift = source.lift;\n }\n }\n _subscribe(subscriber) {\n return this.getSubject().subscribe(subscriber);\n }\n getSubject() {\n const subject = this._subject;\n if (!subject || subject.isStopped) {\n this._subject = this.subjectFactory();\n }\n return this._subject;\n }\n _teardown() {\n this._refCount = 0;\n const { _connection } = this;\n this._subject = this._connection = null;\n _connection === null || _connection === void 0 ? void 0 : _connection.unsubscribe();\n }\n connect() {\n let connection = this._connection;\n if (!connection) {\n connection = this._connection = new Subscription();\n const subject = this.getSubject();\n connection.add(this.source.subscribe(createOperatorSubscriber(subject, undefined, () => {\n this._teardown();\n subject.complete();\n }, (err) => {\n this._teardown();\n subject.error(err);\n }, () => this._teardown())));\n if (connection.closed) {\n this._connection = null;\n connection = Subscription.EMPTY;\n }\n }\n return connection;\n }\n refCount() {\n return higherOrderRefCount()(this);\n }\n}\n","import { Observable } from '../Observable';\nimport { argsArgArrayOrObject } from '../util/argsArgArrayOrObject';\nimport { from } from './from';\nimport { identity } from '../util/identity';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { popResultSelector, popScheduler } from '../util/args';\nimport { createObject } from '../util/createObject';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { executeSchedule } from '../util/executeSchedule';\nexport function combineLatest(...args) {\n const scheduler = popScheduler(args);\n const resultSelector = popResultSelector(args);\n const { args: observables, keys } = argsArgArrayOrObject(args);\n if (observables.length === 0) {\n return from([], scheduler);\n }\n const result = new Observable(combineLatestInit(observables, scheduler, keys\n ?\n (values) => createObject(keys, values)\n :\n identity));\n return resultSelector ? result.pipe(mapOneOrManyArgs(resultSelector)) : result;\n}\nexport function combineLatestInit(observables, scheduler, valueTransform = identity) {\n return (subscriber) => {\n maybeSchedule(scheduler, () => {\n const { length } = observables;\n const values = new Array(length);\n let active = length;\n let remainingFirstValues = length;\n for (let i = 0; i < length; i++) {\n maybeSchedule(scheduler, () => {\n const source = from(observables[i], scheduler);\n let hasFirstValue = false;\n source.subscribe(createOperatorSubscriber(subscriber, (value) => {\n values[i] = value;\n if (!hasFirstValue) {\n hasFirstValue = true;\n remainingFirstValues--;\n }\n if (!remainingFirstValues) {\n subscriber.next(valueTransform(values.slice()));\n }\n }, () => {\n if (!--active) {\n subscriber.complete();\n }\n }));\n }, subscriber);\n }\n }, subscriber);\n };\n}\nfunction maybeSchedule(scheduler, execute, subscription) {\n if (scheduler) {\n executeSchedule(subscription, scheduler, execute);\n }\n else {\n execute();\n }\n}\n","import { concatAll } from '../operators/concatAll';\nimport { popScheduler } from '../util/args';\nimport { from } from './from';\nexport function concat(...args) {\n return concatAll()(from(args, popScheduler(args)));\n}\n","import { mergeAll } from './mergeAll';\nexport function concatAll() {\n return mergeAll(1);\n}\n","import { Observable } from '../Observable';\nimport { innerFrom } from './innerFrom';\nexport function defer(observableFactory) {\n return new Observable((subscriber) => {\n innerFrom(observableFactory()).subscribe(subscriber);\n });\n}\n","import { Observable } from '../Observable';\nexport const EMPTY = new Observable((subscriber) => subscriber.complete());\nexport function empty(scheduler) {\n return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\nfunction emptyScheduled(scheduler) {\n return new Observable((subscriber) => scheduler.schedule(() => subscriber.complete()));\n}\n","import { operate } from '../util/lift';\nexport function subscribeOn(scheduler, delay = 0) {\n return operate((source, subscriber) => {\n subscriber.add(scheduler.schedule(() => source.subscribe(subscriber), delay));\n });\n}\n","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((subscriber) => {\n executeSchedule(subscriber, scheduler, () => {\n const iterator = input[Symbol.asyncIterator]();\n executeSchedule(subscriber, scheduler, () => {\n iterator.next().then((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","import { scheduled } from '../scheduled/scheduled';\nimport { innerFrom } from './innerFrom';\nexport function from(input, scheduler) {\n return scheduler ? scheduled(input, scheduler) : innerFrom(input);\n}\n","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","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","import { Observable } from '../Observable';\nexport function scheduleArray(input, scheduler) {\n return new Observable((subscriber) => {\n let 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","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","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((subscriber) => {\n let iterator;\n executeSchedule(subscriber, scheduler, () => {\n iterator = input[Symbol_iterator]();\n executeSchedule(subscriber, scheduler, () => {\n let value;\n let done;\n try {\n ({ value, done } = iterator.next());\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 () => isFunction(iterator === null || iterator === void 0 ? void 0 : iterator.return) && iterator.return();\n });\n}\n","import { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\nexport function scheduleReadableStreamLike(input, scheduler) {\n return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { Observable } from '../Observable';\nimport { mergeMap } from '../operators/mergeMap';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isFunction } from '../util/isFunction';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nconst nodeEventEmitterMethods = ['addListener', 'removeListener'];\nconst eventTargetMethods = ['addEventListener', 'removeEventListener'];\nconst jqueryMethods = ['on', 'off'];\nexport function fromEvent(target, eventName, options, resultSelector) {\n if (isFunction(options)) {\n resultSelector = options;\n options = undefined;\n }\n if (resultSelector) {\n return fromEvent(target, eventName, options).pipe(mapOneOrManyArgs(resultSelector));\n }\n const [add, remove] = isEventTarget(target)\n ? eventTargetMethods.map((methodName) => (handler) => target[methodName](eventName, handler, options))\n :\n isNodeStyleEventEmitter(target)\n ? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName))\n : isJQueryStyleEventEmitter(target)\n ? jqueryMethods.map(toCommonHandlerRegistry(target, eventName))\n : [];\n if (!add) {\n if (isArrayLike(target)) {\n return mergeMap((subTarget) => fromEvent(subTarget, eventName, options))(innerFrom(target));\n }\n }\n if (!add) {\n throw new TypeError('Invalid event target');\n }\n return new Observable((subscriber) => {\n const handler = (...args) => subscriber.next(1 < args.length ? args : args[0]);\n add(handler);\n return () => remove(handler);\n });\n}\nfunction toCommonHandlerRegistry(target, eventName) {\n return (methodName) => (handler) => target[methodName](eventName, handler);\n}\nfunction isNodeStyleEventEmitter(target) {\n return isFunction(target.addListener) && isFunction(target.removeListener);\n}\nfunction isJQueryStyleEventEmitter(target) {\n return isFunction(target.on) && isFunction(target.off);\n}\nfunction isEventTarget(target) {\n return isFunction(target.addEventListener) && isFunction(target.removeEventListener);\n}\n","import { __asyncValues, __awaiter } 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((subscriber) => {\n const 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((subscriber) => {\n for (let 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((subscriber) => {\n promise\n .then((value) => {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n }, (err) => subscriber.error(err))\n .then(null, reportUnhandledError);\n });\n}\nexport function fromIterable(iterable) {\n return new Observable((subscriber) => {\n for (const value of iterable) {\n subscriber.next(value);\n if (subscriber.closed) {\n return;\n }\n }\n subscriber.complete();\n });\n}\nexport function fromAsyncIterable(asyncIterable) {\n return new Observable((subscriber) => {\n process(asyncIterable, subscriber).catch((err) => 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_1, _a;\n return __awaiter(this, void 0, void 0, function* () {\n try {\n for (asyncIterable_1 = __asyncValues(asyncIterable); asyncIterable_1_1 = yield asyncIterable_1.next(), !asyncIterable_1_1.done;) {\n const value = asyncIterable_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 (asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return)) yield _a.call(asyncIterable_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n subscriber.complete();\n });\n}\n","import { mergeAll } from '../operators/mergeAll';\nimport { innerFrom } from './innerFrom';\nimport { EMPTY } from './empty';\nimport { popNumber, popScheduler } from '../util/args';\nimport { from } from './from';\nexport function merge(...args) {\n const scheduler = popScheduler(args);\n const concurrent = popNumber(args, Infinity);\n const sources = args;\n return !sources.length\n ?\n EMPTY\n : sources.length === 1\n ?\n innerFrom(sources[0])\n :\n mergeAll(concurrent)(from(sources, scheduler));\n}\n","import { popScheduler } from '../util/args';\nimport { from } from './from';\nexport function of(...args) {\n const scheduler = popScheduler(args);\n return from(args, scheduler);\n}\n","import { Observable } from '../Observable';\nimport { isFunction } from '../util/isFunction';\nexport function throwError(errorOrErrorFactory, scheduler) {\n const errorFactory = isFunction(errorOrErrorFactory) ? errorOrErrorFactory : () => errorOrErrorFactory;\n const init = (subscriber) => subscriber.error(errorFactory());\n return new Observable(scheduler ? (subscriber) => scheduler.schedule(init, 0, subscriber) : init);\n}\n","import { Subscriber } from '../Subscriber';\nexport function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {\n return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);\n}\nexport class OperatorSubscriber extends Subscriber {\n constructor(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {\n super(destination);\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._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._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._complete;\n }\n unsubscribe() {\n var _a;\n if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {\n const { closed } = this;\n super.unsubscribe();\n !closed && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));\n }\n }\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { operate } from '../util/lift';\nexport function catchError(selector) {\n return operate((source, subscriber) => {\n let innerSub = null;\n let syncUnsub = false;\n let handledResult;\n innerSub = source.subscribe(createOperatorSubscriber(subscriber, undefined, undefined, (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","import { mergeMap } from './mergeMap';\nimport { isFunction } from '../util/isFunction';\nexport function concatMap(project, resultSelector) {\n return isFunction(resultSelector) ? mergeMap(project, resultSelector, 1) : mergeMap(project, 1);\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function debounceTime(dueTime, scheduler = asyncScheduler) {\n return operate((source, subscriber) => {\n let activeTask = null;\n let lastValue = null;\n let lastTime = null;\n const emit = () => {\n if (activeTask) {\n activeTask.unsubscribe();\n activeTask = null;\n const value = lastValue;\n lastValue = null;\n subscriber.next(value);\n }\n };\n function emitWhenIdle() {\n const targetTime = lastTime + dueTime;\n const now = scheduler.now();\n if (now < targetTime) {\n activeTask = this.schedule(undefined, targetTime - now);\n subscriber.add(activeTask);\n return;\n }\n emit();\n }\n source.subscribe(createOperatorSubscriber(subscriber, (value) => {\n lastValue = value;\n lastTime = scheduler.now();\n if (!activeTask) {\n activeTask = scheduler.schedule(emitWhenIdle, dueTime);\n subscriber.add(activeTask);\n }\n }, () => {\n emit();\n subscriber.complete();\n }, undefined, () => {\n lastValue = activeTask = null;\n }));\n });\n}\n","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function defaultIfEmpty(defaultValue) {\n return operate((source, subscriber) => {\n let hasValue = false;\n source.subscribe(createOperatorSubscriber(subscriber, (value) => {\n hasValue = true;\n subscriber.next(value);\n }, () => {\n if (!hasValue) {\n subscriber.next(defaultValue);\n }\n subscriber.complete();\n }));\n });\n}\n","import { identity } from '../util/identity';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function distinctUntilChanged(comparator, keySelector = identity) {\n comparator = comparator !== null && comparator !== void 0 ? comparator : defaultCompare;\n return operate((source, subscriber) => {\n let previousKey;\n let first = true;\n source.subscribe(createOperatorSubscriber(subscriber, (value) => {\n const currentKey = keySelector(value);\n if (first || !comparator(previousKey, currentKey)) {\n first = false;\n previousKey = currentKey;\n subscriber.next(value);\n }\n }));\n });\n}\nfunction defaultCompare(a, b) {\n return a === b;\n}\n","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function filter(predicate, thisArg) {\n return operate((source, subscriber) => {\n let index = 0;\n source.subscribe(createOperatorSubscriber(subscriber, (value) => predicate.call(thisArg, value, index++) && subscriber.next(value)));\n });\n}\n","import { operate } from '../util/lift';\nexport function finalize(callback) {\n return operate((source, subscriber) => {\n try {\n source.subscribe(subscriber);\n }\n finally {\n subscriber.add(callback);\n }\n });\n}\n","import { EmptyError } from '../util/EmptyError';\nimport { filter } from './filter';\nimport { take } from './take';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { identity } from '../util/identity';\nexport function first(predicate, defaultValue) {\n const hasDefaultValue = arguments.length >= 2;\n return (source) => source.pipe(predicate ? filter((v, i) => predicate(v, i, source)) : identity, take(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(() => new EmptyError()));\n}\n","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { noop } from '../util/noop';\nexport function ignoreElements() {\n return operate((source, subscriber) => {\n source.subscribe(createOperatorSubscriber(subscriber, noop));\n });\n}\n","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function map(project, thisArg) {\n return operate((source, subscriber) => {\n let index = 0;\n source.subscribe(createOperatorSubscriber(subscriber, (value) => {\n subscriber.next(project.call(thisArg, value, index++));\n }));\n });\n}\n","import { map } from './map';\nexport function mapTo(value) {\n return map(() => value);\n}\n","import { mergeMap } from './mergeMap';\nimport { identity } from '../util/identity';\nexport function mergeAll(concurrent = Infinity) {\n return mergeMap(identity, concurrent);\n}\n","import { map } from './map';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { mergeInternals } from './mergeInternals';\nimport { isFunction } from '../util/isFunction';\nexport function mergeMap(project, resultSelector, concurrent = Infinity) {\n if (isFunction(resultSelector)) {\n return mergeMap((a, i) => map((b, ii) => resultSelector(a, b, i, ii))(innerFrom(project(a, i))), concurrent);\n }\n else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return operate((source, subscriber) => mergeInternals(source, subscriber, project, concurrent));\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { executeSchedule } from '../util/executeSchedule';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {\n const buffer = [];\n let active = 0;\n let index = 0;\n let isComplete = false;\n const checkComplete = () => {\n if (isComplete && !buffer.length && !active) {\n subscriber.complete();\n }\n };\n const outerNext = (value) => (active < concurrent ? doInnerSub(value) : buffer.push(value));\n const doInnerSub = (value) => {\n expand && subscriber.next(value);\n active++;\n let innerComplete = false;\n innerFrom(project(value, index++)).subscribe(createOperatorSubscriber(subscriber, (innerValue) => {\n onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);\n if (expand) {\n outerNext(innerValue);\n }\n else {\n subscriber.next(innerValue);\n }\n }, () => {\n innerComplete = true;\n }, undefined, () => {\n if (innerComplete) {\n try {\n active--;\n while (buffer.length && active < concurrent) {\n const bufferedValue = buffer.shift();\n if (innerSubScheduler) {\n executeSchedule(subscriber, innerSubScheduler, () => doInnerSub(bufferedValue));\n }\n else {\n doInnerSub(bufferedValue);\n }\n }\n checkComplete();\n }\n catch (err) {\n subscriber.error(err);\n }\n }\n }));\n };\n source.subscribe(createOperatorSubscriber(subscriber, outerNext, () => {\n isComplete = true;\n checkComplete();\n }));\n return () => {\n additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();\n };\n}\n","import { executeSchedule } from '../util/executeSchedule';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function observeOn(scheduler, delay = 0) {\n return operate((source, subscriber) => {\n source.subscribe(createOperatorSubscriber(subscriber, (value) => executeSchedule(subscriber, scheduler, () => subscriber.next(value), delay), () => executeSchedule(subscriber, scheduler, () => subscriber.complete(), delay), (err) => executeSchedule(subscriber, scheduler, () => subscriber.error(err), delay)));\n });\n}\n","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function refCount() {\n return operate((source, subscriber) => {\n let connection = null;\n source._refCount++;\n const refCounter = createOperatorSubscriber(subscriber, undefined, undefined, undefined, () => {\n if (!source || source._refCount <= 0 || 0 < --source._refCount) {\n connection = null;\n return;\n }\n const sharedConnection = source._connection;\n const conn = connection;\n connection = null;\n if (sharedConnection && (!conn || sharedConnection === conn)) {\n sharedConnection.unsubscribe();\n }\n subscriber.unsubscribe();\n });\n source.subscribe(refCounter);\n if (!refCounter.closed) {\n connection = source.connect();\n }\n });\n}\n","import { operate } from '../util/lift';\nimport { scanInternals } from './scanInternals';\nexport function scan(accumulator, seed) {\n return operate(scanInternals(accumulator, seed, arguments.length >= 2, true));\n}\n","import { createOperatorSubscriber } from './OperatorSubscriber';\nexport function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) {\n return (source, subscriber) => {\n let hasState = hasSeed;\n let state = seed;\n let index = 0;\n source.subscribe(createOperatorSubscriber(subscriber, (value) => {\n const i = index++;\n state = hasState\n ?\n accumulator(state, value, i)\n :\n ((hasState = true), value);\n emitOnNext && subscriber.next(state);\n }, emitBeforeComplete &&\n (() => {\n hasState && subscriber.next(state);\n subscriber.complete();\n })));\n };\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { Subject } from '../Subject';\nimport { SafeSubscriber } from '../Subscriber';\nimport { operate } from '../util/lift';\nexport function share(options = {}) {\n const { connector = () => new Subject(), resetOnError = true, resetOnComplete = true, resetOnRefCountZero = true } = options;\n return (wrapperSource) => {\n let connection;\n let resetConnection;\n let subject;\n let refCount = 0;\n let hasCompleted = false;\n let hasErrored = false;\n const cancelReset = () => {\n resetConnection === null || resetConnection === void 0 ? void 0 : resetConnection.unsubscribe();\n resetConnection = undefined;\n };\n const reset = () => {\n cancelReset();\n connection = subject = undefined;\n hasCompleted = hasErrored = false;\n };\n const resetAndUnsubscribe = () => {\n const conn = connection;\n reset();\n conn === null || conn === void 0 ? void 0 : conn.unsubscribe();\n };\n return operate((source, subscriber) => {\n refCount++;\n if (!hasErrored && !hasCompleted) {\n cancelReset();\n }\n const dest = (subject = subject !== null && subject !== void 0 ? subject : connector());\n subscriber.add(() => {\n refCount--;\n if (refCount === 0 && !hasErrored && !hasCompleted) {\n resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero);\n }\n });\n dest.subscribe(subscriber);\n if (!connection &&\n refCount > 0) {\n connection = new SafeSubscriber({\n next: (value) => dest.next(value),\n error: (err) => {\n hasErrored = true;\n cancelReset();\n resetConnection = handleReset(reset, resetOnError, err);\n dest.error(err);\n },\n complete: () => {\n hasCompleted = true;\n cancelReset();\n resetConnection = handleReset(reset, resetOnComplete);\n dest.complete();\n },\n });\n innerFrom(source).subscribe(connection);\n }\n })(wrapperSource);\n };\n}\nfunction handleReset(reset, on, ...args) {\n if (on === true) {\n reset();\n return;\n }\n if (on === false) {\n return;\n }\n const onSubscriber = new SafeSubscriber({\n next: () => {\n onSubscriber.unsubscribe();\n reset();\n },\n });\n return innerFrom(on(...args)).subscribe(onSubscriber);\n}\n","import { filter } from './filter';\nexport function skip(count) {\n return filter((_, index) => count <= index);\n}\n","import { concat } from '../observable/concat';\nimport { popScheduler } from '../util/args';\nimport { operate } from '../util/lift';\nexport function startWith(...values) {\n const scheduler = popScheduler(values);\n return operate((source, subscriber) => {\n (scheduler ? concat(values, source, scheduler) : concat(values, source)).subscribe(subscriber);\n });\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function switchMap(project, resultSelector) {\n return operate((source, subscriber) => {\n let innerSubscriber = null;\n let index = 0;\n let isComplete = false;\n const checkComplete = () => isComplete && !innerSubscriber && subscriber.complete();\n source.subscribe(createOperatorSubscriber(subscriber, (value) => {\n innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe();\n let innerIndex = 0;\n const outerIndex = index++;\n innerFrom(project(value, outerIndex)).subscribe((innerSubscriber = createOperatorSubscriber(subscriber, (innerValue) => subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue), () => {\n innerSubscriber = null;\n checkComplete();\n })));\n }, () => {\n isComplete = true;\n checkComplete();\n }));\n });\n}\n","import { EMPTY } from '../observable/empty';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function take(count) {\n return count <= 0\n ?\n () => EMPTY\n : operate((source, subscriber) => {\n let seen = 0;\n source.subscribe(createOperatorSubscriber(subscriber, (value) => {\n if (++seen <= count) {\n subscriber.next(value);\n if (count <= seen) {\n subscriber.complete();\n }\n }\n }));\n });\n}\n","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\nimport { noop } from '../util/noop';\nexport function takeUntil(notifier) {\n return operate((source, subscriber) => {\n innerFrom(notifier).subscribe(createOperatorSubscriber(subscriber, () => subscriber.complete(), noop));\n !subscriber.closed && source.subscribe(subscriber);\n });\n}\n","import { isFunction } from '../util/isFunction';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { identity } from '../util/identity';\nexport function tap(observerOrNext, error, complete) {\n const tapObserver = isFunction(observerOrNext) || error || complete\n ?\n { next: observerOrNext, error, complete }\n : observerOrNext;\n return tapObserver\n ? operate((source, subscriber) => {\n var _a;\n (_a = tapObserver.subscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);\n let isUnsub = true;\n source.subscribe(createOperatorSubscriber(subscriber, (value) => {\n var _a;\n (_a = tapObserver.next) === null || _a === void 0 ? void 0 : _a.call(tapObserver, value);\n subscriber.next(value);\n }, () => {\n var _a;\n isUnsub = false;\n (_a = tapObserver.complete) === null || _a === void 0 ? void 0 : _a.call(tapObserver);\n subscriber.complete();\n }, (err) => {\n var _a;\n isUnsub = false;\n (_a = tapObserver.error) === null || _a === void 0 ? void 0 : _a.call(tapObserver, err);\n subscriber.error(err);\n }, () => {\n var _a, _b;\n if (isUnsub) {\n (_a = tapObserver.unsubscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);\n }\n (_b = tapObserver.finalize) === null || _b === void 0 ? void 0 : _b.call(tapObserver);\n }));\n })\n :\n identity;\n}\n","import { EmptyError } from '../util/EmptyError';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nexport function throwIfEmpty(errorFactory = defaultErrorFactory) {\n return operate((source, subscriber) => {\n let hasValue = false;\n source.subscribe(createOperatorSubscriber(subscriber, (value) => {\n hasValue = true;\n subscriber.next(value);\n }, () => (hasValue ? subscriber.complete() : subscriber.error(errorFactory()))));\n });\n}\nfunction defaultErrorFactory() {\n return new EmptyError();\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { isValidDate } from '../util/isDate';\nimport { operate } from '../util/lift';\nimport { innerFrom } from '../observable/innerFrom';\nimport { createErrorClass } from '../util/createErrorClass';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { executeSchedule } from '../util/executeSchedule';\nexport const TimeoutError = createErrorClass((_super) => function TimeoutErrorImpl(info = null) {\n _super(this);\n this.message = 'Timeout has occurred';\n this.name = 'TimeoutError';\n this.info = info;\n});\nexport function timeout(config, schedulerArg) {\n const { first, each, with: _with = timeoutErrorFactory, scheduler = schedulerArg !== null && schedulerArg !== void 0 ? schedulerArg : asyncScheduler, meta = null, } = (isValidDate(config) ? { first: config } : typeof config === 'number' ? { each: config } : config);\n if (first == null && each == null) {\n throw new TypeError('No timeout provided.');\n }\n return operate((source, subscriber) => {\n let originalSourceSubscription;\n let timerSubscription;\n let lastValue = null;\n let seen = 0;\n const startTimer = (delay) => {\n timerSubscription = executeSchedule(subscriber, scheduler, () => {\n try {\n originalSourceSubscription.unsubscribe();\n innerFrom(_with({\n meta,\n lastValue,\n seen,\n })).subscribe(subscriber);\n }\n catch (err) {\n subscriber.error(err);\n }\n }, delay);\n };\n originalSourceSubscription = source.subscribe(createOperatorSubscriber(subscriber, (value) => {\n timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();\n seen++;\n subscriber.next((lastValue = value));\n each > 0 && startTimer(each);\n }, undefined, undefined, () => {\n if (!(timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.closed)) {\n timerSubscription === null || timerSubscription === void 0 ? void 0 : timerSubscription.unsubscribe();\n }\n lastValue = null;\n }));\n !seen && startTimer(first != null ? (typeof first === 'number' ? first : +first - scheduler.now()) : each);\n });\n}\nfunction timeoutErrorFactory(info) {\n throw new TimeoutError(info);\n}\n","import { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\nimport { identity } from '../util/identity';\nimport { noop } from '../util/noop';\nimport { popResultSelector } from '../util/args';\nexport function withLatestFrom(...inputs) {\n const project = popResultSelector(inputs);\n return operate((source, subscriber) => {\n const len = inputs.length;\n const otherValues = new Array(len);\n let hasValue = inputs.map(() => false);\n let ready = false;\n for (let i = 0; i < len; i++) {\n innerFrom(inputs[i]).subscribe(createOperatorSubscriber(subscriber, (value) => {\n otherValues[i] = value;\n if (!ready && !hasValue[i]) {\n hasValue[i] = true;\n (ready = hasValue.every(identity)) && (hasValue = null);\n }\n }, noop));\n }\n source.subscribe(createOperatorSubscriber(subscriber, (value) => {\n if (ready) {\n const values = [value, ...otherValues];\n subscriber.next(project ? project(...values) : values);\n }\n }));\n });\n}\n","import { Subscription } from '../Subscription';\nexport class Action extends Subscription {\n constructor(scheduler, work) {\n super();\n }\n schedule(state, delay = 0) {\n return this;\n }\n}\n","export const intervalProvider = {\n setInterval(handler, timeout, ...args) {\n const { delegate } = intervalProvider;\n if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) {\n return delegate.setInterval(handler, timeout, ...args);\n }\n return setInterval(handler, timeout, ...args);\n },\n clearInterval(handle) {\n const { delegate } = intervalProvider;\n return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle);\n },\n delegate: undefined,\n};\n","import { Action } from './Action';\nimport { intervalProvider } from './intervalProvider';\nimport { arrRemove } from '../util/arrRemove';\nexport class AsyncAction extends Action {\n constructor(scheduler, work) {\n super(scheduler, work);\n this.scheduler = scheduler;\n this.work = work;\n this.pending = false;\n }\n schedule(state, delay = 0) {\n var _a;\n if (this.closed) {\n return this;\n }\n this.state = state;\n const id = this.id;\n const scheduler = this.scheduler;\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, delay);\n }\n this.pending = true;\n this.delay = delay;\n this.id = (_a = this.id) !== null && _a !== void 0 ? _a : this.requestAsyncId(scheduler, this.id, delay);\n return this;\n }\n requestAsyncId(scheduler, _id, delay = 0) {\n return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);\n }\n recycleAsyncId(_scheduler, id, delay = 0) {\n if (delay != null && this.delay === delay && this.pending === false) {\n return id;\n }\n if (id != null) {\n intervalProvider.clearInterval(id);\n }\n return undefined;\n }\n execute(state, delay) {\n if (this.closed) {\n return new Error('executing a cancelled action');\n }\n this.pending = false;\n const error = this._execute(state, delay);\n if (error) {\n return error;\n }\n else if (this.pending === false && this.id != null) {\n this.id = this.recycleAsyncId(this.scheduler, this.id, null);\n }\n }\n _execute(state, _delay) {\n let errored = false;\n let errorValue;\n try {\n this.work(state);\n }\n catch (e) {\n errored = true;\n errorValue = e ? e : new Error('Scheduled action threw falsy error');\n }\n if (errored) {\n this.unsubscribe();\n return errorValue;\n }\n }\n unsubscribe() {\n if (!this.closed) {\n const { id, scheduler } = this;\n const { actions } = scheduler;\n this.work = this.state = this.scheduler = null;\n this.pending = false;\n arrRemove(actions, this);\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, null);\n }\n this.delay = null;\n super.unsubscribe();\n }\n }\n}\n","import { dateTimestampProvider } from './scheduler/dateTimestampProvider';\nexport class Scheduler {\n constructor(schedulerActionCtor, now = Scheduler.now) {\n this.schedulerActionCtor = schedulerActionCtor;\n this.now = now;\n }\n schedule(work, delay = 0, state) {\n return new this.schedulerActionCtor(this, work).schedule(state, delay);\n }\n}\nScheduler.now = dateTimestampProvider.now;\n","import { Scheduler } from '../Scheduler';\nexport class AsyncScheduler extends Scheduler {\n constructor(SchedulerAction, now = Scheduler.now) {\n super(SchedulerAction, now);\n this.actions = [];\n this._active = false;\n }\n flush(action) {\n const { actions } = this;\n if (this._active) {\n actions.push(action);\n return;\n }\n let error;\n this._active = true;\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions.shift()));\n this._active = false;\n if (error) {\n while ((action = actions.shift())) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\nexport const asyncScheduler = new AsyncScheduler(AsyncAction);\nexport const async = asyncScheduler;\n","export const dateTimestampProvider = {\n now() {\n return (dateTimestampProvider.delegate || Date).now();\n },\n delegate: undefined,\n};\n","import { QueueAction } from './QueueAction';\nimport { QueueScheduler } from './QueueScheduler';\nexport const queueScheduler = new QueueScheduler(QueueAction);\nexport const queue = queueScheduler;\n","import { AsyncScheduler } from './AsyncScheduler';\nexport class QueueScheduler extends AsyncScheduler {\n}\n","import { AsyncAction } from './AsyncAction';\nexport class QueueAction extends AsyncAction {\n constructor(scheduler, work) {\n super(scheduler, work);\n this.scheduler = scheduler;\n this.work = work;\n }\n schedule(state, delay = 0) {\n if (delay > 0) {\n return super.schedule(state, delay);\n }\n this.delay = delay;\n this.state = state;\n this.scheduler.flush(this);\n return this;\n }\n execute(state, delay) {\n return delay > 0 || this.closed ? super.execute(state, delay) : this._execute(state, delay);\n }\n requestAsyncId(scheduler, id, delay = 0) {\n if ((delay != null && delay > 0) || (delay == null && this.delay > 0)) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n scheduler.flush(this);\n return 0;\n }\n}\n","export const timeoutProvider = {\n setTimeout(handler, timeout, ...args) {\n const { delegate } = timeoutProvider;\n if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {\n return delegate.setTimeout(handler, timeout, ...args);\n }\n return setTimeout(handler, timeout, ...args);\n },\n clearTimeout(handle) {\n const { delegate } = timeoutProvider;\n return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);\n },\n delegate: undefined,\n};\n","export function getSymbolIterator() {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator';\n }\n return Symbol.iterator;\n}\nexport const iterator = getSymbolIterator();\n","export const observable = (() => (typeof Symbol === 'function' && Symbol.observable) || '@@observable')();\n","import { createErrorClass } from './createErrorClass';\nexport const EmptyError = createErrorClass((_super) => function EmptyErrorImpl() {\n _super(this);\n this.name = 'EmptyError';\n this.message = 'no elements in sequence';\n});\n","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","const { isArray } = Array;\nconst { getPrototypeOf, prototype: objectProto, keys: getKeys } = Object;\nexport function argsArgArrayOrObject(args) {\n if (args.length === 1) {\n const first = args[0];\n if (isArray(first)) {\n return { args: first, keys: null };\n }\n if (isPOJO(first)) {\n const keys = getKeys(first);\n return {\n args: keys.map((key) => first[key]),\n keys,\n };\n }\n }\n return { args: args, keys: null };\n}\nfunction isPOJO(obj) {\n return obj && typeof obj === 'object' && getPrototypeOf(obj) === objectProto;\n}\n","export function arrRemove(arr, item) {\n if (arr) {\n const index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n","export function createErrorClass(createImpl) {\n const _super = (instance) => {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n const ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n","export function createObject(keys, values) {\n return keys.reduce((result, key, i) => ((result[key] = values[i]), result), {});\n}\n","import { config } from '../config';\nlet context = null;\nexport function errorContext(cb) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n const isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n const { errorThrown, error } = context;\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","export function executeSchedule(parentSubscription, scheduler, work, delay = 0, repeat = false) {\n const 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","export function identity(x) {\n return x;\n}\n","export const isArrayLike = ((x) => x && typeof x.length === 'number' && typeof x !== 'function');\n","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","export function isValidDate(value) {\n return value instanceof Date && !isNaN(value);\n}\n","export function isFunction(value) {\n return typeof value === 'function';\n}\n","import { observable as Symbol_observable } from '../symbol/observable';\nimport { isFunction } from './isFunction';\nexport function isInteropObservable(input) {\n return isFunction(input[Symbol_observable]);\n}\n","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","import { isFunction } from \"./isFunction\";\nexport function isPromise(value) {\n return isFunction(value === null || value === void 0 ? void 0 : value.then);\n}\n","import { __asyncGenerator, __await } from \"tslib\";\nimport { isFunction } from './isFunction';\nexport function readableStreamLikeToAsyncGenerator(readableStream) {\n return __asyncGenerator(this, arguments, function* readableStreamLikeToAsyncGenerator_1() {\n const reader = readableStream.getReader();\n try {\n while (true) {\n const { value, done } = yield __await(reader.read());\n if (done) {\n return yield __await(void 0);\n }\n yield yield __await(value);\n }\n }\n finally {\n reader.releaseLock();\n }\n });\n}\nexport function isReadableStreamLike(obj) {\n return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);\n}\n","import { isFunction } from './isFunction';\nexport function isScheduler(value) {\n return value && isFunction(value.schedule);\n}\n","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 (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","import { map } from \"../operators/map\";\nconst { isArray } = Array;\nfunction callOrApply(fn, args) {\n return isArray(args) ? fn(...args) : fn(args);\n}\nexport function mapOneOrManyArgs(fn) {\n return map(args => callOrApply(fn, args));\n}\n","export function noop() { }\n","import { identity } from './identity';\nexport function pipe(...fns) {\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((prev, fn) => fn(prev), input);\n };\n}\n","import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\nexport function reportUnhandledError(err) {\n timeoutProvider.setTimeout(() => {\n const { onUnhandledError } = config;\n if (onUnhandledError) {\n onUnhandledError(err);\n }\n else {\n throw err;\n }\n });\n}\n","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","/*! safe-buffer. MIT License. Feross Aboukhadijeh */\n/* eslint-disable node/no-deprecated-api */\nvar buffer = require('buffer')\nvar Buffer = buffer.Buffer\n\n// alternative to using Object.keys for old browsers\nfunction copyProps (src, dst) {\n for (var key in src) {\n dst[key] = src[key]\n }\n}\nif (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {\n module.exports = buffer\n} else {\n // Copy properties from require('buffer')\n copyProps(buffer, exports)\n exports.Buffer = SafeBuffer\n}\n\nfunction SafeBuffer (arg, encodingOrOffset, length) {\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.prototype = Object.create(Buffer.prototype)\n\n// Copy static methods from Buffer\ncopyProps(Buffer, SafeBuffer)\n\nSafeBuffer.from = function (arg, encodingOrOffset, length) {\n if (typeof arg === 'number') {\n throw new TypeError('Argument must not be a number')\n }\n return Buffer(arg, encodingOrOffset, length)\n}\n\nSafeBuffer.alloc = function (size, fill, encoding) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n var buf = Buffer(size)\n if (fill !== undefined) {\n if (typeof encoding === 'string') {\n buf.fill(fill, encoding)\n } else {\n buf.fill(fill)\n }\n } else {\n buf.fill(0)\n }\n return buf\n}\n\nSafeBuffer.allocUnsafe = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return Buffer(size)\n}\n\nSafeBuffer.allocUnsafeSlow = function (size) {\n if (typeof size !== 'number') {\n throw new TypeError('Argument must be a number')\n }\n return buffer.SlowBuffer(size)\n}\n",";(function (sax) { // wrapper for non-node envs\n sax.parser = function (strict, opt) { return new SAXParser(strict, opt) }\n sax.SAXParser = SAXParser\n sax.SAXStream = SAXStream\n sax.createStream = createStream\n\n // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns.\n // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)),\n // since that's the earliest that a buffer overrun could occur. This way, checks are\n // as rare as required, but as often as necessary to ensure never crossing this bound.\n // Furthermore, buffers are only tested at most once per write(), so passing a very\n // large string into write() might have undesirable effects, but this is manageable by\n // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme\n // edge case, result in creating at most one complete copy of the string passed in.\n // Set to Infinity to have unlimited buffers.\n sax.MAX_BUFFER_LENGTH = 64 * 1024\n\n var buffers = [\n 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype',\n 'procInstName', 'procInstBody', 'entity', 'attribName',\n 'attribValue', 'cdata', 'script'\n ]\n\n sax.EVENTS = [\n 'text',\n 'processinginstruction',\n 'sgmldeclaration',\n 'doctype',\n 'comment',\n 'opentagstart',\n 'attribute',\n 'opentag',\n 'closetag',\n 'opencdata',\n 'cdata',\n 'closecdata',\n 'error',\n 'end',\n 'ready',\n 'script',\n 'opennamespace',\n 'closenamespace'\n ]\n\n function SAXParser (strict, opt) {\n if (!(this instanceof SAXParser)) {\n return new SAXParser(strict, opt)\n }\n\n var parser = this\n clearBuffers(parser)\n parser.q = parser.c = ''\n parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH\n parser.opt = opt || {}\n parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags\n parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase'\n parser.tags = []\n parser.closed = parser.closedRoot = parser.sawRoot = false\n parser.tag = parser.error = null\n parser.strict = !!strict\n parser.noscript = !!(strict || parser.opt.noscript)\n parser.state = S.BEGIN\n parser.strictEntities = parser.opt.strictEntities\n parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES)\n parser.attribList = []\n\n // namespaces form a prototype chain.\n // it always points at the current tag,\n // which protos to its parent tag.\n if (parser.opt.xmlns) {\n parser.ns = Object.create(rootNS)\n }\n\n // mostly just for error reporting\n parser.trackPosition = parser.opt.position !== false\n if (parser.trackPosition) {\n parser.position = parser.line = parser.column = 0\n }\n emit(parser, 'onready')\n }\n\n if (!Object.create) {\n Object.create = function (o) {\n function F () {}\n F.prototype = o\n var newf = new F()\n return newf\n }\n }\n\n if (!Object.keys) {\n Object.keys = function (o) {\n var a = []\n for (var i in o) if (o.hasOwnProperty(i)) a.push(i)\n return a\n }\n }\n\n function checkBufferLength (parser) {\n var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10)\n var maxActual = 0\n for (var i = 0, l = buffers.length; i < l; i++) {\n var len = parser[buffers[i]].length\n if (len > maxAllowed) {\n // Text/cdata nodes can get big, and since they're buffered,\n // we can get here under normal conditions.\n // Avoid issues by emitting the text node now,\n // so at least it won't get any bigger.\n switch (buffers[i]) {\n case 'textNode':\n closeText(parser)\n break\n\n case 'cdata':\n emitNode(parser, 'oncdata', parser.cdata)\n parser.cdata = ''\n break\n\n case 'script':\n emitNode(parser, 'onscript', parser.script)\n parser.script = ''\n break\n\n default:\n error(parser, 'Max buffer length exceeded: ' + buffers[i])\n }\n }\n maxActual = Math.max(maxActual, len)\n }\n // schedule the next check for the earliest possible buffer overrun.\n var m = sax.MAX_BUFFER_LENGTH - maxActual\n parser.bufferCheckPosition = m + parser.position\n }\n\n function clearBuffers (parser) {\n for (var i = 0, l = buffers.length; i < l; i++) {\n parser[buffers[i]] = ''\n }\n }\n\n function flushBuffers (parser) {\n closeText(parser)\n if (parser.cdata !== '') {\n emitNode(parser, 'oncdata', parser.cdata)\n parser.cdata = ''\n }\n if (parser.script !== '') {\n emitNode(parser, 'onscript', parser.script)\n parser.script = ''\n }\n }\n\n SAXParser.prototype = {\n end: function () { end(this) },\n write: write,\n resume: function () { this.error = null; return this },\n close: function () { return this.write(null) },\n flush: function () { flushBuffers(this) }\n }\n\n var Stream\n try {\n Stream = require('stream').Stream\n } catch (ex) {\n Stream = function () {}\n }\n\n var streamWraps = sax.EVENTS.filter(function (ev) {\n return ev !== 'error' && ev !== 'end'\n })\n\n function createStream (strict, opt) {\n return new SAXStream(strict, opt)\n }\n\n function SAXStream (strict, opt) {\n if (!(this instanceof SAXStream)) {\n return new SAXStream(strict, opt)\n }\n\n Stream.apply(this)\n\n this._parser = new SAXParser(strict, opt)\n this.writable = true\n this.readable = true\n\n var me = this\n\n this._parser.onend = function () {\n me.emit('end')\n }\n\n this._parser.onerror = function (er) {\n me.emit('error', er)\n\n // if didn't throw, then means error was handled.\n // go ahead and clear error, so we can write again.\n me._parser.error = null\n }\n\n this._decoder = null\n\n streamWraps.forEach(function (ev) {\n Object.defineProperty(me, 'on' + ev, {\n get: function () {\n return me._parser['on' + ev]\n },\n set: function (h) {\n if (!h) {\n me.removeAllListeners(ev)\n me._parser['on' + ev] = h\n return h\n }\n me.on(ev, h)\n },\n enumerable: true,\n configurable: false\n })\n })\n }\n\n SAXStream.prototype = Object.create(Stream.prototype, {\n constructor: {\n value: SAXStream\n }\n })\n\n SAXStream.prototype.write = function (data) {\n if (typeof Buffer === 'function' &&\n typeof Buffer.isBuffer === 'function' &&\n Buffer.isBuffer(data)) {\n if (!this._decoder) {\n var SD = require('string_decoder').StringDecoder\n this._decoder = new SD('utf8')\n }\n data = this._decoder.write(data)\n }\n\n this._parser.write(data.toString())\n this.emit('data', data)\n return true\n }\n\n SAXStream.prototype.end = function (chunk) {\n if (chunk && chunk.length) {\n this.write(chunk)\n }\n this._parser.end()\n return true\n }\n\n SAXStream.prototype.on = function (ev, handler) {\n var me = this\n if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) {\n me._parser['on' + ev] = function () {\n var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)\n args.splice(0, 0, ev)\n me.emit.apply(me, args)\n }\n }\n\n return Stream.prototype.on.call(me, ev, handler)\n }\n\n // this really needs to be replaced with character classes.\n // XML allows all manner of ridiculous numbers and digits.\n var CDATA = '[CDATA['\n var DOCTYPE = 'DOCTYPE'\n var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'\n var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/'\n var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }\n\n // http://www.w3.org/TR/REC-xml/#NT-NameStartChar\n // This implementation works on strings, a single character at a time\n // as such, it cannot ever support astral-plane characters (10000-EFFFF)\n // without a significant breaking change to either this parser, or the\n // JavaScript language. Implementation of an emoji-capable xml parser\n // is left as an exercise for the reader.\n var nameStart = /[:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]/\n\n var nameBody = /[:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u00B7\\u0300-\\u036F\\u203F-\\u2040.\\d-]/\n\n var entityStart = /[#:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]/\n var entityBody = /[#:_A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u00B7\\u0300-\\u036F\\u203F-\\u2040.\\d-]/\n\n function isWhitespace (c) {\n return c === ' ' || c === '\\n' || c === '\\r' || c === '\\t'\n }\n\n function isQuote (c) {\n return c === '\"' || c === '\\''\n }\n\n function isAttribEnd (c) {\n return c === '>' || isWhitespace(c)\n }\n\n function isMatch (regex, c) {\n return regex.test(c)\n }\n\n function notMatch (regex, c) {\n return !isMatch(regex, c)\n }\n\n var S = 0\n sax.STATE = {\n BEGIN: S++, // leading byte order mark or whitespace\n BEGIN_WHITESPACE: S++, // leading whitespace\n TEXT: S++, // general stuff\n TEXT_ENTITY: S++, // & and such.\n OPEN_WAKA: S++, // <\n SGML_DECL: S++, // \n SCRIPT: S++, //