{ "version": 3, "sources": ["../../../node_modules/regenerator-runtime/runtime.js", "../../../node_modules/zoid9078/dist/zoid.frame.js", "../../../node_modules/zoid9078/index.js", "../../../node_modules/tslib/tslib.es6.mjs", "../../../node_modules/@segment/analytics-core/dist/esm/emitter/interface.js", "../../../node_modules/@segment/analytics-core/dist/esm/plugins/index.js", "../../../node_modules/@segment/analytics-core/dist/esm/events/interfaces.js", "../../../node_modules/dset/dist/index.mjs", "../../../node_modules/@segment/analytics-core/src/utils/pick.ts", "../../../node_modules/@segment/analytics-core/src/validation/errors.ts", "../../../node_modules/@segment/analytics-core/src/validation/helpers.ts", "../../../node_modules/@segment/analytics-core/src/validation/assertions.ts", "../../../node_modules/@segment/analytics-core/src/events/index.ts", "../../../node_modules/@segment/analytics-core/src/callback/index.ts", "../../../node_modules/@segment/analytics-generic-utils/src/create-deferred/create-deferred.ts", "../../../node_modules/@segment/analytics-generic-utils/src/create-deferred/index.ts", "../../../node_modules/@segment/analytics-generic-utils/src/emitter/emitter.ts", "../../../node_modules/@segment/analytics-generic-utils/src/emitter/index.ts", "../../../node_modules/@segment/analytics-generic-utils/src/index.ts", "../../../node_modules/@segment/analytics-core/src/priority-queue/backoff.ts", "../../../node_modules/@segment/analytics-core/src/priority-queue/index.ts", "../../../node_modules/@lukeed/uuid/dist/index.mjs", "../../../node_modules/@segment/analytics-core/src/logger/index.ts", "../../../node_modules/@segment/analytics-core/src/stats/index.ts", "../../../node_modules/@segment/analytics-core/src/context/index.ts", "../../../node_modules/@segment/analytics-core/src/utils/group-by.ts", "../../../node_modules/@segment/analytics-core/src/utils/is-thenable.ts", "../../../node_modules/@segment/analytics-core/src/task/task-group.ts", "../../../node_modules/@segment/analytics-core/src/queue/delivery.ts", "../../../node_modules/@segment/analytics-core/src/queue/event-queue.ts", "../../../node_modules/@segment/analytics-core/dist/esm/analytics/index.js", "../../../node_modules/@segment/analytics-core/src/analytics/dispatch.ts", "../../../node_modules/@segment/analytics-core/src/utils/bind-all.ts", "../../../node_modules/@segment/analytics-core/src/index.ts", "../../../node_modules/@segment/analytics-next/src/core/environment/index.ts", "../../../node_modules/@segment/analytics-next/src/core/connection/index.ts", "../../../node_modules/unfetch/src/index.mjs", "../../../node_modules/@segment/analytics-next/src/lib/get-global.ts", "../../../node_modules/@segment/analytics-next/src/lib/fetch.ts", "../../../node_modules/@segment/analytics-next/src/generated/version.ts", "../../../node_modules/@segment/analytics-next/src/lib/version-type.ts", "../../../node_modules/@segment/analytics-next/src/core/constants/index.ts", "../../../node_modules/@segment/analytics-next/src/core/stats/remote-metrics.ts", "../../../node_modules/@segment/analytics-next/src/core/stats/index.ts", "../../../node_modules/@segment/analytics-next/src/core/context/index.ts", "../../../node_modules/@segment/analytics-next/src/lib/priority-queue/index.ts", "../../../node_modules/@segment/analytics-next/src/lib/priority-queue/persisted.ts", "../../../node_modules/@segment/analytics-next/src/lib/global-analytics-helper.ts", "../../../node_modules/@segment/analytics-next/src/core/callback/index.ts", "../../../node_modules/@segment/analytics-next/src/core/auto-track.ts", "../../../node_modules/obj-case/index.js", "../../../node_modules/@segment/facade/lib/address.js", "../../../node_modules/@segment/facade/lib/clone.js", "../../../node_modules/@segment/facade/lib/is-enabled.js", "../../../node_modules/@segment/isodate/lib/index.js", "../../../node_modules/new-date/lib/milliseconds.js", "../../../node_modules/new-date/lib/seconds.js", "../../../node_modules/new-date/lib/index.js", "../../../node_modules/@segment/isodate-traverse/lib/index.js", "../../../node_modules/@segment/facade/lib/facade.js", "../../../node_modules/inherits/inherits_browser.js", "../../../node_modules/@segment/facade/lib/alias.js", "../../../node_modules/@segment/facade/lib/is-email.js", "../../../node_modules/@segment/facade/lib/group.js", "../../../node_modules/@segment/facade/lib/identify.js", "../../../node_modules/@segment/facade/lib/track.js", "../../../node_modules/@segment/facade/lib/page.js", "../../../node_modules/@segment/facade/lib/screen.js", "../../../node_modules/@segment/facade/lib/delete.js", "../../../node_modules/@segment/facade/lib/index.js", "../../../node_modules/@segment/analytics-next/src/lib/to-facade.ts", "../../../node_modules/@segment/analytics-next/src/plugins/middleware/index.ts", "../../../node_modules/@segment/analytics-next/src/core/query-string/pickPrefix.ts", "../../../node_modules/@segment/analytics-next/src/core/query-string/gracefulDecodeURIComponent.ts", "../../../node_modules/@segment/analytics-next/src/core/query-string/index.ts", "../../../node_modules/@segment/analytics-next/src/lib/parse-cdn.ts", "../../../node_modules/@segment/analytics-next/src/lib/merged-options.ts", "../../../node_modules/@segment/analytics-next/src/lib/load-script.ts", "../../../node_modules/@segment/analytics-next/src/core/stats/metric-helpers.ts", "../../../node_modules/@segment/analytics-next/src/lib/p-while.ts", "../../../node_modules/@segment/analytics-next/src/vendor/tsub/tsub.ts", "../../../node_modules/@segment/analytics-next/src/plugins/routing-middleware/index.ts", "../../../node_modules/@segment/analytics-next/src/lib/is-plan-event-enabled.ts", "../../../node_modules/@segment/analytics-next/src/plugins/ajs-destination/loader.ts", "../../../node_modules/@segment/analytics-next/src/plugins/ajs-destination/utils.ts", "../../../node_modules/@segment/analytics-next/src/plugins/ajs-destination/index.ts", "../../../node_modules/@segment/analytics.js-video-plugins/dist/index.umd.js", "../../../node_modules/@segment/analytics-next/src/plugins/legacy-video-plugins/index.ts", "../../../node_modules/@segment/analytics-next/src/plugins/schema-filter/index.ts", "../../../node_modules/@segment/analytics-next/src/plugins/remote-middleware/index.ts", "../../../node_modules/lodash/isArray.js", "../../../node_modules/lodash/_freeGlobal.js", "../../../node_modules/lodash/_root.js", "../../../node_modules/lodash/_Symbol.js", "../../../node_modules/lodash/_getRawTag.js", "../../../node_modules/lodash/_objectToString.js", "../../../node_modules/lodash/_baseGetTag.js", "../../../node_modules/lodash/isObjectLike.js", "../../../node_modules/lodash/isSymbol.js", "../../../node_modules/lodash/_isKey.js", "../../../node_modules/lodash/isObject.js", "../../../node_modules/lodash/isFunction.js", "../../../node_modules/lodash/_coreJsData.js", "../../../node_modules/lodash/_isMasked.js", "../../../node_modules/lodash/_toSource.js", "../../../node_modules/lodash/_baseIsNative.js", "../../../node_modules/lodash/_getValue.js", "../../../node_modules/lodash/_getNative.js", "../../../node_modules/lodash/_nativeCreate.js", "../../../node_modules/lodash/_hashClear.js", "../../../node_modules/lodash/_hashDelete.js", "../../../node_modules/lodash/_hashGet.js", "../../../node_modules/lodash/_hashHas.js", "../../../node_modules/lodash/_hashSet.js", "../../../node_modules/lodash/_Hash.js", "../../../node_modules/lodash/_listCacheClear.js", "../../../node_modules/lodash/eq.js", "../../../node_modules/lodash/_assocIndexOf.js", "../../../node_modules/lodash/_listCacheDelete.js", "../../../node_modules/lodash/_listCacheGet.js", "../../../node_modules/lodash/_listCacheHas.js", "../../../node_modules/lodash/_listCacheSet.js", "../../../node_modules/lodash/_ListCache.js", "../../../node_modules/lodash/_Map.js", "../../../node_modules/lodash/_mapCacheClear.js", "../../../node_modules/lodash/_isKeyable.js", "../../../node_modules/lodash/_getMapData.js", "../../../node_modules/lodash/_mapCacheDelete.js", "../../../node_modules/lodash/_mapCacheGet.js", "../../../node_modules/lodash/_mapCacheHas.js", "../../../node_modules/lodash/_mapCacheSet.js", "../../../node_modules/lodash/_MapCache.js", "../../../node_modules/lodash/memoize.js", "../../../node_modules/lodash/_memoizeCapped.js", "../../../node_modules/lodash/_stringToPath.js", "../../../node_modules/lodash/_arrayMap.js", "../../../node_modules/lodash/_baseToString.js", "../../../node_modules/lodash/toString.js", "../../../node_modules/lodash/_castPath.js", "../../../node_modules/lodash/_toKey.js", "../../../node_modules/lodash/_baseGet.js", "../../../node_modules/lodash/get.js", "../../../node_modules/lodash/_baseHas.js", "../../../node_modules/lodash/_baseIsArguments.js", "../../../node_modules/lodash/isArguments.js", "../../../node_modules/lodash/_isIndex.js", "../../../node_modules/lodash/isLength.js", "../../../node_modules/lodash/_hasPath.js", "../../../node_modules/lodash/has.js", "../../../node_modules/lodash/_stackClear.js", "../../../node_modules/lodash/_stackDelete.js", "../../../node_modules/lodash/_stackGet.js", "../../../node_modules/lodash/_stackHas.js", "../../../node_modules/lodash/_stackSet.js", "../../../node_modules/lodash/_Stack.js", "../../../node_modules/lodash/_defineProperty.js", "../../../node_modules/lodash/_baseAssignValue.js", "../../../node_modules/lodash/_assignMergeValue.js", "../../../node_modules/lodash/_createBaseFor.js", "../../../node_modules/lodash/_baseFor.js", "../../../node_modules/lodash/_cloneBuffer.js", "../../../node_modules/lodash/_Uint8Array.js", "../../../node_modules/lodash/_cloneArrayBuffer.js", "../../../node_modules/lodash/_cloneTypedArray.js", "../../../node_modules/lodash/_copyArray.js", "../../../node_modules/lodash/_baseCreate.js", "../../../node_modules/lodash/_overArg.js", "../../../node_modules/lodash/_getPrototype.js", "../../../node_modules/lodash/_isPrototype.js", "../../../node_modules/lodash/_initCloneObject.js", "../../../node_modules/lodash/isArrayLike.js", "../../../node_modules/lodash/isArrayLikeObject.js", "../../../node_modules/lodash/stubFalse.js", "../../../node_modules/lodash/isBuffer.js", "../../../node_modules/lodash/isPlainObject.js", "../../../node_modules/lodash/_baseIsTypedArray.js", "../../../node_modules/lodash/_baseUnary.js", "../../../node_modules/lodash/_nodeUtil.js", "../../../node_modules/lodash/isTypedArray.js", "../../../node_modules/lodash/_safeGet.js", "../../../node_modules/lodash/_assignValue.js", "../../../node_modules/lodash/_copyObject.js", "../../../node_modules/lodash/_baseTimes.js", "../../../node_modules/lodash/_arrayLikeKeys.js", "../../../node_modules/lodash/_nativeKeysIn.js", "../../../node_modules/lodash/_baseKeysIn.js", "../../../node_modules/lodash/keysIn.js", "../../../node_modules/lodash/toPlainObject.js", "../../../node_modules/lodash/_baseMergeDeep.js", "../../../node_modules/lodash/_baseMerge.js", "../../../node_modules/lodash/identity.js", "../../../node_modules/lodash/_apply.js", "../../../node_modules/lodash/_overRest.js", "../../../node_modules/lodash/constant.js", "../../../node_modules/lodash/_baseSetToString.js", "../../../node_modules/lodash/_shortOut.js", "../../../node_modules/lodash/_setToString.js", "../../../node_modules/lodash/_baseRest.js", "../../../node_modules/lodash/_isIterateeCall.js", "../../../node_modules/lodash/_createAssigner.js", "../../../node_modules/lodash/merge.js", "../../../node_modules/lodash/_setCacheAdd.js", "../../../node_modules/lodash/_setCacheHas.js", "../../../node_modules/lodash/_SetCache.js", "../../../node_modules/lodash/_baseFindIndex.js", "../../../node_modules/lodash/_baseIsNaN.js", "../../../node_modules/lodash/_strictIndexOf.js", "../../../node_modules/lodash/_baseIndexOf.js", "../../../node_modules/lodash/_arrayIncludes.js", "../../../node_modules/lodash/_arrayIncludesWith.js", "../../../node_modules/lodash/_cacheHas.js", "../../../node_modules/lodash/_Set.js", "../../../node_modules/lodash/noop.js", "../../../node_modules/lodash/_setToArray.js", "../../../node_modules/lodash/_createSet.js", "../../../node_modules/lodash/_baseUniq.js", "../../../node_modules/lodash/uniq.js", "../../../node_modules/lodash/_baseSlice.js", "../../../node_modules/lodash/_castSlice.js", "../../../node_modules/lodash/_hasUnicode.js", "../../../node_modules/lodash/_asciiToArray.js", "../../../node_modules/lodash/_unicodeToArray.js", "../../../node_modules/lodash/_stringToArray.js", "../../../node_modules/lodash/_createCaseFirst.js", "../../../node_modules/lodash/upperFirst.js", "../../../node_modules/lodash/capitalize.js", "../../../node_modules/lodash/_arrayReduce.js", "../../../node_modules/lodash/_basePropertyOf.js", "../../../node_modules/lodash/_deburrLetter.js", "../../../node_modules/lodash/deburr.js", "../../../node_modules/lodash/_asciiWords.js", "../../../node_modules/lodash/_hasUnicodeWord.js", "../../../node_modules/lodash/_unicodeWords.js", "../../../node_modules/lodash/words.js", "../../../node_modules/lodash/_createCompounder.js", "../../../node_modules/lodash/camelCase.js", "../../../node_modules/lodash/_baseRepeat.js", "../../../node_modules/lodash/_trimmedEndIndex.js", "../../../node_modules/lodash/_baseTrim.js", "../../../node_modules/lodash/toNumber.js", "../../../node_modules/lodash/toFinite.js", "../../../node_modules/lodash/toInteger.js", "../../../node_modules/lodash/repeat.js", "../../../node_modules/lodash/_arrayPush.js", "../../../node_modules/lodash/_isFlattenable.js", "../../../node_modules/lodash/_baseFlatten.js", "../../../node_modules/lodash/_arraySome.js", "../../../node_modules/lodash/_equalArrays.js", "../../../node_modules/lodash/_mapToArray.js", "../../../node_modules/lodash/_equalByTag.js", "../../../node_modules/lodash/_baseGetAllKeys.js", "../../../node_modules/lodash/_arrayFilter.js", "../../../node_modules/lodash/stubArray.js", "../../../node_modules/lodash/_getSymbols.js", "../../../node_modules/lodash/_nativeKeys.js", "../../../node_modules/lodash/_baseKeys.js", "../../../node_modules/lodash/keys.js", "../../../node_modules/lodash/_getAllKeys.js", "../../../node_modules/lodash/_equalObjects.js", "../../../node_modules/lodash/_DataView.js", "../../../node_modules/lodash/_Promise.js", "../../../node_modules/lodash/_WeakMap.js", "../../../node_modules/lodash/_getTag.js", "../../../node_modules/lodash/_baseIsEqualDeep.js", "../../../node_modules/lodash/_baseIsEqual.js", "../../../node_modules/lodash/_baseIsMatch.js", "../../../node_modules/lodash/_isStrictComparable.js", "../../../node_modules/lodash/_getMatchData.js", "../../../node_modules/lodash/_matchesStrictComparable.js", "../../../node_modules/lodash/_baseMatches.js", "../../../node_modules/lodash/_baseHasIn.js", "../../../node_modules/lodash/hasIn.js", "../../../node_modules/lodash/_baseMatchesProperty.js", "../../../node_modules/lodash/_baseProperty.js", "../../../node_modules/lodash/_basePropertyDeep.js", "../../../node_modules/lodash/property.js", "../../../node_modules/lodash/_baseIteratee.js", "../../../node_modules/lodash/_baseForOwn.js", "../../../node_modules/lodash/_createBaseEach.js", "../../../node_modules/lodash/_baseEach.js", "../../../node_modules/lodash/_baseMap.js", "../../../node_modules/lodash/_baseSortBy.js", "../../../node_modules/lodash/_compareAscending.js", "../../../node_modules/lodash/_compareMultiple.js", "../../../node_modules/lodash/_baseOrderBy.js", "../../../node_modules/lodash/sortBy.js", "../../../node_modules/lodash/_baseZipObject.js", "../../../node_modules/lodash/zipObject.js", "../../../node_modules/lodash/_baseRange.js", "../../../node_modules/lodash/_createRange.js", "../../../node_modules/lodash/range.js", "../../../node_modules/clipboard/dist/clipboard.js", "../../../node_modules/lodash/now.js", "../../../node_modules/lodash/debounce.js", "../../javascript/packs/embed.js", "../../javascript/components/frame-factory.js", "../../javascript/utils/hashing.js", "../../../node_modules/@hotwired/stimulus/dist/stimulus.js", "../../../node_modules/@segment/analytics-next/src/core/arguments-resolver/index.ts", "../../../node_modules/@segment/analytics-next/src/core/events/index.ts", "../../../node_modules/@segment/analytics-next/src/core/page/get-page-context.ts", "../../../node_modules/@segment/analytics-next/src/lib/pick.ts", "../../../node_modules/@segment/analytics-next/src/core/plugin/index.ts", "../../../node_modules/@segment/analytics-next/src/core/queue/event-queue.ts", "../../../node_modules/@segment/analytics-next/src/core/user/index.ts", "../../../node_modules/@segment/analytics-next/src/lib/bind-all.ts", "../../../node_modules/js-cookie/dist/js.cookie.mjs", "../../../node_modules/@segment/analytics-next/src/core/user/tld.ts", "../../../node_modules/@segment/analytics-next/src/core/storage/localStorage.ts", "../../../node_modules/@segment/analytics-next/src/core/storage/memoryStorage.ts", "../../../node_modules/@segment/analytics-next/src/core/storage/types.ts", "../../../node_modules/@segment/analytics-next/src/core/storage/settings.ts", "../../../node_modules/@segment/analytics-next/src/core/storage/universalStorage.ts", "../../../node_modules/@segment/analytics-next/src/core/storage/index.ts", "../../../node_modules/@segment/analytics-next/src/lib/is-thenable.ts", "../../../node_modules/@segment/analytics-next/src/lib/get-process-env.ts", "../../../node_modules/@segment/analytics-next/src/lib/client-hints/index.ts", "../../../node_modules/@segment/analytics-next/src/plugins/remote-loader/index.ts", "../../../node_modules/@segment/analytics-next/src/plugins/segmentio/index.ts", "../../../node_modules/@segment/analytics-next/src/plugins/segmentio/batched-dispatcher.ts", "../../../node_modules/@segment/analytics-next/src/lib/on-page-change.ts", "../../../node_modules/@segment/analytics-next/src/plugins/segmentio/fetch-dispatcher.ts", "../../../node_modules/@segment/analytics-next/src/plugins/segmentio/normalize.ts", "../../../node_modules/@segment/analytics-next/src/plugins/segmentio/schedule-flush.ts", "../../../node_modules/@segment/analytics-next/src/core/inspector/index.ts", "../../../node_modules/@segment/analytics-next/src/index.ts", "../../../node_modules/@appsignal/javascript/node_modules/tslib/tslib.es6.mjs", "../../../node_modules/@appsignal/core/node_modules/tslib/tslib.es6.mjs", "../../../node_modules/@appsignal/core/src/utils/functional.ts", "../../../node_modules/@appsignal/core/src/utils/hashmap.ts", "../../../node_modules/@appsignal/core/src/utils/error.ts", "../../../node_modules/@appsignal/core/src/utils/url.ts", "../../../node_modules/@appsignal/core/src/utils/environment.ts", "../../../node_modules/@appsignal/core/src/serializable.ts", "../../../node_modules/@appsignal/javascript/src/version.ts", "../../../node_modules/@appsignal/javascript/src/environment.ts", "../../../node_modules/@appsignal/javascript/src/transports/xdomain.ts", "../../../node_modules/@appsignal/javascript/src/transports/xhr.ts", "../../../node_modules/@appsignal/javascript/src/transports/fetch.ts", "../../../node_modules/@appsignal/javascript/src/transports/node.ts", "../../../node_modules/@appsignal/javascript/src/api.ts", "../../../node_modules/@appsignal/javascript/src/span.ts", "../../../node_modules/@appsignal/javascript/src/queue.ts", "../../../node_modules/@appsignal/javascript/src/dispatcher.ts", "../../../node_modules/@appsignal/javascript/src/index.ts", "../../../node_modules/@appsignal/plugin-window-events/src/index.ts", "../../javascript/utils/logger.js", "../../javascript/utils/analytics.js", "../../javascript/controllers/analytics_controller.js", "../../javascript/controllers/bundle_embed_controller.js", "../../javascript/controllers/frame_controller.js", "../../javascript/controllers/horizontal_bundle_analytics_controller.js", "../../../node_modules/micromodal/dist/micromodal.es.js", "../../javascript/utils/modal.js", "../../javascript/controllers/modal_trigger_controller.js", "../../javascript/controllers/powered_by_provenance_controller.js", "../../javascript/controllers/proof_point_status_controller.js", "../../javascript/controllers/tabs_controller.js", "../../javascript/controllers/tabpanels_controller.js", "../../../node_modules/preact/src/constants.js", "../../../node_modules/preact/src/util.js", "../../../node_modules/preact/src/options.js", "../../../node_modules/preact/src/create-element.js", "../../../node_modules/preact/src/component.js", "../../../node_modules/preact/src/diff/props.js", "../../../node_modules/preact/src/create-context.js", "../../../node_modules/preact/src/diff/children.js", "../../../node_modules/preact/src/diff/index.js", "../../../node_modules/preact/src/render.js", "../../../node_modules/preact/src/clone-element.js", "../../../node_modules/preact/src/diff/catch-error.js", "../../javascript/react/components/icons/ExternalLinkIcon.jsx", "../../javascript/react/utils/analytics.js", "../../javascript/react/components/ExternalLink.jsx", "../../../node_modules/i18n-js/src/I18n.ts", "../../../node_modules/i18n-js/src/Locales.ts", "../../../node_modules/make-plural/plurals.mjs", "../../../node_modules/i18n-js/src/Pluralization.ts", "../../../node_modules/i18n-js/src/helpers/camelCaseKeys.ts", "../../../node_modules/i18n-js/src/helpers/isSet.ts", "../../../node_modules/i18n-js/src/helpers/createTranslationOptions.ts", "../../../node_modules/bignumber.js/bignumber.mjs", "../../../node_modules/i18n-js/src/helpers/expandRoundMode.ts", "../../../node_modules/i18n-js/src/helpers/formatNumber.ts", "../../../node_modules/i18n-js/src/helpers/roundNumber.ts", "../../../node_modules/i18n-js/src/helpers/getFullScope.ts", "../../../node_modules/i18n-js/src/helpers/inferType.ts", "../../../node_modules/i18n-js/src/helpers/interpolate.ts", "../../../node_modules/i18n-js/src/helpers/lookup.ts", "../../../node_modules/i18n-js/src/helpers/numberToDelimited.ts", "../../../node_modules/i18n-js/src/helpers/numberToHuman.ts", "../../../node_modules/i18n-js/src/helpers/numberToHumanSize.ts", "../../../node_modules/i18n-js/src/helpers/parseDate.ts", "../../../node_modules/i18n-js/src/helpers/pluralize.ts", "../../../node_modules/i18n-js/src/helpers/strftime.ts", "../../../node_modules/i18n-js/src/helpers/timeAgoInWords.ts", "../../../node_modules/i18n-js/src/MissingTranslation.ts", "../../javascript/translations.json", "../../javascript/utils/translate.js", "../../javascript/react/components/ModalCard/EvidencedMeaning.jsx", "../../../node_modules/preact/hooks/src/index.js", "../images/svgs/branding-wordmark-flag.svg", "../images/svgs/branding-wordmark-logos.svg", "../../javascript/react/components/PoweredByProvenance.jsx", "../../javascript/react/components/TagLine.jsx", "../../javascript/react/components/ModalCard/Footer.jsx", "../../javascript/react/components/ModalCard/MeaningSection.jsx", "../images/svgs/icon-checking-v2.svg", "../images/svgs/icon-evidenced-v2.svg", "../images/svgs/icon-verified-v2.svg", "../../javascript/react/components/ProofPointStatus.jsx", "../images/svgs/branding-logo-flag.svg", "../images/svgs/icon-scheme-default.svg", "../../javascript/react/components/ModalCard/StickyHeader.jsx", "../../javascript/react/components/icons/ThumbsUpIcon.jsx", "../../javascript/react/components/icons/ThumbsDownIcon.jsx", "../../javascript/react/components/feedback/Option.jsx", "../../javascript/react/components/feedback/Feedback.jsx", "../../javascript/react/components/ModalCard/ThirdPartyVerification.jsx", "../../javascript/react/components/ModalCard/stories/StoryButtonList.jsx", "../../javascript/react/components/Details.jsx", "../images/svgs/icon-chevron-down.svg", "../../javascript/react/components/ModalCard/ThemeSection.jsx", "../../javascript/react/components/ModalCard/ThemeSectionV1.jsx", "../../javascript/react/components/images/Placeholder.jsx", "../../javascript/react/components/ModalCard/Header.jsx", "../../javascript/react/components/ModalCard/VerifierSection.jsx", "../../javascript/react/components/ModalCard/CertificateCard.jsx", "../../javascript/react/components/ModalCard/ClaimsSection.jsx", "../../javascript/react/components/ModalCard/CollaboratorActivity.jsx", "../../javascript/react/components/icons/FlagIcon.jsx", "../../javascript/react/components/claims/CollaborationCard.jsx", "../../javascript/react/components/ModalCard/LocationSection.jsx", "../../javascript/react/components/ModalCard/NetworkVerificationSection.jsx", "../../javascript/react/components/ModalCard/ConnectionCard.jsx", "../images/svgs/icon-chevron-left.svg", "../../../node_modules/@appsignal/preact/src/ErrorBoundary.tsx", "../../javascript/react/components/ErrorTracker.jsx", "../../javascript/react/components/InfiniteModal.jsx", "../../javascript/react/components/claims/ProofPoint.jsx", "../../javascript/react/components/ModalCard/ProofPointsSection.jsx", "../../javascript/react/components/ModalCard/OrganizationCard.jsx", "../../javascript/react/components/stories/CoverView.jsx", "../../javascript/react/components/icons/Link.jsx", "../../javascript/react/components/stories/Organization.jsx", "../../javascript/react/components/stories/Share.jsx", "../../javascript/utils/navigatorShare.js", "../../javascript/utils/snackbar.js", "../../javascript/react/components/ui/Snackbar.jsx", "../../javascript/react/components/stories/CreditsView.jsx", "../../javascript/react/components/claims/ClaimCardPJ.jsx", "../../javascript/react/components/stories/VideoSlideContent.jsx", "../../javascript/react/components/stories/Slide.jsx", "../../javascript/react/components/stories/Brand.jsx", "../../javascript/react/components/icons/HelpIcon.jsx", "../../javascript/react/components/stories/HelpButton.jsx", "../../javascript/react/components/stories/Header.jsx", "../../javascript/react/components/icons/LeftIcon.jsx", "../../javascript/react/components/icons/RightIcon.jsx", "../../javascript/react/components/stories/Navigation.jsx", "../../javascript/react/components/icons/CloseIcon.jsx", "../../javascript/react/components/CloseButton.jsx", "../../javascript/react/components/stories/Drawer.jsx", "../../javascript/react/components/ModalCard/Profile.jsx", "../../javascript/react/components/ModalCard/EvidenceSection.jsx", "../../javascript/react/components/ModalCard/HowAchievedSection.jsx", "../../javascript/react/components/ModalCard/ProductSummary.jsx", "../../javascript/react/components/ModalCard/ClaimDescription.jsx", "../../javascript/react/components/ModalCard/recycling/Packaging.jsx", "../../javascript/react/components/ModalCard/recycling/Scheme.jsx", "../../javascript/react/components/ModalCard/recycling/Facility.jsx", "../../javascript/react/components/ModalCard/recycling/Facilities.jsx", "../../javascript/react/components/ModalCard/recycling/Unrecyclable.jsx", "../../javascript/react/components/ModalCard/recycling/Error.jsx", "../../javascript/react/components/ModalCard/recycling/Results.jsx", "../../javascript/react/components/ModalCard/recycling/Attribution.jsx", "../../javascript/react/components/ModalCard/recycling/Lookup.jsx", "../../javascript/react/components/ModalCard/DescriptionSection.jsx", "../../javascript/react/components/Avatar.jsx", "../../javascript/react/components/UserProfile.jsx", "../../javascript/react/components/ModalCard/QuoteSection.jsx", "../../javascript/react/components/ModalCard/VerificationSection.jsx", "../../javascript/react/components/ModalCard/EvidenceVerifierSection.jsx", "../../javascript/react/components/ModalCard/EvidenceFromActivitySection.jsx", "../../javascript/react/components/ModalCard/EvidenceCard.jsx", "../../javascript/react/components/StaticCapsuleList.jsx", "../../javascript/react/components/FooterCTA.jsx", "../images/svgs/icon-climate.svg", "../images/svgs/icon-waste.svg", "../images/svgs/icon-nature.svg", "../images/svgs/icon-workers.svg", "../images/svgs/icon-communities.svg", "../images/svgs/icon-instagram-small.svg", "../../javascript/react/components/ModalCard/about/AboutCard.jsx", "../../javascript/react/components/stories/Progress.jsx", "../../javascript/react/components/stories/ProgressBar.jsx", "../../javascript/react/utils/mouse.js", "../../javascript/react/components/stories/callbacks.js", "../../javascript/react/components/stories/Slider.jsx", "../../javascript/react/components/ModalCard/stories/StoryCard.jsx", "../../javascript/react/components/ModalCard/stories/StoryCardListForInfiniteModal.jsx", "../../javascript/react/components/ModalCard/about/AboutCardForInfiniteModal.jsx", "../../javascript/react/components/ModalCard/FullOrganizationCard.jsx", "../../javascript/react/components/ModalCard/RecyclingCard.jsx", "../../javascript/react/components/ModalCard/FullEvidenceCard.jsx", "../../javascript/react/components/ModalCard/FullCertificateCard.jsx", "../../javascript/react/components/ModalCard/Container.jsx", "../../javascript/controllers/mount_js_controller.js", "../../../node_modules/@appsignal/stimulus/src/index.ts", "../../javascript/utils/stimulus.js"], "sourcesContent": ["/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; };\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n defineProperty(generator, \"_invoke\", { value: makeInvokeMethod(innerFn, self, context) });\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = GeneratorFunctionPrototype;\n defineProperty(Gp, \"constructor\", { value: GeneratorFunctionPrototype, configurable: true });\n defineProperty(\n GeneratorFunctionPrototype,\n \"constructor\",\n { value: GeneratorFunction, configurable: true }\n );\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n defineProperty(this, \"_invoke\", { value: enqueue });\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n });\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per GeneratorResume behavior specified since ES2015:\n // ES2015 spec, step 3: https://262.ecma-international.org/6.0/#sec-generatorresume\n // Latest spec, step 2: https://tc39.es/ecma262/#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var methodName = context.method;\n var method = delegate.iterator[methodName];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method, or a missing .next method, always terminate the\n // yield* loop.\n context.delegate = null;\n\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (methodName === \"throw\" && delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n if (methodName !== \"return\") {\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a '\" + methodName + \"' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n define(Gp, iteratorSymbol, function() {\n return this;\n });\n\n define(Gp, \"toString\", function() {\n return \"[object Generator]\";\n });\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(val) {\n var object = Object(val);\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable != null) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n throw new TypeError(typeof iterable + \" is not iterable\");\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, in modern engines\n // we can explicitly access globalThis. In older engines we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n if (typeof globalThis === \"object\") {\n globalThis.regeneratorRuntime = runtime;\n } else {\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n }\n}\n", "!function(root, factory) {\n \"object\" == typeof exports && \"object\" == typeof module ? module.exports = factory() : \"function\" == typeof define && define.amd ? define(\"zoid\", [], factory) : \"object\" == typeof exports ? exports.zoid = factory() : root.zoid = factory();\n}(\"undefined\" != typeof self ? self : this, (function() {\n return function(modules) {\n var installedModules = {};\n function __webpack_require__(moduleId) {\n if (installedModules[moduleId]) return installedModules[moduleId].exports;\n var module = installedModules[moduleId] = {\n i: moduleId,\n l: !1,\n exports: {}\n };\n modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n module.l = !0;\n return module.exports;\n }\n __webpack_require__.m = modules;\n __webpack_require__.c = installedModules;\n __webpack_require__.d = function(exports, name, getter) {\n __webpack_require__.o(exports, name) || Object.defineProperty(exports, name, {\n enumerable: !0,\n get: getter\n });\n };\n __webpack_require__.r = function(exports) {\n \"undefined\" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(exports, Symbol.toStringTag, {\n value: \"Module\"\n });\n Object.defineProperty(exports, \"__esModule\", {\n value: !0\n });\n };\n __webpack_require__.t = function(value, mode) {\n 1 & mode && (value = __webpack_require__(value));\n if (8 & mode) return value;\n if (4 & mode && \"object\" == typeof value && value && value.__esModule) return value;\n var ns = Object.create(null);\n __webpack_require__.r(ns);\n Object.defineProperty(ns, \"default\", {\n enumerable: !0,\n value: value\n });\n if (2 & mode && \"string\" != typeof value) for (var key in value) __webpack_require__.d(ns, key, function(key) {\n return value[key];\n }.bind(null, key));\n return ns;\n };\n __webpack_require__.n = function(module) {\n var getter = module && module.__esModule ? function() {\n return module.default;\n } : function() {\n return module;\n };\n __webpack_require__.d(getter, \"a\", getter);\n return getter;\n };\n __webpack_require__.o = function(object, property) {\n return {}.hasOwnProperty.call(object, property);\n };\n __webpack_require__.p = \"\";\n return __webpack_require__(__webpack_require__.s = 0);\n }([ function(module, __webpack_exports__, __webpack_require__) {\n \"use strict\";\n __webpack_require__.r(__webpack_exports__);\n __webpack_require__.d(__webpack_exports__, \"PopupOpenError\", (function() {\n return dom_PopupOpenError;\n }));\n __webpack_require__.d(__webpack_exports__, \"create\", (function() {\n return component_create;\n }));\n __webpack_require__.d(__webpack_exports__, \"destroy\", (function() {\n return component_destroy;\n }));\n __webpack_require__.d(__webpack_exports__, \"destroyComponents\", (function() {\n return destroyComponents;\n }));\n __webpack_require__.d(__webpack_exports__, \"destroyAll\", (function() {\n return destroyAll;\n }));\n __webpack_require__.d(__webpack_exports__, \"PROP_TYPE\", (function() {\n return PROP_TYPE;\n }));\n __webpack_require__.d(__webpack_exports__, \"PROP_SERIALIZATION\", (function() {\n return PROP_SERIALIZATION;\n }));\n __webpack_require__.d(__webpack_exports__, \"CONTEXT\", (function() {\n return CONTEXT;\n }));\n __webpack_require__.d(__webpack_exports__, \"EVENT\", (function() {\n return EVENT;\n }));\n function _setPrototypeOf(o, p) {\n return (_setPrototypeOf = Object.setPrototypeOf || function(o, p) {\n o.__proto__ = p;\n return o;\n })(o, p);\n }\n function _inheritsLoose(subClass, superClass) {\n subClass.prototype = Object.create(superClass.prototype);\n subClass.prototype.constructor = subClass;\n _setPrototypeOf(subClass, superClass);\n }\n function _extends() {\n return (_extends = Object.assign || function(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) ({}).hasOwnProperty.call(source, key) && (target[key] = source[key]);\n }\n return target;\n }).apply(this, arguments);\n }\n function utils_isPromise(item) {\n try {\n if (!item) return !1;\n if (\"undefined\" != typeof Promise && item instanceof Promise) return !0;\n if (\"undefined\" != typeof window && \"function\" == typeof window.Window && item instanceof window.Window) return !1;\n if (\"undefined\" != typeof window && \"function\" == typeof window.constructor && item instanceof window.constructor) return !1;\n var _toString = {}.toString;\n if (_toString) {\n var name = _toString.call(item);\n if (\"[object Window]\" === name || \"[object global]\" === name || \"[object DOMWindow]\" === name) return !1;\n }\n if (\"function\" == typeof item.then) return !0;\n } catch (err) {\n return !1;\n }\n return !1;\n }\n var dispatchedErrors = [];\n var possiblyUnhandledPromiseHandlers = [];\n var activeCount = 0;\n var flushPromise;\n function flushActive() {\n if (!activeCount && flushPromise) {\n var promise = flushPromise;\n flushPromise = null;\n promise.resolve();\n }\n }\n function startActive() {\n activeCount += 1;\n }\n function endActive() {\n activeCount -= 1;\n flushActive();\n }\n var promise_ZalgoPromise = function() {\n function ZalgoPromise(handler) {\n var _this = this;\n this.resolved = void 0;\n this.rejected = void 0;\n this.errorHandled = void 0;\n this.value = void 0;\n this.error = void 0;\n this.handlers = void 0;\n this.dispatching = void 0;\n this.stack = void 0;\n this.resolved = !1;\n this.rejected = !1;\n this.errorHandled = !1;\n this.handlers = [];\n if (handler) {\n var _result;\n var _error;\n var resolved = !1;\n var rejected = !1;\n var isAsync = !1;\n startActive();\n try {\n handler((function(res) {\n if (isAsync) _this.resolve(res); else {\n resolved = !0;\n _result = res;\n }\n }), (function(err) {\n if (isAsync) _this.reject(err); else {\n rejected = !0;\n _error = err;\n }\n }));\n } catch (err) {\n endActive();\n this.reject(err);\n return;\n }\n endActive();\n isAsync = !0;\n resolved ? this.resolve(_result) : rejected && this.reject(_error);\n }\n }\n var _proto = ZalgoPromise.prototype;\n _proto.resolve = function(result) {\n if (this.resolved || this.rejected) return this;\n if (utils_isPromise(result)) throw new Error(\"Can not resolve promise with another promise\");\n this.resolved = !0;\n this.value = result;\n this.dispatch();\n return this;\n };\n _proto.reject = function(error) {\n var _this2 = this;\n if (this.resolved || this.rejected) return this;\n if (utils_isPromise(error)) throw new Error(\"Can not reject promise with another promise\");\n if (!error) {\n var _err = error && \"function\" == typeof error.toString ? error.toString() : {}.toString.call(error);\n error = new Error(\"Expected reject to be called with Error, got \" + _err);\n }\n this.rejected = !0;\n this.error = error;\n this.errorHandled || setTimeout((function() {\n _this2.errorHandled || function(err, promise) {\n if (-1 === dispatchedErrors.indexOf(err)) {\n dispatchedErrors.push(err);\n setTimeout((function() {\n throw err;\n }), 1);\n for (var j = 0; j < possiblyUnhandledPromiseHandlers.length; j++) possiblyUnhandledPromiseHandlers[j](err, promise);\n }\n }(error, _this2);\n }), 1);\n this.dispatch();\n return this;\n };\n _proto.asyncReject = function(error) {\n this.errorHandled = !0;\n this.reject(error);\n return this;\n };\n _proto.dispatch = function() {\n var resolved = this.resolved, rejected = this.rejected, handlers = this.handlers;\n if (!this.dispatching && (resolved || rejected)) {\n this.dispatching = !0;\n startActive();\n var chain = function(firstPromise, secondPromise) {\n return firstPromise.then((function(res) {\n secondPromise.resolve(res);\n }), (function(err) {\n secondPromise.reject(err);\n }));\n };\n for (var i = 0; i < handlers.length; i++) {\n var _handlers$i = handlers[i], onSuccess = _handlers$i.onSuccess, onError = _handlers$i.onError, promise = _handlers$i.promise;\n var _result2 = void 0;\n if (resolved) try {\n _result2 = onSuccess ? onSuccess(this.value) : this.value;\n } catch (err) {\n promise.reject(err);\n continue;\n } else if (rejected) {\n if (!onError) {\n promise.reject(this.error);\n continue;\n }\n try {\n _result2 = onError(this.error);\n } catch (err) {\n promise.reject(err);\n continue;\n }\n }\n if (_result2 instanceof ZalgoPromise && (_result2.resolved || _result2.rejected)) {\n var promiseResult = _result2;\n promiseResult.resolved ? promise.resolve(promiseResult.value) : promise.reject(promiseResult.error);\n promiseResult.errorHandled = !0;\n } else utils_isPromise(_result2) ? _result2 instanceof ZalgoPromise && (_result2.resolved || _result2.rejected) ? _result2.resolved ? promise.resolve(_result2.value) : promise.reject(_result2.error) : chain(_result2, promise) : promise.resolve(_result2);\n }\n handlers.length = 0;\n this.dispatching = !1;\n endActive();\n }\n };\n _proto.then = function(onSuccess, onError) {\n if (onSuccess && \"function\" != typeof onSuccess && !onSuccess.call) throw new Error(\"Promise.then expected a function for success handler\");\n if (onError && \"function\" != typeof onError && !onError.call) throw new Error(\"Promise.then expected a function for error handler\");\n var promise = new ZalgoPromise;\n this.handlers.push({\n promise: promise,\n onSuccess: onSuccess,\n onError: onError\n });\n this.errorHandled = !0;\n this.dispatch();\n return promise;\n };\n _proto.catch = function(onError) {\n return this.then(void 0, onError);\n };\n _proto.finally = function(onFinally) {\n if (onFinally && \"function\" != typeof onFinally && !onFinally.call) throw new Error(\"Promise.finally expected a function\");\n return this.then((function(result) {\n return ZalgoPromise.try(onFinally).then((function() {\n return result;\n }));\n }), (function(err) {\n return ZalgoPromise.try(onFinally).then((function() {\n throw err;\n }));\n }));\n };\n _proto.timeout = function(time, err) {\n var _this3 = this;\n if (this.resolved || this.rejected) return this;\n var timeout = setTimeout((function() {\n _this3.resolved || _this3.rejected || _this3.reject(err || new Error(\"Promise timed out after \" + time + \"ms\"));\n }), time);\n return this.then((function(result) {\n clearTimeout(timeout);\n return result;\n }));\n };\n _proto.toPromise = function() {\n if (\"undefined\" == typeof Promise) throw new TypeError(\"Could not find Promise\");\n return Promise.resolve(this);\n };\n ZalgoPromise.resolve = function(value) {\n return value instanceof ZalgoPromise ? value : utils_isPromise(value) ? new ZalgoPromise((function(resolve, reject) {\n return value.then(resolve, reject);\n })) : (new ZalgoPromise).resolve(value);\n };\n ZalgoPromise.reject = function(error) {\n return (new ZalgoPromise).reject(error);\n };\n ZalgoPromise.asyncReject = function(error) {\n return (new ZalgoPromise).asyncReject(error);\n };\n ZalgoPromise.all = function(promises) {\n var promise = new ZalgoPromise;\n var count = promises.length;\n var results = [].slice();\n if (!count) {\n promise.resolve(results);\n return promise;\n }\n var chain = function(i, firstPromise, secondPromise) {\n return firstPromise.then((function(res) {\n results[i] = res;\n 0 == (count -= 1) && promise.resolve(results);\n }), (function(err) {\n secondPromise.reject(err);\n }));\n };\n for (var i = 0; i < promises.length; i++) {\n var prom = promises[i];\n if (prom instanceof ZalgoPromise) {\n if (prom.resolved) {\n results[i] = prom.value;\n count -= 1;\n continue;\n }\n } else if (!utils_isPromise(prom)) {\n results[i] = prom;\n count -= 1;\n continue;\n }\n chain(i, ZalgoPromise.resolve(prom), promise);\n }\n 0 === count && promise.resolve(results);\n return promise;\n };\n ZalgoPromise.hash = function(promises) {\n var result = {};\n var awaitPromises = [];\n var _loop = function(key) {\n if (promises.hasOwnProperty(key)) {\n var value = promises[key];\n utils_isPromise(value) ? awaitPromises.push(value.then((function(res) {\n result[key] = res;\n }))) : result[key] = value;\n }\n };\n for (var key in promises) _loop(key);\n return ZalgoPromise.all(awaitPromises).then((function() {\n return result;\n }));\n };\n ZalgoPromise.map = function(items, method) {\n return ZalgoPromise.all(items.map(method));\n };\n ZalgoPromise.onPossiblyUnhandledException = function(handler) {\n return function(handler) {\n possiblyUnhandledPromiseHandlers.push(handler);\n return {\n cancel: function() {\n possiblyUnhandledPromiseHandlers.splice(possiblyUnhandledPromiseHandlers.indexOf(handler), 1);\n }\n };\n }(handler);\n };\n ZalgoPromise.try = function(method, context, args) {\n if (method && \"function\" != typeof method && !method.call) throw new Error(\"Promise.try expected a function\");\n var result;\n startActive();\n try {\n result = method.apply(context, args || []);\n } catch (err) {\n endActive();\n return ZalgoPromise.reject(err);\n }\n endActive();\n return ZalgoPromise.resolve(result);\n };\n ZalgoPromise.delay = function(_delay) {\n return new ZalgoPromise((function(resolve) {\n setTimeout(resolve, _delay);\n }));\n };\n ZalgoPromise.isPromise = function(value) {\n return !!(value && value instanceof ZalgoPromise) || utils_isPromise(value);\n };\n ZalgoPromise.flush = function() {\n return function(Zalgo) {\n var promise = flushPromise = flushPromise || new Zalgo;\n flushActive();\n return promise;\n }(ZalgoPromise);\n };\n return ZalgoPromise;\n }();\n function isRegex(item) {\n return \"[object RegExp]\" === {}.toString.call(item);\n }\n var WINDOW_TYPE = {\n IFRAME: \"iframe\",\n POPUP: \"popup\"\n };\n var IE_WIN_ACCESS_ERROR = \"Call was rejected by callee.\\r\\n\";\n function isAboutProtocol(win) {\n void 0 === win && (win = window);\n return \"about:\" === win.location.protocol;\n }\n function utils_getParent(win) {\n void 0 === win && (win = window);\n if (win) try {\n if (win.parent && win.parent !== win) return win.parent;\n } catch (err) {}\n }\n function getOpener(win) {\n void 0 === win && (win = window);\n if (win && !utils_getParent(win)) try {\n return win.opener;\n } catch (err) {}\n }\n function canReadFromWindow(win) {\n try {\n return !0;\n } catch (err) {}\n return !1;\n }\n function getActualDomain(win) {\n void 0 === win && (win = window);\n var location = win.location;\n if (!location) throw new Error(\"Can not read window location\");\n var protocol = location.protocol;\n if (!protocol) throw new Error(\"Can not read window protocol\");\n if (\"file:\" === protocol) return \"file://\";\n if (\"about:\" === protocol) {\n var parent = utils_getParent(win);\n return parent && canReadFromWindow() ? getActualDomain(parent) : \"about://\";\n }\n var host = location.host;\n if (!host) throw new Error(\"Can not read window host\");\n return protocol + \"//\" + host;\n }\n function getDomain(win) {\n void 0 === win && (win = window);\n var domain = getActualDomain(win);\n return domain && win.mockDomain && 0 === win.mockDomain.indexOf(\"mock:\") ? win.mockDomain : domain;\n }\n function isSameDomain(win) {\n if (!function(win) {\n try {\n if (win === window) return !0;\n } catch (err) {}\n try {\n var desc = Object.getOwnPropertyDescriptor(win, \"location\");\n if (desc && !1 === desc.enumerable) return !1;\n } catch (err) {}\n try {\n if (isAboutProtocol(win) && canReadFromWindow()) return !0;\n } catch (err) {}\n try {\n if (getActualDomain(win) === getActualDomain(window)) return !0;\n } catch (err) {}\n return !1;\n }(win)) return !1;\n try {\n if (win === window) return !0;\n if (isAboutProtocol(win) && canReadFromWindow()) return !0;\n if (getDomain(window) === getDomain(win)) return !0;\n } catch (err) {}\n return !1;\n }\n function assertSameDomain(win) {\n if (!isSameDomain(win)) throw new Error(\"Expected window to be same domain\");\n return win;\n }\n function isAncestorParent(parent, child) {\n if (!parent || !child) return !1;\n var childParent = utils_getParent(child);\n return childParent ? childParent === parent : -1 !== function(win) {\n var result = [];\n try {\n for (;win.parent !== win; ) {\n result.push(win.parent);\n win = win.parent;\n }\n } catch (err) {}\n return result;\n }(child).indexOf(parent);\n }\n function getFrames(win) {\n var result = [];\n var frames;\n try {\n frames = win.frames;\n } catch (err) {\n frames = win;\n }\n var len;\n try {\n len = frames.length;\n } catch (err) {}\n if (0 === len) return result;\n if (len) {\n for (var i = 0; i < len; i++) {\n var frame = void 0;\n try {\n frame = frames[i];\n } catch (err) {\n continue;\n }\n result.push(frame);\n }\n return result;\n }\n for (var _i = 0; _i < 100; _i++) {\n var _frame = void 0;\n try {\n _frame = frames[_i];\n } catch (err) {\n return result;\n }\n if (!_frame) return result;\n result.push(_frame);\n }\n return result;\n }\n function getAllChildFrames(win) {\n var result = [];\n for (var _i3 = 0, _getFrames2 = getFrames(win); _i3 < _getFrames2.length; _i3++) {\n var frame = _getFrames2[_i3];\n result.push(frame);\n for (var _i5 = 0, _getAllChildFrames2 = getAllChildFrames(frame); _i5 < _getAllChildFrames2.length; _i5++) result.push(_getAllChildFrames2[_i5]);\n }\n return result;\n }\n function getTop(win) {\n void 0 === win && (win = window);\n try {\n if (win.top) return win.top;\n } catch (err) {}\n if (utils_getParent(win) === win) return win;\n try {\n if (isAncestorParent(window, win) && window.top) return window.top;\n } catch (err) {}\n try {\n if (isAncestorParent(win, window) && window.top) return window.top;\n } catch (err) {}\n for (var _i7 = 0, _getAllChildFrames4 = getAllChildFrames(win); _i7 < _getAllChildFrames4.length; _i7++) {\n var frame = _getAllChildFrames4[_i7];\n try {\n if (frame.top) return frame.top;\n } catch (err) {}\n if (utils_getParent(frame) === frame) return frame;\n }\n }\n function getAllFramesInWindow(win) {\n var top = getTop(win);\n if (!top) throw new Error(\"Can not determine top window\");\n var result = [].concat(getAllChildFrames(top), [ top ]);\n -1 === result.indexOf(win) && (result = [].concat(result, [ win ], getAllChildFrames(win)));\n return result;\n }\n var iframeWindows = [];\n var iframeFrames = [];\n function isWindowClosed(win, allowMock) {\n void 0 === allowMock && (allowMock = !0);\n try {\n if (win === window) return !1;\n } catch (err) {\n return !0;\n }\n try {\n if (!win) return !0;\n } catch (err) {\n return !0;\n }\n try {\n if (win.closed) return !0;\n } catch (err) {\n return !err || err.message !== IE_WIN_ACCESS_ERROR;\n }\n if (allowMock && isSameDomain(win)) try {\n if (win.mockclosed) return !0;\n } catch (err) {}\n try {\n if (!win.parent || !win.top) return !0;\n } catch (err) {}\n var iframeIndex = function(collection, item) {\n for (var i = 0; i < collection.length; i++) try {\n if (collection[i] === item) return i;\n } catch (err) {}\n return -1;\n }(iframeWindows, win);\n if (-1 !== iframeIndex) {\n var frame = iframeFrames[iframeIndex];\n if (frame && function(frame) {\n if (!frame.contentWindow) return !0;\n if (!frame.parentNode) return !0;\n var doc = frame.ownerDocument;\n if (doc && doc.documentElement && !doc.documentElement.contains(frame)) {\n var parent = frame;\n for (;parent.parentNode && parent.parentNode !== parent; ) parent = parent.parentNode;\n if (!parent.host || !doc.documentElement.contains(parent.host)) return !0;\n }\n return !1;\n }(frame)) return !0;\n }\n return !1;\n }\n function getAncestor(win) {\n void 0 === win && (win = window);\n return getOpener(win = win || window) || utils_getParent(win) || void 0;\n }\n function anyMatch(collection1, collection2) {\n for (var _i17 = 0; _i17 < collection1.length; _i17++) {\n var item1 = collection1[_i17];\n for (var _i19 = 0; _i19 < collection2.length; _i19++) if (item1 === collection2[_i19]) return !0;\n }\n return !1;\n }\n function getDistanceFromTop(win) {\n void 0 === win && (win = window);\n var distance = 0;\n var parent = win;\n for (;parent; ) (parent = utils_getParent(parent)) && (distance += 1);\n return distance;\n }\n function isSameTopWindow(win1, win2) {\n var top1 = getTop(win1) || win1;\n var top2 = getTop(win2) || win2;\n try {\n if (top1 && top2) return top1 === top2;\n } catch (err) {}\n var allFrames1 = getAllFramesInWindow(win1);\n var allFrames2 = getAllFramesInWindow(win2);\n if (anyMatch(allFrames1, allFrames2)) return !0;\n var opener1 = getOpener(top1);\n var opener2 = getOpener(top2);\n return opener1 && anyMatch(getAllFramesInWindow(opener1), allFrames2) || opener2 && anyMatch(getAllFramesInWindow(opener2), allFrames1), \n !1;\n }\n function matchDomain(pattern, origin) {\n if (\"string\" == typeof pattern) {\n if (\"string\" == typeof origin) return \"*\" === pattern || origin === pattern;\n if (isRegex(origin)) return !1;\n if (Array.isArray(origin)) return !1;\n }\n return isRegex(pattern) ? isRegex(origin) ? pattern.toString() === origin.toString() : !Array.isArray(origin) && Boolean(origin.match(pattern)) : !!Array.isArray(pattern) && (Array.isArray(origin) ? JSON.stringify(pattern) === JSON.stringify(origin) : !isRegex(origin) && pattern.some((function(subpattern) {\n return matchDomain(subpattern, origin);\n })));\n }\n function getDomainFromUrl(url) {\n return url.match(/^(https?|mock|file):\\/\\//) ? url.split(\"/\").slice(0, 3).join(\"/\") : getDomain();\n }\n function onCloseWindow(win, callback, delay, maxtime) {\n void 0 === delay && (delay = 1e3);\n void 0 === maxtime && (maxtime = 1 / 0);\n var timeout;\n !function check() {\n if (isWindowClosed(win)) {\n timeout && clearTimeout(timeout);\n return callback();\n }\n if (maxtime <= 0) clearTimeout(timeout); else {\n maxtime -= delay;\n timeout = setTimeout(check, delay);\n }\n }();\n return {\n cancel: function() {\n timeout && clearTimeout(timeout);\n }\n };\n }\n function isWindow(obj) {\n try {\n if (obj === window) return !0;\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;\n }\n try {\n if (\"[object Window]\" === {}.toString.call(obj)) return !0;\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;\n }\n try {\n if (window.Window && obj instanceof window.Window) return !0;\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;\n }\n try {\n if (obj && obj.self === obj) return !0;\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;\n }\n try {\n if (obj && obj.parent === obj) return !0;\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;\n }\n try {\n if (obj && obj.top === obj) return !0;\n } catch (err) {\n if (err && err.message === IE_WIN_ACCESS_ERROR) return !0;\n }\n try {\n if (obj && \"__unlikely_value__\" === obj.__cross_domain_utils_window_check__) return !1;\n } catch (err) {\n return !0;\n }\n try {\n if (\"postMessage\" in obj && \"self\" in obj && \"location\" in obj) return !0;\n } catch (err) {}\n return !1;\n }\n function getFrameForWindow(win) {\n if (isSameDomain(win)) return assertSameDomain(win).frameElement;\n for (var _i21 = 0, _document$querySelect2 = document.querySelectorAll(\"iframe\"); _i21 < _document$querySelect2.length; _i21++) {\n var frame = _document$querySelect2[_i21];\n if (frame && frame.contentWindow && frame.contentWindow === win) return frame;\n }\n }\n function closeWindow(win) {\n if (function(win) {\n void 0 === win && (win = window);\n return Boolean(utils_getParent(win));\n }(win)) {\n var frame = getFrameForWindow(win);\n if (frame && frame.parentElement) {\n frame.parentElement.removeChild(frame);\n return;\n }\n }\n try {\n win.close();\n } catch (err) {}\n }\n function util_safeIndexOf(collection, item) {\n for (var i = 0; i < collection.length; i++) try {\n if (collection[i] === item) return i;\n } catch (err) {}\n return -1;\n }\n var weakmap_CrossDomainSafeWeakMap = function() {\n function CrossDomainSafeWeakMap() {\n this.name = void 0;\n this.weakmap = void 0;\n this.keys = void 0;\n this.values = void 0;\n this.name = \"__weakmap_\" + (1e9 * Math.random() >>> 0) + \"__\";\n if (function() {\n if (\"undefined\" == typeof WeakMap) return !1;\n if (void 0 === Object.freeze) return !1;\n try {\n var testWeakMap = new WeakMap;\n var testKey = {};\n Object.freeze(testKey);\n testWeakMap.set(testKey, \"__testvalue__\");\n return \"__testvalue__\" === testWeakMap.get(testKey);\n } catch (err) {\n return !1;\n }\n }()) try {\n this.weakmap = new WeakMap;\n } catch (err) {}\n this.keys = [];\n this.values = [];\n }\n var _proto = CrossDomainSafeWeakMap.prototype;\n _proto._cleanupClosedWindows = function() {\n var weakmap = this.weakmap;\n var keys = this.keys;\n for (var i = 0; i < keys.length; i++) {\n var value = keys[i];\n if (isWindow(value) && isWindowClosed(value)) {\n if (weakmap) try {\n weakmap.delete(value);\n } catch (err) {}\n keys.splice(i, 1);\n this.values.splice(i, 1);\n i -= 1;\n }\n }\n };\n _proto.isSafeToReadWrite = function(key) {\n return !isWindow(key);\n };\n _proto.set = function(key, value) {\n if (!key) throw new Error(\"WeakMap expected key\");\n var weakmap = this.weakmap;\n if (weakmap) try {\n weakmap.set(key, value);\n } catch (err) {\n delete this.weakmap;\n }\n if (this.isSafeToReadWrite(key)) try {\n var name = this.name;\n var entry = key[name];\n entry && entry[0] === key ? entry[1] = value : Object.defineProperty(key, name, {\n value: [ key, value ],\n writable: !0\n });\n return;\n } catch (err) {}\n this._cleanupClosedWindows();\n var keys = this.keys;\n var values = this.values;\n var index = util_safeIndexOf(keys, key);\n if (-1 === index) {\n keys.push(key);\n values.push(value);\n } else values[index] = value;\n };\n _proto.get = function(key) {\n if (!key) throw new Error(\"WeakMap expected key\");\n var weakmap = this.weakmap;\n if (weakmap) try {\n if (weakmap.has(key)) return weakmap.get(key);\n } catch (err) {\n delete this.weakmap;\n }\n if (this.isSafeToReadWrite(key)) try {\n var entry = key[this.name];\n return entry && entry[0] === key ? entry[1] : void 0;\n } catch (err) {}\n this._cleanupClosedWindows();\n var index = util_safeIndexOf(this.keys, key);\n if (-1 !== index) return this.values[index];\n };\n _proto.delete = function(key) {\n if (!key) throw new Error(\"WeakMap expected key\");\n var weakmap = this.weakmap;\n if (weakmap) try {\n weakmap.delete(key);\n } catch (err) {\n delete this.weakmap;\n }\n if (this.isSafeToReadWrite(key)) try {\n var entry = key[this.name];\n entry && entry[0] === key && (entry[0] = entry[1] = void 0);\n } catch (err) {}\n this._cleanupClosedWindows();\n var keys = this.keys;\n var index = util_safeIndexOf(keys, key);\n if (-1 !== index) {\n keys.splice(index, 1);\n this.values.splice(index, 1);\n }\n };\n _proto.has = function(key) {\n if (!key) throw new Error(\"WeakMap expected key\");\n var weakmap = this.weakmap;\n if (weakmap) try {\n if (weakmap.has(key)) return !0;\n } catch (err) {\n delete this.weakmap;\n }\n if (this.isSafeToReadWrite(key)) try {\n var entry = key[this.name];\n return !(!entry || entry[0] !== key);\n } catch (err) {}\n this._cleanupClosedWindows();\n return -1 !== util_safeIndexOf(this.keys, key);\n };\n _proto.getOrSet = function(key, getter) {\n if (this.has(key)) return this.get(key);\n var value = getter();\n this.set(key, value);\n return value;\n };\n return CrossDomainSafeWeakMap;\n }();\n function _getPrototypeOf(o) {\n return (_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n })(o);\n }\n function _isNativeReflectConstruct() {\n if (\"undefined\" == typeof Reflect || !Reflect.construct) return !1;\n if (Reflect.construct.sham) return !1;\n if (\"function\" == typeof Proxy) return !0;\n try {\n Date.prototype.toString.call(Reflect.construct(Date, [], (function() {})));\n return !0;\n } catch (e) {\n return !1;\n }\n }\n function construct_construct(Parent, args, Class) {\n return (construct_construct = _isNativeReflectConstruct() ? Reflect.construct : function(Parent, args, Class) {\n var a = [ null ];\n a.push.apply(a, args);\n var instance = new (Function.bind.apply(Parent, a));\n Class && _setPrototypeOf(instance, Class.prototype);\n return instance;\n }).apply(null, arguments);\n }\n function wrapNativeSuper_wrapNativeSuper(Class) {\n var _cache = \"function\" == typeof Map ? new Map : void 0;\n return (wrapNativeSuper_wrapNativeSuper = function(Class) {\n if (null === Class || !(fn = Class, -1 !== Function.toString.call(fn).indexOf(\"[native code]\"))) return Class;\n var fn;\n if (\"function\" != typeof Class) throw new TypeError(\"Super expression must either be null or a function\");\n if (void 0 !== _cache) {\n if (_cache.has(Class)) return _cache.get(Class);\n _cache.set(Class, Wrapper);\n }\n function Wrapper() {\n return construct_construct(Class, arguments, _getPrototypeOf(this).constructor);\n }\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: !1,\n writable: !0,\n configurable: !0\n }\n });\n return _setPrototypeOf(Wrapper, Class);\n })(Class);\n }\n function getFunctionName(fn) {\n return fn.name || fn.__name__ || fn.displayName || \"anonymous\";\n }\n function setFunctionName(fn, name) {\n try {\n delete fn.name;\n fn.name = name;\n } catch (err) {}\n fn.__name__ = fn.displayName = name;\n return fn;\n }\n function base64encode(str) {\n if (\"function\" == typeof btoa) return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (function(m, p1) {\n return String.fromCharCode(parseInt(p1, 16));\n }))).replace(/[=]/g, \"\");\n if (\"undefined\" != typeof Buffer) return Buffer.from(str, \"utf8\").toString(\"base64\").replace(/[=]/g, \"\");\n throw new Error(\"Can not find window.btoa or Buffer\");\n }\n function uniqueID() {\n var chars = \"0123456789abcdef\";\n return \"uid_\" + \"xxxxxxxxxx\".replace(/./g, (function() {\n return chars.charAt(Math.floor(Math.random() * chars.length));\n })) + \"_\" + base64encode((new Date).toISOString().slice(11, 19).replace(\"T\", \".\")).replace(/[^a-zA-Z0-9]/g, \"\").toLowerCase();\n }\n var objectIDs;\n function serializeArgs(args) {\n try {\n return JSON.stringify([].slice.call(args), (function(subkey, val) {\n return \"function\" == typeof val ? \"memoize[\" + function(obj) {\n objectIDs = objectIDs || new weakmap_CrossDomainSafeWeakMap;\n if (null == obj || \"object\" != typeof obj && \"function\" != typeof obj) throw new Error(\"Invalid object\");\n var uid = objectIDs.get(obj);\n if (!uid) {\n uid = typeof obj + \":\" + uniqueID();\n objectIDs.set(obj, uid);\n }\n return uid;\n }(val) + \"]\" : val;\n }));\n } catch (err) {\n throw new Error(\"Arguments not serializable -- can not be used to memoize\");\n }\n }\n function getEmptyObject() {\n return {};\n }\n var memoizeGlobalIndex = 0;\n var memoizeGlobalIndexValidFrom = 0;\n function memoize(method, options) {\n void 0 === options && (options = {});\n var _options$thisNamespac = options.thisNamespace, thisNamespace = void 0 !== _options$thisNamespac && _options$thisNamespac, cacheTime = options.time;\n var simpleCache;\n var thisCache;\n var memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n var memoizedFunction = function() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];\n if (memoizeIndex < memoizeGlobalIndexValidFrom) {\n simpleCache = null;\n thisCache = null;\n memoizeIndex = memoizeGlobalIndex;\n memoizeGlobalIndex += 1;\n }\n var cache;\n cache = thisNamespace ? (thisCache = thisCache || new weakmap_CrossDomainSafeWeakMap).getOrSet(this, getEmptyObject) : simpleCache = simpleCache || {};\n var cacheKey = serializeArgs(args);\n var cacheResult = cache[cacheKey];\n if (cacheResult && cacheTime && Date.now() - cacheResult.time < cacheTime) {\n delete cache[cacheKey];\n cacheResult = null;\n }\n if (cacheResult) return cacheResult.value;\n var time = Date.now();\n var value = method.apply(this, arguments);\n cache[cacheKey] = {\n time: time,\n value: value\n };\n return value;\n };\n memoizedFunction.reset = function() {\n simpleCache = null;\n thisCache = null;\n };\n return setFunctionName(memoizedFunction, (options.name || getFunctionName(method)) + \"::memoized\");\n }\n memoize.clear = function() {\n memoizeGlobalIndexValidFrom = memoizeGlobalIndex;\n };\n function memoizePromise(method) {\n var cache = {};\n function memoizedPromiseFunction() {\n var _arguments = arguments, _this = this;\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2];\n var key = serializeArgs(args);\n if (cache.hasOwnProperty(key)) return cache[key];\n cache[key] = promise_ZalgoPromise.try((function() {\n return method.apply(_this, _arguments);\n })).finally((function() {\n delete cache[key];\n }));\n return cache[key];\n }\n memoizedPromiseFunction.reset = function() {\n cache = {};\n };\n return setFunctionName(memoizedPromiseFunction, getFunctionName(method) + \"::promiseMemoized\");\n }\n function inlineMemoize(method, logic, args) {\n void 0 === args && (args = []);\n var cache = method.__inline_memoize_cache__ = method.__inline_memoize_cache__ || {};\n var key = serializeArgs(args);\n return cache.hasOwnProperty(key) ? cache[key] : cache[key] = logic.apply(void 0, args);\n }\n function src_util_noop() {}\n function once(method) {\n var called = !1;\n return setFunctionName((function() {\n if (!called) {\n called = !0;\n return method.apply(this, arguments);\n }\n }), getFunctionName(method) + \"::once\");\n }\n function stringifyError(err, level) {\n void 0 === level && (level = 1);\n if (level >= 3) return \"stringifyError stack overflow\";\n try {\n if (!err) return \"\";\n if (\"string\" == typeof err) return err;\n if (err instanceof Error) {\n var stack = err && err.stack;\n var message = err && err.message;\n if (stack && message) return -1 !== stack.indexOf(message) ? stack : message + \"\\n\" + stack;\n if (stack) return stack;\n if (message) return message;\n }\n return err && err.toString && \"function\" == typeof err.toString ? err.toString() : {}.toString.call(err);\n } catch (newErr) {\n return \"Error while stringifying error: \" + stringifyError(newErr, level + 1);\n }\n }\n function stringify(item) {\n return \"string\" == typeof item ? item : item && item.toString && \"function\" == typeof item.toString ? item.toString() : {}.toString.call(item);\n }\n function extend(obj, source) {\n if (!source) return obj;\n if (Object.assign) return Object.assign(obj, source);\n for (var key in source) source.hasOwnProperty(key) && (obj[key] = source[key]);\n return obj;\n }\n memoize((function(obj) {\n if (Object.values) return Object.values(obj);\n var result = [];\n for (var key in obj) obj.hasOwnProperty(key) && result.push(obj[key]);\n return result;\n }));\n function identity(item) {\n return item;\n }\n function safeInterval(method, time) {\n var timeout;\n !function loop() {\n timeout = setTimeout((function() {\n method();\n loop();\n }), time);\n }();\n return {\n cancel: function() {\n clearTimeout(timeout);\n }\n };\n }\n function arrayFrom(item) {\n return [].slice.call(item);\n }\n function isDefined(value) {\n return null != value;\n }\n function util_isRegex(item) {\n return \"[object RegExp]\" === {}.toString.call(item);\n }\n function util_getOrSet(obj, key, getter) {\n if (obj.hasOwnProperty(key)) return obj[key];\n var val = getter();\n obj[key] = val;\n return val;\n }\n function cleanup(obj) {\n var tasks = [];\n var cleaned = !1;\n var cleanErr;\n var cleaner = {\n set: function(name, item) {\n if (!cleaned) {\n obj[name] = item;\n cleaner.register((function() {\n delete obj[name];\n }));\n }\n return item;\n },\n register: function(method) {\n var task = once((function() {\n return method(cleanErr);\n }));\n cleaned ? method(cleanErr) : tasks.push(task);\n return {\n cancel: function() {\n var index = tasks.indexOf(task);\n -1 !== index && tasks.splice(index, 1);\n }\n };\n },\n all: function(err) {\n cleanErr = err;\n var results = [];\n cleaned = !0;\n for (;tasks.length; ) {\n var task = tasks.shift();\n results.push(task());\n }\n return promise_ZalgoPromise.all(results).then(src_util_noop);\n }\n };\n return cleaner;\n }\n function assertExists(name, thing) {\n if (null == thing) throw new Error(\"Expected \" + name + \" to be present\");\n return thing;\n }\n var util_ExtendableError = function(_Error) {\n _inheritsLoose(ExtendableError, _Error);\n function ExtendableError(message) {\n var _this6;\n (_this6 = _Error.call(this, message) || this).name = _this6.constructor.name;\n \"function\" == typeof Error.captureStackTrace ? Error.captureStackTrace(function(self) {\n if (void 0 === self) throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n return self;\n }(_this6), _this6.constructor) : _this6.stack = new Error(message).stack;\n return _this6;\n }\n return ExtendableError;\n }(wrapNativeSuper_wrapNativeSuper(Error));\n function getBody() {\n var body = document.body;\n if (!body) throw new Error(\"Body element not found\");\n return body;\n }\n function isDocumentReady() {\n return Boolean(document.body) && \"complete\" === document.readyState;\n }\n function isDocumentInteractive() {\n return Boolean(document.body) && \"interactive\" === document.readyState;\n }\n function urlEncode(str) {\n return encodeURIComponent(str);\n }\n memoize((function() {\n return new promise_ZalgoPromise((function(resolve) {\n if (isDocumentReady() || isDocumentInteractive()) return resolve();\n var interval = setInterval((function() {\n if (isDocumentReady() || isDocumentInteractive()) {\n clearInterval(interval);\n return resolve();\n }\n }), 10);\n }));\n }));\n function parseQuery(queryString) {\n return inlineMemoize(parseQuery, (function() {\n var params = {};\n if (!queryString) return params;\n if (-1 === queryString.indexOf(\"=\")) return params;\n for (var _i2 = 0, _queryString$split2 = queryString.split(\"&\"); _i2 < _queryString$split2.length; _i2++) {\n var pair = _queryString$split2[_i2];\n (pair = pair.split(\"=\"))[0] && pair[1] && (params[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]));\n }\n return params;\n }), [ queryString ]);\n }\n function extendQuery(originalQuery, props) {\n void 0 === props && (props = {});\n return props && Object.keys(props).length ? function(obj) {\n void 0 === obj && (obj = {});\n return Object.keys(obj).filter((function(key) {\n return \"string\" == typeof obj[key] || \"boolean\" == typeof obj[key];\n })).map((function(key) {\n var val = obj[key];\n if (\"string\" != typeof val && \"boolean\" != typeof val) throw new TypeError(\"Invalid type for query\");\n return urlEncode(key) + \"=\" + urlEncode(val.toString());\n })).join(\"&\");\n }(_extends({}, parseQuery(originalQuery), props)) : originalQuery;\n }\n function appendChild(container, child) {\n container.appendChild(child);\n }\n function isElement(element) {\n return element instanceof window.Element || null !== element && \"object\" == typeof element && 1 === element.nodeType && \"object\" == typeof element.style && \"object\" == typeof element.ownerDocument;\n }\n function getElementSafe(id, doc) {\n void 0 === doc && (doc = document);\n return isElement(id) ? id : \"string\" == typeof id ? doc.querySelector(id) : void 0;\n }\n function elementReady(id) {\n return new promise_ZalgoPromise((function(resolve, reject) {\n var name = stringify(id);\n var el = getElementSafe(id);\n if (el) return resolve(el);\n if (isDocumentReady()) return reject(new Error(\"Document is ready and element \" + name + \" does not exist\"));\n var interval = setInterval((function() {\n if (el = getElementSafe(id)) {\n resolve(el);\n clearInterval(interval);\n } else if (isDocumentReady()) {\n clearInterval(interval);\n return reject(new Error(\"Document is ready and element \" + name + \" does not exist\"));\n }\n }), 10);\n }));\n }\n var dom_PopupOpenError = function(_ExtendableError) {\n _inheritsLoose(PopupOpenError, _ExtendableError);\n function PopupOpenError() {\n return _ExtendableError.apply(this, arguments) || this;\n }\n return PopupOpenError;\n }(util_ExtendableError);\n var awaitFrameLoadPromises;\n function awaitFrameLoad(frame) {\n if ((awaitFrameLoadPromises = awaitFrameLoadPromises || new weakmap_CrossDomainSafeWeakMap).has(frame)) {\n var _promise = awaitFrameLoadPromises.get(frame);\n if (_promise) return _promise;\n }\n var promise = new promise_ZalgoPromise((function(resolve, reject) {\n frame.addEventListener(\"load\", (function() {\n !function(frame) {\n !function() {\n for (var i = 0; i < iframeWindows.length; i++) {\n var closed = !1;\n try {\n closed = iframeWindows[i].closed;\n } catch (err) {}\n if (closed) {\n iframeFrames.splice(i, 1);\n iframeWindows.splice(i, 1);\n }\n }\n }();\n if (frame && frame.contentWindow) try {\n iframeWindows.push(frame.contentWindow);\n iframeFrames.push(frame);\n } catch (err) {}\n }(frame);\n resolve(frame);\n }));\n frame.addEventListener(\"error\", (function(err) {\n frame.contentWindow ? resolve(frame) : reject(err);\n }));\n }));\n awaitFrameLoadPromises.set(frame, promise);\n return promise;\n }\n function awaitFrameWindow(frame) {\n return awaitFrameLoad(frame).then((function(loadedFrame) {\n if (!loadedFrame.contentWindow) throw new Error(\"Could not find window in iframe\");\n return loadedFrame.contentWindow;\n }));\n }\n function dom_iframe(options, container) {\n void 0 === options && (options = {});\n var style = options.style || {};\n var frame = function(tag, options, container) {\n void 0 === tag && (tag = \"div\");\n void 0 === options && (options = {});\n tag = tag.toLowerCase();\n var element = document.createElement(tag);\n options.style && extend(element.style, options.style);\n options.class && (element.className = options.class.join(\" \"));\n options.id && element.setAttribute(\"id\", options.id);\n if (options.attributes) for (var _i10 = 0, _Object$keys2 = Object.keys(options.attributes); _i10 < _Object$keys2.length; _i10++) {\n var key = _Object$keys2[_i10];\n element.setAttribute(key, options.attributes[key]);\n }\n options.styleSheet && function(el, styleText, doc) {\n void 0 === doc && (doc = window.document);\n el.styleSheet ? el.styleSheet.cssText = styleText : el.appendChild(doc.createTextNode(styleText));\n }(element, options.styleSheet);\n if (options.html) {\n if (\"iframe\" === tag) throw new Error(\"Iframe html can not be written unless container provided and iframe in DOM\");\n element.innerHTML = options.html;\n }\n return element;\n }(\"iframe\", {\n attributes: _extends({\n allowTransparency: \"true\"\n }, options.attributes || {}),\n style: _extends({\n backgroundColor: \"transparent\",\n border: \"none\"\n }, style),\n html: options.html,\n class: options.class\n });\n var isIE = window.navigator.userAgent.match(/MSIE|Edge/i);\n frame.hasAttribute(\"id\") || frame.setAttribute(\"id\", uniqueID());\n awaitFrameLoad(frame);\n container && function(id, doc) {\n void 0 === doc && (doc = document);\n var element = getElementSafe(id, doc);\n if (element) return element;\n throw new Error(\"Can not find element: \" + stringify(id));\n }(container).appendChild(frame);\n (options.url || isIE) && frame.setAttribute(\"src\", options.url || \"about:blank\");\n return frame;\n }\n function addEventListener(obj, event, handler) {\n obj.addEventListener(event, handler);\n return {\n cancel: function() {\n obj.removeEventListener(event, handler);\n }\n };\n }\n function showElement(element) {\n element.style.setProperty(\"display\", \"\");\n }\n function hideElement(element) {\n element.style.setProperty(\"display\", \"none\", \"important\");\n }\n function destroyElement(element) {\n element && element.parentNode && element.parentNode.removeChild(element);\n }\n function isElementClosed(el) {\n return !(el && el.parentNode && el.ownerDocument && el.ownerDocument.documentElement && el.ownerDocument.documentElement.contains(el));\n }\n function onResize(el, handler, _temp) {\n var _ref2 = void 0 === _temp ? {} : _temp, _ref2$width = _ref2.width, width = void 0 === _ref2$width || _ref2$width, _ref2$height = _ref2.height, height = void 0 === _ref2$height || _ref2$height, _ref2$interval = _ref2.interval, interval = void 0 === _ref2$interval ? 100 : _ref2$interval, _ref2$win = _ref2.win, win = void 0 === _ref2$win ? window : _ref2$win;\n var currentWidth = el.offsetWidth;\n var currentHeight = el.offsetHeight;\n var canceled = !1;\n handler({\n width: currentWidth,\n height: currentHeight\n });\n var check = function() {\n if (!canceled && function(el) {\n return Boolean(el.offsetWidth || el.offsetHeight || el.getClientRects().length);\n }(el)) {\n var newWidth = el.offsetWidth;\n var newHeight = el.offsetHeight;\n (width && newWidth !== currentWidth || height && newHeight !== currentHeight) && handler({\n width: newWidth,\n height: newHeight\n });\n currentWidth = newWidth;\n currentHeight = newHeight;\n }\n };\n var observer;\n var timeout;\n win.addEventListener(\"resize\", check);\n if (void 0 !== win.ResizeObserver) {\n (observer = new win.ResizeObserver(check)).observe(el);\n timeout = safeInterval(check, 10 * interval);\n } else if (void 0 !== win.MutationObserver) {\n (observer = new win.MutationObserver(check)).observe(el, {\n attributes: !0,\n childList: !0,\n subtree: !0,\n characterData: !1\n });\n timeout = safeInterval(check, 10 * interval);\n } else timeout = safeInterval(check, interval);\n return {\n cancel: function() {\n canceled = !0;\n observer.disconnect();\n window.removeEventListener(\"resize\", check);\n timeout.cancel();\n }\n };\n }\n function isShadowElement(element) {\n for (;element.parentNode; ) element = element.parentNode;\n return \"[object ShadowRoot]\" === element.toString();\n }\n var currentScript = \"undefined\" != typeof document ? document.currentScript : null;\n var getCurrentScript = memoize((function() {\n if (currentScript) return currentScript;\n if (currentScript = function() {\n try {\n var stack = function() {\n try {\n throw new Error(\"_\");\n } catch (err) {\n return err.stack || \"\";\n }\n }();\n var stackDetails = /.*at [^(]*\\((.*):(.+):(.+)\\)$/gi.exec(stack);\n var scriptLocation = stackDetails && stackDetails[1];\n if (!scriptLocation) return;\n for (var _i22 = 0, _Array$prototype$slic2 = [].slice.call(document.getElementsByTagName(\"script\")).reverse(); _i22 < _Array$prototype$slic2.length; _i22++) {\n var script = _Array$prototype$slic2[_i22];\n if (script.src && script.src === scriptLocation) return script;\n }\n } catch (err) {}\n }()) return currentScript;\n throw new Error(\"Can not determine current script\");\n }));\n var currentUID = uniqueID();\n memoize((function() {\n var script;\n try {\n script = getCurrentScript();\n } catch (err) {\n return currentUID;\n }\n var uid = script.getAttribute(\"data-uid\");\n if (uid && \"string\" == typeof uid) return uid;\n if ((uid = script.getAttribute(\"data-uid-auto\")) && \"string\" == typeof uid) return uid;\n if (script.src) {\n var hashedString = function(str) {\n var hash = \"\";\n for (var i = 0; i < str.length; i++) {\n var total = str[i].charCodeAt(0) * i;\n str[i + 1] && (total += str[i + 1].charCodeAt(0) * (i - 1));\n hash += String.fromCharCode(97 + Math.abs(total) % 26);\n }\n return hash;\n }(JSON.stringify({\n src: script.src,\n dataset: script.dataset\n }));\n uid = \"uid_\" + hashedString.slice(hashedString.length - 30);\n } else uid = uniqueID();\n script.setAttribute(\"data-uid-auto\", uid);\n return uid;\n }));\n function toPx(val) {\n return function(val) {\n if (\"number\" == typeof val) return val;\n var match = val.match(/^([0-9]+)(px|%)$/);\n if (!match) throw new Error(\"Could not match css value from \" + val);\n return parseInt(match[1], 10);\n }(val) + \"px\";\n }\n function toCSS(val) {\n return \"number\" == typeof val ? toPx(val) : \"string\" == typeof (str = val) && /^[0-9]+%$/.test(str) ? val : toPx(val);\n var str;\n }\n function global_getGlobal(win) {\n void 0 === win && (win = window);\n var globalKey = \"__post_robot_10_0_44__\";\n return win !== window ? win[globalKey] : win[globalKey] = win[globalKey] || {};\n }\n var getObj = function() {\n return {};\n };\n function globalStore(key, defStore) {\n void 0 === key && (key = \"store\");\n void 0 === defStore && (defStore = getObj);\n return util_getOrSet(global_getGlobal(), key, (function() {\n var store = defStore();\n return {\n has: function(storeKey) {\n return store.hasOwnProperty(storeKey);\n },\n get: function(storeKey, defVal) {\n return store.hasOwnProperty(storeKey) ? store[storeKey] : defVal;\n },\n set: function(storeKey, val) {\n store[storeKey] = val;\n return val;\n },\n del: function(storeKey) {\n delete store[storeKey];\n },\n getOrSet: function(storeKey, getter) {\n return util_getOrSet(store, storeKey, getter);\n },\n reset: function() {\n store = defStore();\n },\n keys: function() {\n return Object.keys(store);\n }\n };\n }));\n }\n var WildCard = function() {};\n function getWildcard() {\n var global = global_getGlobal();\n global.WINDOW_WILDCARD = global.WINDOW_WILDCARD || new WildCard;\n return global.WINDOW_WILDCARD;\n }\n function windowStore(key, defStore) {\n void 0 === key && (key = \"store\");\n void 0 === defStore && (defStore = getObj);\n return globalStore(\"windowStore\").getOrSet(key, (function() {\n var winStore = new weakmap_CrossDomainSafeWeakMap;\n var getStore = function(win) {\n return winStore.getOrSet(win, defStore);\n };\n return {\n has: function(win) {\n return getStore(win).hasOwnProperty(key);\n },\n get: function(win, defVal) {\n var store = getStore(win);\n return store.hasOwnProperty(key) ? store[key] : defVal;\n },\n set: function(win, val) {\n getStore(win)[key] = val;\n return val;\n },\n del: function(win) {\n delete getStore(win)[key];\n },\n getOrSet: function(win, getter) {\n return util_getOrSet(getStore(win), key, getter);\n }\n };\n }));\n }\n function getInstanceID() {\n return globalStore(\"instance\").getOrSet(\"instanceID\", uniqueID);\n }\n function resolveHelloPromise(win, _ref) {\n var domain = _ref.domain;\n var helloPromises = windowStore(\"helloPromises\");\n var existingPromise = helloPromises.get(win);\n existingPromise && existingPromise.resolve({\n domain: domain\n });\n var newPromise = promise_ZalgoPromise.resolve({\n domain: domain\n });\n helloPromises.set(win, newPromise);\n return newPromise;\n }\n function sayHello(win, _ref4) {\n return (0, _ref4.send)(win, \"postrobot_hello\", {\n instanceID: getInstanceID()\n }, {\n domain: \"*\",\n timeout: -1\n }).then((function(_ref5) {\n var origin = _ref5.origin, instanceID = _ref5.data.instanceID;\n resolveHelloPromise(win, {\n domain: origin\n });\n return {\n win: win,\n domain: origin,\n instanceID: instanceID\n };\n }));\n }\n function getWindowInstanceID(win, _ref6) {\n var send = _ref6.send;\n return windowStore(\"windowInstanceIDPromises\").getOrSet(win, (function() {\n return sayHello(win, {\n send: send\n }).then((function(_ref7) {\n return _ref7.instanceID;\n }));\n }));\n }\n function markWindowKnown(win) {\n windowStore(\"knownWindows\").set(win, !0);\n }\n function isSerializedType(item) {\n return \"object\" == typeof item && null !== item && \"string\" == typeof item.__type__;\n }\n function determineType(val) {\n return void 0 === val ? \"undefined\" : null === val ? \"null\" : Array.isArray(val) ? \"array\" : \"function\" == typeof val ? \"function\" : \"object\" == typeof val ? val instanceof Error ? \"error\" : \"function\" == typeof val.then ? \"promise\" : \"[object RegExp]\" === {}.toString.call(val) ? \"regex\" : \"[object Date]\" === {}.toString.call(val) ? \"date\" : \"object\" : \"string\" == typeof val ? \"string\" : \"number\" == typeof val ? \"number\" : \"boolean\" == typeof val ? \"boolean\" : void 0;\n }\n function serializeType(type, val) {\n return {\n __type__: type,\n __val__: val\n };\n }\n var _SERIALIZER;\n var SERIALIZER = ((_SERIALIZER = {}).function = function() {}, _SERIALIZER.error = function(_ref) {\n return serializeType(\"error\", {\n message: _ref.message,\n stack: _ref.stack,\n code: _ref.code,\n data: _ref.data\n });\n }, _SERIALIZER.promise = function() {}, _SERIALIZER.regex = function(val) {\n return serializeType(\"regex\", val.source);\n }, _SERIALIZER.date = function(val) {\n return serializeType(\"date\", val.toJSON());\n }, _SERIALIZER.array = function(val) {\n return val;\n }, _SERIALIZER.object = function(val) {\n return val;\n }, _SERIALIZER.string = function(val) {\n return val;\n }, _SERIALIZER.number = function(val) {\n return val;\n }, _SERIALIZER.boolean = function(val) {\n return val;\n }, _SERIALIZER.null = function(val) {\n return val;\n }, _SERIALIZER[void 0] = function(val) {\n return serializeType(\"undefined\", val);\n }, _SERIALIZER);\n var defaultSerializers = {};\n var _DESERIALIZER;\n var DESERIALIZER = ((_DESERIALIZER = {}).function = function() {\n throw new Error(\"Function serialization is not implemented; nothing to deserialize\");\n }, _DESERIALIZER.error = function(_ref2) {\n var stack = _ref2.stack, code = _ref2.code, data = _ref2.data;\n var error = new Error(_ref2.message);\n error.code = code;\n data && (error.data = data);\n error.stack = stack + \"\\n\\n\" + error.stack;\n return error;\n }, _DESERIALIZER.promise = function() {\n throw new Error(\"Promise serialization is not implemented; nothing to deserialize\");\n }, _DESERIALIZER.regex = function(val) {\n return new RegExp(val);\n }, _DESERIALIZER.date = function(val) {\n return new Date(val);\n }, _DESERIALIZER.array = function(val) {\n return val;\n }, _DESERIALIZER.object = function(val) {\n return val;\n }, _DESERIALIZER.string = function(val) {\n return val;\n }, _DESERIALIZER.number = function(val) {\n return val;\n }, _DESERIALIZER.boolean = function(val) {\n return val;\n }, _DESERIALIZER.null = function(val) {\n return val;\n }, _DESERIALIZER[void 0] = function() {}, _DESERIALIZER);\n var defaultDeserializers = {};\n new promise_ZalgoPromise((function(resolve) {\n if (window.document && window.document.body) return resolve(window.document.body);\n var interval = setInterval((function() {\n if (window.document && window.document.body) {\n clearInterval(interval);\n return resolve(window.document.body);\n }\n }), 10);\n }));\n function cleanupProxyWindows() {\n var idToProxyWindow = globalStore(\"idToProxyWindow\");\n for (var _i2 = 0, _idToProxyWindow$keys2 = idToProxyWindow.keys(); _i2 < _idToProxyWindow$keys2.length; _i2++) {\n var id = _idToProxyWindow$keys2[_i2];\n idToProxyWindow.get(id).shouldClean() && idToProxyWindow.del(id);\n }\n }\n function getSerializedWindow(winPromise, _ref) {\n var send = _ref.send, _ref$id = _ref.id, id = void 0 === _ref$id ? uniqueID() : _ref$id;\n var windowNamePromise = winPromise.then((function(win) {\n if (isSameDomain(win)) return assertSameDomain(win).name;\n }));\n var windowTypePromise = winPromise.then((function(window) {\n if (isWindowClosed(window)) throw new Error(\"Window is closed, can not determine type\");\n return getOpener(window) ? WINDOW_TYPE.POPUP : WINDOW_TYPE.IFRAME;\n }));\n windowNamePromise.catch(src_util_noop);\n windowTypePromise.catch(src_util_noop);\n var getName = function() {\n return winPromise.then((function(win) {\n if (!isWindowClosed(win)) return isSameDomain(win) ? assertSameDomain(win).name : windowNamePromise;\n }));\n };\n return {\n id: id,\n getType: function() {\n return windowTypePromise;\n },\n getInstanceID: memoizePromise((function() {\n return winPromise.then((function(win) {\n return getWindowInstanceID(win, {\n send: send\n });\n }));\n })),\n close: function() {\n return winPromise.then(closeWindow);\n },\n getName: getName,\n focus: function() {\n return winPromise.then((function(win) {\n win.focus();\n }));\n },\n isClosed: function() {\n return winPromise.then((function(win) {\n return isWindowClosed(win);\n }));\n },\n setLocation: function(href, opts) {\n void 0 === opts && (opts = {});\n return winPromise.then((function(win) {\n var domain = window.location.protocol + \"//\" + window.location.host;\n var _opts$method = opts.method, method = void 0 === _opts$method ? \"get\" : _opts$method, body = opts.body;\n if (0 === href.indexOf(\"/\")) href = \"\" + domain + href; else if (!href.match(/^https?:\\/\\//) && 0 !== href.indexOf(domain)) throw new Error(\"Expected url to be http or https url, or absolute path, got \" + JSON.stringify(href));\n if (\"post\" === method) return getName().then((function(name) {\n if (!name) throw new Error(\"Can not post to window without target name\");\n !function(_ref3) {\n var url = _ref3.url, target = _ref3.target, body = _ref3.body, _ref3$method = _ref3.method, method = void 0 === _ref3$method ? \"post\" : _ref3$method;\n var form = document.createElement(\"form\");\n form.setAttribute(\"target\", target);\n form.setAttribute(\"method\", method);\n form.setAttribute(\"action\", url);\n form.style.display = \"none\";\n if (body) for (var _i24 = 0, _Object$keys4 = Object.keys(body); _i24 < _Object$keys4.length; _i24++) {\n var _body$key;\n var key = _Object$keys4[_i24];\n var input = document.createElement(\"input\");\n input.setAttribute(\"name\", key);\n input.setAttribute(\"value\", null == (_body$key = body[key]) ? void 0 : _body$key.toString());\n form.appendChild(input);\n }\n getBody().appendChild(form);\n form.submit();\n getBody().removeChild(form);\n }({\n url: href,\n target: name,\n method: method,\n body: body\n });\n }));\n if (\"get\" !== method) throw new Error(\"Unsupported method: \" + method);\n if (isSameDomain(win)) try {\n if (win.location && \"function\" == typeof win.location.replace) {\n win.location.replace(href);\n return;\n }\n } catch (err) {}\n win.location = href;\n }));\n },\n setName: function(name) {\n return winPromise.then((function(win) {\n var sameDomain = isSameDomain(win);\n var frame = getFrameForWindow(win);\n if (!sameDomain) throw new Error(\"Can not set name for cross-domain window: \" + name);\n assertSameDomain(win).name = name;\n frame && frame.setAttribute(\"name\", name);\n windowNamePromise = promise_ZalgoPromise.resolve(name);\n }));\n }\n };\n }\n var window_ProxyWindow = function() {\n function ProxyWindow(_ref2) {\n var send = _ref2.send, win = _ref2.win, serializedWindow = _ref2.serializedWindow;\n this.id = void 0;\n this.isProxyWindow = !0;\n this.serializedWindow = void 0;\n this.actualWindow = void 0;\n this.actualWindowPromise = void 0;\n this.send = void 0;\n this.name = void 0;\n this.actualWindowPromise = new promise_ZalgoPromise;\n this.serializedWindow = serializedWindow || getSerializedWindow(this.actualWindowPromise, {\n send: send\n });\n globalStore(\"idToProxyWindow\").set(this.getID(), this);\n win && this.setWindow(win, {\n send: send\n });\n }\n var _proto = ProxyWindow.prototype;\n _proto.getID = function() {\n return this.serializedWindow.id;\n };\n _proto.getType = function() {\n return this.serializedWindow.getType();\n };\n _proto.isPopup = function() {\n return this.getType().then((function(type) {\n return type === WINDOW_TYPE.POPUP;\n }));\n };\n _proto.setLocation = function(href, opts) {\n var _this = this;\n return this.serializedWindow.setLocation(href, opts).then((function() {\n return _this;\n }));\n };\n _proto.getName = function() {\n return this.serializedWindow.getName();\n };\n _proto.setName = function(name) {\n var _this2 = this;\n return this.serializedWindow.setName(name).then((function() {\n return _this2;\n }));\n };\n _proto.close = function() {\n var _this3 = this;\n return this.serializedWindow.close().then((function() {\n return _this3;\n }));\n };\n _proto.focus = function() {\n var _this4 = this;\n var isPopupPromise = this.isPopup();\n var getNamePromise = this.getName();\n var reopenPromise = promise_ZalgoPromise.hash({\n isPopup: isPopupPromise,\n name: getNamePromise\n }).then((function(_ref3) {\n var name = _ref3.name;\n _ref3.isPopup && name && window.open(\"\", name);\n }));\n var focusPromise = this.serializedWindow.focus();\n return promise_ZalgoPromise.all([ reopenPromise, focusPromise ]).then((function() {\n return _this4;\n }));\n };\n _proto.isClosed = function() {\n return this.serializedWindow.isClosed();\n };\n _proto.getWindow = function() {\n return this.actualWindow;\n };\n _proto.setWindow = function(win, _ref4) {\n var send = _ref4.send;\n this.actualWindow = win;\n this.actualWindowPromise.resolve(this.actualWindow);\n this.serializedWindow = getSerializedWindow(this.actualWindowPromise, {\n send: send,\n id: this.getID()\n });\n windowStore(\"winToProxyWindow\").set(win, this);\n };\n _proto.awaitWindow = function() {\n return this.actualWindowPromise;\n };\n _proto.matchWindow = function(win, _ref5) {\n var _this5 = this;\n var send = _ref5.send;\n return promise_ZalgoPromise.try((function() {\n return _this5.actualWindow ? win === _this5.actualWindow : promise_ZalgoPromise.hash({\n proxyInstanceID: _this5.getInstanceID(),\n knownWindowInstanceID: getWindowInstanceID(win, {\n send: send\n })\n }).then((function(_ref6) {\n var match = _ref6.proxyInstanceID === _ref6.knownWindowInstanceID;\n match && _this5.setWindow(win, {\n send: send\n });\n return match;\n }));\n }));\n };\n _proto.unwrap = function() {\n return this.actualWindow || this;\n };\n _proto.getInstanceID = function() {\n return this.serializedWindow.getInstanceID();\n };\n _proto.shouldClean = function() {\n return Boolean(this.actualWindow && isWindowClosed(this.actualWindow));\n };\n _proto.serialize = function() {\n return this.serializedWindow;\n };\n ProxyWindow.unwrap = function(win) {\n return ProxyWindow.isProxyWindow(win) ? win.unwrap() : win;\n };\n ProxyWindow.serialize = function(win, _ref7) {\n var send = _ref7.send;\n cleanupProxyWindows();\n return ProxyWindow.toProxyWindow(win, {\n send: send\n }).serialize();\n };\n ProxyWindow.deserialize = function(serializedWindow, _ref8) {\n var send = _ref8.send;\n cleanupProxyWindows();\n return globalStore(\"idToProxyWindow\").get(serializedWindow.id) || new ProxyWindow({\n serializedWindow: serializedWindow,\n send: send\n });\n };\n ProxyWindow.isProxyWindow = function(obj) {\n return Boolean(obj && !isWindow(obj) && obj.isProxyWindow);\n };\n ProxyWindow.toProxyWindow = function(win, _ref9) {\n var send = _ref9.send;\n cleanupProxyWindows();\n if (ProxyWindow.isProxyWindow(win)) return win;\n var actualWindow = win;\n return windowStore(\"winToProxyWindow\").get(actualWindow) || new ProxyWindow({\n win: actualWindow,\n send: send\n });\n };\n return ProxyWindow;\n }();\n function addMethod(id, val, name, source, domain) {\n var methodStore = windowStore(\"methodStore\");\n var proxyWindowMethods = globalStore(\"proxyWindowMethods\");\n if (window_ProxyWindow.isProxyWindow(source)) proxyWindowMethods.set(id, {\n val: val,\n name: name,\n domain: domain,\n source: source\n }); else {\n proxyWindowMethods.del(id);\n methodStore.getOrSet(source, (function() {\n return {};\n }))[id] = {\n domain: domain,\n name: name,\n val: val,\n source: source\n };\n }\n }\n function lookupMethod(source, id) {\n var methodStore = windowStore(\"methodStore\");\n var proxyWindowMethods = globalStore(\"proxyWindowMethods\");\n return methodStore.getOrSet(source, (function() {\n return {};\n }))[id] || proxyWindowMethods.get(id);\n }\n function function_serializeFunction(destination, domain, val, key, _ref3) {\n on = (_ref = {\n on: _ref3.on,\n send: _ref3.send\n }).on, send = _ref.send, globalStore(\"builtinListeners\").getOrSet(\"functionCalls\", (function() {\n return on(\"postrobot_method\", {\n domain: \"*\"\n }, (function(_ref2) {\n var source = _ref2.source, origin = _ref2.origin, data = _ref2.data;\n var id = data.id, name = data.name;\n var meth = lookupMethod(source, id);\n if (!meth) throw new Error(\"Could not find method '\" + name + \"' with id: \" + data.id + \" in \" + getDomain(window));\n var methodSource = meth.source, domain = meth.domain, val = meth.val;\n return promise_ZalgoPromise.try((function() {\n if (!matchDomain(domain, origin)) throw new Error(\"Method '\" + data.name + \"' domain \" + JSON.stringify(util_isRegex(meth.domain) ? meth.domain.source : meth.domain) + \" does not match origin \" + origin + \" in \" + getDomain(window));\n if (window_ProxyWindow.isProxyWindow(methodSource)) return methodSource.matchWindow(source, {\n send: send\n }).then((function(match) {\n if (!match) throw new Error(\"Method call '\" + data.name + \"' failed - proxy window does not match source in \" + getDomain(window));\n }));\n })).then((function() {\n return val.apply({\n source: source,\n origin: origin\n }, data.args);\n }), (function(err) {\n return promise_ZalgoPromise.try((function() {\n if (val.onError) return val.onError(err);\n })).then((function() {\n err.stack && (err.stack = \"Remote call to \" + name + \"(\" + function(args) {\n void 0 === args && (args = []);\n return arrayFrom(args).map((function(arg) {\n return \"string\" == typeof arg ? \"'\" + arg + \"'\" : void 0 === arg ? \"undefined\" : null === arg ? \"null\" : \"boolean\" == typeof arg ? arg.toString() : Array.isArray(arg) ? \"[ ... ]\" : \"object\" == typeof arg ? \"{ ... }\" : \"function\" == typeof arg ? \"() => { ... }\" : \"<\" + typeof arg + \">\";\n })).join(\", \");\n }(data.args) + \") failed\\n\\n\" + err.stack);\n throw err;\n }));\n })).then((function(result) {\n return {\n result: result,\n id: id,\n name: name\n };\n }));\n }));\n }));\n var _ref, on, send;\n var id = val.__id__ || uniqueID();\n destination = window_ProxyWindow.unwrap(destination);\n var name = val.__name__ || val.name || key;\n \"string\" == typeof name && \"function\" == typeof name.indexOf && 0 === name.indexOf(\"anonymous::\") && (name = name.replace(\"anonymous::\", key + \"::\"));\n if (window_ProxyWindow.isProxyWindow(destination)) {\n addMethod(id, val, name, destination, domain);\n destination.awaitWindow().then((function(win) {\n addMethod(id, val, name, win, domain);\n }));\n } else addMethod(id, val, name, destination, domain);\n return serializeType(\"cross_domain_function\", {\n id: id,\n name: name\n });\n }\n function serializeMessage(destination, domain, obj, _ref) {\n var _serialize;\n var on = _ref.on, send = _ref.send;\n return function(obj, serializers) {\n void 0 === serializers && (serializers = defaultSerializers);\n var result = JSON.stringify(obj, (function(key) {\n var val = this[key];\n if (isSerializedType(this)) return val;\n var type = determineType(val);\n if (!type) return val;\n var serializer = serializers[type] || SERIALIZER[type];\n return serializer ? serializer(val, key) : val;\n }));\n return void 0 === result ? \"undefined\" : result;\n }(obj, ((_serialize = {}).promise = function(val, key) {\n return function(destination, domain, val, key, _ref) {\n return serializeType(\"cross_domain_zalgo_promise\", {\n then: function_serializeFunction(destination, domain, (function(resolve, reject) {\n return val.then(resolve, reject);\n }), key, {\n on: _ref.on,\n send: _ref.send\n })\n });\n }(destination, domain, val, key, {\n on: on,\n send: send\n });\n }, _serialize.function = function(val, key) {\n return function_serializeFunction(destination, domain, val, key, {\n on: on,\n send: send\n });\n }, _serialize.object = function(val) {\n return isWindow(val) || window_ProxyWindow.isProxyWindow(val) ? serializeType(\"cross_domain_window\", window_ProxyWindow.serialize(val, {\n send: send\n })) : val;\n }, _serialize));\n }\n function deserializeMessage(source, origin, message, _ref2) {\n var _deserialize;\n var send = _ref2.send;\n return function(str, deserializers) {\n void 0 === deserializers && (deserializers = defaultDeserializers);\n if (\"undefined\" !== str) return JSON.parse(str, (function(key, val) {\n if (isSerializedType(this)) return val;\n var type;\n var value;\n if (isSerializedType(val)) {\n type = val.__type__;\n value = val.__val__;\n } else {\n type = determineType(val);\n value = val;\n }\n if (!type) return value;\n var deserializer = deserializers[type] || DESERIALIZER[type];\n return deserializer ? deserializer(value, key) : value;\n }));\n }(message, ((_deserialize = {}).cross_domain_zalgo_promise = function(serializedPromise) {\n return function(source, origin, _ref2) {\n return new promise_ZalgoPromise(_ref2.then);\n }(0, 0, serializedPromise);\n }, _deserialize.cross_domain_function = function(serializedFunction) {\n return function(source, origin, _ref4, _ref5) {\n var id = _ref4.id, name = _ref4.name;\n var send = _ref5.send;\n var getDeserializedFunction = function(opts) {\n void 0 === opts && (opts = {});\n function crossDomainFunctionWrapper() {\n var _arguments = arguments;\n return window_ProxyWindow.toProxyWindow(source, {\n send: send\n }).awaitWindow().then((function(win) {\n var meth = lookupMethod(win, id);\n if (meth && meth.val !== crossDomainFunctionWrapper) return meth.val.apply({\n source: window,\n origin: getDomain()\n }, _arguments);\n var _args = [].slice.call(_arguments);\n return opts.fireAndForget ? send(win, \"postrobot_method\", {\n id: id,\n name: name,\n args: _args\n }, {\n domain: origin,\n fireAndForget: !0\n }) : send(win, \"postrobot_method\", {\n id: id,\n name: name,\n args: _args\n }, {\n domain: origin,\n fireAndForget: !1\n }).then((function(res) {\n return res.data.result;\n }));\n })).catch((function(err) {\n throw err;\n }));\n }\n crossDomainFunctionWrapper.__name__ = name;\n crossDomainFunctionWrapper.__origin__ = origin;\n crossDomainFunctionWrapper.__source__ = source;\n crossDomainFunctionWrapper.__id__ = id;\n crossDomainFunctionWrapper.origin = origin;\n return crossDomainFunctionWrapper;\n };\n var crossDomainFunctionWrapper = getDeserializedFunction();\n crossDomainFunctionWrapper.fireAndForget = getDeserializedFunction({\n fireAndForget: !0\n });\n return crossDomainFunctionWrapper;\n }(source, origin, serializedFunction, {\n send: send\n });\n }, _deserialize.cross_domain_window = function(serializedWindow) {\n return window_ProxyWindow.deserialize(serializedWindow, {\n send: send\n });\n }, _deserialize));\n }\n var SEND_MESSAGE_STRATEGIES = {};\n SEND_MESSAGE_STRATEGIES.postrobot_post_message = function(win, serializedMessage, domain) {\n 0 === domain.indexOf(\"file:\") && (domain = \"*\");\n win.postMessage(serializedMessage, domain);\n };\n SEND_MESSAGE_STRATEGIES.postrobot_global = function(win, serializedMessage) {\n if (!function(win) {\n return (win = win || window).navigator.mockUserAgent || win.navigator.userAgent;\n }(window).match(/MSIE|rv:11|trident|edge\\/12|edge\\/13/i)) throw new Error(\"Global messaging not needed for browser\");\n if (!isSameDomain(win)) throw new Error(\"Post message through global disabled between different domain windows\");\n if (!1 !== isSameTopWindow(window, win)) throw new Error(\"Can only use global to communicate between two different windows, not between frames\");\n var foreignGlobal = global_getGlobal(win);\n if (!foreignGlobal) throw new Error(\"Can not find postRobot global on foreign window\");\n foreignGlobal.receiveMessage({\n source: window,\n origin: getDomain(),\n data: serializedMessage\n });\n };\n function send_sendMessage(win, domain, message, _ref2) {\n var on = _ref2.on, send = _ref2.send;\n return promise_ZalgoPromise.try((function() {\n var domainBuffer = windowStore().getOrSet(win, (function() {\n return {};\n }));\n domainBuffer.buffer = domainBuffer.buffer || [];\n domainBuffer.buffer.push(message);\n domainBuffer.flush = domainBuffer.flush || promise_ZalgoPromise.flush().then((function() {\n if (isWindowClosed(win)) throw new Error(\"Window is closed\");\n var serializedMessage = serializeMessage(win, domain, ((_ref = {}).__post_robot_10_0_44__ = domainBuffer.buffer || [], \n _ref), {\n on: on,\n send: send\n });\n var _ref;\n delete domainBuffer.buffer;\n var strategies = Object.keys(SEND_MESSAGE_STRATEGIES);\n var errors = [];\n for (var _i2 = 0; _i2 < strategies.length; _i2++) {\n var strategyName = strategies[_i2];\n try {\n SEND_MESSAGE_STRATEGIES[strategyName](win, serializedMessage, domain);\n } catch (err) {\n errors.push(err);\n }\n }\n if (errors.length === strategies.length) throw new Error(\"All post-robot messaging strategies failed:\\n\\n\" + errors.map((function(err, i) {\n return i + \". \" + stringifyError(err);\n })).join(\"\\n\\n\"));\n }));\n return domainBuffer.flush.then((function() {\n delete domainBuffer.flush;\n }));\n })).then(src_util_noop);\n }\n function getResponseListener(hash) {\n return globalStore(\"responseListeners\").get(hash);\n }\n function deleteResponseListener(hash) {\n globalStore(\"responseListeners\").del(hash);\n }\n function isResponseListenerErrored(hash) {\n return globalStore(\"erroredResponseListeners\").has(hash);\n }\n function getRequestListener(_ref) {\n var name = _ref.name, win = _ref.win, domain = _ref.domain;\n var requestListeners = windowStore(\"requestListeners\");\n \"*\" === win && (win = null);\n \"*\" === domain && (domain = null);\n if (!name) throw new Error(\"Name required to get request listener\");\n for (var _i4 = 0, _ref3 = [ win, getWildcard() ]; _i4 < _ref3.length; _i4++) {\n var winQualifier = _ref3[_i4];\n if (winQualifier) {\n var nameListeners = requestListeners.get(winQualifier);\n if (nameListeners) {\n var domainListeners = nameListeners[name];\n if (domainListeners) {\n if (domain && \"string\" == typeof domain) {\n if (domainListeners[domain]) return domainListeners[domain];\n if (domainListeners.__domain_regex__) for (var _i6 = 0, _domainListeners$__DO2 = domainListeners.__domain_regex__; _i6 < _domainListeners$__DO2.length; _i6++) {\n var _domainListeners$__DO3 = _domainListeners$__DO2[_i6], listener = _domainListeners$__DO3.listener;\n if (matchDomain(_domainListeners$__DO3.regex, domain)) return listener;\n }\n }\n if (domainListeners[\"*\"]) return domainListeners[\"*\"];\n }\n }\n }\n }\n }\n function handleRequest(source, origin, message, _ref) {\n var on = _ref.on, send = _ref.send;\n var options = getRequestListener({\n name: message.name,\n win: source,\n domain: origin\n });\n var logName = \"postrobot_method\" === message.name && message.data && \"string\" == typeof message.data.name ? message.data.name + \"()\" : message.name;\n function sendResponse(ack, data, error) {\n return promise_ZalgoPromise.flush().then((function() {\n if (!message.fireAndForget && !isWindowClosed(source)) try {\n return send_sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: \"postrobot_message_response\",\n hash: message.hash,\n name: message.name,\n ack: ack,\n data: data,\n error: error\n }, {\n on: on,\n send: send\n });\n } catch (err) {\n throw new Error(\"Send response message failed for \" + logName + \" in \" + getDomain() + \"\\n\\n\" + stringifyError(err));\n }\n }));\n }\n return promise_ZalgoPromise.all([ promise_ZalgoPromise.flush().then((function() {\n if (!message.fireAndForget && !isWindowClosed(source)) try {\n return send_sendMessage(source, origin, {\n id: uniqueID(),\n origin: getDomain(window),\n type: \"postrobot_message_ack\",\n hash: message.hash,\n name: message.name\n }, {\n on: on,\n send: send\n });\n } catch (err) {\n throw new Error(\"Send ack message failed for \" + logName + \" in \" + getDomain() + \"\\n\\n\" + stringifyError(err));\n }\n })), promise_ZalgoPromise.try((function() {\n if (!options) throw new Error(\"No handler found for post message: \" + message.name + \" from \" + origin + \" in \" + window.location.protocol + \"//\" + window.location.host + window.location.pathname);\n if (!matchDomain(options.domain, origin)) throw new Error(\"Request origin \" + origin + \" does not match domain \" + options.domain.toString());\n return options.handler({\n source: source,\n origin: origin,\n data: message.data\n });\n })).then((function(data) {\n return sendResponse(\"success\", data);\n }), (function(error) {\n return sendResponse(\"error\", null, error);\n })) ]).then(src_util_noop).catch((function(err) {\n if (options && options.handleError) return options.handleError(err);\n throw err;\n }));\n }\n function handleAck(source, origin, message) {\n if (!isResponseListenerErrored(message.hash)) {\n var options = getResponseListener(message.hash);\n if (!options) throw new Error(\"No handler found for post message ack for message: \" + message.name + \" from \" + origin + \" in \" + window.location.protocol + \"//\" + window.location.host + window.location.pathname);\n try {\n if (!matchDomain(options.domain, origin)) throw new Error(\"Ack origin \" + origin + \" does not match domain \" + options.domain.toString());\n if (source !== options.win) throw new Error(\"Ack source does not match registered window\");\n } catch (err) {\n options.promise.reject(err);\n }\n options.ack = !0;\n }\n }\n function handleResponse(source, origin, message) {\n if (!isResponseListenerErrored(message.hash)) {\n var options = getResponseListener(message.hash);\n if (!options) throw new Error(\"No handler found for post message response for message: \" + message.name + \" from \" + origin + \" in \" + window.location.protocol + \"//\" + window.location.host + window.location.pathname);\n if (!matchDomain(options.domain, origin)) throw new Error(\"Response origin \" + origin + \" does not match domain \" + (pattern = options.domain, \n Array.isArray(pattern) ? \"(\" + pattern.join(\" | \") + \")\" : isRegex(pattern) ? \"RegExp(\" + pattern.toString() + \")\" : pattern.toString()));\n var pattern;\n if (source !== options.win) throw new Error(\"Response source does not match registered window\");\n deleteResponseListener(message.hash);\n \"error\" === message.ack ? options.promise.reject(message.error) : \"success\" === message.ack && options.promise.resolve({\n source: source,\n origin: origin,\n data: message.data\n });\n }\n }\n function receive_receiveMessage(event, _ref2) {\n var on = _ref2.on, send = _ref2.send;\n var receivedMessages = globalStore(\"receivedMessages\");\n try {\n if (!window || window.closed || !event.source) return;\n } catch (err) {\n return;\n }\n var source = event.source, origin = event.origin;\n var messages = function(message, source, origin, _ref) {\n var on = _ref.on, send = _ref.send;\n var parsedMessage;\n try {\n parsedMessage = deserializeMessage(source, origin, message, {\n on: on,\n send: send\n });\n } catch (err) {\n return;\n }\n if (parsedMessage && \"object\" == typeof parsedMessage && null !== parsedMessage) {\n var parseMessages = parsedMessage.__post_robot_10_0_44__;\n if (Array.isArray(parseMessages)) return parseMessages;\n }\n }(event.data, source, origin, {\n on: on,\n send: send\n });\n if (messages) {\n markWindowKnown(source);\n for (var _i2 = 0; _i2 < messages.length; _i2++) {\n var message = messages[_i2];\n if (receivedMessages.has(message.id)) return;\n receivedMessages.set(message.id, !0);\n if (isWindowClosed(source) && !message.fireAndForget) return;\n 0 === message.origin.indexOf(\"file:\") && (origin = \"file://\");\n try {\n \"postrobot_message_request\" === message.type ? handleRequest(source, origin, message, {\n on: on,\n send: send\n }) : \"postrobot_message_response\" === message.type ? handleResponse(source, origin, message) : \"postrobot_message_ack\" === message.type && handleAck(source, origin, message);\n } catch (err) {\n setTimeout((function() {\n throw err;\n }), 0);\n }\n }\n }\n }\n function on_on(name, options, handler) {\n if (!name) throw new Error(\"Expected name\");\n if (\"function\" == typeof (options = options || {})) {\n handler = options;\n options = {};\n }\n if (!handler) throw new Error(\"Expected handler\");\n (options = options || {}).name = name;\n options.handler = handler || options.handler;\n var win = options.window;\n var domain = options.domain;\n var requestListener = function addRequestListener(_ref4, listener) {\n var name = _ref4.name, win = _ref4.win, domain = _ref4.domain;\n var requestListeners = windowStore(\"requestListeners\");\n if (!name || \"string\" != typeof name) throw new Error(\"Name required to add request listener\");\n if (Array.isArray(win)) {\n var listenersCollection = [];\n for (var _i8 = 0, _win2 = win; _i8 < _win2.length; _i8++) listenersCollection.push(addRequestListener({\n name: name,\n domain: domain,\n win: _win2[_i8]\n }, listener));\n return {\n cancel: function() {\n for (var _i10 = 0; _i10 < listenersCollection.length; _i10++) listenersCollection[_i10].cancel();\n }\n };\n }\n if (Array.isArray(domain)) {\n var _listenersCollection = [];\n for (var _i12 = 0, _domain2 = domain; _i12 < _domain2.length; _i12++) _listenersCollection.push(addRequestListener({\n name: name,\n win: win,\n domain: _domain2[_i12]\n }, listener));\n return {\n cancel: function() {\n for (var _i14 = 0; _i14 < _listenersCollection.length; _i14++) _listenersCollection[_i14].cancel();\n }\n };\n }\n var existingListener = getRequestListener({\n name: name,\n win: win,\n domain: domain\n });\n win && \"*\" !== win || (win = getWildcard());\n domain = domain || \"*\";\n if (existingListener) throw win && domain ? new Error(\"Request listener already exists for \" + name + \" on domain \" + domain.toString() + \" for \" + (win === getWildcard() ? \"wildcard\" : \"specified\") + \" window\") : win ? new Error(\"Request listener already exists for \" + name + \" for \" + (win === getWildcard() ? \"wildcard\" : \"specified\") + \" window\") : domain ? new Error(\"Request listener already exists for \" + name + \" on domain \" + domain.toString()) : new Error(\"Request listener already exists for \" + name);\n var nameListeners = requestListeners.getOrSet(win, (function() {\n return {};\n }));\n var domainListeners = util_getOrSet(nameListeners, name, (function() {\n return {};\n }));\n var strDomain = domain.toString();\n var regexListeners;\n var regexListener;\n util_isRegex(domain) ? (regexListeners = util_getOrSet(domainListeners, \"__domain_regex__\", (function() {\n return [];\n }))).push(regexListener = {\n regex: domain,\n listener: listener\n }) : domainListeners[strDomain] = listener;\n return {\n cancel: function() {\n delete domainListeners[strDomain];\n if (regexListener) {\n regexListeners.splice(regexListeners.indexOf(regexListener, 1));\n regexListeners.length || delete domainListeners.__domain_regex__;\n }\n Object.keys(domainListeners).length || delete nameListeners[name];\n win && !Object.keys(nameListeners).length && requestListeners.del(win);\n }\n };\n }({\n name: name,\n win: win,\n domain: domain\n }, {\n handler: options.handler,\n handleError: options.errorHandler || function(err) {\n throw err;\n },\n window: win,\n domain: domain || \"*\",\n name: name\n });\n return {\n cancel: function() {\n requestListener.cancel();\n }\n };\n }\n var send_send = function send(win, name, data, options) {\n var domainMatcher = (options = options || {}).domain || \"*\";\n var responseTimeout = options.timeout || -1;\n var childTimeout = options.timeout || 5e3;\n var fireAndForget = options.fireAndForget || !1;\n return promise_ZalgoPromise.try((function() {\n !function(name, win, domain) {\n if (!name) throw new Error(\"Expected name\");\n if (domain && \"string\" != typeof domain && !Array.isArray(domain) && !util_isRegex(domain)) throw new TypeError(\"Can not send \" + name + \". Expected domain \" + JSON.stringify(domain) + \" to be a string, array, or regex\");\n if (isWindowClosed(win)) throw new Error(\"Can not send \" + name + \". Target window is closed\");\n }(name, win, domainMatcher);\n if (function(parent, child) {\n var actualParent = getAncestor(child);\n if (actualParent) return actualParent === parent;\n if (child === parent) return !1;\n if (getTop(child) === child) return !1;\n for (var _i15 = 0, _getFrames8 = getFrames(parent); _i15 < _getFrames8.length; _i15++) if (_getFrames8[_i15] === child) return !0;\n return !1;\n }(window, win)) return function(win, timeout, name) {\n void 0 === timeout && (timeout = 5e3);\n void 0 === name && (name = \"Window\");\n var promise = function(win) {\n return windowStore(\"helloPromises\").getOrSet(win, (function() {\n return new promise_ZalgoPromise;\n }));\n }(win);\n -1 !== timeout && (promise = promise.timeout(timeout, new Error(name + \" did not load after \" + timeout + \"ms\")));\n return promise;\n }(win, childTimeout);\n })).then((function(_temp) {\n return function(win, targetDomain, actualDomain, _ref) {\n var send = _ref.send;\n return promise_ZalgoPromise.try((function() {\n return \"string\" == typeof targetDomain ? targetDomain : promise_ZalgoPromise.try((function() {\n return actualDomain || sayHello(win, {\n send: send\n }).then((function(_ref2) {\n return _ref2.domain;\n }));\n })).then((function(normalizedDomain) {\n if (!matchDomain(targetDomain, targetDomain)) throw new Error(\"Domain \" + stringify(targetDomain) + \" does not match \" + stringify(targetDomain));\n return normalizedDomain;\n }));\n }));\n }(win, domainMatcher, (void 0 === _temp ? {} : _temp).domain, {\n send: send\n });\n })).then((function(targetDomain) {\n var domain = targetDomain;\n var logName = \"postrobot_method\" === name && data && \"string\" == typeof data.name ? data.name + \"()\" : name;\n var promise = new promise_ZalgoPromise;\n var hash = name + \"_\" + uniqueID();\n if (!fireAndForget) {\n var responseListener = {\n name: name,\n win: win,\n domain: domain,\n promise: promise\n };\n !function(hash, listener) {\n globalStore(\"responseListeners\").set(hash, listener);\n }(hash, responseListener);\n var reqPromises = windowStore(\"requestPromises\").getOrSet(win, (function() {\n return [];\n }));\n reqPromises.push(promise);\n promise.catch((function() {\n !function(hash) {\n globalStore(\"erroredResponseListeners\").set(hash, !0);\n }(hash);\n deleteResponseListener(hash);\n }));\n var totalAckTimeout = function(win) {\n return windowStore(\"knownWindows\").get(win, !1);\n }(win) ? 1e4 : 2e3;\n var totalResTimeout = responseTimeout;\n var ackTimeout = totalAckTimeout;\n var resTimeout = totalResTimeout;\n var interval = safeInterval((function() {\n if (isWindowClosed(win)) return promise.reject(new Error(\"Window closed for \" + name + \" before \" + (responseListener.ack ? \"response\" : \"ack\")));\n if (responseListener.cancelled) return promise.reject(new Error(\"Response listener was cancelled for \" + name));\n ackTimeout = Math.max(ackTimeout - 500, 0);\n -1 !== resTimeout && (resTimeout = Math.max(resTimeout - 500, 0));\n return responseListener.ack || 0 !== ackTimeout ? 0 === resTimeout ? promise.reject(new Error(\"No response for postMessage \" + logName + \" in \" + getDomain() + \" in \" + totalResTimeout + \"ms\")) : void 0 : promise.reject(new Error(\"No ack for postMessage \" + logName + \" in \" + getDomain() + \" in \" + totalAckTimeout + \"ms\"));\n }), 500);\n promise.finally((function() {\n interval.cancel();\n reqPromises.splice(reqPromises.indexOf(promise, 1));\n })).catch(src_util_noop);\n }\n return send_sendMessage(win, domain, {\n id: uniqueID(),\n origin: getDomain(window),\n type: \"postrobot_message_request\",\n hash: hash,\n name: name,\n data: data,\n fireAndForget: fireAndForget\n }, {\n on: on_on,\n send: send\n }).then((function() {\n return fireAndForget ? promise.resolve() : promise;\n }), (function(err) {\n throw new Error(\"Send request message failed for \" + logName + \" in \" + getDomain() + \"\\n\\n\" + stringifyError(err));\n }));\n }));\n };\n function setup_serializeMessage(destination, domain, obj) {\n return serializeMessage(destination, domain, obj, {\n on: on_on,\n send: send_send\n });\n }\n function setup_deserializeMessage(source, origin, message) {\n return deserializeMessage(source, origin, message, {\n on: on_on,\n send: send_send\n });\n }\n function setup_toProxyWindow(win) {\n return window_ProxyWindow.toProxyWindow(win, {\n send: send_send\n });\n }\n function lib_global_getGlobal(win) {\n void 0 === win && (win = window);\n if (!isSameDomain(win)) throw new Error(\"Can not get global for window on different domain\");\n win.__zoid_9_0_78__ || (win.__zoid_9_0_78__ = {});\n return win.__zoid_9_0_78__;\n }\n function getProxyObject(obj) {\n return {\n get: function() {\n var _this = this;\n return promise_ZalgoPromise.try((function() {\n if (_this.source && _this.source !== window) throw new Error(\"Can not call get on proxy object from a remote window\");\n return obj;\n }));\n }\n };\n }\n var PROP_TYPE = {\n STRING: \"string\",\n OBJECT: \"object\",\n FUNCTION: \"function\",\n BOOLEAN: \"boolean\",\n NUMBER: \"number\",\n ARRAY: \"array\"\n };\n var PROP_SERIALIZATION = {\n JSON: \"json\",\n DOTIFY: \"dotify\",\n BASE64: \"base64\"\n };\n var CONTEXT = WINDOW_TYPE;\n var EVENT = {\n RENDER: \"zoid-render\",\n RENDERED: \"zoid-rendered\",\n DISPLAY: \"zoid-display\",\n ERROR: \"zoid-error\",\n CLOSE: \"zoid-close\",\n DESTROY: \"zoid-destroy\",\n PROPS: \"zoid-props\",\n RESIZE: \"zoid-resize\",\n FOCUS: \"zoid-focus\"\n };\n function normalizeChildProp(propsDef, props, key, value, helpers) {\n if (!propsDef.hasOwnProperty(key)) return value;\n var prop = propsDef[key];\n return \"function\" == typeof prop.childDecorate ? prop.childDecorate({\n value: value,\n uid: helpers.uid,\n tag: helpers.tag,\n close: helpers.close,\n focus: helpers.focus,\n onError: helpers.onError,\n onProps: helpers.onProps,\n resize: helpers.resize,\n getParent: helpers.getParent,\n getParentDomain: helpers.getParentDomain,\n show: helpers.show,\n hide: helpers.hide,\n export: helpers.export,\n getSiblings: helpers.getSiblings\n }) : value;\n }\n function parseChildWindowName(windowName) {\n return inlineMemoize(parseChildWindowName, (function() {\n if (!windowName) throw new Error(\"No window name\");\n var _windowName$split = windowName.split(\"__\"), zoidcomp = _windowName$split[1], name = _windowName$split[2], encodedPayload = _windowName$split[3];\n if (\"zoid\" !== zoidcomp) throw new Error(\"Window not rendered by zoid - got \" + zoidcomp);\n if (!name) throw new Error(\"Expected component name\");\n if (!encodedPayload) throw new Error(\"Expected encoded payload\");\n try {\n return JSON.parse(function(str) {\n if (\"function\" == typeof atob) return decodeURIComponent([].map.call(atob(str), (function(c) {\n return \"%\" + (\"00\" + c.charCodeAt(0).toString(16)).slice(-2);\n })).join(\"\"));\n if (\"undefined\" != typeof Buffer) return Buffer.from(str, \"base64\").toString(\"utf8\");\n throw new Error(\"Can not find window.atob or Buffer\");\n }(encodedPayload));\n } catch (err) {\n throw new Error(\"Can not decode window name payload: \" + encodedPayload + \": \" + stringifyError(err));\n }\n }), [ windowName ]);\n }\n function getChildPayload() {\n try {\n return parseChildWindowName(window.name);\n } catch (err) {}\n }\n function child_focus() {\n return promise_ZalgoPromise.try((function() {\n window.focus();\n }));\n }\n function child_destroy() {\n return promise_ZalgoPromise.try((function() {\n window.close();\n }));\n }\n var props_defaultNoop = function() {\n return src_util_noop;\n };\n var props_decorateOnce = function(_ref) {\n return once(_ref.value);\n };\n function eachProp(props, propsDef, handler) {\n for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) {\n var key = _Object$keys2[_i2];\n var propDef = propsDef[key];\n propDef && handler(key, propDef, props[key]);\n }\n }\n function serializeProps(propsDef, props, method) {\n var params = {};\n return promise_ZalgoPromise.all(function(props, propsDef, handler) {\n var results = [];\n eachProp(props, propsDef, (function(key, propDef, value) {\n var result = function(key, propDef, value) {\n return promise_ZalgoPromise.resolve().then((function() {\n var _METHOD$GET$METHOD$PO, _METHOD$GET$METHOD$PO2;\n if (null != value) {\n var getParam = (_METHOD$GET$METHOD$PO = {}, _METHOD$GET$METHOD$PO.get = propDef.queryParam, \n _METHOD$GET$METHOD$PO.post = propDef.bodyParam, _METHOD$GET$METHOD$PO)[method];\n var getValue = (_METHOD$GET$METHOD$PO2 = {}, _METHOD$GET$METHOD$PO2.get = propDef.queryValue, \n _METHOD$GET$METHOD$PO2.post = propDef.bodyValue, _METHOD$GET$METHOD$PO2)[method];\n if (getParam) return promise_ZalgoPromise.hash({\n finalParam: promise_ZalgoPromise.try((function() {\n return \"function\" == typeof getParam ? getParam({\n value: value\n }) : \"string\" == typeof getParam ? getParam : key;\n })),\n finalValue: promise_ZalgoPromise.try((function() {\n return \"function\" == typeof getValue && isDefined(value) ? getValue({\n value: value\n }) : value;\n }))\n }).then((function(_ref) {\n var finalParam = _ref.finalParam, finalValue = _ref.finalValue;\n var result;\n if (\"boolean\" == typeof finalValue) result = finalValue.toString(); else if (\"string\" == typeof finalValue) result = finalValue.toString(); else if (\"object\" == typeof finalValue && null !== finalValue) {\n if (propDef.serialization === PROP_SERIALIZATION.JSON) result = JSON.stringify(finalValue); else if (propDef.serialization === PROP_SERIALIZATION.BASE64) result = base64encode(JSON.stringify(finalValue)); else if (propDef.serialization === PROP_SERIALIZATION.DOTIFY || !propDef.serialization) {\n result = function dotify(obj, prefix, newobj) {\n void 0 === prefix && (prefix = \"\");\n void 0 === newobj && (newobj = {});\n prefix = prefix ? prefix + \".\" : prefix;\n for (var key in obj) obj.hasOwnProperty(key) && null != obj[key] && \"function\" != typeof obj[key] && (obj[key] && Array.isArray(obj[key]) && obj[key].length && obj[key].every((function(val) {\n return \"object\" != typeof val;\n })) ? newobj[\"\" + prefix + key + \"[]\"] = obj[key].join(\",\") : obj[key] && \"object\" == typeof obj[key] ? newobj = dotify(obj[key], \"\" + prefix + key, newobj) : newobj[\"\" + prefix + key] = obj[key].toString());\n return newobj;\n }(finalValue, key);\n for (var _i10 = 0, _Object$keys6 = Object.keys(result); _i10 < _Object$keys6.length; _i10++) {\n var dotkey = _Object$keys6[_i10];\n params[dotkey] = result[dotkey];\n }\n return;\n }\n } else \"number\" == typeof finalValue && (result = finalValue.toString());\n params[finalParam] = result;\n }));\n }\n }));\n }(key, propDef, value);\n results.push(result);\n }));\n return results;\n }(props, propsDef)).then((function() {\n return params;\n }));\n }\n function parentComponent(_ref) {\n var uid = _ref.uid, options = _ref.options, _ref$overrides = _ref.overrides, overrides = void 0 === _ref$overrides ? {} : _ref$overrides, _ref$parentWin = _ref.parentWin, parentWin = void 0 === _ref$parentWin ? window : _ref$parentWin;\n var propsDef = options.propsDef, containerTemplate = options.containerTemplate, prerenderTemplate = options.prerenderTemplate, tag = options.tag, name = options.name, attributes = options.attributes, dimensions = options.dimensions, autoResize = options.autoResize, url = options.url, domainMatch = options.domain, xports = options.exports;\n var initPromise = new promise_ZalgoPromise;\n var handledErrors = [];\n var clean = cleanup();\n var state = {};\n var internalState = {\n visible: !0\n };\n var event = overrides.event ? overrides.event : (triggered = {}, handlers = {}, \n emitter = {\n on: function(eventName, handler) {\n var handlerList = handlers[eventName] = handlers[eventName] || [];\n handlerList.push(handler);\n var cancelled = !1;\n return {\n cancel: function() {\n if (!cancelled) {\n cancelled = !0;\n handlerList.splice(handlerList.indexOf(handler), 1);\n }\n }\n };\n },\n once: function(eventName, handler) {\n var listener = emitter.on(eventName, (function() {\n listener.cancel();\n handler();\n }));\n return listener;\n },\n trigger: function(eventName) {\n for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) args[_key3 - 1] = arguments[_key3];\n var handlerList = handlers[eventName];\n var promises = [];\n if (handlerList) {\n var _loop = function(_i2) {\n var handler = handlerList[_i2];\n promises.push(promise_ZalgoPromise.try((function() {\n return handler.apply(void 0, args);\n })));\n };\n for (var _i2 = 0; _i2 < handlerList.length; _i2++) _loop(_i2);\n }\n return promise_ZalgoPromise.all(promises).then(src_util_noop);\n },\n triggerOnce: function(eventName) {\n if (triggered[eventName]) return promise_ZalgoPromise.resolve();\n triggered[eventName] = !0;\n for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) args[_key4 - 1] = arguments[_key4];\n return emitter.trigger.apply(emitter, [ eventName ].concat(args));\n },\n reset: function() {\n handlers = {};\n }\n });\n var triggered, handlers, emitter;\n var props = overrides.props ? overrides.props : {};\n var currentProxyWin;\n var currentProxyContainer;\n var childComponent;\n var onErrorOverride = overrides.onError;\n var getProxyContainerOverride = overrides.getProxyContainer;\n var showOverride = overrides.show;\n var hideOverride = overrides.hide;\n var closeOverride = overrides.close;\n var renderContainerOverride = overrides.renderContainer;\n var getProxyWindowOverride = overrides.getProxyWindow;\n var setProxyWinOverride = overrides.setProxyWin;\n var openFrameOverride = overrides.openFrame;\n var openPrerenderFrameOverride = overrides.openPrerenderFrame;\n var prerenderOverride = overrides.prerender;\n var openOverride = overrides.open;\n var openPrerenderOverride = overrides.openPrerender;\n var watchForUnloadOverride = overrides.watchForUnload;\n var getInternalStateOverride = overrides.getInternalState;\n var setInternalStateOverride = overrides.setInternalState;\n var resolveInitPromise = function() {\n return promise_ZalgoPromise.try((function() {\n return overrides.resolveInitPromise ? overrides.resolveInitPromise() : initPromise.resolve();\n }));\n };\n var rejectInitPromise = function(err) {\n return promise_ZalgoPromise.try((function() {\n return overrides.rejectInitPromise ? overrides.rejectInitPromise(err) : initPromise.reject(err);\n }));\n };\n var getPropsForChild = function(domain) {\n var result = {};\n for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) {\n var key = _Object$keys2[_i2];\n var prop = propsDef[key];\n prop && !1 === prop.sendToChild || prop && prop.sameDomain && !matchDomain(domain, getDomain(window)) || (result[key] = props[key]);\n }\n return promise_ZalgoPromise.hash(result);\n };\n var getInternalState = function() {\n return promise_ZalgoPromise.try((function() {\n return getInternalStateOverride ? getInternalStateOverride() : internalState;\n }));\n };\n var setInternalState = function(newInternalState) {\n return promise_ZalgoPromise.try((function() {\n return setInternalStateOverride ? setInternalStateOverride(newInternalState) : internalState = _extends({}, internalState, newInternalState);\n }));\n };\n var getProxyWindow = function() {\n return getProxyWindowOverride ? getProxyWindowOverride() : promise_ZalgoPromise.try((function() {\n var windowProp = props.window;\n if (windowProp) {\n var _proxyWin = setup_toProxyWindow(windowProp);\n clean.register((function() {\n return windowProp.close();\n }));\n return _proxyWin;\n }\n return new window_ProxyWindow({\n send: send_send\n });\n }));\n };\n var getProxyContainer = function(container) {\n return getProxyContainerOverride ? getProxyContainerOverride(container) : promise_ZalgoPromise.try((function() {\n return elementReady(container);\n })).then((function(containerElement) {\n isShadowElement(containerElement) && (containerElement = function insertShadowSlot(element) {\n var shadowHost = function(element) {\n var shadowRoot = function(element) {\n for (;element.parentNode; ) element = element.parentNode;\n if (isShadowElement(element)) return element;\n }(element);\n if (shadowRoot && shadowRoot.host) return shadowRoot.host;\n }(element);\n if (!shadowHost) throw new Error(\"Element is not in shadow dom\");\n var slotName = \"shadow-slot-\" + uniqueID();\n var slot = document.createElement(\"slot\");\n slot.setAttribute(\"name\", slotName);\n element.appendChild(slot);\n var slotProvider = document.createElement(\"div\");\n slotProvider.setAttribute(\"slot\", slotName);\n shadowHost.appendChild(slotProvider);\n return isShadowElement(shadowHost) ? insertShadowSlot(slotProvider) : slotProvider;\n }(containerElement));\n return getProxyObject(containerElement);\n }));\n };\n var setProxyWin = function(proxyWin) {\n return setProxyWinOverride ? setProxyWinOverride(proxyWin) : promise_ZalgoPromise.try((function() {\n currentProxyWin = proxyWin;\n }));\n };\n var show = function() {\n return showOverride ? showOverride() : promise_ZalgoPromise.hash({\n setState: setInternalState({\n visible: !0\n }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(showElement) : null\n }).then(src_util_noop);\n };\n var hide = function() {\n return hideOverride ? hideOverride() : promise_ZalgoPromise.hash({\n setState: setInternalState({\n visible: !1\n }),\n showElement: currentProxyContainer ? currentProxyContainer.get().then(hideElement) : null\n }).then(src_util_noop);\n };\n var getUrl = function() {\n return \"function\" == typeof url ? url({\n props: props\n }) : url;\n };\n var getAttributes = function() {\n return \"function\" == typeof attributes ? attributes({\n props: props\n }) : attributes;\n };\n var getChildDomain = function() {\n return domainMatch && \"string\" == typeof domainMatch ? domainMatch : getDomainFromUrl(getUrl());\n };\n var getDomainMatcher = function() {\n return domainMatch && util_isRegex(domainMatch) ? domainMatch : getChildDomain();\n };\n var openFrame = function(context, _ref2) {\n var windowName = _ref2.windowName;\n return openFrameOverride ? openFrameOverride(context, {\n windowName: windowName\n }) : promise_ZalgoPromise.try((function() {\n if (context === CONTEXT.IFRAME) return getProxyObject(dom_iframe({\n attributes: _extends({\n name: windowName,\n title: name\n }, getAttributes().iframe)\n }));\n }));\n };\n var openPrerenderFrame = function(context) {\n return openPrerenderFrameOverride ? openPrerenderFrameOverride(context) : promise_ZalgoPromise.try((function() {\n if (context === CONTEXT.IFRAME) return getProxyObject(dom_iframe({\n attributes: _extends({\n name: \"__zoid_prerender_frame__\" + name + \"_\" + uniqueID() + \"__\",\n title: \"prerender__\" + name\n }, getAttributes().iframe)\n }));\n }));\n };\n var openPrerender = function(context, proxyWin, proxyPrerenderFrame) {\n return openPrerenderOverride ? openPrerenderOverride(context, proxyWin, proxyPrerenderFrame) : promise_ZalgoPromise.try((function() {\n if (context === CONTEXT.IFRAME) {\n if (!proxyPrerenderFrame) throw new Error(\"Expected proxy frame to be passed\");\n return proxyPrerenderFrame.get().then((function(prerenderFrame) {\n clean.register((function() {\n return destroyElement(prerenderFrame);\n }));\n return awaitFrameWindow(prerenderFrame).then((function(prerenderFrameWindow) {\n return assertSameDomain(prerenderFrameWindow);\n })).then((function(win) {\n return setup_toProxyWindow(win);\n }));\n }));\n }\n throw new Error(\"No render context available for \" + context);\n }));\n };\n var focus = function() {\n return promise_ZalgoPromise.try((function() {\n if (currentProxyWin) return promise_ZalgoPromise.all([ event.trigger(EVENT.FOCUS), currentProxyWin.focus() ]).then(src_util_noop);\n }));\n };\n var getWindowRef = function(target, domain, context) {\n if (domain === getDomain(window)) {\n var global = lib_global_getGlobal(window);\n global.windows = global.windows || {};\n global.windows[uid] = window;\n clean.register((function() {\n delete global.windows[uid];\n }));\n return {\n type: \"global\",\n uid: uid\n };\n }\n return context === CONTEXT.POPUP ? {\n type: \"opener\"\n } : {\n type: \"parent\",\n distance: getDistanceFromTop(window)\n };\n };\n var initChild = function(childExports) {\n return promise_ZalgoPromise.try((function() {\n childComponent = childExports;\n resolveInitPromise();\n clean.register((function() {\n return childExports.close.fireAndForget().catch(src_util_noop);\n }));\n }));\n };\n var resize = function(_ref3) {\n var width = _ref3.width, height = _ref3.height;\n return promise_ZalgoPromise.try((function() {\n event.trigger(EVENT.RESIZE, {\n width: width,\n height: height\n });\n }));\n };\n var destroy = function(err) {\n return promise_ZalgoPromise.try((function() {\n return event.trigger(EVENT.DESTROY);\n })).catch(src_util_noop).then((function() {\n return clean.all(err);\n })).then((function() {\n initPromise.asyncReject(err || new Error(\"Component destroyed\"));\n }));\n };\n var close = memoize((function(err) {\n return promise_ZalgoPromise.try((function() {\n if (closeOverride) {\n if (isWindowClosed(closeOverride.__source__)) return;\n return closeOverride();\n }\n return promise_ZalgoPromise.try((function() {\n return event.trigger(EVENT.CLOSE);\n })).then((function() {\n return destroy(err || new Error(\"Component closed\"));\n }));\n }));\n }));\n var open = function(context, _ref4) {\n var proxyWin = _ref4.proxyWin, proxyFrame = _ref4.proxyFrame, windowName = _ref4.windowName;\n return openOverride ? openOverride(context, {\n proxyWin: proxyWin,\n proxyFrame: proxyFrame,\n windowName: windowName\n }) : promise_ZalgoPromise.try((function() {\n if (context === CONTEXT.IFRAME) {\n if (!proxyFrame) throw new Error(\"Expected proxy frame to be passed\");\n return proxyFrame.get().then((function(frame) {\n return awaitFrameWindow(frame).then((function(win) {\n clean.register((function() {\n return destroyElement(frame);\n }));\n clean.register((function() {\n return function(win) {\n for (var _i2 = 0, _requestPromises$get2 = windowStore(\"requestPromises\").get(win, []); _i2 < _requestPromises$get2.length; _i2++) _requestPromises$get2[_i2].reject(new Error(\"Window \" + (isWindowClosed(win) ? \"closed\" : \"cleaned up\") + \" before response\")).catch(src_util_noop);\n }(win);\n }));\n return win;\n }));\n }));\n }\n throw new Error(\"No render context available for \" + context);\n })).then((function(win) {\n proxyWin.setWindow(win, {\n send: send_send\n });\n return proxyWin.setName(windowName).then((function() {\n return proxyWin;\n }));\n }));\n };\n var watchForUnload = function() {\n return promise_ZalgoPromise.try((function() {\n var unloadWindowListener = addEventListener(window, \"unload\", once((function() {\n destroy(new Error(\"Window navigated away\"));\n })));\n var closeParentWindowListener = onCloseWindow(parentWin, destroy, 3e3);\n clean.register(closeParentWindowListener.cancel);\n clean.register(unloadWindowListener.cancel);\n if (watchForUnloadOverride) return watchForUnloadOverride();\n }));\n };\n var checkWindowClose = function(proxyWin) {\n var closed = !1;\n return proxyWin.isClosed().then((function(isClosed) {\n if (isClosed) {\n closed = !0;\n return close(new Error(\"Detected component window close\"));\n }\n return promise_ZalgoPromise.delay(200).then((function() {\n return proxyWin.isClosed();\n })).then((function(secondIsClosed) {\n if (secondIsClosed) {\n closed = !0;\n return close(new Error(\"Detected component window close\"));\n }\n }));\n })).then((function() {\n return closed;\n }));\n };\n var onError = function(err) {\n return onErrorOverride ? onErrorOverride(err) : promise_ZalgoPromise.try((function() {\n if (-1 === handledErrors.indexOf(err)) {\n handledErrors.push(err);\n initPromise.asyncReject(err);\n return event.trigger(EVENT.ERROR, err);\n }\n }));\n };\n var exportsPromise = new promise_ZalgoPromise;\n var xport = function(actualExports) {\n return promise_ZalgoPromise.try((function() {\n exportsPromise.resolve(actualExports);\n }));\n };\n initChild.onError = onError;\n var renderTemplate = function(renderer, _ref7) {\n return renderer({\n uid: uid,\n container: _ref7.container,\n context: _ref7.context,\n doc: _ref7.doc,\n frame: _ref7.frame,\n prerenderFrame: _ref7.prerenderFrame,\n focus: focus,\n close: close,\n state: state,\n props: props,\n tag: tag,\n dimensions: \"function\" == typeof dimensions ? dimensions({\n props: props\n }) : dimensions,\n event: event\n });\n };\n var prerender = function(proxyPrerenderWin, _ref8) {\n var context = _ref8.context;\n return prerenderOverride ? prerenderOverride(proxyPrerenderWin, {\n context: context\n }) : promise_ZalgoPromise.try((function() {\n if (prerenderTemplate) {\n var prerenderWindow = proxyPrerenderWin.getWindow();\n if (prerenderWindow && isSameDomain(prerenderWindow) && function(win) {\n try {\n if (!win.location.href) return !0;\n if (\"about:blank\" === win.location.href) return !0;\n } catch (err) {}\n return !1;\n }(prerenderWindow)) {\n var doc = (prerenderWindow = assertSameDomain(prerenderWindow)).document;\n var el = renderTemplate(prerenderTemplate, {\n context: context,\n doc: doc\n });\n if (el) {\n if (el.ownerDocument !== doc) throw new Error(\"Expected prerender template to have been created with document from child window\");\n !function(win, el) {\n var tag = el.tagName.toLowerCase();\n if (\"html\" !== tag) throw new Error(\"Expected element to be html, got \" + tag);\n var documentElement = win.document.documentElement;\n for (var _i6 = 0, _arrayFrom2 = arrayFrom(documentElement.children); _i6 < _arrayFrom2.length; _i6++) documentElement.removeChild(_arrayFrom2[_i6]);\n for (var _i8 = 0, _arrayFrom4 = arrayFrom(el.children); _i8 < _arrayFrom4.length; _i8++) documentElement.appendChild(_arrayFrom4[_i8]);\n }(prerenderWindow, el);\n var _autoResize$width = autoResize.width, width = void 0 !== _autoResize$width && _autoResize$width, _autoResize$height = autoResize.height, height = void 0 !== _autoResize$height && _autoResize$height, _autoResize$element = autoResize.element, element = void 0 === _autoResize$element ? \"body\" : _autoResize$element;\n if ((element = getElementSafe(element, doc)) && (width || height)) {\n var prerenderResizeListener = onResize(element, (function(_ref9) {\n resize({\n width: width ? _ref9.width : void 0,\n height: height ? _ref9.height : void 0\n });\n }), {\n width: width,\n height: height,\n win: prerenderWindow\n });\n event.on(EVENT.RENDERED, prerenderResizeListener.cancel);\n }\n }\n }\n }\n }));\n };\n var renderContainer = function(proxyContainer, _ref10) {\n var proxyFrame = _ref10.proxyFrame, proxyPrerenderFrame = _ref10.proxyPrerenderFrame, context = _ref10.context, rerender = _ref10.rerender;\n return renderContainerOverride ? renderContainerOverride(proxyContainer, {\n proxyFrame: proxyFrame,\n proxyPrerenderFrame: proxyPrerenderFrame,\n context: context,\n rerender: rerender\n }) : promise_ZalgoPromise.hash({\n container: proxyContainer.get(),\n frame: proxyFrame ? proxyFrame.get() : null,\n prerenderFrame: proxyPrerenderFrame ? proxyPrerenderFrame.get() : null,\n internalState: getInternalState()\n }).then((function(_ref11) {\n var container = _ref11.container, visible = _ref11.internalState.visible;\n var innerContainer = renderTemplate(containerTemplate, {\n context: context,\n container: container,\n frame: _ref11.frame,\n prerenderFrame: _ref11.prerenderFrame,\n doc: document\n });\n if (innerContainer) {\n visible || hideElement(innerContainer);\n appendChild(container, innerContainer);\n var containerWatcher = function(element, handler) {\n handler = once(handler);\n var cancelled = !1;\n var mutationObservers = [];\n var interval;\n var sacrificialFrame;\n var sacrificialFrameWin;\n var cancel = function() {\n cancelled = !0;\n for (var _i18 = 0; _i18 < mutationObservers.length; _i18++) mutationObservers[_i18].disconnect();\n interval && interval.cancel();\n sacrificialFrameWin && sacrificialFrameWin.removeEventListener(\"unload\", elementClosed);\n sacrificialFrame && destroyElement(sacrificialFrame);\n };\n var elementClosed = function() {\n if (!cancelled) {\n handler();\n cancel();\n }\n };\n if (isElementClosed(element)) {\n elementClosed();\n return {\n cancel: cancel\n };\n }\n if (window.MutationObserver) {\n var mutationElement = element.parentElement;\n for (;mutationElement; ) {\n var mutationObserver = new window.MutationObserver((function() {\n isElementClosed(element) && elementClosed();\n }));\n mutationObserver.observe(mutationElement, {\n childList: !0\n });\n mutationObservers.push(mutationObserver);\n mutationElement = mutationElement.parentElement;\n }\n }\n (sacrificialFrame = document.createElement(\"iframe\")).setAttribute(\"name\", \"__detect_close_\" + uniqueID() + \"__\");\n sacrificialFrame.style.display = \"none\";\n awaitFrameWindow(sacrificialFrame).then((function(frameWin) {\n (sacrificialFrameWin = assertSameDomain(frameWin)).addEventListener(\"unload\", elementClosed);\n }));\n element.appendChild(sacrificialFrame);\n interval = safeInterval((function() {\n isElementClosed(element) && elementClosed();\n }), 1e3);\n return {\n cancel: cancel\n };\n }(innerContainer, (function() {\n var removeError = new Error(\"Detected container element removed from DOM\");\n return promise_ZalgoPromise.delay(1).then((function() {\n if (!isElementClosed(innerContainer)) {\n clean.all(removeError);\n return rerender().then(resolveInitPromise, rejectInitPromise);\n }\n close(removeError);\n }));\n }));\n clean.register((function() {\n return containerWatcher.cancel();\n }));\n clean.register((function() {\n return destroyElement(innerContainer);\n }));\n return currentProxyContainer = getProxyObject(innerContainer);\n }\n }));\n };\n var getHelpers = function() {\n return {\n state: state,\n event: event,\n close: close,\n focus: focus,\n resize: resize,\n onError: onError,\n updateProps: updateProps,\n show: show,\n hide: hide\n };\n };\n var setProps = function(newProps, isUpdate) {\n void 0 === isUpdate && (isUpdate = !1);\n var helpers = getHelpers();\n !function(propsDef, props, inputProps, helpers, isUpdate) {\n void 0 === isUpdate && (isUpdate = !1);\n extend(props, inputProps = inputProps || {});\n var propNames = isUpdate ? [] : [].concat(Object.keys(propsDef));\n for (var _i2 = 0, _Object$keys2 = Object.keys(inputProps); _i2 < _Object$keys2.length; _i2++) {\n var key = _Object$keys2[_i2];\n -1 === propNames.indexOf(key) && propNames.push(key);\n }\n var aliases = [];\n var state = helpers.state, close = helpers.close, focus = helpers.focus, event = helpers.event, onError = helpers.onError;\n for (var _i4 = 0; _i4 < propNames.length; _i4++) {\n var _key = propNames[_i4];\n var propDef = propsDef[_key];\n var value = inputProps[_key];\n if (propDef) {\n var alias = propDef.alias;\n if (alias) {\n !isDefined(value) && isDefined(inputProps[alias]) && (value = inputProps[alias]);\n aliases.push(alias);\n }\n propDef.value && (value = propDef.value({\n props: props,\n state: state,\n close: close,\n focus: focus,\n event: event,\n onError: onError\n }));\n !isDefined(value) && propDef.default && (value = propDef.default({\n props: props,\n state: state,\n close: close,\n focus: focus,\n event: event,\n onError: onError\n }));\n if (isDefined(value) && (\"array\" === propDef.type ? !Array.isArray(value) : typeof value !== propDef.type)) throw new TypeError(\"Prop is not of type \" + propDef.type + \": \" + _key);\n props[_key] = value;\n }\n }\n for (var _i6 = 0; _i6 < aliases.length; _i6++) delete props[aliases[_i6]];\n eachProp(props, propsDef, (function(key, propDef, value) {\n if (propDef && isDefined(value) && propDef.decorate) {\n var decoratedValue = propDef.decorate({\n value: value,\n props: props,\n state: state,\n close: close,\n focus: focus,\n event: event,\n onError: onError\n });\n props[key] = decoratedValue;\n }\n }));\n for (var _i8 = 0, _Object$keys4 = Object.keys(propsDef); _i8 < _Object$keys4.length; _i8++) {\n var _key2 = _Object$keys4[_i8];\n if (!1 !== propsDef[_key2].required && !isDefined(props[_key2])) throw new Error('Expected prop \"' + _key2 + '\" to be defined');\n }\n }(propsDef, props, newProps, helpers, isUpdate);\n };\n var updateProps = function(newProps) {\n setProps(newProps, !0);\n return initPromise.then((function() {\n var child = childComponent;\n var proxyWin = currentProxyWin;\n if (child && proxyWin) return getPropsForChild(getDomainMatcher()).then((function(childProps) {\n return child.updateProps(childProps).catch((function(err) {\n return checkWindowClose(proxyWin).then((function(closed) {\n if (!closed) throw err;\n }));\n }));\n }));\n }));\n };\n return {\n init: function() {\n !function() {\n event.on(EVENT.RENDER, (function() {\n return props.onRender();\n }));\n event.on(EVENT.DISPLAY, (function() {\n return props.onDisplay();\n }));\n event.on(EVENT.RENDERED, (function() {\n return props.onRendered();\n }));\n event.on(EVENT.CLOSE, (function() {\n return props.onClose();\n }));\n event.on(EVENT.DESTROY, (function() {\n return props.onDestroy();\n }));\n event.on(EVENT.RESIZE, (function() {\n return props.onResize();\n }));\n event.on(EVENT.FOCUS, (function() {\n return props.onFocus();\n }));\n event.on(EVENT.PROPS, (function(newProps) {\n return props.onProps(newProps);\n }));\n event.on(EVENT.ERROR, (function(err) {\n return props && props.onError ? props.onError(err) : rejectInitPromise(err).then((function() {\n setTimeout((function() {\n throw err;\n }), 1);\n }));\n }));\n clean.register(event.reset);\n }();\n },\n render: function(_ref13) {\n var target = _ref13.target, container = _ref13.container, context = _ref13.context, rerender = _ref13.rerender;\n return promise_ZalgoPromise.try((function() {\n var domain = getDomainMatcher();\n var childDomain = getChildDomain();\n !function(target, domain, container) {\n if (target !== window) {\n if (!isSameTopWindow(window, target)) throw new Error(\"Can only renderTo an adjacent frame\");\n var origin = getDomain();\n if (!matchDomain(domain, origin) && !isSameDomain(target)) throw new Error(\"Can not render remotely to \" + domain.toString() + \" - can only render to \" + origin);\n if (container && \"string\" != typeof container) throw new Error(\"Container passed to renderTo must be a string selector, got \" + typeof container + \" }\");\n }\n }(target, domain, container);\n var delegatePromise = promise_ZalgoPromise.try((function() {\n if (target !== window) return function(context, target) {\n var delegateProps = {};\n for (var _i4 = 0, _Object$keys4 = Object.keys(props); _i4 < _Object$keys4.length; _i4++) {\n var propName = _Object$keys4[_i4];\n var propDef = propsDef[propName];\n propDef && propDef.allowDelegate && (delegateProps[propName] = props[propName]);\n }\n var childOverridesPromise = send_send(target, \"zoid_delegate_\" + name, {\n uid: uid,\n overrides: {\n props: delegateProps,\n event: event,\n close: close,\n onError: onError,\n getInternalState: getInternalState,\n setInternalState: setInternalState,\n resolveInitPromise: resolveInitPromise,\n rejectInitPromise: rejectInitPromise\n }\n }).then((function(_ref12) {\n var parentComp = _ref12.data.parent;\n clean.register((function(err) {\n if (!isWindowClosed(target)) return parentComp.destroy(err);\n }));\n return parentComp.getDelegateOverrides();\n })).catch((function(err) {\n throw new Error(\"Unable to delegate rendering. Possibly the component is not loaded in the target window.\\n\\n\" + stringifyError(err));\n }));\n getProxyContainerOverride = function() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];\n return childOverridesPromise.then((function(childOverrides) {\n return childOverrides.getProxyContainer.apply(childOverrides, args);\n }));\n };\n renderContainerOverride = function() {\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) args[_key2] = arguments[_key2];\n return childOverridesPromise.then((function(childOverrides) {\n return childOverrides.renderContainer.apply(childOverrides, args);\n }));\n };\n showOverride = function() {\n for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) args[_key3] = arguments[_key3];\n return childOverridesPromise.then((function(childOverrides) {\n return childOverrides.show.apply(childOverrides, args);\n }));\n };\n hideOverride = function() {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) args[_key4] = arguments[_key4];\n return childOverridesPromise.then((function(childOverrides) {\n return childOverrides.hide.apply(childOverrides, args);\n }));\n };\n watchForUnloadOverride = function() {\n for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) args[_key5] = arguments[_key5];\n return childOverridesPromise.then((function(childOverrides) {\n return childOverrides.watchForUnload.apply(childOverrides, args);\n }));\n };\n if (context === CONTEXT.IFRAME) {\n getProxyWindowOverride = function() {\n for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) args[_key6] = arguments[_key6];\n return childOverridesPromise.then((function(childOverrides) {\n return childOverrides.getProxyWindow.apply(childOverrides, args);\n }));\n };\n openFrameOverride = function() {\n for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) args[_key7] = arguments[_key7];\n return childOverridesPromise.then((function(childOverrides) {\n return childOverrides.openFrame.apply(childOverrides, args);\n }));\n };\n openPrerenderFrameOverride = function() {\n for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) args[_key8] = arguments[_key8];\n return childOverridesPromise.then((function(childOverrides) {\n return childOverrides.openPrerenderFrame.apply(childOverrides, args);\n }));\n };\n prerenderOverride = function() {\n for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) args[_key9] = arguments[_key9];\n return childOverridesPromise.then((function(childOverrides) {\n return childOverrides.prerender.apply(childOverrides, args);\n }));\n };\n openOverride = function() {\n for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) args[_key10] = arguments[_key10];\n return childOverridesPromise.then((function(childOverrides) {\n return childOverrides.open.apply(childOverrides, args);\n }));\n };\n openPrerenderOverride = function() {\n for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) args[_key11] = arguments[_key11];\n return childOverridesPromise.then((function(childOverrides) {\n return childOverrides.openPrerender.apply(childOverrides, args);\n }));\n };\n }\n return childOverridesPromise;\n }(context, target);\n }));\n var windowProp = props.window;\n var watchForUnloadPromise = watchForUnload();\n var buildUrlPromise = serializeProps(propsDef, props, \"get\").then((function(query) {\n return function(url, options) {\n var query = options.query || {};\n var hash = options.hash || {};\n var originalUrl;\n var originalHash;\n var _url$split = url.split(\"#\");\n originalHash = _url$split[1];\n var _originalUrl$split = (originalUrl = _url$split[0]).split(\"?\");\n originalUrl = _originalUrl$split[0];\n var queryString = extendQuery(_originalUrl$split[1], query);\n var hashString = extendQuery(originalHash, hash);\n queryString && (originalUrl = originalUrl + \"?\" + queryString);\n hashString && (originalUrl = originalUrl + \"#\" + hashString);\n return originalUrl;\n }(function(url) {\n if (!(domain = getDomainFromUrl(url), 0 === domain.indexOf(\"mock:\"))) return url;\n var domain;\n throw new Error(\"Mock urls not supported out of test mode\");\n }(getUrl()), {\n query: query\n });\n }));\n var buildBodyPromise = serializeProps(propsDef, props, \"post\");\n var onRenderPromise = event.trigger(EVENT.RENDER);\n var getProxyContainerPromise = getProxyContainer(container);\n var getProxyWindowPromise = getProxyWindow();\n var buildWindowNamePromise = getProxyWindowPromise.then((function(proxyWin) {\n return function(_temp) {\n var _ref5 = void 0 === _temp ? {} : _temp, proxyWin = _ref5.proxyWin, childDomain = _ref5.childDomain, domain = _ref5.domain, context = (void 0 === _ref5.target && window, \n _ref5.context);\n return function(proxyWin, childDomain, domain) {\n return getPropsForChild(domain).then((function(childProps) {\n var value = setup_serializeMessage(proxyWin, domain, childProps);\n var propRef = childDomain === getDomain() ? {\n type: \"uid\",\n uid: uid\n } : {\n type: \"raw\",\n value: value\n };\n if (\"uid\" === propRef.type) {\n var global = lib_global_getGlobal(window);\n global.props = global.props || {};\n global.props[uid] = value;\n clean.register((function() {\n delete global.props[uid];\n }));\n }\n return propRef;\n }));\n }(proxyWin, childDomain, domain).then((function(propsRef) {\n return {\n uid: uid,\n context: context,\n tag: tag,\n version: \"9_0_78\",\n childDomain: childDomain,\n parentDomain: getDomain(window),\n parent: getWindowRef(0, childDomain, context),\n props: propsRef,\n exports: setup_serializeMessage(proxyWin, domain, (win = proxyWin, {\n init: initChild,\n close: close,\n checkClose: function() {\n return checkWindowClose(win);\n },\n resize: resize,\n onError: onError,\n show: show,\n hide: hide,\n export: xport\n }))\n };\n var win;\n }));\n }({\n proxyWin: (_ref6 = {\n proxyWin: proxyWin,\n childDomain: childDomain,\n domain: domain,\n target: target,\n context: context\n }).proxyWin,\n childDomain: _ref6.childDomain,\n domain: _ref6.domain,\n target: _ref6.target,\n context: _ref6.context\n }).then((function(childPayload) {\n return \"__zoid__\" + name + \"__\" + base64encode(JSON.stringify(childPayload)) + \"__\";\n }));\n var _ref6;\n }));\n var openFramePromise = buildWindowNamePromise.then((function(windowName) {\n return openFrame(context, {\n windowName: windowName\n });\n }));\n var openPrerenderFramePromise = openPrerenderFrame(context);\n var renderContainerPromise = promise_ZalgoPromise.hash({\n proxyContainer: getProxyContainerPromise,\n proxyFrame: openFramePromise,\n proxyPrerenderFrame: openPrerenderFramePromise\n }).then((function(_ref14) {\n return renderContainer(_ref14.proxyContainer, {\n context: context,\n proxyFrame: _ref14.proxyFrame,\n proxyPrerenderFrame: _ref14.proxyPrerenderFrame,\n rerender: rerender\n });\n })).then((function(proxyContainer) {\n return proxyContainer;\n }));\n var openPromise = promise_ZalgoPromise.hash({\n windowName: buildWindowNamePromise,\n proxyFrame: openFramePromise,\n proxyWin: getProxyWindowPromise\n }).then((function(_ref15) {\n var proxyWin = _ref15.proxyWin;\n return windowProp ? proxyWin : open(context, {\n windowName: _ref15.windowName,\n proxyWin: proxyWin,\n proxyFrame: _ref15.proxyFrame\n });\n }));\n var openPrerenderPromise = promise_ZalgoPromise.hash({\n proxyWin: openPromise,\n proxyPrerenderFrame: openPrerenderFramePromise\n }).then((function(_ref16) {\n return openPrerender(context, _ref16.proxyWin, _ref16.proxyPrerenderFrame);\n }));\n var setStatePromise = openPromise.then((function(proxyWin) {\n currentProxyWin = proxyWin;\n return setProxyWin(proxyWin);\n }));\n var prerenderPromise = promise_ZalgoPromise.hash({\n proxyPrerenderWin: openPrerenderPromise,\n state: setStatePromise\n }).then((function(_ref17) {\n return prerender(_ref17.proxyPrerenderWin, {\n context: context\n });\n }));\n var setWindowNamePromise = promise_ZalgoPromise.hash({\n proxyWin: openPromise,\n windowName: buildWindowNamePromise\n }).then((function(_ref18) {\n if (windowProp) return _ref18.proxyWin.setName(_ref18.windowName);\n }));\n var getMethodPromise = promise_ZalgoPromise.hash({\n body: buildBodyPromise\n }).then((function(_ref19) {\n return options.method ? options.method : Object.keys(_ref19.body).length ? \"post\" : \"get\";\n }));\n var loadUrlPromise = promise_ZalgoPromise.hash({\n proxyWin: openPromise,\n windowUrl: buildUrlPromise,\n body: buildBodyPromise,\n method: getMethodPromise,\n windowName: setWindowNamePromise,\n prerender: prerenderPromise\n }).then((function(_ref20) {\n return _ref20.proxyWin.setLocation(_ref20.windowUrl, {\n method: _ref20.method,\n body: _ref20.body\n });\n }));\n var watchForClosePromise = openPromise.then((function(proxyWin) {\n !function watchForClose(proxyWin, context) {\n var cancelled = !1;\n clean.register((function() {\n cancelled = !0;\n }));\n return promise_ZalgoPromise.delay(2e3).then((function() {\n return proxyWin.isClosed();\n })).then((function(isClosed) {\n if (!cancelled) return isClosed ? close(new Error(\"Detected \" + context + \" close\")) : watchForClose(proxyWin, context);\n }));\n }(proxyWin, context);\n }));\n var onDisplayPromise = promise_ZalgoPromise.hash({\n container: renderContainerPromise,\n prerender: prerenderPromise\n }).then((function() {\n return event.trigger(EVENT.DISPLAY);\n }));\n var openBridgePromise = openPromise.then((function(proxyWin) {}));\n var runTimeoutPromise = loadUrlPromise.then((function() {\n return promise_ZalgoPromise.try((function() {\n var timeout = props.timeout;\n if (timeout) return initPromise.timeout(timeout, new Error(\"Loading component timed out after \" + timeout + \" milliseconds\"));\n }));\n }));\n var onRenderedPromise = initPromise.then((function() {\n return event.trigger(EVENT.RENDERED);\n }));\n return promise_ZalgoPromise.hash({\n initPromise: initPromise,\n buildUrlPromise: buildUrlPromise,\n onRenderPromise: onRenderPromise,\n getProxyContainerPromise: getProxyContainerPromise,\n openFramePromise: openFramePromise,\n openPrerenderFramePromise: openPrerenderFramePromise,\n renderContainerPromise: renderContainerPromise,\n openPromise: openPromise,\n openPrerenderPromise: openPrerenderPromise,\n setStatePromise: setStatePromise,\n prerenderPromise: prerenderPromise,\n loadUrlPromise: loadUrlPromise,\n buildWindowNamePromise: buildWindowNamePromise,\n setWindowNamePromise: setWindowNamePromise,\n watchForClosePromise: watchForClosePromise,\n onDisplayPromise: onDisplayPromise,\n openBridgePromise: openBridgePromise,\n runTimeoutPromise: runTimeoutPromise,\n onRenderedPromise: onRenderedPromise,\n delegatePromise: delegatePromise,\n watchForUnloadPromise: watchForUnloadPromise\n });\n })).catch((function(err) {\n return promise_ZalgoPromise.all([ onError(err), destroy(err) ]).then((function() {\n throw err;\n }), (function() {\n throw err;\n }));\n })).then(src_util_noop);\n },\n destroy: destroy,\n getProps: function() {\n return props;\n },\n setProps: setProps,\n export: xport,\n getHelpers: getHelpers,\n getDelegateOverrides: function() {\n return promise_ZalgoPromise.try((function() {\n return {\n getProxyContainer: getProxyContainer,\n show: show,\n hide: hide,\n renderContainer: renderContainer,\n getProxyWindow: getProxyWindow,\n watchForUnload: watchForUnload,\n openFrame: openFrame,\n openPrerenderFrame: openPrerenderFrame,\n prerender: prerender,\n open: open,\n openPrerender: openPrerender,\n setProxyWin: setProxyWin\n };\n }));\n },\n getExports: function() {\n return xports({\n getExports: function() {\n return exportsPromise;\n }\n });\n }\n };\n }\n function defaultContainerTemplate(_ref) {\n var uid = _ref.uid, frame = _ref.frame, prerenderFrame = _ref.prerenderFrame, doc = _ref.doc, props = _ref.props, event = _ref.event, dimensions = _ref.dimensions;\n var width = dimensions.width, height = dimensions.height;\n if (frame && prerenderFrame) {\n var div = doc.createElement(\"div\");\n div.setAttribute(\"id\", uid);\n var style = doc.createElement(\"style\");\n props.cspNonce && style.setAttribute(\"nonce\", props.cspNonce);\n style.appendChild(doc.createTextNode(\"\\n #\" + uid + \" {\\n display: inline-block;\\n position: relative;\\n width: \" + width + \";\\n height: \" + height + \";\\n }\\n\\n #\" + uid + \" > iframe {\\n display: inline-block;\\n position: absolute;\\n width: 100%;\\n height: 100%;\\n top: 0;\\n left: 0;\\n transition: opacity .2s ease-in-out;\\n }\\n\\n #\" + uid + \" > iframe.zoid-invisible {\\n opacity: 0;\\n }\\n\\n #\" + uid + \" > iframe.zoid-visible {\\n opacity: 1;\\n }\\n \"));\n div.appendChild(frame);\n div.appendChild(prerenderFrame);\n div.appendChild(style);\n prerenderFrame.classList.add(\"zoid-visible\");\n frame.classList.add(\"zoid-invisible\");\n event.on(EVENT.RENDERED, (function() {\n prerenderFrame.classList.remove(\"zoid-visible\");\n prerenderFrame.classList.add(\"zoid-invisible\");\n frame.classList.remove(\"zoid-invisible\");\n frame.classList.add(\"zoid-visible\");\n setTimeout((function() {\n destroyElement(prerenderFrame);\n }), 1);\n }));\n event.on(EVENT.RESIZE, (function(_ref2) {\n var newWidth = _ref2.width, newHeight = _ref2.height;\n \"number\" == typeof newWidth && (div.style.width = toCSS(newWidth));\n \"number\" == typeof newHeight && (div.style.height = toCSS(newHeight));\n }));\n return div;\n }\n }\n var cleanInstances = cleanup();\n var cleanZoid = cleanup();\n function component(opts) {\n var options = function(options) {\n var tag = options.tag, url = options.url, domain = options.domain, bridgeUrl = options.bridgeUrl, _options$props = options.props, props = void 0 === _options$props ? {} : _options$props, _options$dimensions = options.dimensions, dimensions = void 0 === _options$dimensions ? {} : _options$dimensions, _options$autoResize = options.autoResize, autoResize = void 0 === _options$autoResize ? {} : _options$autoResize, _options$allowedParen = options.allowedParentDomains, allowedParentDomains = void 0 === _options$allowedParen ? \"*\" : _options$allowedParen, _options$attributes = options.attributes, attributes = void 0 === _options$attributes ? {} : _options$attributes, _options$defaultConte = options.defaultContext, defaultContext = void 0 === _options$defaultConte ? CONTEXT.IFRAME : _options$defaultConte, _options$containerTem = options.containerTemplate, containerTemplate = void 0 === _options$containerTem ? defaultContainerTemplate : _options$containerTem, _options$prerenderTem = options.prerenderTemplate, prerenderTemplate = void 0 === _options$prerenderTem ? null : _options$prerenderTem, validate = options.validate, _options$eligible = options.eligible, eligible = void 0 === _options$eligible ? function() {\n return {\n eligible: !0\n };\n } : _options$eligible, _options$logger = options.logger, logger = void 0 === _options$logger ? {\n info: src_util_noop\n } : _options$logger, _options$exports = options.exports, xportsDefinition = void 0 === _options$exports ? src_util_noop : _options$exports, method = options.method, _options$children = options.children, children = void 0 === _options$children ? function() {\n return {};\n } : _options$children;\n var name = tag.replace(/-/g, \"_\");\n var propsDef = _extends({}, {\n window: {\n type: PROP_TYPE.OBJECT,\n sendToChild: !1,\n required: !1,\n allowDelegate: !0,\n validate: function(_ref2) {\n var value = _ref2.value;\n if (!isWindow(value) && !window_ProxyWindow.isProxyWindow(value)) throw new Error(\"Expected Window or ProxyWindow\");\n if (isWindow(value)) {\n if (isWindowClosed(value)) throw new Error(\"Window is closed\");\n if (!isSameDomain(value)) throw new Error(\"Window is not same domain\");\n }\n },\n decorate: function(_ref3) {\n return setup_toProxyWindow(_ref3.value);\n }\n },\n timeout: {\n type: PROP_TYPE.NUMBER,\n required: !1,\n sendToChild: !1\n },\n cspNonce: {\n type: PROP_TYPE.STRING,\n required: !1\n },\n onDisplay: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n allowDelegate: !0,\n default: props_defaultNoop,\n decorate: props_decorateOnce\n },\n onRendered: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n default: props_defaultNoop,\n decorate: props_decorateOnce\n },\n onRender: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n default: props_defaultNoop,\n decorate: props_decorateOnce\n },\n onClose: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n allowDelegate: !0,\n default: props_defaultNoop,\n decorate: props_decorateOnce\n },\n onDestroy: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n allowDelegate: !0,\n default: props_defaultNoop,\n decorate: props_decorateOnce\n },\n onResize: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n allowDelegate: !0,\n default: props_defaultNoop\n },\n onFocus: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n allowDelegate: !0,\n default: props_defaultNoop\n },\n close: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref4) {\n return _ref4.close;\n }\n },\n focus: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref5) {\n return _ref5.focus;\n }\n },\n resize: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref6) {\n return _ref6.resize;\n }\n },\n uid: {\n type: PROP_TYPE.STRING,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref7) {\n return _ref7.uid;\n }\n },\n tag: {\n type: PROP_TYPE.STRING,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref8) {\n return _ref8.tag;\n }\n },\n getParent: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref9) {\n return _ref9.getParent;\n }\n },\n getParentDomain: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref10) {\n return _ref10.getParentDomain;\n }\n },\n show: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref11) {\n return _ref11.show;\n }\n },\n hide: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref12) {\n return _ref12.hide;\n }\n },\n export: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref13) {\n return _ref13.export;\n }\n },\n onError: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref14) {\n return _ref14.onError;\n }\n },\n onProps: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref15) {\n return _ref15.onProps;\n }\n },\n getSiblings: {\n type: PROP_TYPE.FUNCTION,\n required: !1,\n sendToChild: !1,\n childDecorate: function(_ref16) {\n return _ref16.getSiblings;\n }\n }\n }, props);\n if (!containerTemplate) throw new Error(\"Container template required\");\n return {\n name: name,\n tag: tag,\n url: url,\n domain: domain,\n bridgeUrl: bridgeUrl,\n method: method,\n propsDef: propsDef,\n dimensions: dimensions,\n autoResize: autoResize,\n allowedParentDomains: allowedParentDomains,\n attributes: attributes,\n defaultContext: defaultContext,\n containerTemplate: containerTemplate,\n prerenderTemplate: prerenderTemplate,\n validate: validate,\n logger: logger,\n eligible: eligible,\n children: children,\n exports: \"function\" == typeof xportsDefinition ? xportsDefinition : function(_ref) {\n var getExports = _ref.getExports;\n var result = {};\n var _loop = function(_i2, _Object$keys2) {\n var key = _Object$keys2[_i2];\n var type = xportsDefinition[key].type;\n var valuePromise = getExports().then((function(res) {\n return res[key];\n }));\n result[key] = type === PROP_TYPE.FUNCTION ? function() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) args[_key] = arguments[_key];\n return valuePromise.then((function(value) {\n return value.apply(void 0, args);\n }));\n } : valuePromise;\n };\n for (var _i2 = 0, _Object$keys2 = Object.keys(xportsDefinition); _i2 < _Object$keys2.length; _i2++) _loop(_i2, _Object$keys2);\n return result;\n }\n };\n }(opts);\n var name = options.name, tag = options.tag, defaultContext = options.defaultContext, eligible = options.eligible, children = options.children;\n var global = lib_global_getGlobal();\n var instances = [];\n var isChild = function() {\n var payload = getChildPayload();\n return Boolean(payload && payload.tag === tag && payload.childDomain === getDomain());\n };\n var registerChild = memoize((function() {\n if (isChild()) {\n if (window.xprops) {\n delete global.components[tag];\n throw new Error(\"Can not register \" + name + \" as child - child already registered\");\n }\n var child = function(options) {\n var tag = options.tag, propsDef = options.propsDef, autoResize = options.autoResize, allowedParentDomains = options.allowedParentDomains;\n var onPropHandlers = [];\n var childPayload = getChildPayload();\n var props;\n var exportsPromise = new promise_ZalgoPromise;\n if (!childPayload) throw new Error(\"No child payload found\");\n if (\"9_0_78\" !== childPayload.version) throw new Error(\"Parent window has zoid version \" + childPayload.version + \", child window has version 9_0_78\");\n var uid = childPayload.uid, parentDomain = childPayload.parentDomain, parentExports = childPayload.exports, context = childPayload.context, propsRef = childPayload.props;\n var parentComponentWindow = function(ref) {\n var type = ref.type;\n if (\"opener\" === type) return assertExists(\"opener\", getOpener(window));\n if (\"parent\" === type && \"number\" == typeof ref.distance) return assertExists(\"parent\", function(win, n) {\n void 0 === n && (n = 1);\n return function(win, n) {\n void 0 === n && (n = 1);\n var parent = win;\n for (var i = 0; i < n; i++) {\n if (!parent) return;\n parent = utils_getParent(parent);\n }\n return parent;\n }(win, getDistanceFromTop(win) - n);\n }(window, ref.distance));\n if (\"global\" === type && ref.uid && \"string\" == typeof ref.uid) {\n var uid = ref.uid;\n var ancestor = getAncestor(window);\n if (!ancestor) throw new Error(\"Can not find ancestor window\");\n for (var _i2 = 0, _getAllFramesInWindow2 = getAllFramesInWindow(ancestor); _i2 < _getAllFramesInWindow2.length; _i2++) {\n var frame = _getAllFramesInWindow2[_i2];\n if (isSameDomain(frame)) {\n var global = lib_global_getGlobal(frame);\n if (global && global.windows && global.windows[uid]) return global.windows[uid];\n }\n }\n }\n throw new Error(\"Unable to find \" + type + \" parent component window\");\n }(childPayload.parent);\n var parent = setup_deserializeMessage(parentComponentWindow, parentDomain, parentExports);\n var show = parent.show, hide = parent.hide, close = parent.close;\n var getParent = function() {\n return parentComponentWindow;\n };\n var getParentDomain = function() {\n return parentDomain;\n };\n var onProps = function(handler) {\n onPropHandlers.push(handler);\n };\n var onError = function(err) {\n return promise_ZalgoPromise.try((function() {\n if (parent && parent.onError) return parent.onError(err);\n throw err;\n }));\n };\n var resize = function(_ref) {\n return parent.resize.fireAndForget({\n width: _ref.width,\n height: _ref.height\n });\n };\n var xport = function(xports) {\n exportsPromise.resolve(xports);\n return parent.export(xports);\n };\n var getSiblings = function(_temp) {\n var anyParent = (void 0 === _temp ? {} : _temp).anyParent;\n var result = [];\n var currentParent = props.parent;\n void 0 === anyParent && (anyParent = !currentParent);\n if (!anyParent && !currentParent) throw new Error(\"No parent found for \" + tag + \" child\");\n for (var _i4 = 0, _getAllFramesInWindow4 = getAllFramesInWindow(window); _i4 < _getAllFramesInWindow4.length; _i4++) {\n var win = _getAllFramesInWindow4[_i4];\n if (isSameDomain(win)) {\n var xprops = assertSameDomain(win).xprops;\n if (xprops && getParent() === xprops.getParent()) {\n var winParent = xprops.parent;\n (anyParent || !currentParent || winParent && winParent.uid === currentParent.uid) && result.push({\n props: xprops,\n exports: lib_global_getGlobal(win).exports\n });\n }\n }\n }\n return result;\n };\n var setProps = function(newProps, origin, isUpdate) {\n void 0 === isUpdate && (isUpdate = !1);\n var normalizedProps = function(parentComponentWindow, propsDef, props, origin, helpers, isUpdate) {\n void 0 === isUpdate && (isUpdate = !1);\n var result = {};\n for (var _i2 = 0, _Object$keys2 = Object.keys(props); _i2 < _Object$keys2.length; _i2++) {\n var key = _Object$keys2[_i2];\n var prop = propsDef[key];\n if (!prop || !prop.sameDomain || origin === getDomain(window) && isSameDomain(parentComponentWindow)) {\n var value = normalizeChildProp(propsDef, 0, key, props[key], helpers);\n result[key] = value;\n prop && prop.alias && !result[prop.alias] && (result[prop.alias] = value);\n }\n }\n if (!isUpdate) for (var _i4 = 0, _Object$keys4 = Object.keys(propsDef); _i4 < _Object$keys4.length; _i4++) {\n var _key = _Object$keys4[_i4];\n props.hasOwnProperty(_key) || (result[_key] = normalizeChildProp(propsDef, 0, _key, void 0, helpers));\n }\n return result;\n }(parentComponentWindow, propsDef, newProps, origin, {\n tag: tag,\n show: show,\n hide: hide,\n close: close,\n focus: child_focus,\n onError: onError,\n resize: resize,\n getSiblings: getSiblings,\n onProps: onProps,\n getParent: getParent,\n getParentDomain: getParentDomain,\n uid: uid,\n export: xport\n }, isUpdate);\n props ? extend(props, normalizedProps) : props = normalizedProps;\n for (var _i6 = 0; _i6 < onPropHandlers.length; _i6++) (0, onPropHandlers[_i6])(props);\n };\n var updateProps = function(newProps) {\n return promise_ZalgoPromise.try((function() {\n return setProps(newProps, parentDomain, !0);\n }));\n };\n return {\n init: function() {\n return promise_ZalgoPromise.try((function() {\n lib_global_getGlobal().exports = options.exports({\n getExports: function() {\n return exportsPromise;\n }\n });\n !function(allowedParentDomains, domain) {\n if (!matchDomain(allowedParentDomains, domain)) throw new Error(\"Can not be rendered by domain: \" + domain);\n }(allowedParentDomains, parentDomain);\n markWindowKnown(parentComponentWindow);\n !function() {\n window.addEventListener(\"beforeunload\", (function() {\n parent.checkClose.fireAndForget();\n }));\n window.addEventListener(\"unload\", (function() {\n parent.checkClose.fireAndForget();\n }));\n onCloseWindow(parentComponentWindow, (function() {\n child_destroy();\n }));\n }();\n return parent.init({\n updateProps: updateProps,\n close: child_destroy\n });\n })).then((function() {\n return (_autoResize$width = autoResize.width, width = void 0 !== _autoResize$width && _autoResize$width, \n _autoResize$height = autoResize.height, height = void 0 !== _autoResize$height && _autoResize$height, \n _autoResize$element = autoResize.element, elementReady(void 0 === _autoResize$element ? \"body\" : _autoResize$element).catch(src_util_noop).then((function(element) {\n return {\n width: width,\n height: height,\n element: element\n };\n }))).then((function(_ref3) {\n var width = _ref3.width, height = _ref3.height, element = _ref3.element;\n element && (width || height) && context !== CONTEXT.POPUP && onResize(element, (function(_ref4) {\n resize({\n width: width ? _ref4.width : void 0,\n height: height ? _ref4.height : void 0\n });\n }), {\n width: width,\n height: height\n });\n }));\n var _autoResize$width, width, _autoResize$height, height, _autoResize$element;\n })).catch((function(err) {\n onError(err);\n }));\n },\n getProps: function() {\n if (props) return props;\n setProps(function(parentComponentWindow, domain, propRef) {\n var props;\n if (\"raw\" === propRef.type) props = propRef.value; else if (\"uid\" === propRef.type) {\n if (!isSameDomain(parentComponentWindow)) throw new Error(\"Parent component window is on a different domain - expected \" + getDomain() + \" - can not retrieve props\");\n var global = lib_global_getGlobal(parentComponentWindow);\n props = assertExists(\"props\", global && global.props[propRef.uid]);\n }\n if (!props) throw new Error(\"Could not find props\");\n return setup_deserializeMessage(parentComponentWindow, domain, props);\n }(parentComponentWindow, parentDomain, propsRef), parentDomain);\n return props;\n }\n };\n }(options);\n child.init();\n return child;\n }\n }));\n registerChild();\n !function() {\n var allowDelegateListener = on_on(\"zoid_allow_delegate_\" + name, (function() {\n return !0;\n }));\n var delegateListener = on_on(\"zoid_delegate_\" + name, (function(_ref2) {\n var _ref2$data = _ref2.data;\n return {\n parent: parentComponent({\n uid: _ref2$data.uid,\n options: options,\n overrides: _ref2$data.overrides,\n parentWin: _ref2.source\n })\n };\n }));\n cleanZoid.register(allowDelegateListener.cancel);\n cleanZoid.register(delegateListener.cancel);\n }();\n global.components = global.components || {};\n if (global.components[tag]) throw new Error(\"Can not register multiple components with the same tag: \" + tag);\n global.components[tag] = !0;\n return {\n init: function init(inputProps) {\n var instance;\n var uid = \"zoid-\" + tag + \"-\" + uniqueID();\n var props = inputProps || {};\n var _eligible = eligible({\n props: props\n }), eligibility = _eligible.eligible, reason = _eligible.reason;\n var onDestroy = props.onDestroy;\n props.onDestroy = function() {\n instance && eligibility && instances.splice(instances.indexOf(instance), 1);\n if (onDestroy) return onDestroy.apply(void 0, arguments);\n };\n var parent = parentComponent({\n uid: uid,\n options: options\n });\n parent.init();\n eligibility ? parent.setProps(props) : props.onDestroy && props.onDestroy();\n cleanInstances.register((function(err) {\n return parent.destroy(err || new Error(\"zoid destroyed all components\"));\n }));\n var clone = function(_temp) {\n var _ref4$decorate = (void 0 === _temp ? {} : _temp).decorate;\n return init((void 0 === _ref4$decorate ? identity : _ref4$decorate)(props));\n };\n var _render = function(target, container, context) {\n return promise_ZalgoPromise.try((function() {\n if (!eligibility) {\n var err = new Error(reason || name + \" component is not eligible\");\n return parent.destroy(err).then((function() {\n throw err;\n }));\n }\n if (!isWindow(target)) throw new Error(\"Must pass window to renderTo\");\n return function(props, context) {\n return promise_ZalgoPromise.try((function() {\n if (props.window) return setup_toProxyWindow(props.window).getType();\n if (context) {\n if (context !== CONTEXT.IFRAME && context !== CONTEXT.POPUP) throw new Error(\"Unrecognized context: \" + context);\n return context;\n }\n return defaultContext;\n }));\n }(props, context);\n })).then((function(finalContext) {\n container = function(context, container) {\n if (container) {\n if (\"string\" != typeof container && !isElement(container)) throw new TypeError(\"Expected string or element selector to be passed\");\n return container;\n }\n if (context === CONTEXT.POPUP) return \"body\";\n throw new Error(\"Expected element to be passed to render iframe\");\n }(finalContext, container);\n if (target !== window && \"string\" != typeof container) throw new Error(\"Must pass string element when rendering to another window\");\n return parent.render({\n target: target,\n container: container,\n context: finalContext,\n rerender: function() {\n var newInstance = clone();\n extend(instance, newInstance);\n return newInstance.renderTo(target, container, context);\n }\n });\n })).catch((function(err) {\n return parent.destroy(err).then((function() {\n throw err;\n }));\n }));\n };\n instance = _extends({}, parent.getExports(), parent.getHelpers(), function() {\n var childComponents = children();\n var result = {};\n var _loop2 = function(_i4, _Object$keys4) {\n var childName = _Object$keys4[_i4];\n var Child = childComponents[childName];\n result[childName] = function(childInputProps) {\n var parentProps = parent.getProps();\n var childProps = _extends({}, childInputProps, {\n parent: {\n uid: uid,\n props: parentProps,\n export: parent.export\n }\n });\n return Child(childProps);\n };\n };\n for (var _i4 = 0, _Object$keys4 = Object.keys(childComponents); _i4 < _Object$keys4.length; _i4++) _loop2(_i4, _Object$keys4);\n return result;\n }(), {\n isEligible: function() {\n return eligibility;\n },\n clone: clone,\n render: function(container, context) {\n return _render(window, container, context);\n },\n renderTo: function(target, container, context) {\n return _render(target, container, context);\n }\n });\n eligibility && instances.push(instance);\n return instance;\n },\n instances: instances,\n driver: function(driverName, dep) {\n throw new Error(\"Driver support not enabled\");\n },\n isChild: isChild,\n canRenderTo: function(win) {\n return send_send(win, \"zoid_allow_delegate_\" + name).then((function(_ref3) {\n return _ref3.data;\n })).catch((function() {\n return !1;\n }));\n },\n registerChild: registerChild\n };\n }\n var component_create = function(options) {\n !function() {\n if (!global_getGlobal().initialized) {\n global_getGlobal().initialized = !0;\n on = (_ref3 = {\n on: on_on,\n send: send_send\n }).on, send = _ref3.send, (global = global_getGlobal()).receiveMessage = global.receiveMessage || function(message) {\n return receive_receiveMessage(message, {\n on: on,\n send: send\n });\n };\n !function(_ref5) {\n var on = _ref5.on, send = _ref5.send;\n globalStore().getOrSet(\"postMessageListener\", (function() {\n return addEventListener(window, \"message\", (function(event) {\n !function(event, _ref4) {\n var on = _ref4.on, send = _ref4.send;\n promise_ZalgoPromise.try((function() {\n var source = event.source || event.sourceElement;\n var origin = event.origin || event.originalEvent && event.originalEvent.origin;\n var data = event.data;\n \"null\" === origin && (origin = \"file://\");\n if (source) {\n if (!origin) throw new Error(\"Post message did not have origin domain\");\n receive_receiveMessage({\n source: source,\n origin: origin,\n data: data\n }, {\n on: on,\n send: send\n });\n }\n }));\n }(event, {\n on: on,\n send: send\n });\n }));\n }));\n }({\n on: on_on,\n send: send_send\n });\n !function(_ref8) {\n var on = _ref8.on, send = _ref8.send;\n globalStore(\"builtinListeners\").getOrSet(\"helloListener\", (function() {\n var listener = on(\"postrobot_hello\", {\n domain: \"*\"\n }, (function(_ref3) {\n resolveHelloPromise(_ref3.source, {\n domain: _ref3.origin\n });\n return {\n instanceID: getInstanceID()\n };\n }));\n var parent = getAncestor();\n parent && sayHello(parent, {\n send: send\n }).catch((function(err) {}));\n return listener;\n }));\n }({\n on: on_on,\n send: send_send\n });\n }\n var _ref3, on, send, global;\n }();\n var comp = component(options);\n var init = function(props) {\n return comp.init(props);\n };\n init.driver = function(name, dep) {\n return comp.driver(name, dep);\n };\n init.isChild = function() {\n return comp.isChild();\n };\n init.canRenderTo = function(win) {\n return comp.canRenderTo(win);\n };\n init.instances = comp.instances;\n var child = comp.registerChild();\n child && (window.xprops = init.xprops = child.getProps());\n return init;\n };\n function destroyComponents(err) {\n var destroyPromise = cleanInstances.all(err);\n cleanInstances = cleanup();\n return destroyPromise;\n }\n var destroyAll = destroyComponents;\n function component_destroy(err) {\n destroyAll();\n delete window.__zoid_9_0_78__;\n !function() {\n !function() {\n var responseListeners = globalStore(\"responseListeners\");\n for (var _i2 = 0, _responseListeners$ke2 = responseListeners.keys(); _i2 < _responseListeners$ke2.length; _i2++) {\n var hash = _responseListeners$ke2[_i2];\n var listener = responseListeners.get(hash);\n listener && (listener.cancelled = !0);\n responseListeners.del(hash);\n }\n }();\n (listener = globalStore().get(\"postMessageListener\")) && listener.cancel();\n var listener;\n delete window.__post_robot_10_0_44__;\n }();\n return cleanZoid.all(err);\n }\n } ]);\n}));", "/* @flow */\n/* eslint import/no-commonjs: 0 */\n\n// eslint-disable-next-line no-process-env\nif (process && process.env && process.env.ZOID_FRAME_ONLY) {\n // $FlowFixMe\n module.exports = require('./dist/zoid.frame');\n // $FlowFixMe\n module.exports.default = module.exports;\n} else {\n // $FlowFixMe\n module.exports = require('./dist/zoid');\n // $FlowFixMe\n module.exports.default = module.exports;\n}\n", "/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nexport function __importStar(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}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n function next() {\n while (env.stack.length) {\n var rec = env.stack.pop();\n try {\n var result = rec.dispose && rec.dispose.call(rec.value);\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n catch (e) {\n fail(e);\n }\n }\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n};\n", "export {};\n//# sourceMappingURL=interface.js.map", "export {};\n//# sourceMappingURL=index.js.map", "export {};\n//# sourceMappingURL=interfaces.js.map", "export function dset(obj, keys, val) {\n\tkeys.split && (keys=keys.split('.'));\n\tvar i=0, l=keys.length, t=obj, x, k;\n\twhile (i < l) {\n\t\tk = ''+keys[i++];\n\t\tif (k === '__proto__' || k === 'constructor' || k === 'prototype') break;\n\t\tt = t[k] = (i === l) ? val : (typeof(x=t[k])===typeof(keys)) ? x : (keys[i]*0 !== 0 || !!~(''+keys[i]).indexOf('.')) ? {} : [];\n\t}\n}\n", "export const pickBy = (\n obj: T,\n fn: (key: K, v: T[K]) => boolean\n) => {\n return (Object.keys(obj) as K[])\n .filter((k) => fn(k, obj[k]))\n .reduce((acc, key) => ((acc[key] = obj[key]), acc), {} as Partial)\n}\n", "export class ValidationError extends Error {\n field: string\n\n constructor(field: string, message: string) {\n super(`${field} ${message}`)\n this.field = field\n }\n}\n", "export function isString(obj: unknown): obj is string {\n return typeof obj === 'string'\n}\n\nexport function isNumber(obj: unknown): obj is number {\n return typeof obj === 'number'\n}\n\nexport function isFunction(obj: unknown): obj is Function {\n return typeof obj === 'function'\n}\n\nexport function exists(val: unknown): val is NonNullable {\n return val !== undefined && val !== null\n}\n\nexport function isPlainObject(\n obj: unknown\n): obj is Record {\n return (\n Object.prototype.toString.call(obj).slice(8, -1).toLowerCase() === 'object'\n )\n}\n", "import { CoreSegmentEvent } from '../events'\nimport { ValidationError } from './errors'\nimport { isString, isPlainObject, exists } from './helpers'\n\nconst stringError = 'is not a string'\nconst objError = 'is not an object'\nconst nilError = 'is nil'\n\n// user identity check could hypothetically could be used in the browser event factory, but not 100% sure -- so this is node only for now\nexport function assertUserIdentity(event: CoreSegmentEvent): void {\n const USER_FIELD_NAME = '.userId/anonymousId/previousId/groupId'\n\n const getAnyUserId = (event: CoreSegmentEvent) =>\n event.userId ?? event.anonymousId ?? event.groupId ?? event.previousId\n\n const id = getAnyUserId(event)\n if (!exists(id)) {\n throw new ValidationError(USER_FIELD_NAME, nilError)\n } else if (!isString(id)) {\n throw new ValidationError(USER_FIELD_NAME, stringError)\n }\n}\n\nexport function assertEventExists(\n event?: CoreSegmentEvent | null\n): asserts event is CoreSegmentEvent {\n if (!exists(event)) {\n throw new ValidationError('Event', nilError)\n }\n if (typeof event !== 'object') {\n throw new ValidationError('Event', objError)\n }\n}\n\nexport function assertEventType(event: CoreSegmentEvent): void {\n if (!isString(event.type)) {\n throw new ValidationError('.type', stringError)\n }\n}\n\nexport function assertTrackEventName(event: CoreSegmentEvent): void {\n if (!isString(event.event)) {\n throw new ValidationError('.event', stringError)\n }\n}\n\nexport function assertTrackEventProperties(event: CoreSegmentEvent): void {\n if (!isPlainObject(event.properties)) {\n throw new ValidationError('.properties', objError)\n }\n}\n\nexport function assertTraits(event: CoreSegmentEvent): void {\n if (!isPlainObject(event.traits)) {\n throw new ValidationError('.traits', objError)\n }\n}\n\nexport function assertMessageId(event: CoreSegmentEvent): void {\n if (!isString(event.messageId)) {\n throw new ValidationError('.messageId', stringError)\n }\n}\n\nexport function validateEvent(event?: CoreSegmentEvent | null) {\n assertEventExists(event)\n assertEventType(event)\n assertMessageId(event)\n\n if (event.type === 'track') {\n assertTrackEventName(event)\n assertTrackEventProperties(event)\n }\n\n if (['group', 'identify'].includes(event.type)) {\n assertTraits(event)\n }\n}\n", "export * from './interfaces'\nimport { dset } from 'dset'\nimport { ID } from '../user'\nimport {\n Integrations,\n EventProperties,\n CoreSegmentEvent,\n CoreOptions,\n CoreExtraContext,\n UserTraits,\n GroupTraits,\n} from './interfaces'\nimport { pickBy } from '../utils/pick'\nimport type { RemoveIndexSignature } from '../utils/ts-helpers'\nimport { validateEvent } from '../validation/assertions'\n\nexport type EventMethodCallHook = ({\n type,\n options,\n}: {\n type: 'track' | 'identify' | 'page' | 'group' | 'alias' | 'screen'\n options?: CoreOptions\n}) => void\n\nexport type EventHook = (event: CoreSegmentEvent) => void\n\nexport interface EventFactorySettings {\n /**\n * Universal `messageId` builder for all events (these must be unique)\n */\n createMessageId: () => string\n /**\n * Hook to do something with an event right before they are returned from the factory.\n * This includes event modification or additional validation.\n */\n onFinishedEvent?: EventHook\n /**\n * Hook whenever an event method is called (track, page, etc.)\n * Can be used to update Options (or just listen)\n */\n onEventMethodCall?: EventMethodCallHook\n}\n\n/**\n * Internal settings object that is used internally by the factory\n */\nclass InternalEventFactorySettings {\n public createMessageId: EventFactorySettings['createMessageId']\n public onEventMethodCall: EventMethodCallHook\n public onFinishedEvent: EventHook\n\n constructor(public settings: EventFactorySettings) {\n this.createMessageId = settings.createMessageId\n this.onEventMethodCall = settings.onEventMethodCall ?? (() => {})\n this.onFinishedEvent = settings.onFinishedEvent ?? (() => {})\n }\n}\n\nexport abstract class CoreEventFactory {\n private settings: InternalEventFactorySettings\n\n constructor(settings: EventFactorySettings) {\n this.settings = new InternalEventFactorySettings(settings)\n }\n\n track(\n event: string,\n properties?: EventProperties,\n options?: CoreOptions,\n globalIntegrations?: Integrations\n ) {\n this.settings.onEventMethodCall({ type: 'track', options })\n return this.normalize({\n ...this.baseEvent(),\n event,\n type: 'track',\n properties: properties ?? {}, // TODO: why is this not a shallow copy like everywhere else?\n options: { ...options },\n integrations: { ...globalIntegrations },\n })\n }\n\n page(\n category: string | null,\n page: string | null,\n properties?: EventProperties,\n options?: CoreOptions,\n globalIntegrations?: Integrations\n ): CoreSegmentEvent {\n this.settings.onEventMethodCall({ type: 'page', options })\n const event: CoreSegmentEvent = {\n type: 'page',\n properties: { ...properties },\n options: { ...options },\n integrations: { ...globalIntegrations },\n }\n\n if (category !== null) {\n event.category = category\n event.properties = event.properties ?? {}\n event.properties.category = category\n }\n\n if (page !== null) {\n event.name = page\n }\n\n return this.normalize({\n ...this.baseEvent(),\n ...event,\n })\n }\n\n screen(\n category: string | null,\n screen: string | null,\n properties?: EventProperties,\n options?: CoreOptions,\n globalIntegrations?: Integrations\n ): CoreSegmentEvent {\n this.settings.onEventMethodCall({ type: 'screen', options })\n const event: CoreSegmentEvent = {\n type: 'screen',\n properties: { ...properties },\n options: { ...options },\n integrations: { ...globalIntegrations },\n }\n\n if (category !== null) {\n event.category = category\n }\n\n if (screen !== null) {\n event.name = screen\n }\n\n return this.normalize({\n ...this.baseEvent(),\n ...event,\n })\n }\n\n identify(\n userId: ID,\n traits?: UserTraits,\n options?: CoreOptions,\n globalIntegrations?: Integrations\n ): CoreSegmentEvent {\n this.settings.onEventMethodCall({ type: 'identify', options })\n return this.normalize({\n ...this.baseEvent(),\n type: 'identify',\n userId,\n traits: traits ?? {},\n options: { ...options },\n integrations: globalIntegrations,\n })\n }\n\n group(\n groupId: ID,\n traits?: GroupTraits,\n options?: CoreOptions,\n globalIntegrations?: Integrations\n ): CoreSegmentEvent {\n this.settings.onEventMethodCall({ type: 'group', options })\n return this.normalize({\n ...this.baseEvent(),\n type: 'group',\n traits: traits ?? {},\n options: { ...options }, // this spreading is intentional\n integrations: { ...globalIntegrations }, //\n groupId,\n })\n }\n\n alias(\n to: string,\n from: string | null, // TODO: can we make this undefined?\n options?: CoreOptions,\n globalIntegrations?: Integrations\n ): CoreSegmentEvent {\n this.settings.onEventMethodCall({ type: 'alias', options })\n const base: CoreSegmentEvent = {\n userId: to,\n type: 'alias',\n options: { ...options },\n integrations: { ...globalIntegrations },\n }\n\n if (from !== null) {\n base.previousId = from\n }\n\n if (to === undefined) {\n return this.normalize({\n ...base,\n ...this.baseEvent(),\n })\n }\n\n return this.normalize({\n ...this.baseEvent(),\n ...base,\n })\n }\n\n private baseEvent(): Partial {\n return {\n integrations: {},\n options: {},\n }\n }\n\n /**\n * Builds the context part of an event based on \"foreign\" keys that\n * are provided in the `Options` parameter for an Event\n */\n private context(\n options: CoreOptions\n ): [CoreExtraContext, Partial] {\n type CoreOptionKeys = keyof RemoveIndexSignature\n /**\n * If the event options are known keys from this list, we move them to the top level of the event.\n * Any other options are moved to context.\n */\n const eventOverrideKeys: CoreOptionKeys[] = [\n 'userId',\n 'anonymousId',\n 'timestamp',\n 'messageId',\n ]\n\n delete options['integrations']\n const providedOptionsKeys = Object.keys(options) as Exclude<\n CoreOptionKeys,\n 'integrations'\n >[]\n\n const context = options.context ?? {}\n const eventOverrides = {}\n\n providedOptionsKeys.forEach((key) => {\n if (key === 'context') {\n return\n }\n\n if (eventOverrideKeys.includes(key)) {\n dset(eventOverrides, key, options[key])\n } else {\n dset(context, key, options[key])\n }\n })\n\n return [context, eventOverrides]\n }\n\n private normalize(event: CoreSegmentEvent): CoreSegmentEvent {\n const integrationBooleans = Object.keys(event.integrations ?? {}).reduce(\n (integrationNames, name) => {\n return {\n ...integrationNames,\n [name]: Boolean(event.integrations?.[name]),\n }\n },\n {} as Record\n )\n\n // filter out any undefined options\n event.options = pickBy(event.options || {}, (_, value) => {\n return value !== undefined\n })\n\n // This is pretty trippy, but here's what's going on:\n // - a) We don't pass initial integration options as part of the event, only if they're true or false\n // - b) We do accept per integration overrides (like integrations.Amplitude.sessionId) at the event level\n // Hence the need to convert base integration options to booleans, but maintain per event integration overrides\n const allIntegrations = {\n // Base config integrations object as booleans\n ...integrationBooleans,\n\n // Per event overrides, for things like amplitude sessionId, for example\n ...event.options?.integrations,\n }\n\n const [context, overrides] = event.options\n ? this.context(event.options)\n : []\n\n const { options, ...rest } = event\n\n const evt: CoreSegmentEvent = {\n timestamp: new Date(),\n ...rest,\n context,\n integrations: allIntegrations,\n ...overrides,\n messageId: options.messageId || this.settings.createMessageId(),\n }\n\n this.settings.onFinishedEvent(evt)\n validateEvent(evt)\n\n return evt\n }\n}\n", "import { CoreContext } from '../context'\nimport type { Callback } from '../events'\n\nexport function pTimeout(promise: Promise, timeout: number): Promise {\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n reject(Error('Promise timed out'))\n }, timeout)\n\n promise\n .then((val) => {\n clearTimeout(timeoutId)\n return resolve(val)\n })\n .catch(reject)\n })\n}\n\nexport function sleep(timeoutInMs: number): Promise {\n return new Promise((resolve) => setTimeout(resolve, timeoutInMs))\n}\n\n/**\n * @param ctx\n * @param callback - the function to invoke\n * @param delay - aka \"timeout\". The amount of time in ms to wait before invoking the callback.\n */\nexport function invokeCallback(\n ctx: Ctx,\n callback: Callback,\n delay: number\n): Promise {\n const cb = () => {\n try {\n return Promise.resolve(callback(ctx))\n } catch (err) {\n return Promise.reject(err)\n }\n }\n\n return (\n sleep(delay)\n // pTimeout ensures that the callback can't cause the context to hang\n .then(() => pTimeout(cb(), 1000))\n .catch((err) => {\n ctx?.log('warn', 'Callback Error', { error: err })\n ctx?.stats.increment('callback_error')\n })\n .then(() => ctx)\n )\n}\n", "/**\n * Return a promise that can be externally resolved\n */\nexport const createDeferred = () => {\n let resolve!: (value: T | PromiseLike) => void\n let reject!: (reason: any) => void\n let settled = false\n const promise = new Promise((_resolve, _reject) => {\n resolve = (...args) => {\n settled = true\n _resolve(...args)\n }\n reject = (...args) => {\n settled = true\n _reject(...args)\n }\n })\n\n return {\n resolve,\n reject,\n promise,\n isSettled: () => settled,\n }\n}\n", "export * from './create-deferred'\n", "type EventName = string\ntype EventFnArgs = any[]\ntype EmitterContract = Record\n\nexport interface EmitterOptions {\n /** How many event listeners for a particular event before emitting a warning (0 = disabled)\n * @default 10\n **/\n maxListeners?: number\n}\n\n/**\n * Event Emitter that takes the expected contract as a generic\n * @example\n * ```ts\n * type Contract = {\n * delivery_success: [DeliverySuccessResponse, Metrics],\n * delivery_failure: [DeliveryError]\n * }\n * new Emitter()\n * .on('delivery_success', (res, metrics) => ...)\n * .on('delivery_failure', (err) => ...)\n * ```\n */\nexport class Emitter {\n maxListeners: number\n constructor(options?: EmitterOptions) {\n this.maxListeners = options?.maxListeners ?? 10\n }\n private callbacks: Partial = {}\n private warned = false\n\n private warnIfPossibleMemoryLeak(\n event: EventName\n ) {\n if (this.warned) {\n return\n }\n if (\n this.maxListeners &&\n this.callbacks[event]!.length > this.maxListeners\n ) {\n console.warn(\n `Event Emitter: Possible memory leak detected; ${String(\n event\n )} has exceeded ${this.maxListeners} listeners.`\n )\n this.warned = true\n }\n }\n\n on(\n event: EventName,\n callback: (...args: Contract[EventName]) => void\n ): this {\n if (!this.callbacks[event]) {\n this.callbacks[event] = [callback] as Contract[EventName]\n } else {\n this.callbacks[event]!.push(callback)\n this.warnIfPossibleMemoryLeak(event)\n }\n return this\n }\n\n once(\n event: EventName,\n callback: (...args: Contract[EventName]) => void\n ): this {\n const on = (...args: Contract[EventName]): void => {\n this.off(event, on)\n callback.apply(this, args)\n }\n\n this.on(event, on)\n return this\n }\n\n off(\n event: EventName,\n callback: (...args: Contract[EventName]) => void\n ): this {\n const fns = this.callbacks[event] ?? []\n const without = fns.filter((fn) => fn !== callback) as Contract[EventName]\n this.callbacks[event] = without\n return this\n }\n\n emit(\n event: EventName,\n ...args: Contract[EventName]\n ): this {\n const callbacks = this.callbacks[event] ?? []\n callbacks.forEach((callback) => {\n callback.apply(this, args)\n })\n return this\n }\n}\n", "export * from './emitter'\n", "export * from './create-deferred'\nexport * from './emitter'\n", "type BackoffParams = {\n /** The number of milliseconds before starting the first retry. Default is 500 */\n minTimeout?: number\n\n /** The maximum number of milliseconds between two retries. Default is Infinity */\n maxTimeout?: number\n\n /** The exponential factor to use. Default is 2. */\n factor?: number\n\n /** The current attempt */\n attempt: number\n}\n\nexport function backoff(params: BackoffParams): number {\n const random = Math.random() + 1\n const {\n minTimeout = 500,\n factor = 2,\n attempt,\n maxTimeout = Infinity,\n } = params\n return Math.min(random * minTimeout * Math.pow(factor, attempt), maxTimeout)\n}\n", "import { Emitter } from '@segment/analytics-generic-utils'\nimport { backoff } from './backoff'\n\n/**\n * @internal\n */\nexport const ON_REMOVE_FROM_FUTURE = 'onRemoveFromFuture'\n\ninterface QueueItem {\n id: string\n}\n\nexport class PriorityQueue extends Emitter {\n protected future: Item[] = []\n protected queue: Item[]\n protected seen: Record\n\n public maxAttempts: number\n\n constructor(\n maxAttempts: number,\n queue: Item[],\n seen?: Record\n ) {\n super()\n this.maxAttempts = maxAttempts\n this.queue = queue\n this.seen = seen ?? {}\n }\n\n push(...items: Item[]): boolean[] {\n const accepted = items.map((operation) => {\n const attempts = this.updateAttempts(operation)\n\n if (attempts > this.maxAttempts || this.includes(operation)) {\n return false\n }\n\n this.queue.push(operation)\n return true\n })\n\n this.queue = this.queue.sort(\n (a, b) => this.getAttempts(a) - this.getAttempts(b)\n )\n return accepted\n }\n\n pushWithBackoff(item: Item): boolean {\n if (this.getAttempts(item) === 0) {\n return this.push(item)[0]\n }\n\n const attempt = this.updateAttempts(item)\n\n if (attempt > this.maxAttempts || this.includes(item)) {\n return false\n }\n\n const timeout = backoff({ attempt: attempt - 1 })\n\n setTimeout(() => {\n this.queue.push(item)\n // remove from future list\n this.future = this.future.filter((f) => f.id !== item.id)\n // Lets listeners know that a 'future' message is now available in the queue\n this.emit(ON_REMOVE_FROM_FUTURE)\n }, timeout)\n\n this.future.push(item)\n return true\n }\n\n public getAttempts(item: Item): number {\n return this.seen[item.id] ?? 0\n }\n\n public updateAttempts(item: Item): number {\n this.seen[item.id] = this.getAttempts(item) + 1\n return this.getAttempts(item)\n }\n\n includes(item: Item): boolean {\n return (\n this.queue.includes(item) ||\n this.future.includes(item) ||\n Boolean(this.queue.find((i) => i.id === item.id)) ||\n Boolean(this.future.find((i) => i.id === item.id))\n )\n }\n\n pop(): Item | undefined {\n return this.queue.shift()\n }\n\n public get length(): number {\n return this.queue.length\n }\n\n public get todo(): number {\n return this.queue.length + this.future.length\n }\n}\n", "var IDX=256, HEX=[], BUFFER;\nwhile (IDX--) HEX[IDX] = (IDX + 256).toString(16).substring(1);\n\nexport function v4() {\n\tvar i=0, num, out='';\n\n\tif (!BUFFER || ((IDX + 16) > 256)) {\n\t\tBUFFER = Array(i=256);\n\t\twhile (i--) BUFFER[i] = 256 * Math.random() | 0;\n\t\ti = IDX = 0;\n\t}\n\n\tfor (; i < 16; i++) {\n\t\tnum = BUFFER[IDX + i];\n\t\tif (i==6) out += HEX[num & 15 | 64];\n\t\telse if (i==8) out += HEX[num & 63 | 128];\n\t\telse out += HEX[num];\n\n\t\tif (i & 1 && i > 1 && i < 11) out += '-';\n\t}\n\n\tIDX++;\n\treturn out;\n}\n", "export type LogLevel = 'debug' | 'info' | 'warn' | 'error'\nexport type LogMessage = {\n level: LogLevel\n message: string\n time?: Date\n extras?: Record\n}\n\nexport interface GenericLogger {\n log(level: LogLevel, message: string, extras?: object): void\n flush(): void\n logs: LogMessage[]\n}\n\nexport class CoreLogger implements GenericLogger {\n private _logs: LogMessage[] = []\n\n log(level: LogLevel, message: string, extras?: object) {\n const time = new Date()\n this._logs.push({\n level,\n message,\n time,\n extras,\n })\n }\n\n public get logs(): LogMessage[] {\n return this._logs\n }\n\n public flush(): void {\n if (this.logs.length > 1) {\n const formatted = this._logs.reduce((logs, log) => {\n const line = {\n ...log,\n json: JSON.stringify(log.extras, null, ' '),\n extras: log.extras,\n }\n\n delete line['time']\n\n let key = log.time?.toISOString() ?? ''\n if (logs[key]) {\n key = `${key}-${Math.random()}`\n }\n\n return {\n ...logs,\n [key]: line,\n }\n }, {} as Record)\n\n // ie doesn't like console.table\n if (console.table) {\n console.table(formatted)\n } else {\n console.log(formatted)\n }\n } else {\n this.logs.forEach((logEntry) => {\n const { level, message, extras } = logEntry\n\n if (level === 'info' || level === 'debug') {\n console.log(message, extras ?? '')\n } else {\n console[level](message, extras ?? '')\n }\n })\n }\n\n this._logs = []\n }\n}\n", "type CompactMetricType = 'g' | 'c'\n\nexport type CoreMetricType = 'gauge' | 'counter'\n\nexport interface CoreMetric {\n metric: string\n value: number\n type: CoreMetricType\n tags: string[]\n timestamp: number // unit milliseconds\n}\n\nexport interface CompactMetric {\n m: string // metric name\n v: number // value\n k: CompactMetricType\n t: string[] // tags\n e: number // timestamp in unit milliseconds\n}\n\nconst compactMetricType = (type: CoreMetricType): CompactMetricType => {\n const enums: Record = {\n gauge: 'g',\n counter: 'c',\n }\n return enums[type]\n}\n\nexport abstract class CoreStats {\n metrics: CoreMetric[] = []\n increment(metric: string, by = 1, tags?: string[]): void {\n this.metrics.push({\n metric,\n value: by,\n tags: tags ?? [],\n type: 'counter',\n timestamp: Date.now(),\n })\n }\n\n gauge(metric: string, value: number, tags?: string[]): void {\n this.metrics.push({\n metric,\n value,\n tags: tags ?? [],\n type: 'gauge',\n timestamp: Date.now(),\n })\n }\n\n flush(): void {\n const formatted = this.metrics.map((m) => ({\n ...m,\n tags: m.tags.join(','),\n }))\n // ie doesn't like console.table\n if (console.table) {\n console.table(formatted)\n } else {\n console.log(formatted)\n }\n this.metrics = []\n }\n\n /**\n * compact keys for smaller payload\n */\n serialize(): CompactMetric[] {\n return this.metrics.map((m) => {\n return {\n m: m.metric,\n v: m.value,\n t: m.tags,\n k: compactMetricType(m.type),\n e: m.timestamp,\n }\n })\n }\n}\n\nexport class NullStats extends CoreStats {\n override gauge(..._args: Parameters) {}\n override increment(..._args: Parameters) {}\n override flush(..._args: Parameters) {}\n override serialize(..._args: Parameters) {\n return []\n }\n}\n", "import { CoreSegmentEvent } from '../events/interfaces'\n\nimport { v4 as uuid } from '@lukeed/uuid'\nimport { dset } from 'dset'\nimport { CoreLogger, LogLevel, LogMessage } from '../logger'\nimport { CoreStats, CoreMetric, NullStats } from '../stats'\n\nexport interface SerializedContext {\n id: string\n event: CoreSegmentEvent\n logs: LogMessage[]\n metrics?: CoreMetric[]\n}\n\nexport interface ContextFailedDelivery {\n reason: unknown\n}\n\nexport interface CancelationOptions {\n retry?: boolean\n reason?: string\n type?: string\n}\n\nexport class ContextCancelation {\n retry: boolean\n type: string\n reason?: string\n\n constructor(options: CancelationOptions) {\n this.retry = options.retry ?? true\n this.type = options.type ?? 'plugin Error'\n this.reason = options.reason ?? ''\n }\n}\n\nexport abstract class CoreContext<\n Event extends CoreSegmentEvent = CoreSegmentEvent\n> {\n event: Event\n logger: CoreLogger\n stats: CoreStats\n attempts = 0\n\n private _failedDelivery?: ContextFailedDelivery\n private _id: string\n\n constructor(\n event: Event,\n id = uuid(),\n stats: CoreStats = new NullStats(),\n logger = new CoreLogger()\n ) {\n this.event = event\n this._id = id\n this.logger = logger\n this.stats = stats\n }\n\n static system(): void {\n // This should be overridden by the subclass to return an instance of the subclass.\n }\n\n isSame(other: CoreContext): boolean {\n return other.id === this.id\n }\n\n cancel(error?: Error | ContextCancelation): never {\n if (error) {\n throw error\n }\n\n throw new ContextCancelation({ reason: 'Context Cancel' })\n }\n\n log(level: LogLevel, message: string, extras?: object): void {\n this.logger.log(level, message, extras)\n }\n\n get id(): string {\n return this._id\n }\n\n updateEvent(path: string, val: unknown): Event {\n // Don't allow integrations that are set to false to be overwritten with integration settings.\n if (path.split('.')[0] === 'integrations') {\n const integrationName = path.split('.')[1]\n\n if (this.event.integrations?.[integrationName] === false) {\n return this.event\n }\n }\n\n dset(this.event, path, val)\n return this.event\n }\n\n failedDelivery(): ContextFailedDelivery | undefined {\n return this._failedDelivery\n }\n\n setFailedDelivery(options: ContextFailedDelivery) {\n this._failedDelivery = options\n }\n\n logs(): LogMessage[] {\n return this.logger.logs\n }\n\n flush(): void {\n this.logger.flush()\n this.stats.flush()\n }\n\n toJSON(): SerializedContext {\n return {\n id: this._id,\n event: this.event,\n logs: this.logger.logs,\n metrics: this.stats.metrics,\n }\n }\n}\n", "type Grouper = (obj: T) => string | number\n\nexport function groupBy(\n collection: T[],\n grouper: keyof T | Grouper\n): Record {\n const results: Record = {}\n\n collection.forEach((item) => {\n let key: string | number | undefined = undefined\n\n if (typeof grouper === 'string') {\n const suggestedKey = item[grouper]\n key =\n typeof suggestedKey !== 'string'\n ? JSON.stringify(suggestedKey)\n : suggestedKey\n } else if (grouper instanceof Function) {\n key = grouper(item)\n }\n\n if (key === undefined) {\n return\n }\n\n results[key] = [...(results[key] ?? []), item]\n })\n\n return results\n}\n", "/**\n * Check if thenable\n * (instanceof Promise doesn't respect realms)\n */\nexport const isThenable = (value: unknown): boolean =>\n typeof value === 'object' &&\n value !== null &&\n 'then' in value &&\n typeof (value as any).then === 'function'\n", "import { isThenable } from '../utils/is-thenable'\n\nexport type TaskGroup = {\n done: () => Promise\n run: any>(\n op: Operation\n ) => ReturnType\n}\n\nexport const createTaskGroup = (): TaskGroup => {\n let taskCompletionPromise: Promise\n let resolvePromise: () => void\n let count = 0\n\n return {\n done: () => taskCompletionPromise,\n run: (op) => {\n const returnValue = op()\n\n if (isThenable(returnValue)) {\n if (++count === 1) {\n taskCompletionPromise = new Promise((res) => (resolvePromise = res))\n }\n\n returnValue.finally(() => --count === 0 && resolvePromise())\n }\n\n return returnValue\n },\n }\n}\n", "import { CoreContext, ContextCancelation } from '../context'\nimport { CorePlugin } from '../plugins'\n\nasync function tryAsync(fn: () => T | Promise): Promise {\n try {\n return await fn()\n } catch (err) {\n return Promise.reject(err)\n }\n}\n\nexport function attempt(\n ctx: Ctx,\n plugin: CorePlugin\n): Promise {\n ctx.log('debug', 'plugin', { plugin: plugin.name })\n const start = new Date().getTime()\n\n const hook = plugin[ctx.event.type]\n if (hook === undefined) {\n return Promise.resolve(ctx)\n }\n\n const newCtx = tryAsync(() => hook.apply(plugin, [ctx]))\n .then((ctx) => {\n const done = new Date().getTime() - start\n ctx.stats.gauge('plugin_time', done, [`plugin:${plugin.name}`])\n\n return ctx\n })\n .catch((err: Error | ContextCancelation) => {\n if (\n err instanceof ContextCancelation &&\n err.type === 'middleware_cancellation'\n ) {\n throw err\n }\n\n if (err instanceof ContextCancelation) {\n ctx.log('warn', err.type, {\n plugin: plugin.name,\n error: err,\n })\n\n return err\n }\n\n ctx.log('error', 'plugin Error', {\n plugin: plugin.name,\n error: err,\n })\n ctx.stats.increment('plugin_error', 1, [`plugin:${plugin.name}`])\n\n return err\n })\n\n return newCtx\n}\n\nexport function ensure(\n ctx: Ctx,\n plugin: CorePlugin\n): Promise {\n return attempt(ctx, plugin).then((newContext) => {\n if (newContext instanceof CoreContext) {\n return newContext\n }\n\n ctx.log('debug', 'Context canceled')\n ctx.stats.increment('context_canceled')\n ctx.cancel(newContext)\n })\n}\n", "import { CoreAnalytics } from '../analytics'\nimport { groupBy } from '../utils/group-by'\nimport { ON_REMOVE_FROM_FUTURE, PriorityQueue } from '../priority-queue'\n\nimport { CoreContext, ContextCancelation } from '../context'\nimport { Emitter } from '@segment/analytics-generic-utils'\nimport { Integrations, JSONObject } from '../events/interfaces'\nimport { CorePlugin } from '../plugins'\nimport { createTaskGroup, TaskGroup } from '../task/task-group'\nimport { attempt, ensure } from './delivery'\n\nexport type EventQueueEmitterContract = {\n message_delivered: [ctx: Ctx]\n message_enriched: [ctx: Ctx, plugin: CorePlugin]\n delivery_success: [ctx: Ctx]\n delivery_retry: [ctx: Ctx]\n delivery_failure: [ctx: Ctx, err: Ctx | Error | ContextCancelation]\n flush: [ctx: Ctx, delivered: boolean]\n initialization_failure: [CorePlugin]\n}\n\nexport abstract class CoreEventQueue<\n Ctx extends CoreContext = CoreContext,\n Plugin extends CorePlugin = CorePlugin\n> extends Emitter> {\n /**\n * All event deliveries get suspended until all the tasks in this task group are complete.\n * For example: a middleware that augments the event object should be loaded safely as a\n * critical task, this way, event queue will wait for it to be ready before sending events.\n *\n * This applies to all the events already in the queue, and the upcoming ones\n */\n criticalTasks: TaskGroup = createTaskGroup()\n queue: PriorityQueue\n plugins: Plugin[] = []\n failedInitializations: string[] = []\n private flushing = false\n\n constructor(priorityQueue: PriorityQueue) {\n super()\n\n this.queue = priorityQueue\n this.queue.on(ON_REMOVE_FROM_FUTURE, () => {\n this.scheduleFlush(0)\n })\n }\n\n async register(\n ctx: Ctx,\n plugin: Plugin,\n instance: CoreAnalytics\n ): Promise {\n this.plugins.push(plugin)\n\n const handleLoadError = (err: any) => {\n this.failedInitializations.push(plugin.name)\n this.emit('initialization_failure', plugin)\n console.warn(plugin.name, err)\n\n ctx.log('warn', 'Failed to load destination', {\n plugin: plugin.name,\n error: err,\n })\n\n // Filter out the failed plugin by excluding it from the list\n this.plugins = this.plugins.filter((p) => p !== plugin)\n }\n\n if (plugin.type === 'destination' && plugin.name !== 'Segment.io') {\n plugin.load(ctx, instance).catch(handleLoadError)\n } else {\n // for non-destinations plugins, we do need to wait for them to load\n // reminder: action destinations can require plugins that are not of type \"destination\".\n // For example, GA4 loads a type 'before' plugins and addition to a type 'destination' plugin\n try {\n await plugin.load(ctx, instance)\n } catch (err) {\n handleLoadError(err)\n }\n }\n }\n\n async deregister(\n ctx: Ctx,\n plugin: CorePlugin,\n instance: CoreAnalytics\n ): Promise {\n try {\n if (plugin.unload) {\n await Promise.resolve(plugin.unload(ctx, instance))\n }\n\n this.plugins = this.plugins.filter((p) => p.name !== plugin.name)\n } catch (e) {\n ctx.log('warn', 'Failed to unload destination', {\n plugin: plugin.name,\n error: e,\n })\n }\n }\n\n async dispatch(ctx: Ctx): Promise {\n ctx.log('debug', 'Dispatching')\n ctx.stats.increment('message_dispatched')\n\n this.queue.push(ctx)\n const willDeliver = this.subscribeToDelivery(ctx)\n this.scheduleFlush(0)\n return willDeliver\n }\n\n private async subscribeToDelivery(ctx: Ctx): Promise {\n return new Promise((resolve) => {\n const onDeliver = (flushed: Ctx, delivered: boolean): void => {\n if (flushed.isSame(ctx)) {\n this.off('flush', onDeliver)\n if (delivered) {\n resolve(flushed)\n } else {\n resolve(flushed)\n }\n }\n }\n\n this.on('flush', onDeliver)\n })\n }\n\n async dispatchSingle(ctx: Ctx): Promise {\n ctx.log('debug', 'Dispatching')\n ctx.stats.increment('message_dispatched')\n\n this.queue.updateAttempts(ctx)\n ctx.attempts = 1\n\n return this.deliver(ctx).catch((err) => {\n const accepted = this.enqueuRetry(err, ctx)\n if (!accepted) {\n ctx.setFailedDelivery({ reason: err })\n return ctx\n }\n\n return this.subscribeToDelivery(ctx)\n })\n }\n\n isEmpty(): boolean {\n return this.queue.length === 0\n }\n\n private scheduleFlush(timeout = 500): void {\n if (this.flushing) {\n return\n }\n\n this.flushing = true\n\n setTimeout(() => {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.flush().then(() => {\n setTimeout(() => {\n this.flushing = false\n\n if (this.queue.length) {\n this.scheduleFlush(0)\n }\n }, 0)\n })\n }, timeout)\n }\n\n private async deliver(ctx: Ctx): Promise {\n await this.criticalTasks.done()\n\n const start = Date.now()\n try {\n ctx = await this.flushOne(ctx)\n const done = Date.now() - start\n this.emit('delivery_success', ctx)\n ctx.stats.gauge('delivered', done)\n ctx.log('debug', 'Delivered', ctx.event)\n return ctx\n } catch (err: any) {\n const error = err as Ctx | Error | ContextCancelation\n ctx.log('error', 'Failed to deliver', error)\n this.emit('delivery_failure', ctx, error)\n ctx.stats.increment('delivery_failed')\n throw err\n }\n }\n\n private enqueuRetry(err: Error, ctx: Ctx): boolean {\n const retriable = !(err instanceof ContextCancelation) || err.retry\n if (!retriable) {\n return false\n }\n\n return this.queue.pushWithBackoff(ctx)\n }\n\n async flush(): Promise {\n if (this.queue.length === 0) {\n return []\n }\n\n let ctx = this.queue.pop()\n if (!ctx) {\n return []\n }\n\n ctx.attempts = this.queue.getAttempts(ctx)\n\n try {\n ctx = await this.deliver(ctx)\n this.emit('flush', ctx, true)\n } catch (err: any) {\n const accepted = this.enqueuRetry(err, ctx)\n\n if (!accepted) {\n ctx.setFailedDelivery({ reason: err })\n this.emit('flush', ctx, false)\n }\n\n return []\n }\n\n return [ctx]\n }\n\n private isReady(): boolean {\n // return this.plugins.every((p) => p.isLoaded())\n // should we wait for every plugin to load?\n return true\n }\n\n private availableExtensions(denyList: Integrations) {\n const available = this.plugins.filter((p) => {\n // Only filter out destination plugins or the Segment.io plugin\n if (p.type !== 'destination' && p.name !== 'Segment.io') {\n return true\n }\n\n let alternativeNameMatch: boolean | JSONObject | undefined = undefined\n p.alternativeNames?.forEach((name) => {\n if (denyList[name] !== undefined) {\n alternativeNameMatch = denyList[name]\n }\n })\n\n // Explicit integration option takes precedence, `All: false` does not apply to Segment.io\n return (\n denyList[p.name] ??\n alternativeNameMatch ??\n (p.name === 'Segment.io' ? true : denyList.All) !== false\n )\n })\n\n const {\n before = [],\n enrichment = [],\n destination = [],\n after = [],\n } = groupBy(available, 'type')\n\n return {\n before,\n enrichment,\n destinations: destination,\n after,\n }\n }\n\n private async flushOne(ctx: Ctx): Promise {\n if (!this.isReady()) {\n throw new Error('Not ready')\n }\n\n if (ctx.attempts > 1) {\n this.emit('delivery_retry', ctx)\n }\n\n const { before, enrichment } = this.availableExtensions(\n ctx.event.integrations ?? {}\n )\n\n for (const beforeWare of before) {\n const temp = await ensure(ctx, beforeWare)\n if (temp instanceof CoreContext) {\n ctx = temp\n }\n\n this.emit('message_enriched', ctx, beforeWare)\n }\n\n for (const enrichmentWare of enrichment) {\n const temp = await attempt(ctx, enrichmentWare)\n if (temp instanceof CoreContext) {\n ctx = temp\n }\n\n this.emit('message_enriched', ctx, enrichmentWare)\n }\n\n // Enrichment and before plugins can re-arrange the deny list dynamically\n // so we need to pluck them at the end\n const { destinations, after } = this.availableExtensions(\n ctx.event.integrations ?? {}\n )\n\n await new Promise((resolve, reject) => {\n setTimeout(() => {\n const attempts = destinations.map((destination) =>\n attempt(ctx, destination)\n )\n Promise.all(attempts).then(resolve).catch(reject)\n }, 0)\n })\n\n ctx.stats.increment('message_delivered')\n\n this.emit('message_delivered', ctx)\n\n const afterCalls = after.map((after) => attempt(ctx, after))\n await Promise.all(afterCalls)\n\n return ctx\n }\n}\n", "export {};\n//# sourceMappingURL=index.js.map", "import { CoreContext } from '../context'\nimport { Callback } from '../events/interfaces'\nimport { CoreEventQueue } from '../queue/event-queue'\nimport { invokeCallback } from '../callback'\nimport { Emitter } from '@segment/analytics-generic-utils'\n\nexport type DispatchOptions = {\n timeout?: number\n debug?: boolean\n callback?: Callback\n}\n\n/* The amount of time in ms to wait before invoking the callback. */\nexport const getDelay = (startTimeInEpochMS: number, timeoutInMS?: number) => {\n const elapsedTime = Date.now() - startTimeInEpochMS\n // increasing the timeout increases the delay by almost the same amount -- this is weird legacy behavior.\n return Math.max((timeoutInMS ?? 300) - elapsedTime, 0)\n}\n/**\n * Push an event into the dispatch queue and invoke any callbacks.\n *\n * @param event - Segment event to enqueue.\n * @param queue - Queue to dispatch against.\n * @param emitter - This is typically an instance of \"Analytics\" -- used for metrics / progress information.\n * @param options\n */\nexport async function dispatch<\n Ctx extends CoreContext,\n EQ extends CoreEventQueue\n>(\n ctx: Ctx,\n queue: EQ,\n emitter: Emitter,\n options?: DispatchOptions\n): Promise {\n emitter.emit('dispatch_start', ctx)\n\n const startTime = Date.now()\n let dispatched: Ctx\n if (queue.isEmpty()) {\n dispatched = await queue.dispatchSingle(ctx)\n } else {\n dispatched = await queue.dispatch(ctx)\n }\n\n if (options?.callback) {\n dispatched = await invokeCallback(\n dispatched,\n options.callback,\n getDelay(startTime, options.timeout)\n )\n }\n if (options?.debug) {\n dispatched.flush()\n }\n\n return dispatched\n}\n", "export function bindAll<\n ObjType extends { [key: string]: any },\n KeyType extends keyof ObjType\n>(obj: ObjType): ObjType {\n const proto = obj.constructor.prototype\n for (const key of Object.getOwnPropertyNames(proto)) {\n if (key !== 'constructor') {\n const desc = Object.getOwnPropertyDescriptor(\n obj.constructor.prototype,\n key\n )\n if (!!desc && typeof desc.value === 'function') {\n obj[key as KeyType] = obj[key].bind(obj)\n }\n }\n }\n\n return obj\n}\n", "export * from './emitter/interface'\nexport * from './plugins'\nexport * from './events/interfaces'\nexport * from './events'\nexport * from './callback'\nexport * from './priority-queue'\nexport { backoff } from './priority-queue/backoff'\nexport * from './context'\nexport * from './queue/event-queue'\nexport * from './analytics'\nexport * from './analytics/dispatch'\nexport * from './validation/helpers'\nexport * from './validation/errors'\nexport * from './validation/assertions'\nexport * from './utils/bind-all'\nexport * from './stats'\nexport { CoreLogger } from './logger'\nexport * from './queue/delivery'\n", "export function isBrowser(): boolean {\n return typeof window !== 'undefined'\n}\n\nexport function isServer(): boolean {\n return !isBrowser()\n}\n", "import { isBrowser } from '../environment'\n\nexport function isOnline(): boolean {\n if (isBrowser()) {\n return window.navigator.onLine\n }\n\n return true\n}\n\nexport function isOffline(): boolean {\n return !isOnline()\n}\n", "export default function(url, options) {\n\toptions = options || {};\n\treturn new Promise( (resolve, reject) => {\n\t\tconst request = new XMLHttpRequest();\n\t\tconst keys = [];\n\t\tconst all = [];\n\t\tconst headers = {};\n\n\t\tconst response = () => ({\n\t\t\tok: (request.status/100|0) == 2,\t\t// 200-299\n\t\t\tstatusText: request.statusText,\n\t\t\tstatus: request.status,\n\t\t\turl: request.responseURL,\n\t\t\ttext: () => Promise.resolve(request.responseText),\n\t\t\tjson: () => Promise.resolve(request.responseText).then(JSON.parse),\n\t\t\tblob: () => Promise.resolve(new Blob([request.response])),\n\t\t\tclone: response,\n\t\t\theaders: {\n\t\t\t\tkeys: () => keys,\n\t\t\t\tentries: () => all,\n\t\t\t\tget: n => headers[n.toLowerCase()],\n\t\t\t\thas: n => n.toLowerCase() in headers\n\t\t\t}\n\t\t});\n\n\t\trequest.open(options.method || 'get', url, true);\n\n\t\trequest.onload = () => {\n\t\t\trequest.getAllResponseHeaders().replace(/^(.*?):[^\\S\\n]*([\\s\\S]*?)$/gm, (m, key, value) => {\n\t\t\t\tkeys.push(key = key.toLowerCase());\n\t\t\t\tall.push([key, value]);\n\t\t\t\theaders[key] = headers[key] ? `${headers[key]},${value}` : value;\n\t\t\t});\n\t\t\tresolve(response());\n\t\t};\n\n\t\trequest.onerror = reject;\n\n\t\trequest.withCredentials = options.credentials=='include';\n\n\t\tfor (const i in options.headers) {\n\t\t\trequest.setRequestHeader(i, options.headers[i]);\n\t\t}\n\n\t\trequest.send(options.body || null);\n\t});\n}\n", "// This an imperfect polyfill for globalThis\nexport const getGlobal = () => {\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 return null\n}\n", "import unfetch from 'unfetch'\nimport { getGlobal } from './get-global'\n\n/**\n * Wrapper around native `fetch` containing `unfetch` fallback.\n */\nexport const fetch: typeof global.fetch = (...args) => {\n const global = getGlobal()\n return ((global && global.fetch) || unfetch)(...args)\n}\n", "// This file is generated.\nexport const version = '1.72.1'\n", "// Default value will be updated to 'web' in `bundle-umd.ts` for web build.\nlet _version: 'web' | 'npm' = 'npm'\n\nexport function setVersionType(version: typeof _version) {\n _version = version\n}\n\nexport function getVersionType(): typeof _version {\n return _version\n}\n", "export const SEGMENT_API_HOST = 'api.segment.io/v1'\n", "import { fetch } from '../../lib/fetch'\nimport { version } from '../../generated/version'\nimport { getVersionType } from '../../lib/version-type'\nimport { SEGMENT_API_HOST } from '../constants'\n\nexport interface MetricsOptions {\n host?: string\n sampleRate?: number\n flushTimer?: number\n maxQueueSize?: number\n protocol?: 'http' | 'https'\n}\n\n/**\n * Type expected by the segment metrics API endpoint\n */\ntype RemoteMetric = {\n type: 'Counter'\n metric: string\n value: 1\n tags: {\n library: string\n library_version: string\n [key: string]: string\n }\n}\n\nconst createRemoteMetric = (\n metric: string,\n tags: string[],\n versionType: 'web' | 'npm'\n): RemoteMetric => {\n const formattedTags = tags.reduce((acc, t) => {\n const [k, v] = t.split(':')\n acc[k] = v\n return acc\n }, {} as Record)\n\n return {\n type: 'Counter',\n metric,\n value: 1,\n tags: {\n ...formattedTags,\n library: 'analytics.js',\n library_version:\n versionType === 'web' ? `next-${version}` : `npm:next-${version}`,\n },\n }\n}\n\nfunction logError(err: unknown): void {\n console.error('Error sending segment performance metrics', err)\n}\n\nexport class RemoteMetrics {\n private host: string\n private flushTimer: number\n private maxQueueSize: number\n private protocol: string\n\n sampleRate: number\n queue: RemoteMetric[]\n\n constructor(options?: MetricsOptions) {\n this.host = options?.host ?? SEGMENT_API_HOST\n this.sampleRate = options?.sampleRate ?? 1\n this.flushTimer = options?.flushTimer ?? 30 * 1000 /* 30s */\n this.maxQueueSize = options?.maxQueueSize ?? 20\n this.protocol = options?.protocol ?? 'https'\n\n this.queue = []\n\n if (this.sampleRate > 0) {\n let flushing = false\n\n const run = (): void => {\n if (flushing) {\n return\n }\n\n flushing = true\n this.flush().catch(logError)\n\n flushing = false\n\n setTimeout(run, this.flushTimer)\n }\n run()\n }\n }\n\n increment(metric: string, tags: string[]): void {\n // All metrics are part of an allow list in Tracking API\n if (!metric.includes('analytics_js.')) {\n return\n }\n\n // /m doesn't like empty tags\n if (tags.length === 0) {\n return\n }\n\n if (Math.random() > this.sampleRate) {\n return\n }\n\n if (this.queue.length >= this.maxQueueSize) {\n return\n }\n\n const remoteMetric = createRemoteMetric(metric, tags, getVersionType())\n this.queue.push(remoteMetric)\n\n if (metric.includes('error')) {\n this.flush().catch(logError)\n }\n }\n\n async flush(): Promise {\n if (this.queue.length <= 0) {\n return\n }\n\n await this.send().catch((error) => {\n logError(error)\n this.sampleRate = 0\n })\n }\n\n private async send(): Promise {\n const payload = { series: this.queue }\n this.queue = []\n\n const headers = { 'Content-Type': 'text/plain' }\n const url = `${this.protocol}://${this.host}/m`\n\n return fetch(url, {\n headers,\n body: JSON.stringify(payload),\n method: 'POST',\n })\n }\n}\n", "import { CoreStats } from '@segment/analytics-core'\nimport { MetricsOptions, RemoteMetrics } from './remote-metrics'\n\nlet remoteMetrics: RemoteMetrics | undefined\n\nexport class Stats extends CoreStats {\n static initRemoteMetrics(options?: MetricsOptions) {\n remoteMetrics = new RemoteMetrics(options)\n }\n\n override increment(metric: string, by?: number, tags?: string[]): void {\n super.increment(metric, by, tags)\n remoteMetrics?.increment(metric, tags ?? [])\n }\n}\n", "import {\n CoreContext,\n ContextCancelation,\n ContextFailedDelivery,\n SerializedContext,\n CancelationOptions,\n} from '@segment/analytics-core'\nimport { SegmentEvent } from '../events/interfaces'\nimport { Stats } from '../stats'\n\nexport class Context extends CoreContext {\n static override system() {\n return new this({ type: 'track', event: 'system' })\n }\n constructor(event: SegmentEvent, id?: string) {\n super(event, id, new Stats())\n }\n}\n\nexport { ContextCancelation }\nexport type { ContextFailedDelivery, SerializedContext, CancelationOptions }\n", "import { PriorityQueue, ON_REMOVE_FROM_FUTURE } from '@segment/analytics-core'\n\nexport { PriorityQueue, ON_REMOVE_FROM_FUTURE }\n", "import { PriorityQueue } from '.'\nimport { Context, SerializedContext } from '../../core/context'\nimport { isBrowser } from '../../core/environment'\n\nlet loc:\n | Storage\n | { getItem: () => void; setItem: () => void; removeItem: () => void } = {\n getItem() {},\n setItem() {},\n removeItem() {},\n}\n\ntry {\n loc = isBrowser() && window.localStorage ? window.localStorage : loc\n} catch (err) {\n console.warn('Unable to access localStorage', err)\n}\n\nfunction persisted(key: string): Context[] {\n const items = loc.getItem(key)\n return (items ? JSON.parse(items) : []).map(\n (p: SerializedContext) => new Context(p.event, p.id)\n )\n}\n\nfunction persistItems(key: string, items: Context[]): void {\n const existing = persisted(key)\n const all = [...items, ...existing]\n\n const merged = all.reduce((acc, item) => {\n return {\n ...acc,\n [item.id]: item,\n }\n }, {} as Record)\n\n loc.setItem(key, JSON.stringify(Object.values(merged)))\n}\n\nfunction seen(key: string): Record {\n const stored = loc.getItem(key)\n return stored ? JSON.parse(stored) : {}\n}\n\nfunction persistSeen(key: string, memory: Record): void {\n const stored = seen(key)\n\n loc.setItem(\n key,\n JSON.stringify({\n ...stored,\n ...memory,\n })\n )\n}\n\nfunction remove(key: string): void {\n loc.removeItem(key)\n}\n\nconst now = (): number => new Date().getTime()\n\nfunction mutex(key: string, onUnlock: Function, attempt = 0): void {\n const lockTimeout = 50\n const lockKey = `persisted-queue:v1:${key}:lock`\n\n const expired = (lock: number): boolean => new Date().getTime() > lock\n const rawLock = loc.getItem(lockKey)\n const lock = rawLock ? (JSON.parse(rawLock) as number) : null\n\n const allowed = lock === null || expired(lock)\n if (allowed) {\n loc.setItem(lockKey, JSON.stringify(now() + lockTimeout))\n onUnlock()\n loc.removeItem(lockKey)\n return\n }\n\n if (!allowed && attempt < 3) {\n setTimeout(() => {\n mutex(key, onUnlock, attempt + 1)\n }, lockTimeout)\n } else {\n console.error('Unable to retrieve lock')\n }\n}\n\nexport class PersistedPriorityQueue extends PriorityQueue {\n constructor(maxAttempts: number, key: string) {\n super(maxAttempts, [])\n\n const itemsKey = `persisted-queue:v1:${key}:items`\n const seenKey = `persisted-queue:v1:${key}:seen`\n\n let saved: Context[] = []\n let lastSeen: Record = {}\n\n mutex(key, () => {\n try {\n saved = persisted(itemsKey)\n lastSeen = seen(seenKey)\n remove(itemsKey)\n remove(seenKey)\n\n this.queue = [...saved, ...this.queue]\n this.seen = { ...lastSeen, ...this.seen }\n } catch (err) {\n console.error(err)\n }\n })\n\n window.addEventListener('pagehide', () => {\n // we deliberately want to use the less powerful 'pagehide' API to only persist on events where the analytics instance gets destroyed, and not on tab away.\n if (this.todo > 0) {\n const items = [...this.queue, ...this.future]\n try {\n mutex(key, () => {\n persistItems(itemsKey, items)\n persistSeen(seenKey, this.seen)\n })\n } catch (err) {\n console.error(err)\n }\n }\n })\n }\n}\n", "import { AnalyticsSnippet } from '../browser/standalone-interface'\n\n/**\n * Stores the global window analytics key\n */\nlet _globalAnalyticsKey = 'analytics'\n\n/**\n * Gets the global analytics/buffer\n * @param key name of the window property where the buffer is stored (default: analytics)\n * @returns AnalyticsSnippet\n */\nexport function getGlobalAnalytics(): AnalyticsSnippet | undefined {\n return (window as any)[_globalAnalyticsKey]\n}\n\n/**\n * Replaces the global window key for the analytics/buffer object\n * @param key key name\n */\nexport function setGlobalAnalyticsKey(key: string) {\n _globalAnalyticsKey = key\n}\n\n/**\n * Sets the global analytics object\n * @param analytics analytics snippet\n */\nexport function setGlobalAnalytics(analytics: AnalyticsSnippet): void {\n ;(window as any)[_globalAnalyticsKey] = analytics\n}\n", "export { invokeCallback, pTimeout } from '@segment/analytics-core'\n", "import { Analytics } from './analytics'\nimport { EventProperties, Options } from './events'\nimport { pTimeout } from './callback'\n\n// Check if a user is opening the link in a new tab\nfunction userNewTab(event: Event): boolean {\n const typedEvent = event as Event & {\n ctrlKey: boolean\n shiftKey: boolean\n metaKey: boolean\n button: number\n }\n if (\n typedEvent.ctrlKey ||\n typedEvent.shiftKey ||\n typedEvent.metaKey ||\n (typedEvent.button && typedEvent.button == 1)\n ) {\n return true\n }\n return false\n}\n\n// Check if the link opens in new tab\nfunction linkNewTab(element: HTMLAnchorElement, href: string | null): boolean {\n if (element.target === '_blank' && href) {\n return true\n }\n return false\n}\n\nexport interface JQueryShim {\n toArray(): TElement[]\n}\n\nexport function link(\n this: Analytics,\n links: Element | Array | JQueryShim | null,\n event: string | Function,\n properties?: EventProperties | Function,\n options?: Options\n): Analytics {\n let elements: Array = []\n // always arrays, handles jquery\n if (!links) {\n return this\n }\n if (links instanceof Element) {\n elements = [links]\n } else if ('toArray' in links) {\n elements = links.toArray()\n } else {\n elements = links\n }\n\n elements.forEach((el: Element) => {\n el.addEventListener(\n 'click',\n (elementEvent: Event) => {\n const ev = event instanceof Function ? event(el) : event\n const props =\n properties instanceof Function ? properties(el) : properties\n const href =\n el.getAttribute('href') ||\n el.getAttributeNS('http://www.w3.org/1999/xlink', 'href') ||\n el.getAttribute('xlink:href') ||\n el.getElementsByTagName('a')[0]?.getAttribute('href')\n\n const trackEvent = pTimeout(\n this.track(ev, props, options ?? {}),\n this.settings.timeout ?? 500\n )\n\n if (\n !linkNewTab(el as HTMLAnchorElement, href) &&\n !userNewTab(elementEvent)\n ) {\n if (href) {\n elementEvent.preventDefault\n ? elementEvent.preventDefault()\n : (elementEvent.returnValue = false)\n trackEvent\n .catch(console.error)\n .then(() => {\n window.location.href = href\n })\n .catch(console.error)\n }\n }\n },\n false\n )\n })\n\n return this\n}\n\nexport type LinkArgs = Parameters\n\nexport function form(\n this: Analytics,\n forms: HTMLFormElement | Array | null,\n event: string | Function,\n properties?: EventProperties | Function,\n options?: Options\n): Analytics {\n // always arrays, handles jquery\n if (!forms) return this\n if (forms instanceof HTMLFormElement) forms = [forms]\n\n const elements = forms\n\n elements.forEach((el) => {\n if (!(el instanceof Element))\n throw new TypeError('Must pass HTMLElement to trackForm/trackSubmit.')\n const handler = (elementEvent: Event): void => {\n elementEvent.preventDefault\n ? elementEvent.preventDefault()\n : (elementEvent.returnValue = false)\n\n const ev = event instanceof Function ? event(el) : event\n const props = properties instanceof Function ? properties(el) : properties\n\n const trackEvent = pTimeout(\n this.track(ev, props, options ?? {}),\n this.settings.timeout ?? 500\n )\n\n trackEvent\n .catch(console.error)\n .then(() => {\n el.submit()\n })\n .catch(console.error)\n }\n\n // Support the events happening through jQuery or Zepto instead of through\n // the normal DOM API, because `el.submit` doesn't bubble up events...\n\n const $ = (window as any).jQuery || (window as any).Zepto\n if ($) {\n $(el).submit(handler)\n } else {\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n el.addEventListener('submit', handler, false)\n }\n })\n\n return this\n}\n\nexport type FormArgs = Parameters\n", "\nvar identity = function(_){ return _; };\n\n\n/**\n * Module exports, export\n */\n\nmodule.exports = multiple(find);\nmodule.exports.find = module.exports;\n\n\n/**\n * Export the replacement function, return the modified object\n */\n\nmodule.exports.replace = function (obj, key, val, options) {\n multiple(replace).call(this, obj, key, val, options);\n return obj;\n};\n\n\n/**\n * Export the delete function, return the modified object\n */\n\nmodule.exports.del = function (obj, key, options) {\n multiple(del).call(this, obj, key, null, options);\n return obj;\n};\n\n\n/**\n * Compose applying the function to a nested key\n */\n\nfunction multiple (fn) {\n return function (obj, path, val, options) {\n var normalize = options && isFunction(options.normalizer) ? options.normalizer : defaultNormalize;\n path = normalize(path);\n\n var key;\n var finished = false;\n\n while (!finished) loop();\n\n function loop() {\n for (key in obj) {\n var normalizedKey = normalize(key);\n if (0 === path.indexOf(normalizedKey)) {\n var temp = path.substr(normalizedKey.length);\n if (temp.charAt(0) === '.' || temp.length === 0) {\n path = temp.substr(1);\n var child = obj[key];\n\n // we're at the end and there is nothing.\n if (null == child) {\n finished = true;\n return;\n }\n\n // we're at the end and there is something.\n if (!path.length) {\n finished = true;\n return;\n }\n\n // step into child\n obj = child;\n\n // but we're done here\n return;\n }\n }\n }\n\n key = undefined;\n // if we found no matching properties\n // on the current object, there's no match.\n finished = true;\n }\n\n if (!key) return;\n if (null == obj) return obj;\n\n // the `obj` and `key` is one above the leaf object and key, so\n // start object: { a: { 'b.c': 10 } }\n // end object: { 'b.c': 10 }\n // end key: 'b.c'\n // this way, you can do `obj[key]` and get `10`.\n return fn(obj, key, val);\n };\n}\n\n\n/**\n * Find an object by its key\n *\n * find({ first_name : 'Calvin' }, 'firstName')\n */\n\nfunction find (obj, key) {\n if (obj.hasOwnProperty(key)) return obj[key];\n}\n\n\n/**\n * Delete a value for a given key\n *\n * del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' }\n */\n\nfunction del (obj, key) {\n if (obj.hasOwnProperty(key)) delete obj[key];\n return obj;\n}\n\n\n/**\n * Replace an objects existing value with a new one\n *\n * replace({ a : 'b' }, 'a', 'c') -> { a : 'c' }\n */\n\nfunction replace (obj, key, val) {\n if (obj.hasOwnProperty(key)) obj[key] = val;\n return obj;\n}\n\n/**\n * Normalize a `dot.separated.path`.\n *\n * A.HELL(!*&#(!)O_WOR LD.bar => ahelloworldbar\n *\n * @param {String} path\n * @return {String}\n */\n\nfunction defaultNormalize(path) {\n return path.replace(/[^a-zA-Z0-9\\.]+/g, '').toLowerCase();\n}\n\n/**\n * Check if a value is a function.\n *\n * @param {*} val\n * @return {boolean} Returns `true` if `val` is a function, otherwise `false`.\n */\n\nfunction isFunction(val) {\n return typeof val === 'function';\n}\n", "\"use strict\";\n\nimport get from \"obj-case\";\n\nfunction trait(a, b) {\n return function () {\n // @ts-ignore\n let traits = this.traits();\n // @ts-ignore\n let props = this.properties ? this.properties() : {};\n\n return (\n get(traits, \"address.\" + a) ||\n get(traits, a) ||\n (b ? get(traits, \"address.\" + b) : null) ||\n (b ? get(traits, b) : null) ||\n get(props, \"address.\" + a) ||\n get(props, a) ||\n (b ? get(props, \"address.\" + b) : null) ||\n (b ? get(props, b) : null)\n );\n };\n}\n\n/**\n * Add address getters to `proto`.\n *\n * @ignore\n * @param {Function} proto\n */\nexport default function (proto) {\n proto.zip = trait(\"postalCode\", \"zip\");\n proto.country = trait(\"country\");\n proto.street = trait(\"street\");\n proto.state = trait(\"state\");\n proto.city = trait(\"city\");\n proto.region = trait(\"region\");\n}\n", "export function clone(properties) {\n if (typeof properties !== 'object') return properties\n\n if (Object.prototype.toString.call(properties) === '[object Object]') {\n const temp = {};\n for (const key in properties) {\n if (Object.prototype.hasOwnProperty.call(properties, key)) {\n temp[key] = clone(properties[key]);\n }\n }\n return temp;\n } else if (Array.isArray(properties)) {\n return properties.map(clone);\n } else {\n // this is dangerous because it means this is not cloned\n return properties;\n }\n}\n", "\"use strict\";\n\n// A few integrations are disabled by default. They must be explicitly enabled\n// by setting options[Provider] = true.\nlet disabled = {\n Salesforce: true,\n};\n\n/**\n * Check whether an integration should be enabled by default.\n *\n * @ignore\n * @param {string} integration\n * @return {boolean}\n */\nexport default function (integration) {\n return !disabled[integration];\n}\n", "'use strict';\n\n/**\n * Matcher, slightly modified from:\n *\n * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js\n */\n\nvar matcher = /^(\\d{4})(?:-?(\\d{2})(?:-?(\\d{2}))?)?(?:([ T])(\\d{2}):?(\\d{2})(?::?(\\d{2})(?:[,\\.](\\d{1,}))?)?(?:(Z)|([+\\-])(\\d{2})(?::?(\\d{2}))?)?)?$/;\n\n/**\n * Convert an ISO date string to a date. Fallback to native `Date.parse`.\n *\n * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js\n *\n * @param {String} iso\n * @return {Date}\n */\n\nexports.parse = function(iso) {\n var numericKeys = [1, 5, 6, 7, 11, 12];\n var arr = matcher.exec(iso);\n var offset = 0;\n\n // fallback to native parsing\n if (!arr) {\n return new Date(iso);\n }\n\n /* eslint-disable no-cond-assign */\n // remove undefined values\n for (var i = 0, val; val = numericKeys[i]; i++) {\n arr[val] = parseInt(arr[val], 10) || 0;\n }\n /* eslint-enable no-cond-assign */\n\n // allow undefined days and months\n arr[2] = parseInt(arr[2], 10) || 1;\n arr[3] = parseInt(arr[3], 10) || 1;\n\n // month is 0-11\n arr[2]--;\n\n // allow abitrary sub-second precision\n arr[8] = arr[8] ? (arr[8] + '00').substring(0, 3) : 0;\n\n // apply timezone if one exists\n if (arr[4] === ' ') {\n offset = new Date().getTimezoneOffset();\n } else if (arr[9] !== 'Z' && arr[10]) {\n offset = arr[11] * 60 + arr[12];\n if (arr[10] === '+') {\n offset = 0 - offset;\n }\n }\n\n var millis = Date.UTC(arr[1], arr[2], arr[3], arr[5], arr[6] + offset, arr[7], arr[8]);\n return new Date(millis);\n};\n\n\n/**\n * Checks whether a `string` is an ISO date string. `strict` mode requires that\n * the date string at least have a year, month and date.\n *\n * @param {String} string\n * @param {Boolean} strict\n * @return {Boolean}\n */\n\nexports.is = function(string, strict) {\n if (typeof string !== 'string') {\n return false;\n }\n if (strict && (/^\\d{4}-\\d{2}-\\d{2}/).test(string) === false) {\n return false;\n }\n return matcher.test(string);\n};\n", "\"use strict\";\n\n/**\n * Matcher.\n */\n\nvar matcher = /\\d{13}/;\n\n/**\n * Check whether a string is a millisecond date string.\n *\n * @param {string} string\n * @return {boolean}\n */\nexports.is = function (string) {\n return matcher.test(string);\n};\n\n/**\n * Convert a millisecond string to a date.\n *\n * @param {string} millis\n * @return {Date}\n */\nexports.parse = function (millis) {\n millis = parseInt(millis, 10);\n return new Date(millis);\n};\n", "\"use strict\";\n\n/**\n * Matcher.\n */\n\nvar matcher = /\\d{10}/;\n\n/**\n * Check whether a string is a second date string.\n *\n * @param {string} string\n * @return {Boolean}\n */\nexports.is = function (string) {\n return matcher.test(string);\n};\n\n/**\n * Convert a second string to a date.\n *\n * @param {string} seconds\n * @return {Date}\n */\nexports.parse = function (seconds) {\n var millis = parseInt(seconds, 10) * 1000;\n return new Date(millis);\n};\n", "\"use strict\";\n\nvar isodate = require(\"@segment/isodate\");\nvar milliseconds = require(\"./milliseconds\");\nvar seconds = require(\"./seconds\");\n\nvar objProto = Object.prototype;\nvar toStr = objProto.toString;\n\nfunction isDate(value) {\n return toStr.call(value) === \"[object Date]\";\n}\n\nfunction isNumber(value) {\n return toStr.call(value) === \"[object Number]\";\n}\n\n/**\n * Returns a new Javascript Date object, allowing a variety of extra input types\n * over the native Date constructor.\n *\n * @param {Date|string|number} val\n */\nmodule.exports = function newDate(val) {\n if (isDate(val)) return val;\n if (isNumber(val)) return new Date(toMs(val));\n\n // date strings\n if (isodate.is(val)) {\n return isodate.parse(val);\n }\n if (milliseconds.is(val)) {\n return milliseconds.parse(val);\n }\n if (seconds.is(val)) {\n return seconds.parse(val);\n }\n\n // fallback to Date.parse\n return new Date(val);\n};\n\n/**\n * If the number passed val is seconds from the epoch, turn it into milliseconds.\n * Milliseconds would be greater than 31557600000 (December 31, 1970).\n *\n * @param {number} num\n */\nfunction toMs(num) {\n if (num < 31557600000) return num * 1000;\n return num;\n}\n", "'use strict';\n\nvar isodate = require('@segment/isodate');\n\n/**\n * Expose `traverse`.\n */\nmodule.exports = traverse;\n\n/**\n * Recursively traverse an object or array, and convert\n * all ISO date strings parse into Date objects.\n *\n * @param {Object} input - object, array, or string to convert\n * @param {Boolean} strict - only convert strings with year, month, and date\n * @return {Object}\n */\nfunction traverse(input, strict) {\n if (strict === undefined) strict = true;\n if (input && typeof input === 'object') {\n return traverseObject(input, strict);\n } else if (Array.isArray(input)) {\n return traverseArray(input, strict);\n } else if (isodate.is(input, strict)) {\n return isodate.parse(input);\n }\n return input;\n}\n\n/**\n * Object traverser helper function.\n *\n * @param {Object} obj - object to traverse\n * @param {Boolean} strict - only convert strings with year, month, and date\n * @return {Object}\n */\nfunction traverseObject(obj, strict) {\n Object.keys(obj).forEach(function(key) {\n obj[key] = traverse(obj[key], strict);\n });\n return obj;\n}\n\n/**\n * Array traverser helper function\n *\n * @param {Array} arr - array to traverse\n * @param {Boolean} strict - only convert strings with year, month, and date\n * @return {Array}\n */\nfunction traverseArray(arr, strict) {\n arr.forEach(function(value, index) {\n arr[index] = traverse(value, strict);\n });\n return arr;\n}\n", "\"use strict\";\n\nimport address from \"./address\";\nimport { clone } from \"./clone\";\nimport isEnabled from \"./is-enabled\";\nimport newDate from \"new-date\";\nimport objCase from \"obj-case\";\nimport traverse from \"@segment/isodate-traverse\";\n\n/**\n * A *Facade* is an object meant for creating convience wrappers around\n * objects. When developing integrations, you probably want to look at its\n * subclasses, such as {@link Track} or {@link Identify}, rather than this\n * general-purpose class.\n *\n * This letructor will initialize a new `Facade` with an `obj` of arguments.\n *\n * If the inputted `obj` doesn't have a `timestamp` property, one will be added\n * with the value `new Date()`. Otherwise, the `timestamp` property will be\n * converted to a Date using the `new-date` package.\n *\n * By default, the inputted object will be defensively copied, and all ISO\n * strings present in the string will be converted into Dates.\n *\n * @param {Object} obj - The object to wrap.\n * @param {Object} opts - Options about what kind of Facade to create.\n * @param {boolean} [opts.clone=true] - Whether to make defensive clones. If enabled,\n * the inputted object will be cloned, and any objects derived from this facade\n * will be cloned before being returned.\n * @param {boolean} [opts.traverse=true] - Whether to perform ISODate-Traverse\n * on the inputted object.\n *\n * @see {@link https://github.com/segmentio/new-date|new-date}\n * @see {@link https://github.com/segmentio/isodate-traverse|isodate-traverse}\n */\nexport function Facade (obj, opts) {\n opts = opts || {};\n this.raw = clone(obj);\n if (!(\"clone\" in opts)) opts.clone = true;\n if (opts.clone) obj = clone(obj);\n if (!(\"traverse\" in opts)) opts.traverse = true;\n if (!(\"timestamp\" in obj)) obj.timestamp = new Date();\n else obj.timestamp = newDate(obj.timestamp);\n if (opts.traverse) traverse(obj);\n this.opts = opts;\n this.obj = obj;\n}\n\nconst f = Facade.prototype;\n\n/**\n * Get a potentially-nested field in this facade. `field` should be a\n * period-separated sequence of properties.\n *\n * If the first field passed in points to a function (e.g. the `field` passed\n * in is `a.b.c` and this facade's `obj.a` is a function), then that function\n * will be called, and then the deeper fields will be fetched (using obj-case)\n * from what that function returns. If the first field isn't a function, then\n * this function works just like obj-case.\n *\n * Because this function uses obj-case, the camel- or snake-case of the input\n * is irrelevant.\n *\n * @example\n * YourClass.prototype.height = function() {\n * return this.proxy('getDimensions.height') ||\n * this.proxy('props.size.side_length');\n * }\n * @param {string} field - A sequence of properties, joined by periods (`.`).\n * @return {*} - A property of the inputted object.\n * @see {@link https://github.com/segmentio/obj-case|obj-case}\n */\nf.proxy = function(field) {\n let fields = field.split(\".\");\n field = fields.shift();\n\n // Call a function at the beginning to take advantage of facaded fields\n let obj = this[field] || this.obj[field];\n if (!obj) return obj;\n if (typeof obj === \"function\") obj = obj.call(this) || {};\n if (fields.length === 0) return this.opts.clone ? transform(obj) : obj;\n\n obj = objCase(obj, fields.join(\".\"));\n return this.opts.clone ? transform(obj) : obj;\n};\n\n/**\n * Directly access a specific `field` from the underlying object. Only\n * \"top-level\" fields will work with this function. \"Nested\" fields *will not\n * work* with this function.\n *\n * @param {string} field\n * @return {*}\n */\nf.field = function(field) {\n let obj = this.obj[field];\n return this.opts.clone ? transform(obj) : obj;\n};\n\n/**\n * Utility method to always proxy a particular `field`. In other words, it\n * returns a function that will always return `this.proxy(field)`.\n *\n * @example\n * MyClass.prototype.height = Facade.proxy('options.dimensions.height');\n *\n * @param {string} field\n * @return {Function}\n */\nFacade.proxy = function(field) {\n return function() {\n return this.proxy(field);\n };\n};\n\n/**\n * Utility method to always access a `field`. In other words, it returns a\n * function that will always return `this.field(field)`.\n *\n * @param {string} field\n * @return {Function}\n */\nFacade.field = function(field) {\n return function() {\n return this.field(field);\n };\n};\n\n/**\n * Create a helper function for fetching a \"plural\" thing.\n *\n * The generated method will take the inputted `path` and append an \"s\" to it\n * and calls `this.proxy` with this \"pluralized\" path. If that produces an\n * array, that will be returned. Otherwise, a one-element array containing\n * `this.proxy(path)` will be returned.\n *\n * @example\n * MyClass.prototype.birds = Facade.multi('animals.bird');\n *\n * @param {string} path\n * @return {Function}\n */\nFacade.multi = function(path) {\n return function() {\n let multi = this.proxy(path + \"s\");\n if (Array.isArray(multi)) return multi;\n let one = this.proxy(path);\n if (one) one = [this.opts.clone ? clone(one) : one];\n return one || [];\n };\n};\n\n/**\n * Create a helper function for getting a \"singular\" thing.\n *\n * The generated method will take the inputted path and call\n * `this.proxy(path)`. If a truthy thing is produced, it will be returned.\n * Otherwise, `this.proxy(path + 's')` will be called, and if that produces an\n * array the first element of that array will be returned. Otherwise,\n * `undefined` is returned.\n *\n * @example\n * MyClass.prototype.bird = Facade.one('animals.bird');\n *\n * @param {string} path\n * @return {Function}\n */\nFacade.one = function(path) {\n return function() {\n let one = this.proxy(path);\n if (one) return one;\n let multi = this.proxy(path + \"s\");\n if (Array.isArray(multi)) return multi[0];\n };\n};\n\n/**\n * Gets the underlying object this facade wraps around.\n *\n * If this facade has a property `type`, it will be invoked as a function and\n * will be assigned as the property `type` of the outputted object.\n *\n * @return {Object}\n */\nf.json = function() {\n let ret = this.opts.clone ? clone(this.obj) : this.obj;\n if (this.type) ret.type = this.type();\n return ret;\n};\n\n/**\n * Gets a copy of the unmodified input object this facade wraps around.\n * \n * Unlike the `json` method which does make some subtle modifications \n * to datetime values and the `type` property. This method returns a copy of \n * the unmodified input object\n * \n * @return {Object}\n */\nf.rawEvent = function() {\n return this.raw;\n};\n\n/**\n * Get the options of a call. If an integration is passed, only the options for\n * that integration are included. If the integration is not enabled, then\n * `undefined` is returned.\n *\n * Options are taken from the `options` property of the underlying object,\n * falling back to the object's `context` or simply `{}`.\n *\n * @param {string} integration - The name of the integration to get settings\n * for. Casing does not matter.\n * @return {Object|undefined}\n */\nf.options = function(integration) {\n let obj = this.obj.options || this.obj.context || {};\n let options = this.opts.clone ? clone(obj) : obj;\n if (!integration) return options;\n if (!this.enabled(integration)) return;\n let integrations = this.integrations();\n let value = integrations[integration] || objCase(integrations, integration);\n if (typeof value !== \"object\") value = objCase(this.options(), integration);\n return typeof value === \"object\" ? value : {};\n};\n\n/**\n * An alias for {@link Facade#options}.\n */\nf.context = f.options;\n\n/**\n * Check whether an integration is enabled.\n *\n * Basically, this method checks whether this integration is explicitly\n * enabled. If it isn'texplicitly mentioned, it checks whether it has been\n * enabled at the global level. Some integrations (e.g. Salesforce), cannot\n * enabled by these global event settings.\n *\n * More concretely, the deciding factors here are:\n *\n * 1. If `this.integrations()` has the integration set to `true`, return `true`.\n * 2. If `this.integrations().providers` has the integration set to `true`, return `true`.\n * 3. If integrations are set to default-disabled via global parameters (i.e.\n * `options.providers.all`, `options.all`, or `integrations.all`), then return\n * false.\n * 4. If the integration is one of the special default-deny integrations\n * (currently, only Salesforce), then return false.\n * 5. Else, return true.\n *\n * @param {string} integration\n * @return {boolean}\n */\nf.enabled = function(integration) {\n let allEnabled = this.proxy(\"options.providers.all\");\n if (typeof allEnabled !== \"boolean\") allEnabled = this.proxy(\"options.all\");\n if (typeof allEnabled !== \"boolean\")\n allEnabled = this.proxy(\"integrations.all\");\n if (typeof allEnabled !== \"boolean\") allEnabled = true;\n\n let enabled = allEnabled && isEnabled(integration);\n let options = this.integrations();\n\n // If the integration is explicitly enabled or disabled, use that\n // First, check options.providers for backwards compatibility\n if (options.providers && options.providers.hasOwnProperty(integration)) {\n enabled = options.providers[integration];\n }\n\n // Next, check for the integration's existence in 'options' to enable it.\n // If the settings are a boolean, use that, otherwise it should be enabled.\n if (options.hasOwnProperty(integration)) {\n let settings = options[integration];\n if (typeof settings === \"boolean\") {\n enabled = settings;\n } else {\n enabled = true;\n }\n }\n\n return !!enabled;\n};\n\n/**\n * Get all `integration` options.\n *\n * @ignore\n * @param {string} integration\n * @return {Object}\n */\nf.integrations = function() {\n return (\n this.obj.integrations || this.proxy(\"options.providers\") || this.options()\n );\n};\n\n/**\n * Check whether the user is active.\n *\n * @return {boolean}\n */\nf.active = function() {\n let active = this.proxy(\"options.active\");\n if (active === null || active === undefined) active = true;\n return active;\n};\n\n/**\n * Get `sessionId / anonymousId`.\n *\n * @return {*}\n */\nf.anonymousId = function() {\n return this.field(\"anonymousId\") || this.field(\"sessionId\");\n};\n\n/**\n * An alias for {@link Facade#anonymousId}.\n *\n * @function\n * @return {string}\n */\nf.sessionId = f.anonymousId;\n\n/**\n * Get `groupId` from `context.groupId`.\n *\n * @function\n * @return {string}\n */\nf.groupId = Facade.proxy(\"options.groupId\");\n\n/**\n * Get the call's \"traits\". All event types can pass in traits, though {@link\n * Identify} and {@link Group} override this implementation.\n *\n * Traits are gotten from `options.traits`, augmented with a property `id` with\n * the event's `userId`.\n *\n * The parameter `aliases` is meant to transform keys in `options.traits` into\n * new keys. Each alias like `{ \"xxx\": \"yyy\" }` will take whatever is at `xxx`\n * in the traits, and move it to `yyy`. If `xxx` is a method of this facade,\n * it'll be called as a function instead of treated as a key into the traits.\n *\n * @example\n * let obj = { options: { traits: { foo: \"bar\" } }, anonymousId: \"xxx\" }\n * let facade = new Facade(obj)\n *\n * facade.traits() // { \"foo\": \"bar\" }\n * facade.traits({ \"foo\": \"asdf\" }) // { \"asdf\": \"bar\" }\n * facade.traits({ \"sessionId\": \"rofl\" }) // { \"rofl\": \"xxx\" }\n *\n * @param {Object} aliases - A mapping from keys to the new keys they should be\n * transformed to.\n * @return {Object}\n */\nf.traits = function(aliases) {\n let ret = this.proxy(\"options.traits\") || {};\n let id = this.userId();\n aliases = aliases || {};\n\n if (id) ret.id = id;\n\n for (const alias in aliases) {\n if (Object.prototype.hasOwnProperty.call(aliases, alias)) {\n const value = this[alias] == null\n ? this.proxy(\"options.traits.\" + alias)\n : this[alias]();\n if (value == null) continue;\n ret[aliases[alias]] = value;\n delete ret[alias];\n }\n }\n\n return ret;\n};\n\n/**\n * The library and version of the client used to produce the message.\n *\n * If the library name cannot be determined, it is set to `\"unknown\"`. If the\n * version cannot be determined, it is set to `null`.\n *\n * @return {{name: string, version: string}}\n */\nf.library = function() {\n let library = this.proxy(\"options.library\");\n if (!library) return { name: \"unknown\", version: null };\n if (typeof library === \"string\") return { name: library, version: null };\n return library;\n};\n\n/**\n * Return the device information, falling back to an empty object.\n *\n * Interesting values of `type` are `\"ios\"` and `\"android\"`, but other values\n * are possible if the client is doing something unusual with `context.device`.\n *\n * @return {{type: string}}\n */\nf.device = function() {\n let device = this.proxy(\"context.device\");\n if (typeof device !== \"object\" || device === null) {\n device = {};\n }\n let library = this.library().name;\n if (device.type) return device;\n\n if (library.indexOf(\"ios\") > -1) device.type = \"ios\";\n if (library.indexOf(\"android\") > -1) device.type = \"android\";\n return device;\n};\n\n/**\n * Get the User-Agent from `context.userAgent`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return string\n */\nf.userAgent = Facade.proxy(\"context.userAgent\");\n\n/**\n * Get the timezone from `context.timezone`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return string\n */\nf.timezone = Facade.proxy(\"context.timezone\");\n\n/**\n * Get the timestamp from `context.timestamp`.\n *\n * @function\n * @return string\n */\nf.timestamp = Facade.field(\"timestamp\");\n\n/**\n * Get the channel from `channel`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return string\n */\nf.channel = Facade.field(\"channel\");\n\n/**\n * Get the IP address from `context.ip`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return string\n */\nf.ip = Facade.proxy(\"context.ip\");\n\n/**\n * Get the user ID from `userId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return string\n */\nf.userId = Facade.field(\"userId\");\n\n/**\n * Get the ZIP/Postal code from `traits`, `traits.address`, `properties`, or\n * `properties.address`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @name zip\n * @function\n * @memberof f\n * @return {string}\n */\n\n/**\n * Get the country from `traits`, `traits.address`, `properties`, or\n * `properties.address`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @name country\n * @function\n * @memberof f\n * @return {string}\n */\n\n/**\n * Get the street from `traits`, `traits.address`, `properties`, or\n * `properties.address`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @name street\n * @function\n * @memberof f\n * @return {string}\n */\n\n/**\n * Get the state from `traits`, `traits.address`, `properties`, or\n * `properties.address`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @name state\n * @function\n * @memberof f\n * @return {string}\n */\n\n/**\n * Get the city from `traits`, `traits.address`, `properties`, or\n * `properties.address`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @name city\n * @function\n * @memberof f\n * @return {string}\n */\n\n/**\n * Get the region from `traits`, `traits.address`, `properties`, or\n * `properties.address`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @name region\n * @function\n * @memberof f\n * @return {string}\n */\n\naddress(f);\n\n/**\n * Return the cloned and traversed object\n *\n * @ignore\n * @param {*} obj\n * @return {*}\n */\nfunction transform (obj) {\n return clone(obj);\n}\n", "if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n", "\"use strict\";\n\nimport inherit from \"inherits\";\nimport { Facade } from \"./facade\";\n\n/**\n * Initialize a new `Alias` facade with a `dictionary` of arguments.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.from] - The previous ID of the user.\n * @param {string} [dictionary.to] - The new ID of the user.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Facade\n */\nexport function Alias(dictionary, opts) {\n Facade.call(this, dictionary, opts);\n}\n\ninherit(Alias, Facade);\n\n/**\n * Return the type of facade this is. This will always return `\"alias\"`.\n *\n * @return {string}\n */\nAlias.prototype.action = function () {\n return \"alias\";\n};\n\n/**\n * An alias for {@link Alias#action}.\n *\n * @function\n * @return {string}\n */\nAlias.prototype.type = Alias.prototype.action;\n\n/**\n * Get the user's previous ID from `previousId` or `from`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nAlias.prototype.previousId = function () {\n return this.field(\"previousId\") || this.field(\"from\");\n};\n\n/**\n * An alias for {@link Alias#previousId}.\n *\n * @function\n * @return {string}\n */\nAlias.prototype.from = Alias.prototype.previousId;\n\n/**\n * Get the user's new ID from `userId` or `to`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nAlias.prototype.userId = function () {\n return this.field(\"userId\") || this.field(\"to\");\n};\n\n/**\n * An alias for {@link Alias#userId}.\n *\n * @function\n * @return {string}\n */\nAlias.prototype.to = Alias.prototype.userId;\n", "const matcher = /.+\\@.+\\..+/;\n\nexport default function isEmail(string) {\n return matcher.test(string);\n}\n", "\"use strict\";\n\nimport inherit from \"inherits\";\nimport isEmail from \"./is-email\";\nimport newDate from \"new-date\";\nimport { Facade } from \"./facade\";\n\n/**\n * Initialize a new `Group` facade with a `dictionary` of arguments.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.userId] - The user to add to the group.\n * @param {string} [dictionary.groupId] - The ID of the group.\n * @param {Object} [dictionary.traits] - The traits of the group.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Facade\n */\nexport function Group(dictionary, opts) {\n Facade.call(this, dictionary, opts);\n}\n\ninherit(Group, Facade);\n\nconst g = Group.prototype;\n\n/**\n * Return the type of facade this is. This will always return `\"group\"`.\n *\n * @return {string}\n */\ng.action = function () {\n return \"group\";\n};\n\n/**\n * An alias for {@link Group#action}.\n *\n * @function\n * @return {string}\n */\ng.type = g.action;\n\n/**\n * Get the group ID from `groupId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ng.groupId = Facade.field(\"groupId\");\n\n/**\n * Get the time of creation of the group from `traits.createdAt`,\n * `traits.created`, `properties.createdAt`, or `properties.created`.\n *\n * @return {Date}\n */\ng.created = function () {\n var created =\n this.proxy(\"traits.createdAt\") ||\n this.proxy(\"traits.created\") ||\n this.proxy(\"properties.createdAt\") ||\n this.proxy(\"properties.created\");\n\n if (created) return newDate(created);\n};\n\n/**\n * Get the group's email from `traits.email`, falling back to `groupId` only if\n * it looks like a valid email.\n *\n * @return {string}\n */\ng.email = function () {\n var email = this.proxy(\"traits.email\");\n if (email) return email;\n var groupId = this.groupId();\n if (isEmail(groupId)) return groupId;\n};\n\n/**\n * Get the group's traits. This is identical to how {@link Facade#traits}\n * works, except it looks at `traits.*` instead of `options.traits.*`.\n *\n * Traits are gotten from `traits`, augmented with a property `id` with\n * the event's `groupId`.\n *\n * The parameter `aliases` is meant to transform keys in `traits` into new\n * keys. Each alias like `{ \"xxx\": \"yyy\" }` will take whatever is at `xxx` in\n * the traits, and move it to `yyy`. If `xxx` is a method of this facade, it'll\n * be called as a function instead of treated as a key into the traits.\n *\n * @example\n * var obj = { traits: { foo: \"bar\" }, anonymousId: \"xxx\" }\n * var group = new Group(obj)\n *\n * group.traits() // { \"foo\": \"bar\" }\n * group.traits({ \"foo\": \"asdf\" }) // { \"asdf\": \"bar\" }\n * group.traits({ \"sessionId\": \"rofl\" }) // { \"rofl\": \"xxx\" }\n *\n * @param {Object} aliases - A mapping from keys to the new keys they should be\n * transformed to.\n * @return {Object}\n */\ng.traits = function (aliases) {\n var ret = this.properties();\n var id = this.groupId();\n aliases = aliases || {};\n\n if (id) ret.id = id;\n\n for (const alias in aliases) {\n if (Object.prototype.hasOwnProperty.call(aliases, alias)) {\n const value = this[alias] == null\n ? this.proxy(\"traits.\" + alias)\n : this[alias]();\n if (value == null) continue;\n ret[aliases[alias]] = value;\n delete ret[alias];\n }\n }\n\n return ret;\n};\n\n/**\n * Get the group's name from `traits.name`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\ng.name = Facade.proxy(\"traits.name\");\n\n/**\n * Get the group's industry from `traits.industry`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\ng.industry = Facade.proxy(\"traits.industry\");\n\n/**\n * Get the group's employee count from `traits.employees`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\ng.employees = Facade.proxy(\"traits.employees\");\n\n/**\n * Get the group's properties from `traits` or `properties`, falling back to\n * simply an empty object.\n *\n * @return {Object}\n */\ng.properties = function () {\n // TODO remove this function\n return this.field(\"traits\") || this.field(\"properties\") || {};\n};\n", "\"use strict\";\n\nimport { Facade } from \"./facade\";\nimport get from \"obj-case\";\nimport inherit from \"inherits\";\nimport isEmail from \"./is-email\";\nimport newDate from \"new-date\";\n\nlet trim = (str) => str.trim();\n\n/**\n * Initialize a new `Identify` facade with a `dictionary` of arguments.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.userId] - The ID of the user.\n * @param {string} [dictionary.anonymousId] - The anonymous ID of the user.\n * @param {string} [dictionary.traits] - The user's traits.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Facade\n */\nexport function Identify(dictionary, opts) {\n Facade.call(this, dictionary, opts);\n}\n\ninherit(Identify, Facade);\n\nconst i = Identify.prototype;\n\n/**\n * Return the type of facade this is. This will always return `\"identify\"`.\n *\n * @return {string}\n */\ni.action = function () {\n return \"identify\";\n};\n\n/**\n * An alias for {@link Identify#action}.\n *\n * @function\n * @return {string}\n */\ni.type = i.action;\n\n/**\n * Get the user's traits. This is identical to how {@link Facade#traits} works,\n * except it looks at `traits.*` instead of `options.traits.*`.\n *\n * Traits are gotten from `traits`, augmented with a property `id` with\n * the event's `userId`.\n *\n * The parameter `aliases` is meant to transform keys in `traits` into new\n * keys. Each alias like `{ \"xxx\": \"yyy\" }` will take whatever is at `xxx` in\n * the traits, and move it to `yyy`. If `xxx` is a method of this facade, it'll\n * be called as a function instead of treated as a key into the traits.\n *\n * @example\n * let obj = { traits: { foo: \"bar\" }, anonymousId: \"xxx\" }\n * let identify = new Identify(obj)\n *\n * identify.traits() // { \"foo\": \"bar\" }\n * identify.traits({ \"foo\": \"asdf\" }) // { \"asdf\": \"bar\" }\n * identify.traits({ \"sessionId\": \"rofl\" }) // { \"rofl\": \"xxx\" }\n *\n * @param {Object} aliases - A mapping from keys to the new keys they should be\n * transformed to.\n * @return {Object}\n */\ni.traits = function (aliases) {\n let ret = this.field(\"traits\") || {};\n let id = this.userId();\n aliases = aliases || {};\n\n if (id) ret.id = id;\n\n for (let alias in aliases) {\n let value =\n this[alias] == null ? this.proxy(\"traits.\" + alias) : this[alias]();\n if (value == null) continue;\n ret[aliases[alias]] = value;\n if (alias !== aliases[alias]) delete ret[alias];\n }\n\n return ret;\n};\n\n/**\n * Get the user's email from `traits.email`, falling back to `userId` only if\n * it looks like a valid email.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.email = function () {\n let email = this.proxy(\"traits.email\");\n if (email) return email;\n\n let userId = this.userId();\n if (isEmail(userId)) return userId;\n};\n\n/**\n * Get the time of creation of the user from `traits.created` or\n * `traits.createdAt`.\n *\n * @return {Date}\n */\ni.created = function () {\n let created = this.proxy(\"traits.created\") || this.proxy(\"traits.createdAt\");\n if (created) return newDate(created);\n};\n\n/**\n * Get the time of creation of the user's company from `traits.company.created`\n * or `traits.company.createdAt`.\n *\n * @return {Date}\n */\ni.companyCreated = function () {\n let created =\n this.proxy(\"traits.company.created\") ||\n this.proxy(\"traits.company.createdAt\");\n\n if (created) {\n return newDate(created);\n }\n};\n\n/**\n * Get the user's company name from `traits.company.name`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.companyName = function () {\n return this.proxy(\"traits.company.name\");\n};\n\n/**\n * Get the user's name `traits.name`, falling back to combining {@link\n * Identify#firstName} and {@link Identify#lastName} if possible.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.name = function () {\n let name = this.proxy(\"traits.name\");\n if (typeof name === \"string\") {\n return trim(name);\n }\n\n let firstName = this.firstName();\n let lastName = this.lastName();\n if (firstName && lastName) {\n return trim(firstName + \" \" + lastName);\n }\n};\n\n/**\n * Get the user's first name from `traits.firstName`, optionally splitting it\n * out of a the full name if that's all that was provided.\n *\n * Splitting the full name works on the assumption that the full name is of the\n * form \"FirstName LastName\"; it will not work for non-Western names.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.firstName = function () {\n let firstName = this.proxy(\"traits.firstName\");\n if (typeof firstName === \"string\") {\n return trim(firstName);\n }\n\n let name = this.proxy(\"traits.name\");\n if (typeof name === \"string\") {\n return trim(name).split(\" \")[0];\n }\n};\n\n/**\n * Get the user's last name from `traits.lastName`, optionally splitting it out\n * of a the full name if that's all that was provided.\n *\n * Splitting the full name works on the assumption that the full name is of the\n * form \"FirstName LastName\"; it will not work for non-Western names.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.lastName = function () {\n let lastName = this.proxy(\"traits.lastName\");\n if (typeof lastName === \"string\") {\n return trim(lastName);\n }\n\n let name = this.proxy(\"traits.name\");\n if (typeof name !== \"string\") {\n return;\n }\n\n let space = trim(name).indexOf(\" \");\n if (space === -1) {\n return;\n }\n\n return trim(name.substr(space + 1));\n};\n\n/**\n * Get the user's \"unique id\" from `userId`, `traits.username`, or\n * `traits.email`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.uid = function () {\n return this.userId() || this.username() || this.email();\n};\n\n/**\n * Get the user's description from `traits.description` or `traits.background`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.description = function () {\n return this.proxy(\"traits.description\") || this.proxy(\"traits.background\");\n};\n\n/**\n * Get the user's age from `traits.age`, falling back to computing it from\n * `traits.birthday` and the current time.\n *\n * @return {number}\n */\ni.age = function () {\n let date = this.birthday();\n let age = get(this.traits(), \"age\");\n if (age != null) return age;\n if (!(date instanceof Date)) return;\n let now = new Date();\n return now.getFullYear() - date.getFullYear();\n};\n\n/**\n * Get the URL of the user's avatar from `traits.avatar`, `traits.photoUrl`, or\n * `traits.avatarUrl`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.avatar = function () {\n let traits = this.traits();\n return (\n get(traits, \"avatar\") || get(traits, \"photoUrl\") || get(traits, \"avatarUrl\")\n );\n};\n\n/**\n * Get the user's job position from `traits.position` or `traits.jobTitle`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\ni.position = function () {\n let traits = this.traits();\n return get(traits, \"position\") || get(traits, \"jobTitle\");\n};\n\n/**\n * Get the user's username from `traits.username`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\ni.username = Facade.proxy(\"traits.username\");\n\n/**\n * Get the user's website from `traits.website`, or if there are multiple in\n * `traits.websites`, return the first one.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\ni.website = Facade.one(\"traits.website\");\n\n/**\n * Get the user's websites from `traits.websites`, or if there is only one in\n * `traits.website`, then wrap it in an array.\n *\n * This *should* be an array of strings, but may not be if the client isn't\n * adhering to the spec.\n *\n * @function\n * @return {array}\n */\ni.websites = Facade.multi(\"traits.website\");\n\n/**\n * Get the user's phone number from `traits.phone`, or if there are multiple in\n * `traits.phones`, return the first one.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\ni.phone = Facade.one(\"traits.phone\");\n\n/**\n * Get the user's phone numbers from `traits.phones`, or if there is only one\n * in `traits.phone`, then wrap it in an array.\n *\n * This *should* be an array of strings, but may not be if the client isn't\n * adhering to the spec.\n *\n * @function\n * @return {array}\n */\ni.phones = Facade.multi(\"traits.phone\");\n\n/**\n * Get the user's address from `traits.address`.\n *\n * This *should* be an object, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {object}\n */\ni.address = Facade.proxy(\"traits.address\");\n\n/**\n * Get the user's gender from `traits.gender`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\ni.gender = Facade.proxy(\"traits.gender\");\n\n/**\n * Get the user's birthday from `traits.birthday`.\n *\n * This *should* be a Date if `opts.traverse` was enabled (it is by default)\n * when letructing this Identify. Otherwise, it should be a string. But it\n * may be neither if the client isn't adhering to the spec.\n * spec.\n *\n * @function\n * @return {object}\n */\ni.birthday = Facade.proxy(\"traits.birthday\");\n", "\"use strict\";\n\nimport inherit from \"inherits\";\nimport { Facade } from \"./facade\";\nimport { Identify } from \"./identify\";\nimport isEmail from \"./is-email\";\nimport get from \"obj-case\";\n\n/**\n * Initialize a new `Track` facade with a `dictionary` of arguments.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.event] - The name of the event being tracked.\n * @param {string} [dictionary.userId] - The ID of the user being tracked.\n * @param {string} [dictionary.anonymousId] - The anonymous ID of the user.\n * @param {string} [dictionary.properties] - Properties of the track event.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Facade\n */\nexport function Track(dictionary, opts) {\n Facade.call(this, dictionary, opts);\n}\n\ninherit(Track, Facade);\n\nlet t = Track.prototype;\n\n/**\n * Return the type of facade this is. This will always return `\"track\"`.\n *\n * @return {string}\n */\nt.action = function () {\n return \"track\";\n};\n\n/**\n * An alias for {@link Track#action}.\n *\n * @function\n * @return {string}\n */\nt.type = t.action;\n\n/**\n * Get the event name from `event`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.event = Facade.field(\"event\");\n\n/**\n * Get the event value, usually the monetary value, from `properties.value`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\nt.value = Facade.proxy(\"properties.value\");\n\n/**\n * Get the event cateogry from `properties.category`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.category = Facade.proxy(\"properties.category\");\n\n/**\n * Get the event ID from `properties.id`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.id = Facade.proxy(\"properties.id\");\n\n/**\n * Get the product ID from `properties.productId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.productId = function () {\n return (\n this.proxy(\"properties.product_id\") || this.proxy(\"properties.productId\")\n );\n};\n\n/**\n * Get the promotion ID from `properties.promotionId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.promotionId = function () {\n return (\n this.proxy(\"properties.promotion_id\") ||\n this.proxy(\"properties.promotionId\")\n );\n};\n\n/**\n * Get the cart ID from `properties.cartId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.cartId = function () {\n return this.proxy(\"properties.cart_id\") || this.proxy(\"properties.cartId\");\n};\n\n/**\n * Get the checkout ID from `properties.checkoutId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.checkoutId = function () {\n return (\n this.proxy(\"properties.checkout_id\") || this.proxy(\"properties.checkoutId\")\n );\n};\n\n/**\n * Get the payment ID from `properties.paymentId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.paymentId = function () {\n return (\n this.proxy(\"properties.payment_id\") || this.proxy(\"properties.paymentId\")\n );\n};\n\n/**\n * Get the coupon ID from `properties.couponId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.couponId = function () {\n return (\n this.proxy(\"properties.coupon_id\") || this.proxy(\"properties.couponId\")\n );\n};\n\n/**\n * Get the wishlist ID from `properties.wishlistId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.wishlistId = function () {\n return (\n this.proxy(\"properties.wishlist_id\") || this.proxy(\"properties.wishlistId\")\n );\n};\n\n/**\n * Get the review ID from `properties.reviewId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.reviewId = function () {\n return (\n this.proxy(\"properties.review_id\") || this.proxy(\"properties.reviewId\")\n );\n};\n\n/**\n * Get the order ID from `properties.id` or `properties.orderId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.orderId = function () {\n // doesn't follow above convention since this fallback order was how it used to be\n return (\n this.proxy(\"properties.id\") ||\n this.proxy(\"properties.order_id\") ||\n this.proxy(\"properties.orderId\")\n );\n};\n\n/**\n * Get the SKU from `properties.sku`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.sku = Facade.proxy(\"properties.sku\");\n\n/**\n * Get the amount of tax for this purchase from `properties.tax`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\nt.tax = Facade.proxy(\"properties.tax\");\n\n/**\n * Get the name of this event from `properties.name`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.name = Facade.proxy(\"properties.name\");\n\n/**\n * Get the price of this purchase from `properties.price`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\nt.price = Facade.proxy(\"properties.price\");\n\n/**\n * Get the total for this purchase from `properties.total`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\nt.total = Facade.proxy(\"properties.total\");\n\n/**\n * Whether this is a repeat purchase from `properties.repeat`.\n *\n * This *should* be a boolean, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {boolean}\n */\nt.repeat = Facade.proxy(\"properties.repeat\");\n\n/**\n * Get the coupon for this purchase from `properties.coupon`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.coupon = Facade.proxy(\"properties.coupon\");\n\n/**\n * Get the shipping for this purchase from `properties.shipping`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\nt.shipping = Facade.proxy(\"properties.shipping\");\n\n/**\n * Get the discount for this purchase from `properties.discount`.\n *\n * This *should* be a number, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {number}\n */\nt.discount = Facade.proxy(\"properties.discount\");\n\n/**\n * Get the shipping method for this purchase from `properties.shippingMethod`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.shippingMethod = function () {\n return (\n this.proxy(\"properties.shipping_method\") ||\n this.proxy(\"properties.shippingMethod\")\n );\n};\n\n/**\n * Get the payment method for this purchase from `properties.paymentMethod`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.paymentMethod = function () {\n return (\n this.proxy(\"properties.payment_method\") ||\n this.proxy(\"properties.paymentMethod\")\n );\n};\n\n/**\n * Get a description for this event from `properties.description`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.description = Facade.proxy(\"properties.description\");\n\n/**\n * Get a plan, as in the plan the user is on, for this event from\n * `properties.plan`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string}\n */\nt.plan = Facade.proxy(\"properties.plan\");\n\n/**\n * Get the subtotal for this purchase from `properties.subtotal`.\n *\n * If `properties.subtotal` isn't available, then fall back to computing the\n * total from `properties.total` or `properties.revenue`, and then subtracting\n * tax, shipping, and discounts.\n *\n * If neither subtotal, total, nor revenue are available, then return 0.\n *\n * @return {number}\n */\nt.subtotal = function () {\n let subtotal = get(this.properties(), \"subtotal\");\n let total = this.total() || this.revenue();\n\n if (subtotal) return subtotal;\n if (!total) return 0;\n\n if (this.total()) {\n let n = this.tax();\n if (n) total -= n;\n n = this.shipping();\n if (n) total -= n;\n n = this.discount();\n if (n) total += n;\n }\n\n return total;\n};\n\n/**\n * Get the products for this event from `properties.products` if it's an\n * array, falling back to an empty array.\n *\n * @return {Array}\n */\nt.products = function () {\n let props = this.properties();\n let products = get(props, \"products\");\n if (Array.isArray(products)) {\n return products.filter(item => item !== null)\n }\n return [];\n};\n\n/**\n * Get the quantity for this event from `properties.quantity`, falling back to\n * a quantity of one.\n *\n * @return {number}\n */\nt.quantity = function () {\n let props = this.obj.properties || {};\n return props.quantity || 1;\n};\n\n/**\n * Get the currency for this event from `properties.currency`, falling back to\n * \"USD\".\n *\n * @return {string}\n */\nt.currency = function () {\n let props = this.obj.properties || {};\n return props.currency || \"USD\";\n};\n\n/**\n * Get the referrer for this event from `context.referrer.url`,\n * `context.page.referrer`, or `properties.referrer`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\nt.referrer = function () {\n // TODO re-examine whether this function is necessary\n return (\n this.proxy(\"context.referrer.url\") ||\n this.proxy(\"context.page.referrer\") ||\n this.proxy(\"properties.referrer\")\n );\n};\n\n/**\n * Get the query for this event from `options.query`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @function\n * @return {string|object}\n */\nt.query = Facade.proxy(\"options.query\");\n\n/**\n * Get the page's properties. This is identical to how {@link Facade#traits}\n * works, except it looks at `properties.*` instead of `options.traits.*`.\n *\n * Properties are gotten from `properties`.\n *\n * The parameter `aliases` is meant to transform keys in `properties` into new\n * keys. Each alias like `{ \"xxx\": \"yyy\" }` will take whatever is at `xxx` in\n * the traits, and move it to `yyy`. If `xxx` is a method of this facade, it'll\n * be called as a function instead of treated as a key into the traits.\n *\n * @example\n * let obj = { properties: { foo: \"bar\" }, anonymousId: \"xxx\" }\n * let track = new Track(obj)\n *\n * track.traits() // { \"foo\": \"bar\" }\n * track.traits({ \"foo\": \"asdf\" }) // { \"asdf\": \"bar\" }\n * track.traits({ \"sessionId\": \"rofl\" }) // { \"rofl\": \"xxx\" }\n *\n * @param {Object} aliases - A mapping from keys to the new keys they should be\n * transformed to.\n * @return {Object}\n */\nt.properties = function (aliases) {\n let ret = this.field(\"properties\") || {};\n aliases = aliases || {};\n\n for (const alias in aliases) {\n if (Object.prototype.hasOwnProperty.call(aliases, alias)) {\n const value = this[alias] == null\n ? this.proxy(\"properties.\" + alias)\n : this[alias]();\n if (value == null) continue;\n ret[aliases[alias]] = value;\n delete ret[alias];\n }\n }\n\n return ret;\n};\n\n/**\n * Get the username of the user for this event from `traits.username`,\n * `properties.username`, `userId`, or `anonymousId`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string|undefined}\n */\nt.username = function () {\n return (\n this.proxy(\"traits.username\") ||\n this.proxy(\"properties.username\") ||\n this.userId() ||\n this.sessionId()\n );\n};\n\n/**\n * Get the email of the user for this event from `trais.email`,\n * `properties.email`, or `options.traits.email`, falling back to `userId` if\n * it looks like a valid email.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string|undefined}\n */\nt.email = function () {\n let email =\n this.proxy(\"traits.email\") ||\n this.proxy(\"properties.email\") ||\n this.proxy(\"options.traits.email\");\n if (email) return email;\n\n let userId = this.userId();\n if (isEmail(userId)) return userId;\n};\n\n/**\n * Get the revenue for this event.\n *\n * If this is an \"Order Completed\" event, this will be the `properties.total`\n * falling back to the `properties.revenue`. For all other events, this is\n * simply taken from `properties.revenue`.\n *\n * If there are dollar signs in these properties, they will be removed. The\n * result will be parsed into a number.\n *\n * @return {number}\n */\nt.revenue = function () {\n let revenue = this.proxy(\"properties.revenue\");\n let event = this.event();\n let orderCompletedRegExp = /^[ _]?completed[ _]?order[ _]?|^[ _]?order[ _]?completed[ _]?$/i;\n\n // it's always revenue, unless it's called during an order completion.\n if (!revenue && event && event.match(orderCompletedRegExp)) {\n revenue = this.proxy(\"properties.total\");\n }\n\n return currency(revenue);\n};\n\n/**\n * Get the revenue for this event in \"cents\" -- in other words, multiply the\n * {@link Track#revenue} by 100, or return 0 if there isn't a numerical revenue\n * for this event.\n *\n * @return {number}\n */\nt.cents = function () {\n let revenue = this.revenue();\n return typeof revenue !== \"number\" ? this.value() || 0 : revenue * 100;\n};\n\n/**\n * Convert this event into an {@link Identify} facade.\n *\n * This works by taking this event's underlying object and creating an Identify\n * from it. This event's traits, taken from `options.traits`, will be used as\n * the Identify's traits.\n *\n * @return {Identify}\n */\nt.identify = function () {\n // TODO: remove me.\n let json = this.json();\n json.traits = this.traits();\n return new Identify(json, this.opts);\n};\n\n/**\n * Get float from currency value.\n *\n * @ignore\n * @param {*} val\n * @return {number}\n */\nfunction currency(val) {\n if (!val) return;\n if (typeof val === \"number\") {\n return val;\n }\n if (typeof val !== \"string\") {\n return;\n }\n\n val = val.replace(/\\$/g, \"\");\n val = parseFloat(val);\n\n if (!isNaN(val)) {\n return val;\n }\n}\n", "\"use strict\";\n\nimport inherit from \"inherits\";\nimport { Facade } from \"./facade\";\nimport { Track } from \"./track\";\nimport isEmail from \"./is-email\";\n\n/**\n * Initialize a new `Page` facade with a `dictionary` of arguments.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.category] - The page category.\n * @param {string} [dictionary.name] - The page name.\n * @param {string} [dictionary.properties] - The page properties.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Facade\n */\nexport function Page(dictionary, opts) {\n Facade.call(this, dictionary, opts);\n}\n\ninherit(Page, Facade);\n\nconst p = Page.prototype;\n\n/**\n * Return the type of facade this is. This will always return `\"page\"`.\n *\n * @return {string}\n */\np.action = function () {\n return \"page\";\n};\n\n/**\n * An alias for {@link Page#action}.\n *\n * @function\n * @return {string}\n */\np.type = p.action;\n\n/**\n * Get the page category from `category`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.category = Facade.field(\"category\");\n\n/**\n * Get the page name from `name`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.name = Facade.field(\"name\");\n\n/**\n * Get the page title from `properties.title`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.title = Facade.proxy(\"properties.title\");\n\n/**\n * Get the page path from `properties.path`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.path = Facade.proxy(\"properties.path\");\n\n/**\n * Get the page URL from `properties.url`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.url = Facade.proxy(\"properties.url\");\n\n/**\n * Get the HTTP referrer from `context.referrer.url`, `context.page.referrer`,\n * or `properties.referrer`.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.referrer = function () {\n return (\n this.proxy(\"context.referrer.url\") ||\n this.proxy(\"context.page.referrer\") ||\n this.proxy(\"properties.referrer\")\n );\n};\n\n/**\n * Get the page's properties. This is identical to how {@link Facade#traits}\n * works, except it looks at `properties.*` instead of `options.traits.*`.\n *\n * Properties are gotten from `properties`, augmented with the page's `name`\n * and `category`.\n *\n * The parameter `aliases` is meant to transform keys in `properties` into new\n * keys. Each alias like `{ \"xxx\": \"yyy\" }` will take whatever is at `xxx` in\n * the traits, and move it to `yyy`. If `xxx` is a method of this facade, it'll\n * be called as a function instead of treated as a key into the traits.\n *\n * @example\n * let obj = { properties: { foo: \"bar\" }, anonymousId: \"xxx\" }\n * let page = new Page(obj)\n *\n * page.traits() // { \"foo\": \"bar\" }\n * page.traits({ \"foo\": \"asdf\" }) // { \"asdf\": \"bar\" }\n * page.traits({ \"sessionId\": \"rofl\" }) // { \"rofl\": \"xxx\" }\n *\n * @param {Object} aliases - A mapping from keys to the new keys they should be\n * transformed to.\n * @return {Object}\n */\np.properties = function (aliases) {\n let props = this.field(\"properties\") || {};\n let category = this.category();\n let name = this.name();\n aliases = aliases || {};\n\n if (category) props.category = category;\n if (name) props.name = name;\n\n for (const alias in aliases) {\n if (Object.prototype.hasOwnProperty.call(aliases, alias)) {\n const value = this[alias] == null\n ? this.proxy(\"properties.\" + alias)\n : this[alias]();\n if (value == null) continue;\n props[aliases[alias]] = value;\n if (alias !== aliases[alias]) delete props[alias];\n }\n }\n\n return props;\n};\n\n/**\n * Get the user's email from `context.traits.email` or `properties.email`,\n * falling back to `userId` if it's a valid email.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.email = function () {\n let email =\n this.proxy(\"context.traits.email\") || this.proxy(\"properties.email\");\n if (email) return email;\n\n let userId = this.userId();\n if (isEmail(userId)) return userId;\n};\n\n/**\n * Get the page fullName. This is `$category $name` if both are present, and\n * just `name` otherwiser.\n *\n * This *should* be a string, but may not be if the client isn't adhering to\n * the spec.\n *\n * @return {string}\n */\np.fullName = function () {\n let category = this.category();\n let name = this.name();\n return name && category ? category + \" \" + name : name;\n};\n\n/**\n * Get an event name from this page call. If `name` is present, this will be\n * `Viewed $name Page`; otherwise, it will be `Loaded a Page`.\n *\n * @param {string} name - The name of this page.\n * @return {string}\n */\np.event = function (name) {\n return name ? \"Viewed \" + name + \" Page\" : \"Loaded a Page\";\n};\n\n/**\n * Convert this Page to a {@link Track} facade. The inputted `name` will be\n * converted to the Track's event name via {@link Page#event}.\n *\n * @param {string} name\n * @return {Track}\n */\np.track = function (name) {\n let json = this.json();\n json.event = this.event(name);\n json.timestamp = this.timestamp();\n json.properties = this.properties();\n return new Track(json, this.opts);\n};\n", "\"use strict\";\n\nimport inherit from \"inherits\";\nimport { Page } from \"./page\";\nimport { Track } from \"./track\";\n\n/**\n * Initialize a new `Screen` facade with a `dictionary` of arguments.\n *\n * Note that this class extends {@link Page}, so its methods are available to\n * instances of this class as well.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.category] - The page category.\n * @param {string} [dictionary.name] - The page name.\n * @param {string} [dictionary.properties] - The page properties.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Page\n */\nexport function Screen(dictionary, opts) {\n Page.call(this, dictionary, opts);\n}\n\ninherit(Screen, Page);\n\n/**\n * Return the type of facade this is. This will always return `\"screen\"`.\n *\n * @return {string}\n */\nScreen.prototype.action = function () {\n return \"screen\";\n};\n\n/**\n * An alias for {@link Screen#action}.\n *\n * @function\n * @return {string}\n */\nScreen.prototype.type = Screen.prototype.action;\n\n/**\n * Get an event name from this screen call. If `name` is present, this will be\n * `Viewed $name Screen`; otherwise, it will be `Loaded a Screen`.\n *\n * @param {string} name - The name of this screen.\n * @return {string}\n */\nScreen.prototype.event = function (name) {\n return name ? \"Viewed \" + name + \" Screen\" : \"Loaded a Screen\";\n};\n\n/**\n * Convert this Screen to a {@link Track} facade. The inputted `name` will be\n * converted to the Track's event name via {@link Screen#event}.\n *\n * @param {string} name\n * @return {Track}\n */\nScreen.prototype.track = function (name) {\n let json = this.json();\n json.event = this.event(name);\n json.timestamp = this.timestamp();\n json.properties = this.properties();\n return new Track(json, this.opts);\n};\n", "\"use strict\";\n\nimport inherit from \"inherits\";\nimport { Facade } from \"./facade\";\n\n/**\n * Initialize a new `Delete` facade with a `dictionary` of arguments.\n *\n * @param {Object} dictionary - The object to wrap.\n * @param {string} [dictionary.category] - The delete category.\n * @param {string} [dictionary.name] - The delete name.\n * @param {string} [dictionary.properties] - The delete properties.\n * @param {Object} opts - Options about what kind of Facade to create.\n *\n * @augments Facade\n */\nexport function Delete(dictionary, opts) {\n Facade.call(this, dictionary, opts);\n}\n\ninherit(Delete, Facade);\n\n/**\n * Return the type of facade this is. This will always return `\"delete\"`.\n *\n * @return {string}\n */\nDelete.prototype.type = function () {\n return \"delete\";\n};\n", "\"use strict\";\n\nimport { Facade } from \"./facade\";\nimport { Alias } from \"./alias\";\nimport { Group } from \"./group\";\nimport { Identify } from \"./identify\";\nimport { Track } from \"./track\";\nimport { Page } from \"./page\";\nimport { Screen } from \"./screen\";\nimport { Delete } from \"./delete\";\n\nexport default {\n ...Facade,\n Alias,\n Group,\n Identify,\n Track,\n Page,\n Screen,\n Delete,\n};\n\nexport { Facade, Alias, Group, Identify, Track, Page, Screen, Delete };\n", "import {\n Alias,\n Facade,\n Group,\n Identify,\n Options,\n Page,\n Screen,\n Track,\n} from '@segment/facade'\nimport { SegmentEvent } from '../core/events'\n\nexport type SegmentFacade = Facade & {\n obj: SegmentEvent\n}\n\nexport function toFacade(evt: SegmentEvent, options?: Options): SegmentFacade {\n let fcd = new Facade(evt, options)\n\n if (evt.type === 'track') {\n fcd = new Track(evt, options)\n }\n\n if (evt.type === 'identify') {\n fcd = new Identify(evt, options)\n }\n\n if (evt.type === 'page') {\n fcd = new Page(evt, options)\n }\n\n if (evt.type === 'alias') {\n fcd = new Alias(evt, options)\n }\n\n if (evt.type === 'group') {\n fcd = new Group(evt, options)\n }\n\n if (evt.type === 'screen') {\n fcd = new Screen(evt, options)\n }\n\n Object.defineProperty(fcd, 'obj', {\n value: evt,\n writable: true,\n })\n\n return fcd as SegmentFacade\n}\n", "import { Context, ContextCancelation } from '../../core/context'\nimport { SegmentEvent } from '../../core/events'\nimport { Plugin } from '../../core/plugin'\nimport { SegmentFacade, toFacade } from '../../lib/to-facade'\n\nexport interface MiddlewareParams {\n payload: SegmentFacade\n\n integrations?: SegmentEvent['integrations']\n next: (payload: MiddlewareParams['payload'] | null) => void\n}\n\nexport interface DestinationMiddlewareParams {\n payload: SegmentFacade\n integration: string\n next: (payload: MiddlewareParams['payload'] | null) => void\n}\n\nexport type MiddlewareFunction = (\n middleware: MiddlewareParams\n) => void | Promise\n\nexport type DestinationMiddlewareFunction = (\n middleware: DestinationMiddlewareParams\n) => void | Promise\n\nexport async function applyDestinationMiddleware(\n destination: string,\n evt: SegmentEvent,\n middleware: DestinationMiddlewareFunction[]\n): Promise {\n // Clone the event so mutations are localized to a single destination.\n let modifiedEvent = toFacade(evt, {\n clone: true,\n traverse: false,\n }).rawEvent() as SegmentEvent\n async function applyMiddleware(\n event: SegmentEvent,\n fn: DestinationMiddlewareFunction\n ): Promise {\n let nextCalled = false\n let returnedEvent: SegmentEvent | null = null\n\n await fn({\n payload: toFacade(event, {\n clone: true,\n traverse: false,\n }),\n integration: destination,\n next(evt) {\n nextCalled = true\n\n if (evt === null) {\n returnedEvent = null\n }\n\n if (evt) {\n returnedEvent = evt.obj\n }\n },\n })\n\n if (!nextCalled && returnedEvent !== null) {\n returnedEvent = returnedEvent as SegmentEvent\n returnedEvent.integrations = {\n ...event.integrations,\n [destination]: false,\n }\n }\n\n return returnedEvent\n }\n\n for (const md of middleware) {\n const result = await applyMiddleware(modifiedEvent, md)\n if (result === null) {\n return null\n }\n modifiedEvent = result\n }\n\n return modifiedEvent\n}\n\nexport function sourceMiddlewarePlugin(\n fn: MiddlewareFunction,\n integrations: SegmentEvent['integrations']\n): Plugin {\n async function apply(ctx: Context): Promise {\n let nextCalled = false\n\n await fn({\n payload: toFacade(ctx.event, {\n clone: true,\n traverse: false,\n }),\n integrations: integrations ?? {},\n next(evt) {\n nextCalled = true\n if (evt) {\n ctx.event = evt.obj\n }\n },\n })\n\n if (!nextCalled) {\n throw new ContextCancelation({\n retry: false,\n type: 'middleware_cancellation',\n reason: 'Middleware `next` function skipped',\n })\n }\n\n return ctx\n }\n\n return {\n name: `Source Middleware ${fn.name}`,\n type: 'before',\n version: '0.1.0',\n\n isLoaded: (): boolean => true,\n load: (ctx): Promise => Promise.resolve(ctx),\n\n track: apply,\n page: apply,\n identify: apply,\n alias: apply,\n group: apply,\n }\n}\n", "import { QueryStringParams } from '.'\n\n/**\n * Returns an object containing only the properties prefixed by the input\n * string.\n * Ex: prefix('ajs_traits_', { ajs_traits_address: '123 St' })\n * will return { address: '123 St' }\n **/\nexport function pickPrefix(\n prefix: string,\n object: QueryStringParams\n): QueryStringParams {\n return Object.keys(object).reduce((acc: QueryStringParams, key: string) => {\n if (key.startsWith(prefix)) {\n const field = key.substr(prefix.length)\n acc[field] = object[key]!\n }\n return acc\n }, {})\n}\n", "/**\n * Tries to gets the unencoded version of an encoded component of a\n * Uniform Resource Identifier (URI). If input string is malformed,\n * returns it back as-is.\n *\n * Note: All occurences of the `+` character become ` ` (spaces).\n **/\nexport function gracefulDecodeURIComponent(\n encodedURIComponent: string\n): string {\n try {\n return decodeURIComponent(encodedURIComponent.replace(/\\+/g, ' '))\n } catch {\n return encodedURIComponent\n }\n}\n", "import { pickPrefix } from './pickPrefix'\nimport { gracefulDecodeURIComponent } from './gracefulDecodeURIComponent'\nimport { Analytics } from '../analytics'\nimport { Context } from '../context'\nimport { isPlainObject } from '@segment/analytics-core'\n\nexport interface QueryStringParams {\n [key: string]: string | null\n}\n\nexport function queryString(\n analytics: Analytics,\n query: string\n): Promise {\n const a = document.createElement('a')\n a.href = query\n const parsed = a.search.slice(1)\n const params = parsed.split('&').reduce((acc: QueryStringParams, str) => {\n const [k, v] = str.split('=')\n acc[k] = gracefulDecodeURIComponent(v)\n return acc\n }, {})\n\n const calls = []\n\n const { ajs_uid, ajs_event, ajs_aid } = params\n const { aid: aidPattern = /.+/, uid: uidPattern = /.+/ } = isPlainObject(\n analytics.options.useQueryString\n )\n ? analytics.options.useQueryString\n : {}\n\n if (ajs_aid) {\n const anonId = Array.isArray(params.ajs_aid)\n ? params.ajs_aid[0]\n : params.ajs_aid\n\n if (aidPattern.test(anonId)) {\n analytics.setAnonymousId(anonId)\n }\n }\n\n if (ajs_uid) {\n const uid = Array.isArray(params.ajs_uid)\n ? params.ajs_uid[0]\n : params.ajs_uid\n\n if (uidPattern.test(uid)) {\n const traits = pickPrefix('ajs_trait_', params)\n\n calls.push(analytics.identify(uid, traits))\n }\n }\n\n if (ajs_event) {\n const event = Array.isArray(params.ajs_event)\n ? params.ajs_event[0]\n : params.ajs_event\n const props = pickPrefix('ajs_prop_', params)\n calls.push(analytics.track(event, props))\n }\n\n return Promise.all(calls)\n}\n", "import { getGlobalAnalytics } from './global-analytics-helper'\nimport { embeddedWriteKey } from './embedded-write-key'\n\nconst analyticsScriptRegex =\n /(https:\\/\\/.*)\\/analytics\\.js\\/v1\\/(?:.*?)\\/(?:platform|analytics.*)?/\nconst getCDNUrlFromScriptTag = (): string | undefined => {\n let cdn: string | undefined\n const scripts = Array.prototype.slice.call(\n document.querySelectorAll('script')\n )\n scripts.forEach((s) => {\n const src = s.getAttribute('src') ?? ''\n const result = analyticsScriptRegex.exec(src)\n\n if (result && result[1]) {\n cdn = result[1]\n }\n })\n return cdn\n}\n\nlet _globalCDN: string | undefined // set globalCDN as in-memory singleton\nconst getGlobalCDNUrl = (): string | undefined => {\n const result = _globalCDN ?? getGlobalAnalytics()?._cdn\n return result\n}\n\nexport const setGlobalCDNUrl = (cdn: string) => {\n const globalAnalytics = getGlobalAnalytics()\n if (globalAnalytics) {\n globalAnalytics._cdn = cdn\n }\n _globalCDN = cdn\n}\n\nexport const getCDN = (): string => {\n const globalCdnUrl = getGlobalCDNUrl()\n\n if (globalCdnUrl) return globalCdnUrl\n\n const cdnFromScriptTag = getCDNUrlFromScriptTag()\n\n if (cdnFromScriptTag) {\n return cdnFromScriptTag\n } else {\n // it's possible that the CDN is not found in the page because:\n // - the script is loaded through a proxy\n // - the script is removed after execution\n // in this case, we fall back to the default Segment CDN\n return `https://cdn.segment.com`\n }\n}\n\nexport const getNextIntegrationsURL = () => {\n const cdn = getCDN()\n return `${cdn}/next-integrations`\n}\n\n/**\n * Replaces the CDN URL in the script tag with the one from Analytics.js 1.0\n *\n * @returns the path to Analytics JS 1.0\n **/\nexport function getLegacyAJSPath(): string {\n const writeKey = embeddedWriteKey() ?? getGlobalAnalytics()?._writeKey\n\n const scripts = Array.prototype.slice.call(\n document.querySelectorAll('script')\n )\n let path: string | undefined = undefined\n\n for (const s of scripts) {\n const src = s.getAttribute('src') ?? ''\n const result = analyticsScriptRegex.exec(src)\n\n if (result && result[1]) {\n path = src\n break\n }\n }\n\n if (path) {\n return path.replace('analytics.min.js', 'analytics.classic.js')\n }\n\n return `https://cdn.segment.com/analytics.js/v1/${writeKey}/analytics.classic.js`\n}\n", "import { JSONObject, Options } from '../core/events/interfaces'\nimport { CDNSettings } from '../browser'\n\n/**\n * Merge legacy settings and initialized Integration option overrides.\n *\n * This will merge any options that were passed from initialization into\n * overrides for settings that are returned by the Segment CDN.\n *\n * i.e. this allows for passing options directly into destinations from\n * the Analytics constructor.\n */\nexport function mergedOptions(\n cdnSettings: CDNSettings,\n options: Options\n): Record {\n const optionOverrides = Object.entries(options.integrations ?? {}).reduce(\n (overrides, [integration, options]) => {\n if (typeof options === 'object') {\n return {\n ...overrides,\n [integration]: options,\n }\n }\n\n return {\n ...overrides,\n [integration]: {},\n }\n },\n {} as Record\n )\n\n return Object.entries(cdnSettings.integrations).reduce(\n (integrationSettings, [integration, settings]) => {\n return {\n ...integrationSettings,\n [integration]: {\n ...settings,\n ...optionOverrides[integration],\n },\n }\n },\n {} as Record\n )\n}\n", "function findScript(src: string): HTMLScriptElement | undefined {\n const scripts = Array.prototype.slice.call(\n window.document.querySelectorAll('script')\n )\n return scripts.find((s) => s.src === src)\n}\n\nexport function loadScript(\n src: string,\n attributes?: Record\n): Promise {\n const found = findScript(src)\n\n if (found !== undefined) {\n const status = found?.getAttribute('status')\n\n if (status === 'loaded') {\n return Promise.resolve(found)\n }\n\n if (status === 'loading') {\n return new Promise((resolve, reject) => {\n found.addEventListener('load', () => resolve(found))\n found.addEventListener('error', (err) => reject(err))\n })\n }\n }\n\n return new Promise((resolve, reject) => {\n const script = window.document.createElement('script')\n\n script.type = 'text/javascript'\n script.src = src\n script.async = true\n\n script.setAttribute('status', 'loading')\n for (const [k, v] of Object.entries(attributes ?? {})) {\n script.setAttribute(k, v)\n }\n\n script.onload = (): void => {\n script.onerror = script.onload = null\n script.setAttribute('status', 'loaded')\n resolve(script)\n }\n\n script.onerror = (): void => {\n script.onerror = script.onload = null\n script.setAttribute('status', 'error')\n reject(new Error(`Failed to load ${src}`))\n }\n\n const tag = window.document.getElementsByTagName('script')[0]\n tag.parentElement?.insertBefore(script, tag)\n })\n}\n\nexport function unloadScript(src: string): Promise {\n const found = findScript(src)\n\n if (found !== undefined) {\n found.remove()\n }\n\n return Promise.resolve()\n}\n", "import { Context } from '../context'\n\nexport interface RecordIntegrationMetricProps {\n integrationName: string\n methodName: string\n didError?: boolean\n type: 'classic' | 'action'\n}\n\nexport function recordIntegrationMetric(\n ctx: Context,\n {\n methodName,\n integrationName,\n type,\n didError = false,\n }: RecordIntegrationMetricProps\n): void {\n ctx.stats.increment(\n `analytics_js.integration.invoke${didError ? '.error' : ''}`,\n 1,\n [\n `method:${methodName}`,\n `integration_name:${integrationName}`,\n `type:${type}`,\n ]\n )\n}\n", "export const pWhile = async (\n condition: (value: T | undefined) => boolean,\n action: () => T | PromiseLike\n): Promise => {\n const loop = async (actionResult: T | undefined): Promise => {\n if (condition(actionResult)) {\n return loop(await action())\n }\n }\n\n return loop(undefined)\n}\n", "// @ts-nocheck\n// prettier-ignore\n/* eslint-disable */\n// @segment/tsub 2.0.0 - GENERATED DO NOT MODIFY\n\n/*! For license information please see tsub.js.LICENSE.txt */\n!function(t,r){if(\"object\"==typeof exports&&\"object\"==typeof module)module.exports=r();else if(\"function\"==typeof define&&define.amd)define([],r);else{var e=r();for(var n in e)(\"object\"==typeof exports?exports:t)[n]=e[n]}}(self,(()=>(()=>{var t={2870:function(t,r,e){\"use strict\";var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(r,\"__esModule\",{value:!0}),r.Store=r.matches=r.transform=void 0;var o=e(4303);Object.defineProperty(r,\"transform\",{enumerable:!0,get:function(){return n(o).default}});var s=e(2370);Object.defineProperty(r,\"matches\",{enumerable:!0,get:function(){return n(s).default}});var i=e(1444);Object.defineProperty(r,\"Store\",{enumerable:!0,get:function(){return n(i).default}})},2370:function(t,r,e){\"use strict\";var n=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(r,\"__esModule\",{value:!0});var o=n(e(7843));function s(t,r){if(!Array.isArray(t))return!0===i(t,r);var e,n,o,f,p=t[0];switch(p){case\"!\":return!s(t[1],r);case\"or\":for(var l=1;l\":case\">=\":return function(t,r,e,n){if(u(t)&&(t=s(t,n)),u(r)&&(r=s(r,n)),\"number\"!=typeof t||\"number\"!=typeof r)return!1;switch(e){case\"<=\":return t<=r;case\">=\":return t>=r;case\"<\":return t\":return t>r;default:throw new Error(\"Invalid operator in compareNumbers: \".concat(e))}}(i(t[1],r),i(t[2],r),p,r);case\"in\":return function(t,r,e){return void 0!==r.find((function(r){return i(r,e)===t}))}(i(t[1],r),i(t[2],r),r);case\"contains\":return o=i(t[1],r),f=i(t[2],r),\"string\"==typeof o&&\"string\"==typeof f&&-1!==o.indexOf(f);case\"match\":return e=i(t[1],r),n=i(t[2],r),\"string\"==typeof e&&\"string\"==typeof n&&function(t,r){var e,n;t:for(;t.length>0;){var o,s;if(o=(e=a(t)).star,s=e.chunk,t=e.pattern,o&&\"\"===s)return!0;var i=c(s,r),u=i.t,f=i.ok,p=i.err;if(p)return!1;if(!f||!(0===u.length||t.length>0)){if(o)for(var l=0;l0)continue;r=u;continue t}if(p)return!1}return!1}r=u}return 0===r.length}(n,e);case\"lowercase\":var v=i(t[1],r);return\"string\"!=typeof v?null:v.toLowerCase();case\"typeof\":return typeof i(t[1],r);case\"length\":return function(t){return null===t?0:Array.isArray(t)||\"string\"==typeof t?t.length:NaN}(i(t[1],r));default:throw new Error(\"FQL IR could not evaluate for token: \".concat(p))}}function i(t,r){return Array.isArray(t)?t:\"object\"==typeof t?t.value:(0,o.default)(r,t)}function u(t){return!!Array.isArray(t)&&((\"lowercase\"===t[0]||\"length\"===t[0]||\"typeof\"===t[0])&&2===t.length||(\"contains\"===t[0]||\"match\"===t[0])&&3===t.length)}function a(t){for(var r={star:!1,chunk:\"\",pattern:\"\"};t.length>0&&\"*\"===t[0];)t=t.slice(1),r.star=!0;var e,n=!1;t:for(e=0;e0;){if(0===r.length)return o;switch(t[0]){case\"[\":var s=r[0];r=r.slice(1);var i=!0;(t=t.slice(1)).length>0&&\"^\"===t[0]&&(i=!1,t=t.slice(1));for(var u=!1,a=0;;){if(t.length>0&&\"]\"===t[0]&&a>0){t=t.slice(1);break}var c,p=\"\";if(c=(e=f(t)).char,t=e.newChunk,e.err)return o;if(p=c,\"-\"===t[0]&&(p=(n=f(t.slice(1))).char,t=n.newChunk,n.err))return o;c<=s&&s<=p&&(u=!0),a++}if(u!==i)return o;break;case\"?\":r=r.slice(1),t=t.slice(1);break;case\"\\\\\":if(0===(t=t.slice(1)).length)return o.err=!0,o;default:if(t[0]!==r[0])return o;r=r.slice(1),t=t.slice(1)}}return o.t=r,o.ok=!0,o.err=!1,o}function f(t){var r={char:\"\",newChunk:\"\",err:!1};return 0===t.length||\"-\"===t[0]||\"]\"===t[0]||\"\\\\\"===t[0]&&0===(t=t.slice(1)).length?(r.err=!0,r):(r.char=t[0],r.newChunk=t.slice(1),0===r.newChunk.length&&(r.err=!0),r)}r.default=function(t,r){if(!r)throw new Error(\"No matcher supplied!\");switch(r.type){case\"all\":return!0;case\"fql\":return function(t,r){if(!t)return!1;try{t=JSON.parse(t)}catch(r){throw new Error('Failed to JSON.parse FQL intermediate representation \"'.concat(t,'\": ').concat(r))}var e=s(t,r);return\"boolean\"==typeof e&&e}(r.ir,t);default:throw new Error(\"Matcher of type \".concat(r.type,\" unsupported.\"))}}},1444:(t,r)=>{\"use strict\";Object.defineProperty(r,\"__esModule\",{value:!0});var e=function(){function t(t){this.rules=[],this.rules=t||[]}return t.prototype.getRulesByDestinationName=function(t){for(var r=[],e=0,n=this.rules;e1?(i.pop(),c=(0,s.default)(e,i.join(\".\"))):c=t,\"object\"==typeof c){if(o.copy){var f=(0,s.default)(e,o.copy);void 0!==f&&(0,u.dset)(t,n,f)}else if(o.move){var p=(0,s.default)(e,o.move);void 0!==p&&(0,u.dset)(t,n,p),(0,a.unset)(t,o.move)}else o.hasOwnProperty(\"set\")&&(0,u.dset)(t,n,o.set);if(o.to_string){var l=(0,s.default)(t,n);if(\"string\"==typeof l||\"object\"==typeof l&&null!==l)continue;void 0!==l?(0,u.dset)(t,n,JSON.stringify(l)):(0,u.dset)(t,n,\"undefined\")}}}}function v(t,r){return!(r.sample.percent<=0)&&(r.sample.percent>=1||(r.sample.path?function(t,r){var e=(0,s.default)(t,r.sample.path),n=(0,o.default)(JSON.stringify(e)),u=-64,a=[];y(n.slice(0,8),a);for(var c=0,f=0;f<64&&1!==a[f];f++)c++;if(0!==c){var p=[];y(n.slice(9,16),p),u-=c,a.splice(0,c),p.splice(64-c),a=a.concat(p)}return a[63]=0===a[63]?1:0,(0,i.default)(parseInt(a.join(\"\"),2),u)=1;o/=2)n-o>=0?(n-=o,r.push(1)):r.push(0)}r.default=function(t,r){for(var e=t,n=0,o=r;n{r.dset=function(t,r,e){r.split&&(r=r.split(\".\"));for(var n,o,s=0,i=r.length,u=t;s{\"use strict\";var r=\"function\"==typeof Float64Array?Float64Array:void 0;t.exports=r},7382:(t,r,e)=>{\"use strict\";var n,o=e(5569),s=e(3304),i=e(8482);n=o()?s:i,t.exports=n},8482:t=>{\"use strict\";t.exports=function(){throw new Error(\"not implemented\")}},6322:(t,r,e)=>{\"use strict\";var n,o=e(2508),s=e(5679),i=e(882);n=o()?s:i,t.exports=n},882:t=>{\"use strict\";t.exports=function(){throw new Error(\"not implemented\")}},5679:t=>{\"use strict\";var r=\"function\"==typeof Uint16Array?Uint16Array:void 0;t.exports=r},4773:(t,r,e)=>{\"use strict\";var n,o=e(9773),s=e(3004),i=e(3078);n=o()?s:i,t.exports=n},3078:t=>{\"use strict\";t.exports=function(){throw new Error(\"not implemented\")}},3004:t=>{\"use strict\";var r=\"function\"==typeof Uint32Array?Uint32Array:void 0;t.exports=r},7980:(t,r,e)=>{\"use strict\";var n,o=e(8114),s=e(6737),i=e(3357);n=o()?s:i,t.exports=n},3357:t=>{\"use strict\";t.exports=function(){throw new Error(\"not implemented\")}},6737:t=>{\"use strict\";var r=\"function\"==typeof Uint8Array?Uint8Array:void 0;t.exports=r},2684:t=>{\"use strict\";var r=\"function\"==typeof Float64Array?Float64Array:null;t.exports=r},5569:(t,r,e)=>{\"use strict\";var n=e(3876);t.exports=n},3876:(t,r,e)=>{\"use strict\";var n=e(1448),o=e(2684);t.exports=function(){var t,r;if(\"function\"!=typeof o)return!1;try{r=new o([1,3.14,-3.14,NaN]),t=n(r)&&1===r[0]&&3.14===r[1]&&-3.14===r[2]&&r[3]!=r[3]}catch(r){t=!1}return t}},9048:(t,r,e)=>{\"use strict\";var n=e(3763);t.exports=n},3763:t=>{\"use strict\";var r=Object.prototype.hasOwnProperty;t.exports=function(t,e){return null!=t&&r.call(t,e)}},7009:(t,r,e)=>{\"use strict\";var n=e(6784);t.exports=n},6784:t=>{\"use strict\";t.exports=function(){return\"function\"==typeof Symbol&&\"symbol\"==typeof Symbol(\"foo\")}},3123:(t,r,e)=>{\"use strict\";var n=e(8481);t.exports=n},8481:(t,r,e)=>{\"use strict\";var n=e(7009)();t.exports=function(){return n&&\"symbol\"==typeof Symbol.toStringTag}},2508:(t,r,e)=>{\"use strict\";var n=e(3403);t.exports=n},3403:(t,r,e)=>{\"use strict\";var n=e(768),o=e(9668),s=e(187);t.exports=function(){var t,r;if(\"function\"!=typeof s)return!1;try{r=new s(r=[1,3.14,-3.14,o+1,o+2]),t=n(r)&&1===r[0]&&3===r[1]&&r[2]===o-2&&0===r[3]&&1===r[4]}catch(r){t=!1}return t}},187:t=>{\"use strict\";var r=\"function\"==typeof Uint16Array?Uint16Array:null;t.exports=r},9773:(t,r,e)=>{\"use strict\";var n=e(2822);t.exports=n},2822:(t,r,e)=>{\"use strict\";var n=e(2744),o=e(3899),s=e(746);t.exports=function(){var t,r;if(\"function\"!=typeof s)return!1;try{r=new s(r=[1,3.14,-3.14,o+1,o+2]),t=n(r)&&1===r[0]&&3===r[1]&&r[2]===o-2&&0===r[3]&&1===r[4]}catch(r){t=!1}return t}},746:t=>{\"use strict\";var r=\"function\"==typeof Uint32Array?Uint32Array:null;t.exports=r},8114:(t,r,e)=>{\"use strict\";var n=e(8066);t.exports=n},8066:(t,r,e)=>{\"use strict\";var n=e(8279),o=e(3443),s=e(2731);t.exports=function(){var t,r;if(\"function\"!=typeof s)return!1;try{r=new s(r=[1,3.14,-3.14,o+1,o+2]),t=n(r)&&1===r[0]&&3===r[1]&&r[2]===o-2&&0===r[3]&&1===r[4]}catch(r){t=!1}return t}},2731:t=>{\"use strict\";var r=\"function\"==typeof Uint8Array?Uint8Array:null;t.exports=r},1448:(t,r,e)=>{\"use strict\";var n=e(1453);t.exports=n},1453:(t,r,e)=>{\"use strict\";var n=e(6208),o=\"function\"==typeof Float64Array;t.exports=function(t){return o&&t instanceof Float64Array||\"[object Float64Array]\"===n(t)}},9331:(t,r,e)=>{\"use strict\";var n=e(7980),o={uint16:e(6322),uint8:n};t.exports=o},5902:(t,r,e)=>{\"use strict\";var n=e(4106);t.exports=n},4106:(t,r,e)=>{\"use strict\";var n,o,s=e(9331);(o=new s.uint16(1))[0]=4660,n=52===new s.uint8(o.buffer)[0],t.exports=n},768:(t,r,e)=>{\"use strict\";var n=e(3823);t.exports=n},3823:(t,r,e)=>{\"use strict\";var n=e(6208),o=\"function\"==typeof Uint16Array;t.exports=function(t){return o&&t instanceof Uint16Array||\"[object Uint16Array]\"===n(t)}},2744:(t,r,e)=>{\"use strict\";var n=e(2326);t.exports=n},2326:(t,r,e)=>{\"use strict\";var n=e(6208),o=\"function\"==typeof Uint32Array;t.exports=function(t){return o&&t instanceof Uint32Array||\"[object Uint32Array]\"===n(t)}},8279:(t,r,e)=>{\"use strict\";var n=e(208);t.exports=n},208:(t,r,e)=>{\"use strict\";var n=e(6208),o=\"function\"==typeof Uint8Array;t.exports=function(t){return o&&t instanceof Uint8Array||\"[object Uint8Array]\"===n(t)}},6315:t=>{\"use strict\";t.exports=1023},1686:t=>{\"use strict\";t.exports=2147483647},3105:t=>{\"use strict\";t.exports=2146435072},3449:t=>{\"use strict\";t.exports=2147483648},6988:t=>{\"use strict\";t.exports=-1023},9777:t=>{\"use strict\";t.exports=1023},3690:t=>{\"use strict\";t.exports=-1074},2918:(t,r,e)=>{\"use strict\";var n=e(4772).NEGATIVE_INFINITY;t.exports=n},4165:t=>{\"use strict\";var r=Number.POSITIVE_INFINITY;t.exports=r},6488:t=>{\"use strict\";t.exports=22250738585072014e-324},9668:t=>{\"use strict\";t.exports=65535},3899:t=>{\"use strict\";t.exports=4294967295},3443:t=>{\"use strict\";t.exports=255},7011:(t,r,e)=>{\"use strict\";var n=e(812);t.exports=n},812:(t,r,e)=>{\"use strict\";var n=e(4165),o=e(2918);t.exports=function(t){return t===n||t===o}},1883:(t,r,e)=>{\"use strict\";var n=e(1797);t.exports=n},1797:t=>{\"use strict\";t.exports=function(t){return t!=t}},513:(t,r,e)=>{\"use strict\";var n=e(5760);t.exports=n},5760:t=>{\"use strict\";t.exports=function(t){return Math.abs(t)}},5848:(t,r,e)=>{\"use strict\";var n=e(677);t.exports=n},677:(t,r,e)=>{\"use strict\";var n=e(3449),o=e(1686),s=e(7838),i=e(1921),u=e(2490),a=[0,0];t.exports=function(t,r){var e,c;return s.assign(t,a,1,0),e=a[0],e&=o,c=i(r),u(e|=c&=n,a[1])}},5500:(t,r,e)=>{\"use strict\";var n=e(8397);t.exports=n},8397:(t,r,e)=>{\"use strict\";var n=e(4165),o=e(2918),s=e(6315),i=e(9777),u=e(6988),a=e(3690),c=e(1883),f=e(7011),p=e(5848),l=e(4948),v=e(8478),y=e(7838),d=e(2490),h=[0,0],x=[0,0];t.exports=function(t,r){var e,b;return 0===t||c(t)||f(t)?t:(l(h,t),r+=h[1],(r+=v(t=h[0]))i?t<0?o:n:(r<=u?(r+=52,b=2220446049250313e-31):b=1,y(x,t),e=x[0],e&=2148532223,b*d(e|=r+s<<20,x[1])))}},4772:(t,r,e)=>{\"use strict\";var n=e(7548);t.exports=n},7548:t=>{\"use strict\";t.exports=Number},8478:(t,r,e)=>{\"use strict\";var n=e(4500);t.exports=n},4500:(t,r,e)=>{\"use strict\";var n=e(1921),o=e(3105),s=e(6315);t.exports=function(t){var r=n(t);return(r=(r&o)>>>20)-s|0}},2490:(t,r,e)=>{\"use strict\";var n=e(9639);t.exports=n},4445:(t,r,e)=>{\"use strict\";var n,o,s;!0===e(5902)?(o=1,s=0):(o=0,s=1),n={HIGH:o,LOW:s},t.exports=n},9639:(t,r,e)=>{\"use strict\";var n=e(4773),o=e(7382),s=e(4445),i=new o(1),u=new n(i.buffer),a=s.HIGH,c=s.LOW;t.exports=function(t,r){return u[a]=t,u[c]=r,i[0]}},5646:(t,r,e)=>{\"use strict\";var n;n=!0===e(5902)?1:0,t.exports=n},1921:(t,r,e)=>{\"use strict\";var n=e(6285);t.exports=n},6285:(t,r,e)=>{\"use strict\";var n=e(4773),o=e(7382),s=e(5646),i=new o(1),u=new n(i.buffer);t.exports=function(t){return i[0]=t,u[s]}},9024:(t,r,e)=>{\"use strict\";var n=e(6488),o=e(7011),s=e(1883),i=e(513);t.exports=function(t,r,e,u){return s(t)||o(t)?(r[u]=t,r[u+e]=0,r):0!==t&&i(t){\"use strict\";var n=e(7576),o=e(9422);n(o,\"assign\",e(9024)),t.exports=o},9422:(t,r,e)=>{\"use strict\";var n=e(9024);t.exports=function(t){return n(t,[0,0],1,0)}},5239:(t,r,e)=>{\"use strict\";var n=e(4773),o=e(7382),s=e(5782),i=new o(1),u=new n(i.buffer),a=s.HIGH,c=s.LOW;t.exports=function(t,r,e,n){return i[0]=t,r[n]=u[a],r[n+e]=u[c],r}},7838:(t,r,e)=>{\"use strict\";var n=e(7576),o=e(4010);n(o,\"assign\",e(5239)),t.exports=o},5782:(t,r,e)=>{\"use strict\";var n,o,s;!0===e(5902)?(o=1,s=0):(o=0,s=1),n={HIGH:o,LOW:s},t.exports=n},4010:(t,r,e)=>{\"use strict\";var n=e(5239);t.exports=function(t){return n(t,[0,0],1,0)}},7576:(t,r,e)=>{\"use strict\";var n=e(7063);t.exports=n},7063:(t,r,e)=>{\"use strict\";var n=e(6691);t.exports=function(t,r,e){n(t,r,{configurable:!1,enumerable:!1,writable:!1,value:e})}},2073:t=>{\"use strict\";var r=Object.defineProperty;t.exports=r},1680:t=>{\"use strict\";var r=\"function\"==typeof Object.defineProperty?Object.defineProperty:null;t.exports=r},1471:(t,r,e)=>{\"use strict\";var n=e(1680);t.exports=function(){try{return n({},\"x\",{}),!0}catch(t){return!1}}},6691:(t,r,e)=>{\"use strict\";var n,o=e(1471),s=e(2073),i=e(1309);n=o()?s:i,t.exports=n},1309:t=>{\"use strict\";var r=Object.prototype,e=r.toString,n=r.__defineGetter__,o=r.__defineSetter__,s=r.__lookupGetter__,i=r.__lookupSetter__;t.exports=function(t,u,a){var c,f,p,l;if(\"object\"!=typeof t||null===t||\"[object Array]\"===e.call(t))throw new TypeError(\"invalid argument. First argument must be an object. Value: `\"+t+\"`.\");if(\"object\"!=typeof a||null===a||\"[object Array]\"===e.call(a))throw new TypeError(\"invalid argument. Property descriptor must be an object. Value: `\"+a+\"`.\");if((f=\"value\"in a)&&(s.call(t,u)||i.call(t,u)?(c=t.__proto__,t.__proto__=r,delete t[u],t[u]=a.value,t.__proto__=c):t[u]=a.value),p=\"get\"in a,l=\"set\"in a,f&&(p||l))throw new Error(\"invalid argument. Cannot specify one or more accessors and a value or writable attribute in the property descriptor.\");return p&&n&&n.call(t,u,a.get),l&&o&&o.call(t,u,a.set),t}},6208:(t,r,e)=>{\"use strict\";var n,o=e(3123),s=e(7407),i=e(4210);n=o()?i:s,t.exports=n},7407:(t,r,e)=>{\"use strict\";var n=e(173);t.exports=function(t){return n.call(t)}},4210:(t,r,e)=>{\"use strict\";var n=e(9048),o=e(1403),s=e(173);t.exports=function(t){var r,e,i;if(null==t)return s.call(t);e=t[o],r=n(t,o);try{t[o]=void 0}catch(r){return s.call(t)}return i=s.call(t),r?t[o]=e:delete t[o],i}},173:t=>{\"use strict\";var r=Object.prototype.toString;t.exports=r},1403:t=>{\"use strict\";var r=\"function\"==typeof Symbol?Symbol.toStringTag:\"\";t.exports=r},7843:function(t){t.exports=function(t,r,e,n,o){for(r=r.split?r.split(\".\"):r,n=0;n{\"use strict\";e.r(r),e.d(r,{default:()=>s});for(var n=[],o=0;o<64;)n[o]=0|4294967296*Math.sin(++o%Math.PI);function s(t){var r,e,s,i=[r=1732584193,e=4023233417,~r,~e],u=[],a=unescape(encodeURI(t))+\"\u0080\",c=a.length;for(t=--c/4+2|15,u[--t]=8*c;~c;)u[c>>2]|=a.charCodeAt(c)<<8*c--;for(o=a=0;o>4]+n[a]+~~u[o|15&[a,5*a+1,3*a+5,7*a][c]])<<(c=[7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21][4*c+a++%4])|s>>>-c),r,e])r=0|c[1],e=c[2];for(a=4;a;)i[--a]+=c[a]}for(t=\"\";a<32;)t+=(i[a>>3]>>4*(1^a++)&15).toString(16);return t}}},r={};function e(n){var o=r[n];if(void 0!==o)return o.exports;var s=r[n]={exports:{}};return t[n].call(s.exports,s,s.exports,e),s.exports}return e.d=(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},e.o=(t,r)=>Object.prototype.hasOwnProperty.call(t,r),e.r=t=>{\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(t,\"__esModule\",{value:!0})},e(2870)})()));", "// @ts-ignore\nimport * as tsub from '../../vendor/tsub/tsub'\nimport type { Matcher, Rule, Store } from '../../vendor/tsub/types'\nimport { DestinationMiddlewareFunction } from '../middleware'\n\n// TODO: update tsub definition\ntype RoutingRuleMatcher = Matcher & {\n config?: {\n expr: string\n }\n}\n\nexport type RoutingRule = Rule & {\n matchers: RoutingRuleMatcher[]\n}\n\nexport const tsubMiddleware =\n (rules: RoutingRule[]): DestinationMiddlewareFunction =>\n ({ payload, integration, next }): void => {\n const store = new tsub.Store(rules) as Store\n const rulesToApply = store.getRulesByDestinationName(integration)\n\n rulesToApply.forEach((rule: Rule) => {\n const { matchers, transformers } = rule\n\n for (let i = 0; i < matchers.length; i++) {\n if (tsub.matches(payload.obj, matchers[i])) {\n payload.obj = tsub.transform(payload.obj, transformers[i])\n\n if (payload.obj === null) {\n return next(null)\n }\n }\n }\n })\n\n next(payload)\n }\n", "import { PlanEvent, TrackPlan } from '../core/events/interfaces'\n\n/**\n * Determines whether a track event is allowed to be sent based on the\n * user's tracking plan.\n * If the user does not have a tracking plan or the event is allowed based\n * on the tracking plan configuration, returns true.\n */\nexport function isPlanEventEnabled(\n plan: TrackPlan | undefined,\n planEvent: PlanEvent | undefined\n): boolean {\n // Always prioritize the event's `enabled` status\n if (typeof planEvent?.enabled === 'boolean') {\n return planEvent.enabled\n }\n\n // Assume absence of a tracking plan means events are enabled\n return plan?.__default?.enabled ?? true\n}\n", "import { Analytics } from '../../core/analytics'\nimport { RemoteIntegrationSettings } from '../../browser'\nimport { getNextIntegrationsURL } from '../../lib/parse-cdn'\nimport { Context } from '../../core/context'\nimport { User } from '../../core/user'\nimport { loadScript, unloadScript } from '../../lib/load-script'\nimport {\n LegacyIntegration,\n ClassicIntegrationBuilder,\n ClassicIntegrationSource,\n} from './types'\n\nfunction normalizeName(name: string): string {\n return name.toLowerCase().replace('.', '').replace(/\\s+/g, '-')\n}\n\nfunction obfuscatePathName(pathName: string, obfuscate = false): string | void {\n return obfuscate ? btoa(pathName).replace(/=/g, '') : undefined\n}\n\nexport function resolveIntegrationNameFromSource(\n integrationSource: ClassicIntegrationSource\n) {\n return (\n 'Integration' in integrationSource\n ? integrationSource.Integration\n : integrationSource\n ).prototype.name\n}\n\nfunction recordLoadMetrics(fullPath: string, ctx: Context, name: string): void {\n try {\n const [metric] =\n window?.performance?.getEntriesByName(fullPath, 'resource') ?? []\n // we assume everything that took under 100ms is cached\n metric &&\n ctx.stats.gauge('legacy_destination_time', Math.round(metric.duration), [\n name,\n ...(metric.duration < 100 ? ['cached'] : []),\n ])\n } catch (_) {\n // not available\n }\n}\n\nexport function buildIntegration(\n integrationSource: ClassicIntegrationSource,\n integrationSettings: { [key: string]: any },\n analyticsInstance: Analytics\n): LegacyIntegration {\n let integrationCtr: ClassicIntegrationBuilder\n // GA and Appcues use a different interface to instantiating integrations\n if ('Integration' in integrationSource) {\n const analyticsStub = {\n user: (): User => analyticsInstance.user(),\n addIntegration: (): void => {},\n }\n\n integrationSource(analyticsStub)\n integrationCtr = integrationSource.Integration\n } else {\n integrationCtr = integrationSource\n }\n\n const integration = new integrationCtr(integrationSettings)\n integration.analytics = analyticsInstance\n return integration\n}\n\nexport async function loadIntegration(\n ctx: Context,\n name: string,\n version: string,\n obfuscate?: boolean\n): Promise {\n const pathName = normalizeName(name)\n const obfuscatedPathName = obfuscatePathName(pathName, obfuscate)\n const path = getNextIntegrationsURL()\n\n const fullPath = `${path}/integrations/${\n obfuscatedPathName ?? pathName\n }/${version}/${obfuscatedPathName ?? pathName}.dynamic.js.gz`\n\n try {\n await loadScript(fullPath)\n recordLoadMetrics(fullPath, ctx, name)\n } catch (err) {\n ctx.stats.gauge('legacy_destination_time', -1, [`plugin:${name}`, `failed`])\n throw err\n }\n\n // @ts-ignore\n const deps: string[] = window[`${pathName}Deps`]\n await Promise.all(deps.map((dep) => loadScript(path + dep + '.gz')))\n\n // @ts-ignore\n window[`${pathName}Loader`]()\n\n return window[\n // @ts-ignore\n `${pathName}Integration`\n ] as ClassicIntegrationSource\n}\n\nexport async function unloadIntegration(\n name: string,\n version: string,\n obfuscate?: boolean\n): Promise {\n const path = getNextIntegrationsURL()\n const pathName = normalizeName(name)\n const obfuscatedPathName = obfuscatePathName(name, obfuscate)\n\n const fullPath = `${path}/integrations/${\n obfuscatedPathName ?? pathName\n }/${version}/${obfuscatedPathName ?? pathName}.dynamic.js.gz`\n\n return unloadScript(fullPath)\n}\n\nexport function resolveVersion(\n integrationConfig?: RemoteIntegrationSettings\n): string {\n return (\n integrationConfig?.versionSettings?.override ??\n integrationConfig?.versionSettings?.version ??\n 'latest'\n )\n}\n", "import { Integrations } from '@segment/analytics-core'\nimport { RemoteIntegrationSettings } from '../..'\n\nexport const isInstallableIntegration = (\n name: string,\n integrationSettings: RemoteIntegrationSettings\n) => {\n const { type, bundlingStatus, versionSettings } = integrationSettings\n // We use `!== 'unbundled'` (versus `=== 'bundled'`) to be inclusive of\n // destinations without a defined value for `bundlingStatus`\n const deviceMode =\n bundlingStatus !== 'unbundled' &&\n (type === 'browser' || versionSettings?.componentTypes?.includes('browser'))\n\n // checking for iterable is a quick fix we need in place to prevent\n // errors showing Iterable as a failed destiantion. Ideally, we should\n // fix the Iterable metadata instead, but that's a longer process.\n return !name.startsWith('Segment') && name !== 'Iterable' && deviceMode\n}\n\nexport const isDisabledIntegration = (\n integrationName: string,\n globalIntegrations: Integrations\n) => {\n const allDisableAndNotDefined =\n globalIntegrations.All === false &&\n globalIntegrations[integrationName] === undefined\n\n return (\n globalIntegrations[integrationName] === false || allDisableAndNotDefined\n )\n}\n", "import { Integrations, JSONObject } from '../../core/events'\nimport { Alias, Facade, Group, Identify, Page, Track } from '@segment/facade'\nimport { Analytics, InitOptions } from '../../core/analytics'\nimport { CDNSettings } from '../../browser'\nimport { isOffline, isOnline } from '../../core/connection'\nimport { Context, ContextCancelation } from '../../core/context'\nimport { isServer } from '../../core/environment'\nimport { InternalPluginWithAddMiddleware, Plugin } from '../../core/plugin'\nimport { attempt } from '@segment/analytics-core'\nimport { isPlanEventEnabled } from '../../lib/is-plan-event-enabled'\nimport { mergedOptions } from '../../lib/merged-options'\nimport { pWhile } from '../../lib/p-while'\nimport { PriorityQueue } from '../../lib/priority-queue'\nimport { PersistedPriorityQueue } from '../../lib/priority-queue/persisted'\nimport {\n applyDestinationMiddleware,\n DestinationMiddlewareFunction,\n} from '../middleware'\nimport {\n buildIntegration,\n loadIntegration,\n resolveIntegrationNameFromSource,\n resolveVersion,\n unloadIntegration,\n} from './loader'\nimport { LegacyIntegration, ClassicIntegrationSource } from './types'\nimport { isPlainObject } from '@segment/analytics-core'\nimport {\n isDisabledIntegration as shouldSkipIntegration,\n isInstallableIntegration,\n} from './utils'\nimport { recordIntegrationMetric } from '../../core/stats/metric-helpers'\nimport { createDeferred } from '@segment/analytics-generic-utils'\n\nexport type ClassType = new (...args: unknown[]) => T\n\nasync function flushQueue(\n xt: Plugin,\n queue: PriorityQueue\n): Promise> {\n const failedQueue: Context[] = []\n\n if (isOffline()) {\n return queue\n }\n\n await pWhile(\n () => queue.length > 0 && isOnline(),\n async () => {\n const ctx = queue.pop()\n if (!ctx) {\n return\n }\n\n const result = await attempt(ctx, xt)\n const success = result instanceof Context\n if (!success) {\n failedQueue.push(ctx)\n }\n }\n )\n\n // re-add failed tasks\n failedQueue.map((failed) => queue.pushWithBackoff(failed))\n return queue\n}\n\nexport class LegacyDestination implements InternalPluginWithAddMiddleware {\n name: string\n version: string\n settings: JSONObject\n options: InitOptions = {}\n readonly type = 'destination'\n middleware: DestinationMiddlewareFunction[] = []\n\n private _ready: boolean | undefined\n private _initialized: boolean | undefined\n private onReady: Promise | undefined\n private initializePromise = createDeferred()\n private disableAutoISOConversion: boolean\n\n integrationSource?: ClassicIntegrationSource\n integration: LegacyIntegration | undefined\n\n buffer: PriorityQueue\n flushing = false\n\n constructor(\n name: string,\n version: string,\n writeKey: string,\n settings: JSONObject = {},\n options: InitOptions,\n integrationSource?: ClassicIntegrationSource\n ) {\n this.name = name\n this.version = version\n this.settings = { ...settings }\n this.disableAutoISOConversion = options.disableAutoISOConversion || false\n this.integrationSource = integrationSource\n\n // AJS-Renderer sets an extraneous `type` setting that clobbers\n // existing type defaults. We need to remove it if it's present\n if (this.settings['type'] && this.settings['type'] === 'browser') {\n delete this.settings['type']\n }\n\n this.initializePromise.promise.then(\n (isInitialized) => (this._initialized = isInitialized),\n () => {}\n )\n\n this.options = options\n this.buffer = options.disableClientPersistence\n ? new PriorityQueue(4, [])\n : new PersistedPriorityQueue(4, `${writeKey}:dest-${name}`)\n\n this.scheduleFlush()\n }\n\n isLoaded(): boolean {\n return !!this._ready\n }\n\n ready(): Promise {\n return this.initializePromise.promise.then(\n () => this.onReady ?? Promise.resolve()\n )\n }\n\n async load(ctx: Context, analyticsInstance: Analytics): Promise {\n if (this._ready || this.onReady !== undefined) {\n return\n }\n\n const integrationSource =\n this.integrationSource ??\n (await loadIntegration(\n ctx,\n this.name,\n this.version,\n this.options.obfuscate\n ))\n\n this.integration = buildIntegration(\n integrationSource,\n this.settings,\n analyticsInstance\n )\n\n this.onReady = new Promise((resolve) => {\n const onReadyFn = (): void => {\n this._ready = true\n resolve(true)\n }\n\n this.integration!.once('ready', onReadyFn)\n })\n\n this.integration!.on('initialize', () => {\n this.initializePromise.resolve(true)\n })\n\n try {\n recordIntegrationMetric(ctx, {\n integrationName: this.name,\n methodName: 'initialize',\n type: 'classic',\n })\n this.integration.initialize()\n } catch (error) {\n recordIntegrationMetric(ctx, {\n integrationName: this.name,\n methodName: 'initialize',\n type: 'classic',\n didError: true,\n })\n this.initializePromise.resolve(false)\n throw error\n }\n }\n\n unload(_ctx: Context, _analyticsInstance: Analytics): Promise {\n return unloadIntegration(this.name, this.version, this.options.obfuscate)\n }\n\n addMiddleware(...fn: DestinationMiddlewareFunction[]): void {\n this.middleware = this.middleware.concat(...fn)\n }\n\n shouldBuffer(ctx: Context): boolean {\n return (\n // page events can't be buffered because of destinations that automatically add page views\n ctx.event.type !== 'page' &&\n (isOffline() || this._ready !== true || this._initialized !== true)\n )\n }\n\n private async send(\n ctx: Context,\n clz: ClassType,\n eventType: 'track' | 'identify' | 'page' | 'alias' | 'group'\n ): Promise {\n if (this.shouldBuffer(ctx)) {\n this.buffer.push(ctx)\n this.scheduleFlush()\n return ctx\n }\n\n const plan = this.options?.plan?.track\n const ev = ctx.event.event\n\n if (plan && ev && this.name !== 'Segment.io') {\n // events are always sent to segment (legacy behavior)\n const planEvent = plan[ev]\n if (!isPlanEventEnabled(plan, planEvent)) {\n ctx.updateEvent('integrations', {\n ...ctx.event.integrations,\n All: false,\n 'Segment.io': true,\n })\n ctx.cancel(\n new ContextCancelation({\n retry: false,\n reason: `Event ${ev} disabled for integration ${this.name} in tracking plan`,\n type: 'Dropped by plan',\n })\n )\n } else {\n ctx.updateEvent('integrations', {\n ...ctx.event.integrations,\n ...planEvent?.integrations,\n })\n }\n\n if (planEvent?.enabled && planEvent?.integrations![this.name] === false) {\n ctx.cancel(\n new ContextCancelation({\n retry: false,\n reason: `Event ${ev} disabled for integration ${this.name} in tracking plan`,\n type: 'Dropped by plan',\n })\n )\n }\n }\n\n const afterMiddleware = await applyDestinationMiddleware(\n this.name,\n ctx.event,\n this.middleware\n )\n\n if (afterMiddleware === null) {\n return ctx\n }\n\n const event = new clz(afterMiddleware, {\n traverse: !this.disableAutoISOConversion,\n })\n\n recordIntegrationMetric(ctx, {\n integrationName: this.name,\n methodName: eventType,\n type: 'classic',\n })\n\n try {\n if (this.integration) {\n await this.integration!.invoke.call(this.integration, eventType, event)\n }\n } catch (err) {\n recordIntegrationMetric(ctx, {\n integrationName: this.name,\n methodName: eventType,\n type: 'classic',\n didError: true,\n })\n throw err\n }\n\n return ctx\n }\n\n async track(ctx: Context): Promise {\n return this.send(ctx, Track as ClassType, 'track')\n }\n\n async page(ctx: Context): Promise {\n if (this.integration?._assumesPageview && !this._initialized) {\n this.integration.initialize()\n }\n\n await this.initializePromise.promise\n return this.send(ctx, Page as ClassType, 'page')\n }\n\n async identify(ctx: Context): Promise {\n return this.send(ctx, Identify as ClassType, 'identify')\n }\n\n async alias(ctx: Context): Promise {\n return this.send(ctx, Alias as ClassType, 'alias')\n }\n\n async group(ctx: Context): Promise {\n return this.send(ctx, Group as ClassType, 'group')\n }\n\n private scheduleFlush(): void {\n if (this.flushing) {\n return\n }\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n setTimeout(async () => {\n if (isOffline() || this._ready !== true || this._initialized !== true) {\n this.scheduleFlush()\n return\n }\n\n this.flushing = true\n this.buffer = await flushQueue(this, this.buffer)\n this.flushing = false\n\n if (this.buffer.todo > 0) {\n this.scheduleFlush()\n }\n }, Math.random() * 5000)\n }\n}\n\nexport function ajsDestinations(\n writeKey: string,\n settings: CDNSettings,\n globalIntegrations: Integrations = {},\n options: InitOptions = {},\n routingMiddleware?: DestinationMiddlewareFunction,\n legacyIntegrationSources?: ClassicIntegrationSource[]\n): LegacyDestination[] {\n if (isServer()) {\n return []\n }\n\n if (settings.plan) {\n options = options ?? {}\n options.plan = settings.plan\n }\n\n const routingRules = settings.middlewareSettings?.routingRules ?? []\n const remoteIntegrationsConfig = settings.integrations\n const localIntegrationsConfig = options.integrations\n // merged remote CDN settings with user provided options\n const integrationOptions = mergedOptions(settings, options ?? {}) as Record<\n string,\n JSONObject\n >\n\n const adhocIntegrationSources = legacyIntegrationSources?.reduce(\n (acc, integrationSource) => ({\n ...acc,\n [resolveIntegrationNameFromSource(integrationSource)]: integrationSource,\n }),\n {} as Record\n )\n\n const installableIntegrations = new Set([\n // Remotely configured installable integrations\n ...Object.keys(remoteIntegrationsConfig).filter((name) =>\n isInstallableIntegration(name, remoteIntegrationsConfig[name])\n ),\n\n // Directly provided integration sources are only installable if settings for them are available\n ...Object.keys(adhocIntegrationSources || {}).filter(\n (name) =>\n isPlainObject(remoteIntegrationsConfig[name]) ||\n isPlainObject(localIntegrationsConfig?.[name])\n ),\n ])\n\n return Array.from(installableIntegrations)\n .filter((name) => !shouldSkipIntegration(name, globalIntegrations))\n .map((name) => {\n const integrationSettings = remoteIntegrationsConfig[name]\n const version = resolveVersion(integrationSettings)\n const destination = new LegacyDestination(\n name,\n version,\n writeKey,\n integrationOptions[name],\n options,\n adhocIntegrationSources?.[name]\n )\n\n const routing = routingRules.filter(\n (rule) => rule.destinationName === name\n )\n if (routing.length > 0 && routingMiddleware) {\n destination.addMiddleware(routingMiddleware)\n }\n\n return destination\n })\n}\n", "!function(e,t){\"object\"==typeof exports&&\"object\"==typeof module?module.exports=t():\"function\"==typeof define&&define.amd?define([],t):\"object\"==typeof exports?exports.analyticsVideoPlugins=t():e.analyticsVideoPlugins=t()}(window,(function(){return function(e){var t={};function a(n){if(t[n])return t[n].exports;var i=t[n]={i:n,l:!1,exports:{}};return e[n].call(i.exports,i,i.exports,a),i.l=!0,i.exports}return a.m=e,a.c=t,a.d=function(e,t,n){a.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},a.r=function(e){\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(e,\"__esModule\",{value:!0})},a.t=function(e,t){if(1&t&&(e=a(e)),8&t)return e;if(4&t&&\"object\"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(a.r(n),Object.defineProperty(n,\"default\",{enumerable:!0,value:e}),2&t&&\"string\"!=typeof e)for(var i in e)a.d(n,i,function(t){return e[t]}.bind(null,i));return n},a.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return a.d(t,\"a\",t),t},a.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},a.p=\"\",a(a.s=2)}([function(e,t,a){\"use strict\";a.r(t);var n=\"function\"==typeof fetch?fetch.bind():function(e,t){return t=t||{},new Promise((function(a,n){var i=new XMLHttpRequest;for(var r in i.open(t.method||\"get\",e,!0),t.headers)i.setRequestHeader(r,t.headers[r]);function o(){var e,t=[],a=[],n={};return i.getAllResponseHeaders().replace(/^(.*?):[^\\S\\n]*([\\s\\S]*?)$/gm,(function(i,r,o){t.push(r=r.toLowerCase()),a.push([r,o]),e=n[r],n[r]=e?e+\",\"+o:o})),{ok:2==(i.status/100|0),status:i.status,statusText:i.statusText,url:i.responseURL,clone:o,text:function(){return Promise.resolve(i.responseText)},json:function(){return Promise.resolve(i.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([i.response]))},headers:{keys:function(){return t},entries:function(){return a},get:function(e){return n[e.toLowerCase()]},has:function(e){return e.toLowerCase()in n}}}}i.withCredentials=\"include\"==t.credentials,i.onload=function(){a(o())},i.onerror=n,i.send(t.body)}))};t.default=n},function(e,t,a){\"use strict\";Object.defineProperty(t,\"__esModule\",{value:!0});var n=function(){function e(e,t){for(var a=0;a=10&&(this.track(\"Video Content Playing\",this.metadata.content),this.mostRecentHeartbeat=Math.floor(t))}},{key:\"trackPause\",value:function(){this.isPaused=!0,this.track(\"Video Playback Paused\",this.metadata.playback)}},{key:\"retrieveMetadata\",value:function(e){var t=this;return new Promise((function(a,n){var r=e.id;(0,i.default)(\"https://api.vimeo.com/videos/\"+r,{headers:{Authorization:\"Bearer \"+t.authToken}}).then((function(e){return e.ok?e.json():n(e)})).then((function(e){t.metadata.content.title=e.name,t.metadata.content.description=e.description,t.metadata.content.publisher=e.user.name,t.metadata.playback.position=0,t.metadata.playback.totalLength=e.duration})).catch((function(e){return console.error(\"Request to Vimeo API Failed with: \",e),n(e)}))}))}},{key:\"updateMetadata\",value:function(e){var t=this;return new Promise((function(a,n){t.player.getVolume().then((function(n){n&&(t.metadata.playback.sound=100*n),t.metadata.playback.position=e.seconds,a()})).catch(n)}))}}]),t}(r(a(1)).default);t.default=o},function(e,t,a){\"use strict\";Object.defineProperty(t,\"__esModule\",{value:!0});var n=function(){function e(e,t){for(var a=0;a2e3}}]),t}(r.default);function l(e){var t=e.match(/PT(\\d+H)?(\\d+M)?(\\d+S)?/);return t=t.slice(1).map((function(e){if(null!=e)return e.replace(/\\D/,\"\")})),3600*(parseInt(t[0])||0)+60*(parseInt(t[1])||0)+(parseInt(t[2])||0)}t.default=s}])}));", "import { Analytics } from '../../core/analytics'\n\nexport async function loadLegacyVideoPlugins(\n analytics: Analytics\n): Promise {\n const plugins = await import(\n // @ts-expect-error\n '@segment/analytics.js-video-plugins/dist/index.umd.js'\n )\n\n // This is super gross, but we need to support the `window.analytics.plugins` namespace\n // that is linked in the segment docs in order to be backwards compatible with ajs-classic\n\n // @ts-expect-error\n analytics._plugins = plugins\n}\n", "import { CDNSettings } from '../../browser'\nimport { Context } from '../../core/context'\nimport { PlanEvent, TrackPlan } from '../../core/events/interfaces'\nimport { Plugin } from '../../core/plugin'\nimport { isPlanEventEnabled } from '../../lib/is-plan-event-enabled'\nimport { RemotePlugin } from '../remote-loader'\n\nfunction disabledActionDestinations(\n plan: PlanEvent | undefined,\n settings: CDNSettings\n): { [destination: string]: string[] } {\n if (!plan || !Object.keys(plan)) {\n return {}\n }\n\n const disabledIntegrations = plan.integrations\n ? Object.keys(plan.integrations).filter(\n (i) => plan.integrations![i] === false\n )\n : []\n\n // This accounts for cases like Fullstory, where the settings.integrations\n // contains a \"Fullstory\" object but settings.remotePlugins contains \"Fullstory (Actions)\"\n const disabledRemotePlugins: string[] = []\n ;(settings.remotePlugins ?? []).forEach((p: RemotePlugin) => {\n disabledIntegrations.forEach((int) => {\n if (p.creationName == int) {\n disabledRemotePlugins.push(p.name)\n }\n })\n })\n\n return (settings.remotePlugins ?? []).reduce((acc, p) => {\n if (p.settings['subscriptions']) {\n if (disabledRemotePlugins.includes(p.name)) {\n // @ts-expect-error element implicitly has an 'any' type because p.settings is a JSONObject\n p.settings['subscriptions'].forEach(\n // @ts-expect-error parameter 'sub' implicitly has an 'any' type\n (sub) => (acc[`${p.name} ${sub.partnerAction}`] = false)\n )\n }\n }\n return acc\n }, {})\n}\n\nexport function schemaFilter(\n track: TrackPlan | undefined,\n settings: CDNSettings\n): Plugin {\n function filter(ctx: Context): Context {\n const plan = track\n const ev = ctx.event.event\n\n if (plan && ev) {\n const planEvent = plan[ev]\n if (!isPlanEventEnabled(plan, planEvent)) {\n ctx.updateEvent('integrations', {\n ...ctx.event.integrations,\n All: false,\n 'Segment.io': true,\n })\n return ctx\n } else {\n const disabledActions = disabledActionDestinations(planEvent, settings)\n\n ctx.updateEvent('integrations', {\n ...ctx.event.integrations,\n ...planEvent?.integrations,\n ...disabledActions,\n })\n }\n }\n\n return ctx\n }\n\n return {\n name: 'Schema Filter',\n version: '0.1.0',\n isLoaded: () => true,\n load: () => Promise.resolve(),\n type: 'before',\n page: filter,\n alias: filter,\n track: filter,\n identify: filter,\n group: filter,\n }\n}\n", "import { CDNSettings } from '../../browser'\nimport { Context } from '../../core/context'\nimport { isServer } from '../../core/environment'\nimport { loadScript } from '../../lib/load-script'\nimport { getNextIntegrationsURL } from '../../lib/parse-cdn'\nimport { MiddlewareFunction } from '../middleware'\n\nexport async function remoteMiddlewares(\n ctx: Context,\n settings: CDNSettings,\n obfuscate?: boolean\n): Promise {\n if (isServer()) {\n return []\n }\n const path = getNextIntegrationsURL()\n const remoteMiddleware = settings.enabledMiddleware ?? {}\n const names = Object.entries(remoteMiddleware)\n .filter(([_, enabled]) => enabled)\n .map(([name]) => name)\n\n const scripts = names.map(async (name) => {\n const nonNamespaced = name.replace('@segment/', '')\n let bundleName = nonNamespaced\n if (obfuscate) {\n bundleName = btoa(nonNamespaced).replace(/=/g, '')\n }\n const fullPath = `${path}/middleware/${bundleName}/latest/${bundleName}.js.gz`\n\n try {\n await loadScript(fullPath)\n // @ts-ignore\n return window[`${nonNamespaced}Middleware`] as MiddlewareFunction\n } catch (error: any) {\n ctx.log('error', error)\n ctx.stats.increment('failed_remote_middleware')\n }\n })\n\n let middleware = await Promise.all(scripts)\n middleware = middleware.filter(Boolean)\n\n return middleware as MiddlewareFunction[]\n}\n", "/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\nmodule.exports = isArray;\n", "/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n", "var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n", "var root = require('./_root');\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n", "var Symbol = require('./_Symbol');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n", "var Symbol = require('./_Symbol'),\n getRawTag = require('./_getRawTag'),\n objectToString = require('./_objectToString');\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n", "/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n", "var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n", "var isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used to match property names within property paths. */\nvar reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/;\n\n/**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\nfunction isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n}\n\nmodule.exports = isKey;\n", "/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n", "var baseGetTag = require('./_baseGetTag'),\n isObject = require('./isObject');\n\n/** `Object#toString` result references. */\nvar asyncTag = '[object AsyncFunction]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n proxyTag = '[object Proxy]';\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\nmodule.exports = isFunction;\n", "var root = require('./_root');\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\nmodule.exports = coreJsData;\n", "var coreJsData = require('./_coreJsData');\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\nmodule.exports = isMasked;\n", "/** Used for built-in method references. */\nvar funcProto = Function.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\nmodule.exports = toSource;\n", "var isFunction = require('./isFunction'),\n isMasked = require('./_isMasked'),\n isObject = require('./isObject'),\n toSource = require('./_toSource');\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\nmodule.exports = baseIsNative;\n", "/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\nmodule.exports = getValue;\n", "var baseIsNative = require('./_baseIsNative'),\n getValue = require('./_getValue');\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\nmodule.exports = getNative;\n", "var getNative = require('./_getNative');\n\n/* Built-in method references that are verified to be native. */\nvar nativeCreate = getNative(Object, 'create');\n\nmodule.exports = nativeCreate;\n", "var nativeCreate = require('./_nativeCreate');\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\nmodule.exports = hashClear;\n", "/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = hashDelete;\n", "var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\nmodule.exports = hashGet;\n", "var nativeCreate = require('./_nativeCreate');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\nmodule.exports = hashHas;\n", "var nativeCreate = require('./_nativeCreate');\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\nmodule.exports = hashSet;\n", "var hashClear = require('./_hashClear'),\n hashDelete = require('./_hashDelete'),\n hashGet = require('./_hashGet'),\n hashHas = require('./_hashHas'),\n hashSet = require('./_hashSet');\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\nmodule.exports = Hash;\n", "/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\nmodule.exports = listCacheClear;\n", "/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\nmodule.exports = eq;\n", "var eq = require('./eq');\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\nmodule.exports = assocIndexOf;\n", "var assocIndexOf = require('./_assocIndexOf');\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype;\n\n/** Built-in value references. */\nvar splice = arrayProto.splice;\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\nmodule.exports = listCacheDelete;\n", "var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\nmodule.exports = listCacheGet;\n", "var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\nmodule.exports = listCacheHas;\n", "var assocIndexOf = require('./_assocIndexOf');\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\nmodule.exports = listCacheSet;\n", "var listCacheClear = require('./_listCacheClear'),\n listCacheDelete = require('./_listCacheDelete'),\n listCacheGet = require('./_listCacheGet'),\n listCacheHas = require('./_listCacheHas'),\n listCacheSet = require('./_listCacheSet');\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\nmodule.exports = ListCache;\n", "var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Map = getNative(root, 'Map');\n\nmodule.exports = Map;\n", "var Hash = require('./_Hash'),\n ListCache = require('./_ListCache'),\n Map = require('./_Map');\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\nmodule.exports = mapCacheClear;\n", "/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\nmodule.exports = isKeyable;\n", "var isKeyable = require('./_isKeyable');\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\nmodule.exports = getMapData;\n", "var getMapData = require('./_getMapData');\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\nmodule.exports = mapCacheDelete;\n", "var getMapData = require('./_getMapData');\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\nmodule.exports = mapCacheGet;\n", "var getMapData = require('./_getMapData');\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\nmodule.exports = mapCacheHas;\n", "var getMapData = require('./_getMapData');\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\nmodule.exports = mapCacheSet;\n", "var mapCacheClear = require('./_mapCacheClear'),\n mapCacheDelete = require('./_mapCacheDelete'),\n mapCacheGet = require('./_mapCacheGet'),\n mapCacheHas = require('./_mapCacheHas'),\n mapCacheSet = require('./_mapCacheSet');\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\nmodule.exports = MapCache;\n", "var MapCache = require('./_MapCache');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\nfunction memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n}\n\n// Expose `MapCache`.\nmemoize.Cache = MapCache;\n\nmodule.exports = memoize;\n", "var memoize = require('./memoize');\n\n/** Used as the maximum memoize cache size. */\nvar MAX_MEMOIZE_SIZE = 500;\n\n/**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\nfunction memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n}\n\nmodule.exports = memoizeCapped;\n", "var memoizeCapped = require('./_memoizeCapped');\n\n/** Used to match property names within property paths. */\nvar rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n/** Used to match backslashes in property paths. */\nvar reEscapeChar = /\\\\(\\\\)?/g;\n\n/**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\nvar stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n});\n\nmodule.exports = stringToPath;\n", "/**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n}\n\nmodule.exports = arrayMap;\n", "var Symbol = require('./_Symbol'),\n arrayMap = require('./_arrayMap'),\n isArray = require('./isArray'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n/**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = baseToString;\n", "var baseToString = require('./_baseToString');\n\n/**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\nfunction toString(value) {\n return value == null ? '' : baseToString(value);\n}\n\nmodule.exports = toString;\n", "var isArray = require('./isArray'),\n isKey = require('./_isKey'),\n stringToPath = require('./_stringToPath'),\n toString = require('./toString');\n\n/**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\nfunction castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n}\n\nmodule.exports = castPath;\n", "var isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\nfunction toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n}\n\nmodule.exports = toKey;\n", "var castPath = require('./_castPath'),\n toKey = require('./_toKey');\n\n/**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\nfunction baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n}\n\nmodule.exports = baseGet;\n", "var baseGet = require('./_baseGet');\n\n/**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\nfunction get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n}\n\nmodule.exports = get;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.has` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHas(object, key) {\n return object != null && hasOwnProperty.call(object, key);\n}\n\nmodule.exports = baseHas;\n", "var baseGetTag = require('./_baseGetTag'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]';\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\nmodule.exports = baseIsArguments;\n", "var baseIsArguments = require('./_baseIsArguments'),\n isObjectLike = require('./isObjectLike');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\nmodule.exports = isArguments;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\nmodule.exports = isIndex;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\nmodule.exports = isLength;\n", "var castPath = require('./_castPath'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isIndex = require('./_isIndex'),\n isLength = require('./isLength'),\n toKey = require('./_toKey');\n\n/**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\nfunction hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n}\n\nmodule.exports = hasPath;\n", "var baseHas = require('./_baseHas'),\n hasPath = require('./_hasPath');\n\n/**\n * Checks if `path` is a direct property of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = { 'a': { 'b': 2 } };\n * var other = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b');\n * // => true\n *\n * _.has(object, ['a', 'b']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\nfunction has(object, path) {\n return object != null && hasPath(object, path, baseHas);\n}\n\nmodule.exports = has;\n", "var ListCache = require('./_ListCache');\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\nmodule.exports = stackClear;\n", "/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\nmodule.exports = stackDelete;\n", "/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\nmodule.exports = stackGet;\n", "/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\nmodule.exports = stackHas;\n", "var ListCache = require('./_ListCache'),\n Map = require('./_Map'),\n MapCache = require('./_MapCache');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\nmodule.exports = stackSet;\n", "var ListCache = require('./_ListCache'),\n stackClear = require('./_stackClear'),\n stackDelete = require('./_stackDelete'),\n stackGet = require('./_stackGet'),\n stackHas = require('./_stackHas'),\n stackSet = require('./_stackSet');\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\nmodule.exports = Stack;\n", "var getNative = require('./_getNative');\n\nvar defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n}());\n\nmodule.exports = defineProperty;\n", "var defineProperty = require('./_defineProperty');\n\n/**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n}\n\nmodule.exports = baseAssignValue;\n", "var baseAssignValue = require('./_baseAssignValue'),\n eq = require('./eq');\n\n/**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nmodule.exports = assignMergeValue;\n", "/**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n}\n\nmodule.exports = createBaseFor;\n", "var createBaseFor = require('./_createBaseFor');\n\n/**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\nvar baseFor = createBaseFor();\n\nmodule.exports = baseFor;\n", "var root = require('./_root');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;\n\n/**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\nfunction cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n}\n\nmodule.exports = cloneBuffer;\n", "var root = require('./_root');\n\n/** Built-in value references. */\nvar Uint8Array = root.Uint8Array;\n\nmodule.exports = Uint8Array;\n", "var Uint8Array = require('./_Uint8Array');\n\n/**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\nfunction cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n}\n\nmodule.exports = cloneArrayBuffer;\n", "var cloneArrayBuffer = require('./_cloneArrayBuffer');\n\n/**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\nfunction cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n}\n\nmodule.exports = cloneTypedArray;\n", "/**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\nfunction copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n}\n\nmodule.exports = copyArray;\n", "var isObject = require('./isObject');\n\n/** Built-in value references. */\nvar objectCreate = Object.create;\n\n/**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\nvar baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n}());\n\nmodule.exports = baseCreate;\n", "/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\nmodule.exports = overArg;\n", "var overArg = require('./_overArg');\n\n/** Built-in value references. */\nvar getPrototype = overArg(Object.getPrototypeOf, Object);\n\nmodule.exports = getPrototype;\n", "/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\nmodule.exports = isPrototype;\n", "var baseCreate = require('./_baseCreate'),\n getPrototype = require('./_getPrototype'),\n isPrototype = require('./_isPrototype');\n\n/**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\nfunction initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n}\n\nmodule.exports = initCloneObject;\n", "var isFunction = require('./isFunction'),\n isLength = require('./isLength');\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\nmodule.exports = isArrayLike;\n", "var isArrayLike = require('./isArrayLike'),\n isObjectLike = require('./isObjectLike');\n\n/**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\nfunction isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n}\n\nmodule.exports = isArrayLikeObject;\n", "/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = stubFalse;\n", "var root = require('./_root'),\n stubFalse = require('./stubFalse');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined;\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\nmodule.exports = isBuffer;\n", "var baseGetTag = require('./_baseGetTag'),\n getPrototype = require('./_getPrototype'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to infer the `Object` constructor. */\nvar objectCtorString = funcToString.call(Object);\n\n/**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\nfunction isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n}\n\nmodule.exports = isPlainObject;\n", "var baseGetTag = require('./_baseGetTag'),\n isLength = require('./isLength'),\n isObjectLike = require('./isObjectLike');\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\nmodule.exports = baseIsTypedArray;\n", "/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\nmodule.exports = baseUnary;\n", "var freeGlobal = require('./_freeGlobal');\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\nmodule.exports = nodeUtil;\n", "var baseIsTypedArray = require('./_baseIsTypedArray'),\n baseUnary = require('./_baseUnary'),\n nodeUtil = require('./_nodeUtil');\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\nmodule.exports = isTypedArray;\n", "/**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n}\n\nmodule.exports = safeGet;\n", "var baseAssignValue = require('./_baseAssignValue'),\n eq = require('./eq');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\nfunction assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n}\n\nmodule.exports = assignValue;\n", "var assignValue = require('./_assignValue'),\n baseAssignValue = require('./_baseAssignValue');\n\n/**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\nfunction copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n}\n\nmodule.exports = copyObject;\n", "/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\nmodule.exports = baseTimes;\n", "var baseTimes = require('./_baseTimes'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isIndex = require('./_isIndex'),\n isTypedArray = require('./isTypedArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = arrayLikeKeys;\n", "/**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = nativeKeysIn;\n", "var isObject = require('./isObject'),\n isPrototype = require('./_isPrototype'),\n nativeKeysIn = require('./_nativeKeysIn');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeysIn;\n", "var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeysIn = require('./_baseKeysIn'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\nfunction keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n}\n\nmodule.exports = keysIn;\n", "var copyObject = require('./_copyObject'),\n keysIn = require('./keysIn');\n\n/**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\nfunction toPlainObject(value) {\n return copyObject(value, keysIn(value));\n}\n\nmodule.exports = toPlainObject;\n", "var assignMergeValue = require('./_assignMergeValue'),\n cloneBuffer = require('./_cloneBuffer'),\n cloneTypedArray = require('./_cloneTypedArray'),\n copyArray = require('./_copyArray'),\n initCloneObject = require('./_initCloneObject'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray'),\n isArrayLikeObject = require('./isArrayLikeObject'),\n isBuffer = require('./isBuffer'),\n isFunction = require('./isFunction'),\n isObject = require('./isObject'),\n isPlainObject = require('./isPlainObject'),\n isTypedArray = require('./isTypedArray'),\n safeGet = require('./_safeGet'),\n toPlainObject = require('./toPlainObject');\n\n/**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n}\n\nmodule.exports = baseMergeDeep;\n", "var Stack = require('./_Stack'),\n assignMergeValue = require('./_assignMergeValue'),\n baseFor = require('./_baseFor'),\n baseMergeDeep = require('./_baseMergeDeep'),\n isObject = require('./isObject'),\n keysIn = require('./keysIn'),\n safeGet = require('./_safeGet');\n\n/**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\nfunction baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n}\n\nmodule.exports = baseMerge;\n", "/**\n * This method returns the first argument it receives.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {*} value Any value.\n * @returns {*} Returns `value`.\n * @example\n *\n * var object = { 'a': 1 };\n *\n * console.log(_.identity(object) === object);\n * // => true\n */\nfunction identity(value) {\n return value;\n}\n\nmodule.exports = identity;\n", "/**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\nfunction apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n}\n\nmodule.exports = apply;\n", "var apply = require('./_apply');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max;\n\n/**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\nfunction overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n}\n\nmodule.exports = overRest;\n", "/**\n * Creates a function that returns `value`.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {*} value The value to return from the new function.\n * @returns {Function} Returns the new constant function.\n * @example\n *\n * var objects = _.times(2, _.constant({ 'a': 1 }));\n *\n * console.log(objects);\n * // => [{ 'a': 1 }, { 'a': 1 }]\n *\n * console.log(objects[0] === objects[1]);\n * // => true\n */\nfunction constant(value) {\n return function() {\n return value;\n };\n}\n\nmodule.exports = constant;\n", "var constant = require('./constant'),\n defineProperty = require('./_defineProperty'),\n identity = require('./identity');\n\n/**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n};\n\nmodule.exports = baseSetToString;\n", "/** Used to detect hot functions by number of calls within a span of milliseconds. */\nvar HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeNow = Date.now;\n\n/**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\nfunction shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n}\n\nmodule.exports = shortOut;\n", "var baseSetToString = require('./_baseSetToString'),\n shortOut = require('./_shortOut');\n\n/**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\nvar setToString = shortOut(baseSetToString);\n\nmodule.exports = setToString;\n", "var identity = require('./identity'),\n overRest = require('./_overRest'),\n setToString = require('./_setToString');\n\n/**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\nfunction baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n}\n\nmodule.exports = baseRest;\n", "var eq = require('./eq'),\n isArrayLike = require('./isArrayLike'),\n isIndex = require('./_isIndex'),\n isObject = require('./isObject');\n\n/**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\nfunction isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n}\n\nmodule.exports = isIterateeCall;\n", "var baseRest = require('./_baseRest'),\n isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\nfunction createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n}\n\nmodule.exports = createAssigner;\n", "var baseMerge = require('./_baseMerge'),\n createAssigner = require('./_createAssigner');\n\n/**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\nvar merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n});\n\nmodule.exports = merge;\n", "/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\nmodule.exports = setCacheAdd;\n", "/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\nmodule.exports = setCacheHas;\n", "var MapCache = require('./_MapCache'),\n setCacheAdd = require('./_setCacheAdd'),\n setCacheHas = require('./_setCacheHas');\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\nmodule.exports = SetCache;\n", "/**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = baseFindIndex;\n", "/**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\nfunction baseIsNaN(value) {\n return value !== value;\n}\n\nmodule.exports = baseIsNaN;\n", "/**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n}\n\nmodule.exports = strictIndexOf;\n", "var baseFindIndex = require('./_baseFindIndex'),\n baseIsNaN = require('./_baseIsNaN'),\n strictIndexOf = require('./_strictIndexOf');\n\n/**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n}\n\nmodule.exports = baseIndexOf;\n", "var baseIndexOf = require('./_baseIndexOf');\n\n/**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n}\n\nmodule.exports = arrayIncludes;\n", "/**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\nfunction arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n}\n\nmodule.exports = arrayIncludesWith;\n", "/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\nmodule.exports = cacheHas;\n", "var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Set = getNative(root, 'Set');\n\nmodule.exports = Set;\n", "/**\n * This method returns `undefined`.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Util\n * @example\n *\n * _.times(2, _.noop);\n * // => [undefined, undefined]\n */\nfunction noop() {\n // No operation performed.\n}\n\nmodule.exports = noop;\n", "/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\nmodule.exports = setToArray;\n", "var Set = require('./_Set'),\n noop = require('./noop'),\n setToArray = require('./_setToArray');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0;\n\n/**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\nvar createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n};\n\nmodule.exports = createSet;\n", "var SetCache = require('./_SetCache'),\n arrayIncludes = require('./_arrayIncludes'),\n arrayIncludesWith = require('./_arrayIncludesWith'),\n cacheHas = require('./_cacheHas'),\n createSet = require('./_createSet'),\n setToArray = require('./_setToArray');\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\nfunction baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n}\n\nmodule.exports = baseUniq;\n", "var baseUniq = require('./_baseUniq');\n\n/**\n * Creates a duplicate-free version of an array, using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons, in which only the first occurrence of each element\n * is kept. The order of result values is determined by the order they occur\n * in the array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniq([2, 1, 2]);\n * // => [2, 1]\n */\nfunction uniq(array) {\n return (array && array.length) ? baseUniq(array) : [];\n}\n\nmodule.exports = uniq;\n", "/**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\nfunction baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n}\n\nmodule.exports = baseSlice;\n", "var baseSlice = require('./_baseSlice');\n\n/**\n * Casts `array` to a slice if it's needed.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {number} start The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the cast slice.\n */\nfunction castSlice(array, start, end) {\n var length = array.length;\n end = end === undefined ? length : end;\n return (!start && end >= length) ? array : baseSlice(array, start, end);\n}\n\nmodule.exports = castSlice;\n", "/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsZWJ = '\\\\u200d';\n\n/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\nvar reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n/**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\nfunction hasUnicode(string) {\n return reHasUnicode.test(string);\n}\n\nmodule.exports = hasUnicode;\n", "/**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction asciiToArray(string) {\n return string.split('');\n}\n\nmodule.exports = asciiToArray;\n", "/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsVarRange = '\\\\ufe0e\\\\ufe0f';\n\n/** Used to compose unicode capture groups. */\nvar rsAstral = '[' + rsAstralRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\nvar reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n/**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction unicodeToArray(string) {\n return string.match(reUnicode) || [];\n}\n\nmodule.exports = unicodeToArray;\n", "var asciiToArray = require('./_asciiToArray'),\n hasUnicode = require('./_hasUnicode'),\n unicodeToArray = require('./_unicodeToArray');\n\n/**\n * Converts `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\nfunction stringToArray(string) {\n return hasUnicode(string)\n ? unicodeToArray(string)\n : asciiToArray(string);\n}\n\nmodule.exports = stringToArray;\n", "var castSlice = require('./_castSlice'),\n hasUnicode = require('./_hasUnicode'),\n stringToArray = require('./_stringToArray'),\n toString = require('./toString');\n\n/**\n * Creates a function like `_.lowerFirst`.\n *\n * @private\n * @param {string} methodName The name of the `String` case method to use.\n * @returns {Function} Returns the new case function.\n */\nfunction createCaseFirst(methodName) {\n return function(string) {\n string = toString(string);\n\n var strSymbols = hasUnicode(string)\n ? stringToArray(string)\n : undefined;\n\n var chr = strSymbols\n ? strSymbols[0]\n : string.charAt(0);\n\n var trailing = strSymbols\n ? castSlice(strSymbols, 1).join('')\n : string.slice(1);\n\n return chr[methodName]() + trailing;\n };\n}\n\nmodule.exports = createCaseFirst;\n", "var createCaseFirst = require('./_createCaseFirst');\n\n/**\n * Converts the first character of `string` to upper case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.upperFirst('fred');\n * // => 'Fred'\n *\n * _.upperFirst('FRED');\n * // => 'FRED'\n */\nvar upperFirst = createCaseFirst('toUpperCase');\n\nmodule.exports = upperFirst;\n", "var toString = require('./toString'),\n upperFirst = require('./upperFirst');\n\n/**\n * Converts the first character of `string` to upper case and the remaining\n * to lower case.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to capitalize.\n * @returns {string} Returns the capitalized string.\n * @example\n *\n * _.capitalize('FRED');\n * // => 'Fred'\n */\nfunction capitalize(string) {\n return upperFirst(toString(string).toLowerCase());\n}\n\nmodule.exports = capitalize;\n", "/**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\nfunction arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n}\n\nmodule.exports = arrayReduce;\n", "/**\n * The base implementation of `_.propertyOf` without support for deep paths.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyOf(object) {\n return function(key) {\n return object == null ? undefined : object[key];\n };\n}\n\nmodule.exports = basePropertyOf;\n", "var basePropertyOf = require('./_basePropertyOf');\n\n/** Used to map Latin Unicode letters to basic Latin letters. */\nvar deburredLetters = {\n // Latin-1 Supplement block.\n '\\xc0': 'A', '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n '\\xe0': 'a', '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n '\\xc7': 'C', '\\xe7': 'c',\n '\\xd0': 'D', '\\xf0': 'd',\n '\\xc8': 'E', '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n '\\xe8': 'e', '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n '\\xcc': 'I', '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n '\\xec': 'i', '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n '\\xd1': 'N', '\\xf1': 'n',\n '\\xd2': 'O', '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n '\\xf2': 'o', '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n '\\xd9': 'U', '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n '\\xf9': 'u', '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n '\\xdd': 'Y', '\\xfd': 'y', '\\xff': 'y',\n '\\xc6': 'Ae', '\\xe6': 'ae',\n '\\xde': 'Th', '\\xfe': 'th',\n '\\xdf': 'ss',\n // Latin Extended-A block.\n '\\u0100': 'A', '\\u0102': 'A', '\\u0104': 'A',\n '\\u0101': 'a', '\\u0103': 'a', '\\u0105': 'a',\n '\\u0106': 'C', '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n '\\u0107': 'c', '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n '\\u010e': 'D', '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n '\\u0112': 'E', '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n '\\u0113': 'e', '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n '\\u011c': 'G', '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n '\\u011d': 'g', '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n '\\u0124': 'H', '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n '\\u0128': 'I', '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n '\\u0129': 'i', '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n '\\u0134': 'J', '\\u0135': 'j',\n '\\u0136': 'K', '\\u0137': 'k', '\\u0138': 'k',\n '\\u0139': 'L', '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n '\\u013a': 'l', '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n '\\u0143': 'N', '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n '\\u0144': 'n', '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n '\\u014c': 'O', '\\u014e': 'O', '\\u0150': 'O',\n '\\u014d': 'o', '\\u014f': 'o', '\\u0151': 'o',\n '\\u0154': 'R', '\\u0156': 'R', '\\u0158': 'R',\n '\\u0155': 'r', '\\u0157': 'r', '\\u0159': 'r',\n '\\u015a': 'S', '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n '\\u015b': 's', '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n '\\u0162': 'T', '\\u0164': 'T', '\\u0166': 'T',\n '\\u0163': 't', '\\u0165': 't', '\\u0167': 't',\n '\\u0168': 'U', '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n '\\u0169': 'u', '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n '\\u0174': 'W', '\\u0175': 'w',\n '\\u0176': 'Y', '\\u0177': 'y', '\\u0178': 'Y',\n '\\u0179': 'Z', '\\u017b': 'Z', '\\u017d': 'Z',\n '\\u017a': 'z', '\\u017c': 'z', '\\u017e': 'z',\n '\\u0132': 'IJ', '\\u0133': 'ij',\n '\\u0152': 'Oe', '\\u0153': 'oe',\n '\\u0149': \"'n\", '\\u017f': 's'\n};\n\n/**\n * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n * letters to basic Latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\nvar deburrLetter = basePropertyOf(deburredLetters);\n\nmodule.exports = deburrLetter;\n", "var deburrLetter = require('./_deburrLetter'),\n toString = require('./toString');\n\n/** Used to match Latin Unicode letters (excluding mathematical operators). */\nvar reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n/** Used to compose unicode character classes. */\nvar rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange;\n\n/** Used to compose unicode capture groups. */\nvar rsCombo = '[' + rsComboRange + ']';\n\n/**\n * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n */\nvar reComboMark = RegExp(rsCombo, 'g');\n\n/**\n * Deburrs `string` by converting\n * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n * letters to basic Latin letters and removing\n * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('d\u00E9j\u00E0 vu');\n * // => 'deja vu'\n */\nfunction deburr(string) {\n string = toString(string);\n return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n}\n\nmodule.exports = deburr;\n", "/** Used to match words composed of alphanumeric characters. */\nvar reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n/**\n * Splits an ASCII `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\nfunction asciiWords(string) {\n return string.match(reAsciiWord) || [];\n}\n\nmodule.exports = asciiWords;\n", "/** Used to detect strings that need a more robust regexp to match words. */\nvar reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n/**\n * Checks if `string` contains a word composed of Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a word is found, else `false`.\n */\nfunction hasUnicodeWord(string) {\n return reHasUnicodeWord.test(string);\n}\n\nmodule.exports = hasUnicodeWord;\n", "/** Used to compose unicode character classes. */\nvar rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsDingbatRange = '\\\\u2700-\\\\u27bf',\n rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n rsPunctuationRange = '\\\\u2000-\\\\u206f',\n rsSpaceRange = ' \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000',\n rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n rsVarRange = '\\\\ufe0e\\\\ufe0f',\n rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n/** Used to compose unicode capture groups. */\nvar rsApos = \"['\\u2019]\",\n rsBreak = '[' + rsBreakRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsDigits = '\\\\d+',\n rsDingbat = '[' + rsDingbatRange + ']',\n rsLower = '[' + rsLowerRange + ']',\n rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsUpper = '[' + rsUpperRange + ']',\n rsZWJ = '\\\\u200d';\n\n/** Used to compose unicode regexes. */\nvar rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq;\n\n/** Used to match complex or compound words. */\nvar reUnicodeWord = RegExp([\n rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n rsUpper + '+' + rsOptContrUpper,\n rsOrdUpper,\n rsOrdLower,\n rsDigits,\n rsEmoji\n].join('|'), 'g');\n\n/**\n * Splits a Unicode `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\nfunction unicodeWords(string) {\n return string.match(reUnicodeWord) || [];\n}\n\nmodule.exports = unicodeWords;\n", "var asciiWords = require('./_asciiWords'),\n hasUnicodeWord = require('./_hasUnicodeWord'),\n toString = require('./toString'),\n unicodeWords = require('./_unicodeWords');\n\n/**\n * Splits `string` into an array of its words.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {RegExp|string} [pattern] The pattern to match words.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the words of `string`.\n * @example\n *\n * _.words('fred, barney, & pebbles');\n * // => ['fred', 'barney', 'pebbles']\n *\n * _.words('fred, barney, & pebbles', /[^, ]+/g);\n * // => ['fred', 'barney', '&', 'pebbles']\n */\nfunction words(string, pattern, guard) {\n string = toString(string);\n pattern = guard ? undefined : pattern;\n\n if (pattern === undefined) {\n return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);\n }\n return string.match(pattern) || [];\n}\n\nmodule.exports = words;\n", "var arrayReduce = require('./_arrayReduce'),\n deburr = require('./deburr'),\n words = require('./words');\n\n/** Used to compose unicode capture groups. */\nvar rsApos = \"['\\u2019]\";\n\n/** Used to match apostrophes. */\nvar reApos = RegExp(rsApos, 'g');\n\n/**\n * Creates a function like `_.camelCase`.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\nfunction createCompounder(callback) {\n return function(string) {\n return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n };\n}\n\nmodule.exports = createCompounder;\n", "var capitalize = require('./capitalize'),\n createCompounder = require('./_createCompounder');\n\n/**\n * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the camel cased string.\n * @example\n *\n * _.camelCase('Foo Bar');\n * // => 'fooBar'\n *\n * _.camelCase('--foo-bar--');\n * // => 'fooBar'\n *\n * _.camelCase('__FOO_BAR__');\n * // => 'fooBar'\n */\nvar camelCase = createCompounder(function(result, word, index) {\n word = word.toLowerCase();\n return result + (index ? capitalize(word) : word);\n});\n\nmodule.exports = camelCase;\n", "/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeFloor = Math.floor;\n\n/**\n * The base implementation of `_.repeat` which doesn't coerce arguments.\n *\n * @private\n * @param {string} string The string to repeat.\n * @param {number} n The number of times to repeat the string.\n * @returns {string} Returns the repeated string.\n */\nfunction baseRepeat(string, n) {\n var result = '';\n if (!string || n < 1 || n > MAX_SAFE_INTEGER) {\n return result;\n }\n // Leverage the exponentiation by squaring algorithm for a faster repeat.\n // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.\n do {\n if (n % 2) {\n result += string;\n }\n n = nativeFloor(n / 2);\n if (n) {\n string += string;\n }\n } while (n);\n\n return result;\n}\n\nmodule.exports = baseRepeat;\n", "/** Used to match a single whitespace character. */\nvar reWhitespace = /\\s/;\n\n/**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\nfunction trimmedEndIndex(string) {\n var index = string.length;\n\n while (index-- && reWhitespace.test(string.charAt(index))) {}\n return index;\n}\n\nmodule.exports = trimmedEndIndex;\n", "var trimmedEndIndex = require('./_trimmedEndIndex');\n\n/** Used to match leading whitespace. */\nvar reTrimStart = /^\\s+/;\n\n/**\n * The base implementation of `_.trim`.\n *\n * @private\n * @param {string} string The string to trim.\n * @returns {string} Returns the trimmed string.\n */\nfunction baseTrim(string) {\n return string\n ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')\n : string;\n}\n\nmodule.exports = baseTrim;\n", "var baseTrim = require('./_baseTrim'),\n isObject = require('./isObject'),\n isSymbol = require('./isSymbol');\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = baseTrim(value);\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = toNumber;\n", "var toNumber = require('./toNumber');\n\n/** Used as references for various `Number` constants. */\nvar INFINITY = 1 / 0,\n MAX_INTEGER = 1.7976931348623157e+308;\n\n/**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\nfunction toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n}\n\nmodule.exports = toFinite;\n", "var toFinite = require('./toFinite');\n\n/**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\nfunction toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n}\n\nmodule.exports = toInteger;\n", "var baseRepeat = require('./_baseRepeat'),\n isIterateeCall = require('./_isIterateeCall'),\n toInteger = require('./toInteger'),\n toString = require('./toString');\n\n/**\n * Repeats the given string `n` times.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to repeat.\n * @param {number} [n=1] The number of times to repeat the string.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {string} Returns the repeated string.\n * @example\n *\n * _.repeat('*', 3);\n * // => '***'\n *\n * _.repeat('abc', 2);\n * // => 'abcabc'\n *\n * _.repeat('abc', 0);\n * // => ''\n */\nfunction repeat(string, n, guard) {\n if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n return baseRepeat(toString(string), n);\n}\n\nmodule.exports = repeat;\n", "/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\nmodule.exports = arrayPush;\n", "var Symbol = require('./_Symbol'),\n isArguments = require('./isArguments'),\n isArray = require('./isArray');\n\n/** Built-in value references. */\nvar spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;\n\n/**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\nfunction isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n}\n\nmodule.exports = isFlattenable;\n", "var arrayPush = require('./_arrayPush'),\n isFlattenable = require('./_isFlattenable');\n\n/**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\nfunction baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n}\n\nmodule.exports = baseFlatten;\n", "/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\nmodule.exports = arraySome;\n", "var SetCache = require('./_SetCache'),\n arraySome = require('./_arraySome'),\n cacheHas = require('./_cacheHas');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\nmodule.exports = equalArrays;\n", "/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\nmodule.exports = mapToArray;\n", "var Symbol = require('./_Symbol'),\n Uint8Array = require('./_Uint8Array'),\n eq = require('./eq'),\n equalArrays = require('./_equalArrays'),\n mapToArray = require('./_mapToArray'),\n setToArray = require('./_setToArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** `Object#toString` result references. */\nvar boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]';\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\nmodule.exports = equalByTag;\n", "var arrayPush = require('./_arrayPush'),\n isArray = require('./isArray');\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\nmodule.exports = baseGetAllKeys;\n", "/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\nmodule.exports = arrayFilter;\n", "/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\nmodule.exports = stubArray;\n", "var arrayFilter = require('./_arrayFilter'),\n stubArray = require('./stubArray');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Built-in value references. */\nvar propertyIsEnumerable = objectProto.propertyIsEnumerable;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols;\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\nmodule.exports = getSymbols;\n", "var overArg = require('./_overArg');\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeKeys = overArg(Object.keys, Object);\n\nmodule.exports = nativeKeys;\n", "var isPrototype = require('./_isPrototype'),\n nativeKeys = require('./_nativeKeys');\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\nmodule.exports = baseKeys;\n", "var arrayLikeKeys = require('./_arrayLikeKeys'),\n baseKeys = require('./_baseKeys'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\nmodule.exports = keys;\n", "var baseGetAllKeys = require('./_baseGetAllKeys'),\n getSymbols = require('./_getSymbols'),\n keys = require('./keys');\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\nmodule.exports = getAllKeys;\n", "var getAllKeys = require('./_getAllKeys');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\nmodule.exports = equalObjects;\n", "var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView');\n\nmodule.exports = DataView;\n", "var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar Promise = getNative(root, 'Promise');\n\nmodule.exports = Promise;\n", "var getNative = require('./_getNative'),\n root = require('./_root');\n\n/* Built-in method references that are verified to be native. */\nvar WeakMap = getNative(root, 'WeakMap');\n\nmodule.exports = WeakMap;\n", "var DataView = require('./_DataView'),\n Map = require('./_Map'),\n Promise = require('./_Promise'),\n Set = require('./_Set'),\n WeakMap = require('./_WeakMap'),\n baseGetTag = require('./_baseGetTag'),\n toSource = require('./_toSource');\n\n/** `Object#toString` result references. */\nvar mapTag = '[object Map]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n setTag = '[object Set]',\n weakMapTag = '[object WeakMap]';\n\nvar dataViewTag = '[object DataView]';\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\nmodule.exports = getTag;\n", "var Stack = require('./_Stack'),\n equalArrays = require('./_equalArrays'),\n equalByTag = require('./_equalByTag'),\n equalObjects = require('./_equalObjects'),\n getTag = require('./_getTag'),\n isArray = require('./isArray'),\n isBuffer = require('./isBuffer'),\n isTypedArray = require('./isTypedArray');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n objectTag = '[object Object]';\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\nmodule.exports = baseIsEqualDeep;\n", "var baseIsEqualDeep = require('./_baseIsEqualDeep'),\n isObjectLike = require('./isObjectLike');\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\nmodule.exports = baseIsEqual;\n", "var Stack = require('./_Stack'),\n baseIsEqual = require('./_baseIsEqual');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\nfunction baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n}\n\nmodule.exports = baseIsMatch;\n", "var isObject = require('./isObject');\n\n/**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\nfunction isStrictComparable(value) {\n return value === value && !isObject(value);\n}\n\nmodule.exports = isStrictComparable;\n", "var isStrictComparable = require('./_isStrictComparable'),\n keys = require('./keys');\n\n/**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\nfunction getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n}\n\nmodule.exports = getMatchData;\n", "/**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n}\n\nmodule.exports = matchesStrictComparable;\n", "var baseIsMatch = require('./_baseIsMatch'),\n getMatchData = require('./_getMatchData'),\n matchesStrictComparable = require('./_matchesStrictComparable');\n\n/**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n}\n\nmodule.exports = baseMatches;\n", "/**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\nfunction baseHasIn(object, key) {\n return object != null && key in Object(object);\n}\n\nmodule.exports = baseHasIn;\n", "var baseHasIn = require('./_baseHasIn'),\n hasPath = require('./_hasPath');\n\n/**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\nfunction hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n}\n\nmodule.exports = hasIn;\n", "var baseIsEqual = require('./_baseIsEqual'),\n get = require('./get'),\n hasIn = require('./hasIn'),\n isKey = require('./_isKey'),\n isStrictComparable = require('./_isStrictComparable'),\n matchesStrictComparable = require('./_matchesStrictComparable'),\n toKey = require('./_toKey');\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\nfunction baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n}\n\nmodule.exports = baseMatchesProperty;\n", "/**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n}\n\nmodule.exports = baseProperty;\n", "var baseGet = require('./_baseGet');\n\n/**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\nfunction basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n}\n\nmodule.exports = basePropertyDeep;\n", "var baseProperty = require('./_baseProperty'),\n basePropertyDeep = require('./_basePropertyDeep'),\n isKey = require('./_isKey'),\n toKey = require('./_toKey');\n\n/**\n * Creates a function that returns the value at `path` of a given object.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Util\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n * @example\n *\n * var objects = [\n * { 'a': { 'b': 2 } },\n * { 'a': { 'b': 1 } }\n * ];\n *\n * _.map(objects, _.property('a.b'));\n * // => [2, 1]\n *\n * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');\n * // => [1, 2]\n */\nfunction property(path) {\n return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);\n}\n\nmodule.exports = property;\n", "var baseMatches = require('./_baseMatches'),\n baseMatchesProperty = require('./_baseMatchesProperty'),\n identity = require('./identity'),\n isArray = require('./isArray'),\n property = require('./property');\n\n/**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\nfunction baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n}\n\nmodule.exports = baseIteratee;\n", "var baseFor = require('./_baseFor'),\n keys = require('./keys');\n\n/**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\nfunction baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n}\n\nmodule.exports = baseForOwn;\n", "var isArrayLike = require('./isArrayLike');\n\n/**\n * Creates a `baseEach` or `baseEachRight` function.\n *\n * @private\n * @param {Function} eachFunc The function to iterate over a collection.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\nfunction createBaseEach(eachFunc, fromRight) {\n return function(collection, iteratee) {\n if (collection == null) {\n return collection;\n }\n if (!isArrayLike(collection)) {\n return eachFunc(collection, iteratee);\n }\n var length = collection.length,\n index = fromRight ? length : -1,\n iterable = Object(collection);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (iteratee(iterable[index], index, iterable) === false) {\n break;\n }\n }\n return collection;\n };\n}\n\nmodule.exports = createBaseEach;\n", "var baseForOwn = require('./_baseForOwn'),\n createBaseEach = require('./_createBaseEach');\n\n/**\n * The base implementation of `_.forEach` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\nvar baseEach = createBaseEach(baseForOwn);\n\nmodule.exports = baseEach;\n", "var baseEach = require('./_baseEach'),\n isArrayLike = require('./isArrayLike');\n\n/**\n * The base implementation of `_.map` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\nfunction baseMap(collection, iteratee) {\n var index = -1,\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value, key, collection) {\n result[++index] = iteratee(value, key, collection);\n });\n return result;\n}\n\nmodule.exports = baseMap;\n", "/**\n * The base implementation of `_.sortBy` which uses `comparer` to define the\n * sort order of `array` and replaces criteria objects with their corresponding\n * values.\n *\n * @private\n * @param {Array} array The array to sort.\n * @param {Function} comparer The function to define sort order.\n * @returns {Array} Returns `array`.\n */\nfunction baseSortBy(array, comparer) {\n var length = array.length;\n\n array.sort(comparer);\n while (length--) {\n array[length] = array[length].value;\n }\n return array;\n}\n\nmodule.exports = baseSortBy;\n", "var isSymbol = require('./isSymbol');\n\n/**\n * Compares values to sort them in ascending order.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {number} Returns the sort order indicator for `value`.\n */\nfunction compareAscending(value, other) {\n if (value !== other) {\n var valIsDefined = value !== undefined,\n valIsNull = value === null,\n valIsReflexive = value === value,\n valIsSymbol = isSymbol(value);\n\n var othIsDefined = other !== undefined,\n othIsNull = other === null,\n othIsReflexive = other === other,\n othIsSymbol = isSymbol(other);\n\n if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||\n (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||\n (valIsNull && othIsDefined && othIsReflexive) ||\n (!valIsDefined && othIsReflexive) ||\n !valIsReflexive) {\n return 1;\n }\n if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||\n (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||\n (othIsNull && valIsDefined && valIsReflexive) ||\n (!othIsDefined && valIsReflexive) ||\n !othIsReflexive) {\n return -1;\n }\n }\n return 0;\n}\n\nmodule.exports = compareAscending;\n", "var compareAscending = require('./_compareAscending');\n\n/**\n * Used by `_.orderBy` to compare multiple properties of a value to another\n * and stable sort them.\n *\n * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,\n * specify an order of \"desc\" for descending or \"asc\" for ascending sort order\n * of corresponding values.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {boolean[]|string[]} orders The order to sort by for each property.\n * @returns {number} Returns the sort order indicator for `object`.\n */\nfunction compareMultiple(object, other, orders) {\n var index = -1,\n objCriteria = object.criteria,\n othCriteria = other.criteria,\n length = objCriteria.length,\n ordersLength = orders.length;\n\n while (++index < length) {\n var result = compareAscending(objCriteria[index], othCriteria[index]);\n if (result) {\n if (index >= ordersLength) {\n return result;\n }\n var order = orders[index];\n return result * (order == 'desc' ? -1 : 1);\n }\n }\n // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications\n // that causes it, under certain circumstances, to provide the same value for\n // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247\n // for more details.\n //\n // This also ensures a stable sort in V8 and other engines.\n // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.\n return object.index - other.index;\n}\n\nmodule.exports = compareMultiple;\n", "var arrayMap = require('./_arrayMap'),\n baseGet = require('./_baseGet'),\n baseIteratee = require('./_baseIteratee'),\n baseMap = require('./_baseMap'),\n baseSortBy = require('./_baseSortBy'),\n baseUnary = require('./_baseUnary'),\n compareMultiple = require('./_compareMultiple'),\n identity = require('./identity'),\n isArray = require('./isArray');\n\n/**\n * The base implementation of `_.orderBy` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.\n * @param {string[]} orders The sort orders of `iteratees`.\n * @returns {Array} Returns the new sorted array.\n */\nfunction baseOrderBy(collection, iteratees, orders) {\n if (iteratees.length) {\n iteratees = arrayMap(iteratees, function(iteratee) {\n if (isArray(iteratee)) {\n return function(value) {\n return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);\n }\n }\n return iteratee;\n });\n } else {\n iteratees = [identity];\n }\n\n var index = -1;\n iteratees = arrayMap(iteratees, baseUnary(baseIteratee));\n\n var result = baseMap(collection, function(value, key, collection) {\n var criteria = arrayMap(iteratees, function(iteratee) {\n return iteratee(value);\n });\n return { 'criteria': criteria, 'index': ++index, 'value': value };\n });\n\n return baseSortBy(result, function(object, other) {\n return compareMultiple(object, other, orders);\n });\n}\n\nmodule.exports = baseOrderBy;\n", "var baseFlatten = require('./_baseFlatten'),\n baseOrderBy = require('./_baseOrderBy'),\n baseRest = require('./_baseRest'),\n isIterateeCall = require('./_isIterateeCall');\n\n/**\n * Creates an array of elements, sorted in ascending order by the results of\n * running each element in a collection thru each iteratee. This method\n * performs a stable sort, that is, it preserves the original sort order of\n * equal elements. The iteratees are invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {...(Function|Function[])} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 30 },\n * { 'user': 'barney', 'age': 34 }\n * ];\n *\n * _.sortBy(users, [function(o) { return o.user; }]);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]\n *\n * _.sortBy(users, ['user', 'age']);\n * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]\n */\nvar sortBy = baseRest(function(collection, iteratees) {\n if (collection == null) {\n return [];\n }\n var length = iteratees.length;\n if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {\n iteratees = [];\n } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {\n iteratees = [iteratees[0]];\n }\n return baseOrderBy(collection, baseFlatten(iteratees, 1), []);\n});\n\nmodule.exports = sortBy;\n", "/**\n * This base implementation of `_.zipObject` which assigns values using `assignFunc`.\n *\n * @private\n * @param {Array} props The property identifiers.\n * @param {Array} values The property values.\n * @param {Function} assignFunc The function to assign values.\n * @returns {Object} Returns the new object.\n */\nfunction baseZipObject(props, values, assignFunc) {\n var index = -1,\n length = props.length,\n valsLength = values.length,\n result = {};\n\n while (++index < length) {\n var value = index < valsLength ? values[index] : undefined;\n assignFunc(result, props[index], value);\n }\n return result;\n}\n\nmodule.exports = baseZipObject;\n", "var assignValue = require('./_assignValue'),\n baseZipObject = require('./_baseZipObject');\n\n/**\n * This method is like `_.fromPairs` except that it accepts two arrays,\n * one of property identifiers and one of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 0.4.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObject(['a', 'b'], [1, 2]);\n * // => { 'a': 1, 'b': 2 }\n */\nfunction zipObject(props, values) {\n return baseZipObject(props || [], values || [], assignValue);\n}\n\nmodule.exports = zipObject;\n", "/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeCeil = Math.ceil,\n nativeMax = Math.max;\n\n/**\n * The base implementation of `_.range` and `_.rangeRight` which doesn't\n * coerce arguments.\n *\n * @private\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @param {number} step The value to increment or decrement by.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the range of numbers.\n */\nfunction baseRange(start, end, step, fromRight) {\n var index = -1,\n length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),\n result = Array(length);\n\n while (length--) {\n result[fromRight ? length : ++index] = start;\n start += step;\n }\n return result;\n}\n\nmodule.exports = baseRange;\n", "var baseRange = require('./_baseRange'),\n isIterateeCall = require('./_isIterateeCall'),\n toFinite = require('./toFinite');\n\n/**\n * Creates a `_.range` or `_.rangeRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new range function.\n */\nfunction createRange(fromRight) {\n return function(start, end, step) {\n if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {\n end = step = undefined;\n }\n // Ensure the sign of `-0` is preserved.\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);\n return baseRange(start, end, step, fromRight);\n };\n}\n\nmodule.exports = createRange;\n", "var createRange = require('./_createRange');\n\n/**\n * Creates an array of numbers (positive and/or negative) progressing from\n * `start` up to, but not including, `end`. A step of `-1` is used if a negative\n * `start` is specified without an `end` or `step`. If `end` is not specified,\n * it's set to `start` with `start` then set to `0`.\n *\n * **Note:** JavaScript follows the IEEE-754 standard for resolving\n * floating-point values which can produce unexpected results.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Util\n * @param {number} [start=0] The start of the range.\n * @param {number} end The end of the range.\n * @param {number} [step=1] The value to increment or decrement by.\n * @returns {Array} Returns the range of numbers.\n * @see _.inRange, _.rangeRight\n * @example\n *\n * _.range(4);\n * // => [0, 1, 2, 3]\n *\n * _.range(-4);\n * // => [0, -1, -2, -3]\n *\n * _.range(1, 5);\n * // => [1, 2, 3, 4]\n *\n * _.range(0, 20, 5);\n * // => [0, 5, 10, 15]\n *\n * _.range(0, -4, -1);\n * // => [0, -1, -2, -3]\n *\n * _.range(1, 4, 0);\n * // => [1, 1, 1]\n *\n * _.range(0);\n * // => []\n */\nvar range = createRange();\n\nmodule.exports = range;\n", "/*!\n * clipboard.js v2.0.11\n * https://clipboardjs.com/\n *\n * Licensed MIT \u00A9 Zeno Rocha\n */\n(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"ClipboardJS\"] = factory();\n\telse\n\t\troot[\"ClipboardJS\"] = factory();\n})(this, function() {\nreturn /******/ (function() { // webpackBootstrap\n/******/ \tvar __webpack_modules__ = ({\n\n/***/ 686:\n/***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {\n\n\"use strict\";\n\n// EXPORTS\n__webpack_require__.d(__webpack_exports__, {\n \"default\": function() { return /* binding */ clipboard; }\n});\n\n// EXTERNAL MODULE: ./node_modules/tiny-emitter/index.js\nvar tiny_emitter = __webpack_require__(279);\nvar tiny_emitter_default = /*#__PURE__*/__webpack_require__.n(tiny_emitter);\n// EXTERNAL MODULE: ./node_modules/good-listener/src/listen.js\nvar listen = __webpack_require__(370);\nvar listen_default = /*#__PURE__*/__webpack_require__.n(listen);\n// EXTERNAL MODULE: ./node_modules/select/src/select.js\nvar src_select = __webpack_require__(817);\nvar select_default = /*#__PURE__*/__webpack_require__.n(src_select);\n;// CONCATENATED MODULE: ./src/common/command.js\n/**\n * Executes a given operation type.\n * @param {String} type\n * @return {Boolean}\n */\nfunction command(type) {\n try {\n return document.execCommand(type);\n } catch (err) {\n return false;\n }\n}\n;// CONCATENATED MODULE: ./src/actions/cut.js\n\n\n/**\n * Cut action wrapper.\n * @param {String|HTMLElement} target\n * @return {String}\n */\n\nvar ClipboardActionCut = function ClipboardActionCut(target) {\n var selectedText = select_default()(target);\n command('cut');\n return selectedText;\n};\n\n/* harmony default export */ var actions_cut = (ClipboardActionCut);\n;// CONCATENATED MODULE: ./src/common/create-fake-element.js\n/**\n * Creates a fake textarea element with a value.\n * @param {String} value\n * @return {HTMLElement}\n */\nfunction createFakeElement(value) {\n var isRTL = document.documentElement.getAttribute('dir') === 'rtl';\n var fakeElement = document.createElement('textarea'); // Prevent zooming on iOS\n\n fakeElement.style.fontSize = '12pt'; // Reset box model\n\n fakeElement.style.border = '0';\n fakeElement.style.padding = '0';\n fakeElement.style.margin = '0'; // Move element out of screen horizontally\n\n fakeElement.style.position = 'absolute';\n fakeElement.style[isRTL ? 'right' : 'left'] = '-9999px'; // Move element to the same position vertically\n\n var yPosition = window.pageYOffset || document.documentElement.scrollTop;\n fakeElement.style.top = \"\".concat(yPosition, \"px\");\n fakeElement.setAttribute('readonly', '');\n fakeElement.value = value;\n return fakeElement;\n}\n;// CONCATENATED MODULE: ./src/actions/copy.js\n\n\n\n/**\n * Create fake copy action wrapper using a fake element.\n * @param {String} target\n * @param {Object} options\n * @return {String}\n */\n\nvar fakeCopyAction = function fakeCopyAction(value, options) {\n var fakeElement = createFakeElement(value);\n options.container.appendChild(fakeElement);\n var selectedText = select_default()(fakeElement);\n command('copy');\n fakeElement.remove();\n return selectedText;\n};\n/**\n * Copy action wrapper.\n * @param {String|HTMLElement} target\n * @param {Object} options\n * @return {String}\n */\n\n\nvar ClipboardActionCopy = function ClipboardActionCopy(target) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n container: document.body\n };\n var selectedText = '';\n\n if (typeof target === 'string') {\n selectedText = fakeCopyAction(target, options);\n } else if (target instanceof HTMLInputElement && !['text', 'search', 'url', 'tel', 'password'].includes(target === null || target === void 0 ? void 0 : target.type)) {\n // If input type doesn't support `setSelectionRange`. Simulate it. https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange\n selectedText = fakeCopyAction(target.value, options);\n } else {\n selectedText = select_default()(target);\n command('copy');\n }\n\n return selectedText;\n};\n\n/* harmony default export */ var actions_copy = (ClipboardActionCopy);\n;// CONCATENATED MODULE: ./src/actions/default.js\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n\n\n/**\n * Inner function which performs selection from either `text` or `target`\n * properties and then executes copy or cut operations.\n * @param {Object} options\n */\n\nvar ClipboardActionDefault = function ClipboardActionDefault() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n // Defines base properties passed from constructor.\n var _options$action = options.action,\n action = _options$action === void 0 ? 'copy' : _options$action,\n container = options.container,\n target = options.target,\n text = options.text; // Sets the `action` to be performed which can be either 'copy' or 'cut'.\n\n if (action !== 'copy' && action !== 'cut') {\n throw new Error('Invalid \"action\" value, use either \"copy\" or \"cut\"');\n } // Sets the `target` property using an element that will be have its content copied.\n\n\n if (target !== undefined) {\n if (target && _typeof(target) === 'object' && target.nodeType === 1) {\n if (action === 'copy' && target.hasAttribute('disabled')) {\n throw new Error('Invalid \"target\" attribute. Please use \"readonly\" instead of \"disabled\" attribute');\n }\n\n if (action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) {\n throw new Error('Invalid \"target\" attribute. You can\\'t cut text from elements with \"readonly\" or \"disabled\" attributes');\n }\n } else {\n throw new Error('Invalid \"target\" value, use a valid Element');\n }\n } // Define selection strategy based on `text` property.\n\n\n if (text) {\n return actions_copy(text, {\n container: container\n });\n } // Defines which selection strategy based on `target` property.\n\n\n if (target) {\n return action === 'cut' ? actions_cut(target) : actions_copy(target, {\n container: container\n });\n }\n};\n\n/* harmony default export */ var actions_default = (ClipboardActionDefault);\n;// CONCATENATED MODULE: ./src/clipboard.js\nfunction clipboard_typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { clipboard_typeof = function _typeof(obj) { return typeof obj; }; } else { clipboard_typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return clipboard_typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (clipboard_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\n\n\n\n\n\n/**\n * Helper function to retrieve attribute value.\n * @param {String} suffix\n * @param {Element} element\n */\n\nfunction getAttributeValue(suffix, element) {\n var attribute = \"data-clipboard-\".concat(suffix);\n\n if (!element.hasAttribute(attribute)) {\n return;\n }\n\n return element.getAttribute(attribute);\n}\n/**\n * Base class which takes one or more elements, adds event listeners to them,\n * and instantiates a new `ClipboardAction` on each click.\n */\n\n\nvar Clipboard = /*#__PURE__*/function (_Emitter) {\n _inherits(Clipboard, _Emitter);\n\n var _super = _createSuper(Clipboard);\n\n /**\n * @param {String|HTMLElement|HTMLCollection|NodeList} trigger\n * @param {Object} options\n */\n function Clipboard(trigger, options) {\n var _this;\n\n _classCallCheck(this, Clipboard);\n\n _this = _super.call(this);\n\n _this.resolveOptions(options);\n\n _this.listenClick(trigger);\n\n return _this;\n }\n /**\n * Defines if attributes would be resolved using internal setter functions\n * or custom functions that were passed in the constructor.\n * @param {Object} options\n */\n\n\n _createClass(Clipboard, [{\n key: \"resolveOptions\",\n value: function resolveOptions() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n this.action = typeof options.action === 'function' ? options.action : this.defaultAction;\n this.target = typeof options.target === 'function' ? options.target : this.defaultTarget;\n this.text = typeof options.text === 'function' ? options.text : this.defaultText;\n this.container = clipboard_typeof(options.container) === 'object' ? options.container : document.body;\n }\n /**\n * Adds a click event listener to the passed trigger.\n * @param {String|HTMLElement|HTMLCollection|NodeList} trigger\n */\n\n }, {\n key: \"listenClick\",\n value: function listenClick(trigger) {\n var _this2 = this;\n\n this.listener = listen_default()(trigger, 'click', function (e) {\n return _this2.onClick(e);\n });\n }\n /**\n * Defines a new `ClipboardAction` on each click event.\n * @param {Event} e\n */\n\n }, {\n key: \"onClick\",\n value: function onClick(e) {\n var trigger = e.delegateTarget || e.currentTarget;\n var action = this.action(trigger) || 'copy';\n var text = actions_default({\n action: action,\n container: this.container,\n target: this.target(trigger),\n text: this.text(trigger)\n }); // Fires an event based on the copy operation result.\n\n this.emit(text ? 'success' : 'error', {\n action: action,\n text: text,\n trigger: trigger,\n clearSelection: function clearSelection() {\n if (trigger) {\n trigger.focus();\n }\n\n window.getSelection().removeAllRanges();\n }\n });\n }\n /**\n * Default `action` lookup function.\n * @param {Element} trigger\n */\n\n }, {\n key: \"defaultAction\",\n value: function defaultAction(trigger) {\n return getAttributeValue('action', trigger);\n }\n /**\n * Default `target` lookup function.\n * @param {Element} trigger\n */\n\n }, {\n key: \"defaultTarget\",\n value: function defaultTarget(trigger) {\n var selector = getAttributeValue('target', trigger);\n\n if (selector) {\n return document.querySelector(selector);\n }\n }\n /**\n * Allow fire programmatically a copy action\n * @param {String|HTMLElement} target\n * @param {Object} options\n * @returns Text copied.\n */\n\n }, {\n key: \"defaultText\",\n\n /**\n * Default `text` lookup function.\n * @param {Element} trigger\n */\n value: function defaultText(trigger) {\n return getAttributeValue('text', trigger);\n }\n /**\n * Destroy lifecycle.\n */\n\n }, {\n key: \"destroy\",\n value: function destroy() {\n this.listener.destroy();\n }\n }], [{\n key: \"copy\",\n value: function copy(target) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {\n container: document.body\n };\n return actions_copy(target, options);\n }\n /**\n * Allow fire programmatically a cut action\n * @param {String|HTMLElement} target\n * @returns Text cutted.\n */\n\n }, {\n key: \"cut\",\n value: function cut(target) {\n return actions_cut(target);\n }\n /**\n * Returns the support of the given action, or all actions if no action is\n * given.\n * @param {String} [action]\n */\n\n }, {\n key: \"isSupported\",\n value: function isSupported() {\n var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['copy', 'cut'];\n var actions = typeof action === 'string' ? [action] : action;\n var support = !!document.queryCommandSupported;\n actions.forEach(function (action) {\n support = support && !!document.queryCommandSupported(action);\n });\n return support;\n }\n }]);\n\n return Clipboard;\n}((tiny_emitter_default()));\n\n/* harmony default export */ var clipboard = (Clipboard);\n\n/***/ }),\n\n/***/ 828:\n/***/ (function(module) {\n\nvar DOCUMENT_NODE_TYPE = 9;\n\n/**\n * A polyfill for Element.matches()\n */\nif (typeof Element !== 'undefined' && !Element.prototype.matches) {\n var proto = Element.prototype;\n\n proto.matches = proto.matchesSelector ||\n proto.mozMatchesSelector ||\n proto.msMatchesSelector ||\n proto.oMatchesSelector ||\n proto.webkitMatchesSelector;\n}\n\n/**\n * Finds the closest parent that matches a selector.\n *\n * @param {Element} element\n * @param {String} selector\n * @return {Function}\n */\nfunction closest (element, selector) {\n while (element && element.nodeType !== DOCUMENT_NODE_TYPE) {\n if (typeof element.matches === 'function' &&\n element.matches(selector)) {\n return element;\n }\n element = element.parentNode;\n }\n}\n\nmodule.exports = closest;\n\n\n/***/ }),\n\n/***/ 438:\n/***/ (function(module, __unused_webpack_exports, __webpack_require__) {\n\nvar closest = __webpack_require__(828);\n\n/**\n * Delegates event to a selector.\n *\n * @param {Element} element\n * @param {String} selector\n * @param {String} type\n * @param {Function} callback\n * @param {Boolean} useCapture\n * @return {Object}\n */\nfunction _delegate(element, selector, type, callback, useCapture) {\n var listenerFn = listener.apply(this, arguments);\n\n element.addEventListener(type, listenerFn, useCapture);\n\n return {\n destroy: function() {\n element.removeEventListener(type, listenerFn, useCapture);\n }\n }\n}\n\n/**\n * Delegates event to a selector.\n *\n * @param {Element|String|Array} [elements]\n * @param {String} selector\n * @param {String} type\n * @param {Function} callback\n * @param {Boolean} useCapture\n * @return {Object}\n */\nfunction delegate(elements, selector, type, callback, useCapture) {\n // Handle the regular Element usage\n if (typeof elements.addEventListener === 'function') {\n return _delegate.apply(null, arguments);\n }\n\n // Handle Element-less usage, it defaults to global delegation\n if (typeof type === 'function') {\n // Use `document` as the first parameter, then apply arguments\n // This is a short way to .unshift `arguments` without running into deoptimizations\n return _delegate.bind(null, document).apply(null, arguments);\n }\n\n // Handle Selector-based usage\n if (typeof elements === 'string') {\n elements = document.querySelectorAll(elements);\n }\n\n // Handle Array-like based usage\n return Array.prototype.map.call(elements, function (element) {\n return _delegate(element, selector, type, callback, useCapture);\n });\n}\n\n/**\n * Finds closest match and invokes callback.\n *\n * @param {Element} element\n * @param {String} selector\n * @param {String} type\n * @param {Function} callback\n * @return {Function}\n */\nfunction listener(element, selector, type, callback) {\n return function(e) {\n e.delegateTarget = closest(e.target, selector);\n\n if (e.delegateTarget) {\n callback.call(element, e);\n }\n }\n}\n\nmodule.exports = delegate;\n\n\n/***/ }),\n\n/***/ 879:\n/***/ (function(__unused_webpack_module, exports) {\n\n/**\n * Check if argument is a HTML element.\n *\n * @param {Object} value\n * @return {Boolean}\n */\nexports.node = function(value) {\n return value !== undefined\n && value instanceof HTMLElement\n && value.nodeType === 1;\n};\n\n/**\n * Check if argument is a list of HTML elements.\n *\n * @param {Object} value\n * @return {Boolean}\n */\nexports.nodeList = function(value) {\n var type = Object.prototype.toString.call(value);\n\n return value !== undefined\n && (type === '[object NodeList]' || type === '[object HTMLCollection]')\n && ('length' in value)\n && (value.length === 0 || exports.node(value[0]));\n};\n\n/**\n * Check if argument is a string.\n *\n * @param {Object} value\n * @return {Boolean}\n */\nexports.string = function(value) {\n return typeof value === 'string'\n || value instanceof String;\n};\n\n/**\n * Check if argument is a function.\n *\n * @param {Object} value\n * @return {Boolean}\n */\nexports.fn = function(value) {\n var type = Object.prototype.toString.call(value);\n\n return type === '[object Function]';\n};\n\n\n/***/ }),\n\n/***/ 370:\n/***/ (function(module, __unused_webpack_exports, __webpack_require__) {\n\nvar is = __webpack_require__(879);\nvar delegate = __webpack_require__(438);\n\n/**\n * Validates all params and calls the right\n * listener function based on its target type.\n *\n * @param {String|HTMLElement|HTMLCollection|NodeList} target\n * @param {String} type\n * @param {Function} callback\n * @return {Object}\n */\nfunction listen(target, type, callback) {\n if (!target && !type && !callback) {\n throw new Error('Missing required arguments');\n }\n\n if (!is.string(type)) {\n throw new TypeError('Second argument must be a String');\n }\n\n if (!is.fn(callback)) {\n throw new TypeError('Third argument must be a Function');\n }\n\n if (is.node(target)) {\n return listenNode(target, type, callback);\n }\n else if (is.nodeList(target)) {\n return listenNodeList(target, type, callback);\n }\n else if (is.string(target)) {\n return listenSelector(target, type, callback);\n }\n else {\n throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList');\n }\n}\n\n/**\n * Adds an event listener to a HTML element\n * and returns a remove listener function.\n *\n * @param {HTMLElement} node\n * @param {String} type\n * @param {Function} callback\n * @return {Object}\n */\nfunction listenNode(node, type, callback) {\n node.addEventListener(type, callback);\n\n return {\n destroy: function() {\n node.removeEventListener(type, callback);\n }\n }\n}\n\n/**\n * Add an event listener to a list of HTML elements\n * and returns a remove listener function.\n *\n * @param {NodeList|HTMLCollection} nodeList\n * @param {String} type\n * @param {Function} callback\n * @return {Object}\n */\nfunction listenNodeList(nodeList, type, callback) {\n Array.prototype.forEach.call(nodeList, function(node) {\n node.addEventListener(type, callback);\n });\n\n return {\n destroy: function() {\n Array.prototype.forEach.call(nodeList, function(node) {\n node.removeEventListener(type, callback);\n });\n }\n }\n}\n\n/**\n * Add an event listener to a selector\n * and returns a remove listener function.\n *\n * @param {String} selector\n * @param {String} type\n * @param {Function} callback\n * @return {Object}\n */\nfunction listenSelector(selector, type, callback) {\n return delegate(document.body, selector, type, callback);\n}\n\nmodule.exports = listen;\n\n\n/***/ }),\n\n/***/ 817:\n/***/ (function(module) {\n\nfunction select(element) {\n var selectedText;\n\n if (element.nodeName === 'SELECT') {\n element.focus();\n\n selectedText = element.value;\n }\n else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {\n var isReadOnly = element.hasAttribute('readonly');\n\n if (!isReadOnly) {\n element.setAttribute('readonly', '');\n }\n\n element.select();\n element.setSelectionRange(0, element.value.length);\n\n if (!isReadOnly) {\n element.removeAttribute('readonly');\n }\n\n selectedText = element.value;\n }\n else {\n if (element.hasAttribute('contenteditable')) {\n element.focus();\n }\n\n var selection = window.getSelection();\n var range = document.createRange();\n\n range.selectNodeContents(element);\n selection.removeAllRanges();\n selection.addRange(range);\n\n selectedText = selection.toString();\n }\n\n return selectedText;\n}\n\nmodule.exports = select;\n\n\n/***/ }),\n\n/***/ 279:\n/***/ (function(module) {\n\nfunction E () {\n // Keep this empty so it's easier to inherit from\n // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)\n}\n\nE.prototype = {\n on: function (name, callback, ctx) {\n var e = this.e || (this.e = {});\n\n (e[name] || (e[name] = [])).push({\n fn: callback,\n ctx: ctx\n });\n\n return this;\n },\n\n once: function (name, callback, ctx) {\n var self = this;\n function listener () {\n self.off(name, listener);\n callback.apply(ctx, arguments);\n };\n\n listener._ = callback\n return this.on(name, listener, ctx);\n },\n\n emit: function (name) {\n var data = [].slice.call(arguments, 1);\n var evtArr = ((this.e || (this.e = {}))[name] || []).slice();\n var i = 0;\n var len = evtArr.length;\n\n for (i; i < len; i++) {\n evtArr[i].fn.apply(evtArr[i].ctx, data);\n }\n\n return this;\n },\n\n off: function (name, callback) {\n var e = this.e || (this.e = {});\n var evts = e[name];\n var liveEvents = [];\n\n if (evts && callback) {\n for (var i = 0, len = evts.length; i < len; i++) {\n if (evts[i].fn !== callback && evts[i].fn._ !== callback)\n liveEvents.push(evts[i]);\n }\n }\n\n // Remove event from queue to prevent memory leak\n // Suggested by https://github.com/lazd\n // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910\n\n (liveEvents.length)\n ? e[name] = liveEvents\n : delete e[name];\n\n return this;\n }\n};\n\nmodule.exports = E;\nmodule.exports.TinyEmitter = E;\n\n\n/***/ })\n\n/******/ \t});\n/************************************************************************/\n/******/ \t// The module cache\n/******/ \tvar __webpack_module_cache__ = {};\n/******/ \t\n/******/ \t// The require function\n/******/ \tfunction __webpack_require__(moduleId) {\n/******/ \t\t// Check if module is in cache\n/******/ \t\tif(__webpack_module_cache__[moduleId]) {\n/******/ \t\t\treturn __webpack_module_cache__[moduleId].exports;\n/******/ \t\t}\n/******/ \t\t// Create a new module (and put it into the cache)\n/******/ \t\tvar module = __webpack_module_cache__[moduleId] = {\n/******/ \t\t\t// no module.id needed\n/******/ \t\t\t// no module.loaded needed\n/******/ \t\t\texports: {}\n/******/ \t\t};\n/******/ \t\n/******/ \t\t// Execute the module function\n/******/ \t\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n/******/ \t\n/******/ \t\t// Return the exports of the module\n/******/ \t\treturn module.exports;\n/******/ \t}\n/******/ \t\n/************************************************************************/\n/******/ \t/* webpack/runtime/compat get default export */\n/******/ \t!function() {\n/******/ \t\t// getDefaultExport function for compatibility with non-harmony modules\n/******/ \t\t__webpack_require__.n = function(module) {\n/******/ \t\t\tvar getter = module && module.__esModule ?\n/******/ \t\t\t\tfunction() { return module['default']; } :\n/******/ \t\t\t\tfunction() { return module; };\n/******/ \t\t\t__webpack_require__.d(getter, { a: getter });\n/******/ \t\t\treturn getter;\n/******/ \t\t};\n/******/ \t}();\n/******/ \t\n/******/ \t/* webpack/runtime/define property getters */\n/******/ \t!function() {\n/******/ \t\t// define getter functions for harmony exports\n/******/ \t\t__webpack_require__.d = function(exports, definition) {\n/******/ \t\t\tfor(var key in definition) {\n/******/ \t\t\t\tif(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {\n/******/ \t\t\t\t\tObject.defineProperty(exports, key, { enumerable: true, get: definition[key] });\n/******/ \t\t\t\t}\n/******/ \t\t\t}\n/******/ \t\t};\n/******/ \t}();\n/******/ \t\n/******/ \t/* webpack/runtime/hasOwnProperty shorthand */\n/******/ \t!function() {\n/******/ \t\t__webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }\n/******/ \t}();\n/******/ \t\n/************************************************************************/\n/******/ \t// module exports must be returned from runtime so entry inlining is disabled\n/******/ \t// startup\n/******/ \t// Load entry module and return exports\n/******/ \treturn __webpack_require__(686);\n/******/ })()\n.default;\n});", "var root = require('./_root');\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\nmodule.exports = now;\n", "var isObject = require('./isObject'),\n now = require('./now'),\n toNumber = require('./toNumber');\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\nmodule.exports = debounce;\n", "/**\n * This code is needed to enable the Preact Developer Tools.\n * It should be stripped out by Webpack in a production build as\n * it should automatically detect it as unreachable code.\n * Must be the first import.\n */\n// Polyfill - see: https://github.com/babel/babel/issues/9849#issuecomment-487040428\nimport 'regenerator-runtime/runtime.js'\n\nimport FrameFactory from '../components/frame-factory'\nimport AnalyticsController from '../controllers/analytics_controller'\nimport BundleEmbedController from '../controllers/bundle_embed_controller'\nimport FrameController from '../controllers/frame_controller'\nimport HorizontalBundleAnalyticsController from '../controllers/horizontal_bundle_analytics_controller'\nimport ModalTriggerController from '../controllers/modal_trigger_controller'\nimport PoweredByProvenanceController from '../controllers/powered_by_provenance_controller'\nimport ProofPointStatusController from '../controllers/proof_point_status_controller'\nimport TabsController from '../controllers/tabs_controller'\nimport TabpanelsController from '../controllers/tabpanels_controller'\nimport MountJSController from '../controllers/mount_js_controller'\n\nimport { initLogging } from '../utils/logger'\nimport { initStimulus } from '../utils/stimulus'\n\nwindow.provenance = window.provenance || {}\nwindow.provenance.frameFactory = new FrameFactory()\n\ninitLogging()\n\nconst controllers = [\n {identifier: 'analytics', controllerConstructor: AnalyticsController},\n {identifier: 'bundle-embed', controllerConstructor: BundleEmbedController},\n {identifier: 'frame', controllerConstructor: FrameController},\n {identifier: 'horizontal-bundle-analytics', controllerConstructor: HorizontalBundleAnalyticsController},\n {identifier: 'modal-trigger', controllerConstructor: ModalTriggerController},\n {identifier: 'proof-point-status', controllerConstructor: ProofPointStatusController},\n {identifier: 'powered-by-provenance', controllerConstructor: PoweredByProvenanceController},\n {identifier: 'tabs', controllerConstructor: TabsController},\n {identifier: 'tabpanels', controllerConstructor: TabpanelsController},\n {identifier: 'mount-js', controllerConstructor: MountJSController },\n]\n\ninitStimulus(controllers)\n", "import zoid from 'zoid9078'\nimport { hashCode } from '../utils/hashing'\n\nexport default class FrameFactory {\n constructor () {\n this.frameComponents = {}\n // Setup frames used by the 2-step experience loading process. These can be\n // removed once that approach has been completely deprecated.\n this.getFrame()\n this.getFrame('small')\n this.getFrame('story')\n this.getFrame('full')\n }\n\n getFrame (variant = 'embed', url = null) {\n console.debug('APP:frame', variant, url)\n\n let key = variant\n if (url != null) {\n key = `${variant}-${hashCode(url)}`\n } else {\n url = `${window.provenance.rootUrl}/x`\n }\n\n if (this.frameComponents[key]) {\n console.debug('found cached frame')\n return this.frameComponents[key]\n }\n\n let height = '100%'\n let autoResizeHeight = true\n\n switch (variant) {\n case 'small':\n height = '482px'\n break\n case 'story':\n break\n case 'full':\n autoResizeHeight = false\n break\n }\n\n const component = zoid.create({\n tag: `provenance-experience-${key}`,\n url,\n dimensions: {\n height,\n width: '100%'\n },\n autoResize: {\n height: autoResizeHeight,\n width: false\n },\n props: {\n url: {\n type: 'string',\n required: true\n },\n version: {\n type: 'string',\n required: false\n },\n openModal: {\n type: 'function',\n required: false\n }\n }\n })\n\n this.frameComponents[key] = {\n component,\n class: `ProvenanceModal--${variant}Variant`\n }\n return this.frameComponents[key]\n }\n}\n", "export function hashCode (s) {\n return Math.abs(s.split('').reduce(function (a, b) { a = ((a << 5) - a) + b.charCodeAt(0); return a & a }, 0))\n}\n", "/*\nStimulus 3.2.1\nCopyright \u00A9 2023 Basecamp, LLC\n */\nclass EventListener {\n constructor(eventTarget, eventName, eventOptions) {\n this.eventTarget = eventTarget;\n this.eventName = eventName;\n this.eventOptions = eventOptions;\n this.unorderedBindings = new Set();\n }\n connect() {\n this.eventTarget.addEventListener(this.eventName, this, this.eventOptions);\n }\n disconnect() {\n this.eventTarget.removeEventListener(this.eventName, this, this.eventOptions);\n }\n bindingConnected(binding) {\n this.unorderedBindings.add(binding);\n }\n bindingDisconnected(binding) {\n this.unorderedBindings.delete(binding);\n }\n handleEvent(event) {\n const extendedEvent = extendEvent(event);\n for (const binding of this.bindings) {\n if (extendedEvent.immediatePropagationStopped) {\n break;\n }\n else {\n binding.handleEvent(extendedEvent);\n }\n }\n }\n hasBindings() {\n return this.unorderedBindings.size > 0;\n }\n get bindings() {\n return Array.from(this.unorderedBindings).sort((left, right) => {\n const leftIndex = left.index, rightIndex = right.index;\n return leftIndex < rightIndex ? -1 : leftIndex > rightIndex ? 1 : 0;\n });\n }\n}\nfunction extendEvent(event) {\n if (\"immediatePropagationStopped\" in event) {\n return event;\n }\n else {\n const { stopImmediatePropagation } = event;\n return Object.assign(event, {\n immediatePropagationStopped: false,\n stopImmediatePropagation() {\n this.immediatePropagationStopped = true;\n stopImmediatePropagation.call(this);\n },\n });\n }\n}\n\nclass Dispatcher {\n constructor(application) {\n this.application = application;\n this.eventListenerMaps = new Map();\n this.started = false;\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.eventListeners.forEach((eventListener) => eventListener.connect());\n }\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.eventListeners.forEach((eventListener) => eventListener.disconnect());\n }\n }\n get eventListeners() {\n return Array.from(this.eventListenerMaps.values()).reduce((listeners, map) => listeners.concat(Array.from(map.values())), []);\n }\n bindingConnected(binding) {\n this.fetchEventListenerForBinding(binding).bindingConnected(binding);\n }\n bindingDisconnected(binding, clearEventListeners = false) {\n this.fetchEventListenerForBinding(binding).bindingDisconnected(binding);\n if (clearEventListeners)\n this.clearEventListenersForBinding(binding);\n }\n handleError(error, message, detail = {}) {\n this.application.handleError(error, `Error ${message}`, detail);\n }\n clearEventListenersForBinding(binding) {\n const eventListener = this.fetchEventListenerForBinding(binding);\n if (!eventListener.hasBindings()) {\n eventListener.disconnect();\n this.removeMappedEventListenerFor(binding);\n }\n }\n removeMappedEventListenerFor(binding) {\n const { eventTarget, eventName, eventOptions } = binding;\n const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n const cacheKey = this.cacheKey(eventName, eventOptions);\n eventListenerMap.delete(cacheKey);\n if (eventListenerMap.size == 0)\n this.eventListenerMaps.delete(eventTarget);\n }\n fetchEventListenerForBinding(binding) {\n const { eventTarget, eventName, eventOptions } = binding;\n return this.fetchEventListener(eventTarget, eventName, eventOptions);\n }\n fetchEventListener(eventTarget, eventName, eventOptions) {\n const eventListenerMap = this.fetchEventListenerMapForEventTarget(eventTarget);\n const cacheKey = this.cacheKey(eventName, eventOptions);\n let eventListener = eventListenerMap.get(cacheKey);\n if (!eventListener) {\n eventListener = this.createEventListener(eventTarget, eventName, eventOptions);\n eventListenerMap.set(cacheKey, eventListener);\n }\n return eventListener;\n }\n createEventListener(eventTarget, eventName, eventOptions) {\n const eventListener = new EventListener(eventTarget, eventName, eventOptions);\n if (this.started) {\n eventListener.connect();\n }\n return eventListener;\n }\n fetchEventListenerMapForEventTarget(eventTarget) {\n let eventListenerMap = this.eventListenerMaps.get(eventTarget);\n if (!eventListenerMap) {\n eventListenerMap = new Map();\n this.eventListenerMaps.set(eventTarget, eventListenerMap);\n }\n return eventListenerMap;\n }\n cacheKey(eventName, eventOptions) {\n const parts = [eventName];\n Object.keys(eventOptions)\n .sort()\n .forEach((key) => {\n parts.push(`${eventOptions[key] ? \"\" : \"!\"}${key}`);\n });\n return parts.join(\":\");\n }\n}\n\nconst defaultActionDescriptorFilters = {\n stop({ event, value }) {\n if (value)\n event.stopPropagation();\n return true;\n },\n prevent({ event, value }) {\n if (value)\n event.preventDefault();\n return true;\n },\n self({ event, value, element }) {\n if (value) {\n return element === event.target;\n }\n else {\n return true;\n }\n },\n};\nconst descriptorPattern = /^(?:(?:([^.]+?)\\+)?(.+?)(?:\\.(.+?))?(?:@(window|document))?->)?(.+?)(?:#([^:]+?))(?::(.+))?$/;\nfunction parseActionDescriptorString(descriptorString) {\n const source = descriptorString.trim();\n const matches = source.match(descriptorPattern) || [];\n let eventName = matches[2];\n let keyFilter = matches[3];\n if (keyFilter && ![\"keydown\", \"keyup\", \"keypress\"].includes(eventName)) {\n eventName += `.${keyFilter}`;\n keyFilter = \"\";\n }\n return {\n eventTarget: parseEventTarget(matches[4]),\n eventName,\n eventOptions: matches[7] ? parseEventOptions(matches[7]) : {},\n identifier: matches[5],\n methodName: matches[6],\n keyFilter: matches[1] || keyFilter,\n };\n}\nfunction parseEventTarget(eventTargetName) {\n if (eventTargetName == \"window\") {\n return window;\n }\n else if (eventTargetName == \"document\") {\n return document;\n }\n}\nfunction parseEventOptions(eventOptions) {\n return eventOptions\n .split(\":\")\n .reduce((options, token) => Object.assign(options, { [token.replace(/^!/, \"\")]: !/^!/.test(token) }), {});\n}\nfunction stringifyEventTarget(eventTarget) {\n if (eventTarget == window) {\n return \"window\";\n }\n else if (eventTarget == document) {\n return \"document\";\n }\n}\n\nfunction camelize(value) {\n return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());\n}\nfunction namespaceCamelize(value) {\n return camelize(value.replace(/--/g, \"-\").replace(/__/g, \"_\"));\n}\nfunction capitalize(value) {\n return value.charAt(0).toUpperCase() + value.slice(1);\n}\nfunction dasherize(value) {\n return value.replace(/([A-Z])/g, (_, char) => `-${char.toLowerCase()}`);\n}\nfunction tokenize(value) {\n return value.match(/[^\\s]+/g) || [];\n}\n\nfunction isSomething(object) {\n return object !== null && object !== undefined;\n}\nfunction hasProperty(object, property) {\n return Object.prototype.hasOwnProperty.call(object, property);\n}\n\nconst allModifiers = [\"meta\", \"ctrl\", \"alt\", \"shift\"];\nclass Action {\n constructor(element, index, descriptor, schema) {\n this.element = element;\n this.index = index;\n this.eventTarget = descriptor.eventTarget || element;\n this.eventName = descriptor.eventName || getDefaultEventNameForElement(element) || error(\"missing event name\");\n this.eventOptions = descriptor.eventOptions || {};\n this.identifier = descriptor.identifier || error(\"missing identifier\");\n this.methodName = descriptor.methodName || error(\"missing method name\");\n this.keyFilter = descriptor.keyFilter || \"\";\n this.schema = schema;\n }\n static forToken(token, schema) {\n return new this(token.element, token.index, parseActionDescriptorString(token.content), schema);\n }\n toString() {\n const eventFilter = this.keyFilter ? `.${this.keyFilter}` : \"\";\n const eventTarget = this.eventTargetName ? `@${this.eventTargetName}` : \"\";\n return `${this.eventName}${eventFilter}${eventTarget}->${this.identifier}#${this.methodName}`;\n }\n shouldIgnoreKeyboardEvent(event) {\n if (!this.keyFilter) {\n return false;\n }\n const filters = this.keyFilter.split(\"+\");\n if (this.keyFilterDissatisfied(event, filters)) {\n return true;\n }\n const standardFilter = filters.filter((key) => !allModifiers.includes(key))[0];\n if (!standardFilter) {\n return false;\n }\n if (!hasProperty(this.keyMappings, standardFilter)) {\n error(`contains unknown key filter: ${this.keyFilter}`);\n }\n return this.keyMappings[standardFilter].toLowerCase() !== event.key.toLowerCase();\n }\n shouldIgnoreMouseEvent(event) {\n if (!this.keyFilter) {\n return false;\n }\n const filters = [this.keyFilter];\n if (this.keyFilterDissatisfied(event, filters)) {\n return true;\n }\n return false;\n }\n get params() {\n const params = {};\n const pattern = new RegExp(`^data-${this.identifier}-(.+)-param$`, \"i\");\n for (const { name, value } of Array.from(this.element.attributes)) {\n const match = name.match(pattern);\n const key = match && match[1];\n if (key) {\n params[camelize(key)] = typecast(value);\n }\n }\n return params;\n }\n get eventTargetName() {\n return stringifyEventTarget(this.eventTarget);\n }\n get keyMappings() {\n return this.schema.keyMappings;\n }\n keyFilterDissatisfied(event, filters) {\n const [meta, ctrl, alt, shift] = allModifiers.map((modifier) => filters.includes(modifier));\n return event.metaKey !== meta || event.ctrlKey !== ctrl || event.altKey !== alt || event.shiftKey !== shift;\n }\n}\nconst defaultEventNames = {\n a: () => \"click\",\n button: () => \"click\",\n form: () => \"submit\",\n details: () => \"toggle\",\n input: (e) => (e.getAttribute(\"type\") == \"submit\" ? \"click\" : \"input\"),\n select: () => \"change\",\n textarea: () => \"input\",\n};\nfunction getDefaultEventNameForElement(element) {\n const tagName = element.tagName.toLowerCase();\n if (tagName in defaultEventNames) {\n return defaultEventNames[tagName](element);\n }\n}\nfunction error(message) {\n throw new Error(message);\n}\nfunction typecast(value) {\n try {\n return JSON.parse(value);\n }\n catch (o_O) {\n return value;\n }\n}\n\nclass Binding {\n constructor(context, action) {\n this.context = context;\n this.action = action;\n }\n get index() {\n return this.action.index;\n }\n get eventTarget() {\n return this.action.eventTarget;\n }\n get eventOptions() {\n return this.action.eventOptions;\n }\n get identifier() {\n return this.context.identifier;\n }\n handleEvent(event) {\n const actionEvent = this.prepareActionEvent(event);\n if (this.willBeInvokedByEvent(event) && this.applyEventModifiers(actionEvent)) {\n this.invokeWithEvent(actionEvent);\n }\n }\n get eventName() {\n return this.action.eventName;\n }\n get method() {\n const method = this.controller[this.methodName];\n if (typeof method == \"function\") {\n return method;\n }\n throw new Error(`Action \"${this.action}\" references undefined method \"${this.methodName}\"`);\n }\n applyEventModifiers(event) {\n const { element } = this.action;\n const { actionDescriptorFilters } = this.context.application;\n const { controller } = this.context;\n let passes = true;\n for (const [name, value] of Object.entries(this.eventOptions)) {\n if (name in actionDescriptorFilters) {\n const filter = actionDescriptorFilters[name];\n passes = passes && filter({ name, value, event, element, controller });\n }\n else {\n continue;\n }\n }\n return passes;\n }\n prepareActionEvent(event) {\n return Object.assign(event, { params: this.action.params });\n }\n invokeWithEvent(event) {\n const { target, currentTarget } = event;\n try {\n this.method.call(this.controller, event);\n this.context.logDebugActivity(this.methodName, { event, target, currentTarget, action: this.methodName });\n }\n catch (error) {\n const { identifier, controller, element, index } = this;\n const detail = { identifier, controller, element, index, event };\n this.context.handleError(error, `invoking action \"${this.action}\"`, detail);\n }\n }\n willBeInvokedByEvent(event) {\n const eventTarget = event.target;\n if (event instanceof KeyboardEvent && this.action.shouldIgnoreKeyboardEvent(event)) {\n return false;\n }\n if (event instanceof MouseEvent && this.action.shouldIgnoreMouseEvent(event)) {\n return false;\n }\n if (this.element === eventTarget) {\n return true;\n }\n else if (eventTarget instanceof Element && this.element.contains(eventTarget)) {\n return this.scope.containsElement(eventTarget);\n }\n else {\n return this.scope.containsElement(this.action.element);\n }\n }\n get controller() {\n return this.context.controller;\n }\n get methodName() {\n return this.action.methodName;\n }\n get element() {\n return this.scope.element;\n }\n get scope() {\n return this.context.scope;\n }\n}\n\nclass ElementObserver {\n constructor(element, delegate) {\n this.mutationObserverInit = { attributes: true, childList: true, subtree: true };\n this.element = element;\n this.started = false;\n this.delegate = delegate;\n this.elements = new Set();\n this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.mutationObserver.observe(this.element, this.mutationObserverInit);\n this.refresh();\n }\n }\n pause(callback) {\n if (this.started) {\n this.mutationObserver.disconnect();\n this.started = false;\n }\n callback();\n if (!this.started) {\n this.mutationObserver.observe(this.element, this.mutationObserverInit);\n this.started = true;\n }\n }\n stop() {\n if (this.started) {\n this.mutationObserver.takeRecords();\n this.mutationObserver.disconnect();\n this.started = false;\n }\n }\n refresh() {\n if (this.started) {\n const matches = new Set(this.matchElementsInTree());\n for (const element of Array.from(this.elements)) {\n if (!matches.has(element)) {\n this.removeElement(element);\n }\n }\n for (const element of Array.from(matches)) {\n this.addElement(element);\n }\n }\n }\n processMutations(mutations) {\n if (this.started) {\n for (const mutation of mutations) {\n this.processMutation(mutation);\n }\n }\n }\n processMutation(mutation) {\n if (mutation.type == \"attributes\") {\n this.processAttributeChange(mutation.target, mutation.attributeName);\n }\n else if (mutation.type == \"childList\") {\n this.processRemovedNodes(mutation.removedNodes);\n this.processAddedNodes(mutation.addedNodes);\n }\n }\n processAttributeChange(element, attributeName) {\n if (this.elements.has(element)) {\n if (this.delegate.elementAttributeChanged && this.matchElement(element)) {\n this.delegate.elementAttributeChanged(element, attributeName);\n }\n else {\n this.removeElement(element);\n }\n }\n else if (this.matchElement(element)) {\n this.addElement(element);\n }\n }\n processRemovedNodes(nodes) {\n for (const node of Array.from(nodes)) {\n const element = this.elementFromNode(node);\n if (element) {\n this.processTree(element, this.removeElement);\n }\n }\n }\n processAddedNodes(nodes) {\n for (const node of Array.from(nodes)) {\n const element = this.elementFromNode(node);\n if (element && this.elementIsActive(element)) {\n this.processTree(element, this.addElement);\n }\n }\n }\n matchElement(element) {\n return this.delegate.matchElement(element);\n }\n matchElementsInTree(tree = this.element) {\n return this.delegate.matchElementsInTree(tree);\n }\n processTree(tree, processor) {\n for (const element of this.matchElementsInTree(tree)) {\n processor.call(this, element);\n }\n }\n elementFromNode(node) {\n if (node.nodeType == Node.ELEMENT_NODE) {\n return node;\n }\n }\n elementIsActive(element) {\n if (element.isConnected != this.element.isConnected) {\n return false;\n }\n else {\n return this.element.contains(element);\n }\n }\n addElement(element) {\n if (!this.elements.has(element)) {\n if (this.elementIsActive(element)) {\n this.elements.add(element);\n if (this.delegate.elementMatched) {\n this.delegate.elementMatched(element);\n }\n }\n }\n }\n removeElement(element) {\n if (this.elements.has(element)) {\n this.elements.delete(element);\n if (this.delegate.elementUnmatched) {\n this.delegate.elementUnmatched(element);\n }\n }\n }\n}\n\nclass AttributeObserver {\n constructor(element, attributeName, delegate) {\n this.attributeName = attributeName;\n this.delegate = delegate;\n this.elementObserver = new ElementObserver(element, this);\n }\n get element() {\n return this.elementObserver.element;\n }\n get selector() {\n return `[${this.attributeName}]`;\n }\n start() {\n this.elementObserver.start();\n }\n pause(callback) {\n this.elementObserver.pause(callback);\n }\n stop() {\n this.elementObserver.stop();\n }\n refresh() {\n this.elementObserver.refresh();\n }\n get started() {\n return this.elementObserver.started;\n }\n matchElement(element) {\n return element.hasAttribute(this.attributeName);\n }\n matchElementsInTree(tree) {\n const match = this.matchElement(tree) ? [tree] : [];\n const matches = Array.from(tree.querySelectorAll(this.selector));\n return match.concat(matches);\n }\n elementMatched(element) {\n if (this.delegate.elementMatchedAttribute) {\n this.delegate.elementMatchedAttribute(element, this.attributeName);\n }\n }\n elementUnmatched(element) {\n if (this.delegate.elementUnmatchedAttribute) {\n this.delegate.elementUnmatchedAttribute(element, this.attributeName);\n }\n }\n elementAttributeChanged(element, attributeName) {\n if (this.delegate.elementAttributeValueChanged && this.attributeName == attributeName) {\n this.delegate.elementAttributeValueChanged(element, attributeName);\n }\n }\n}\n\nfunction add(map, key, value) {\n fetch(map, key).add(value);\n}\nfunction del(map, key, value) {\n fetch(map, key).delete(value);\n prune(map, key);\n}\nfunction fetch(map, key) {\n let values = map.get(key);\n if (!values) {\n values = new Set();\n map.set(key, values);\n }\n return values;\n}\nfunction prune(map, key) {\n const values = map.get(key);\n if (values != null && values.size == 0) {\n map.delete(key);\n }\n}\n\nclass Multimap {\n constructor() {\n this.valuesByKey = new Map();\n }\n get keys() {\n return Array.from(this.valuesByKey.keys());\n }\n get values() {\n const sets = Array.from(this.valuesByKey.values());\n return sets.reduce((values, set) => values.concat(Array.from(set)), []);\n }\n get size() {\n const sets = Array.from(this.valuesByKey.values());\n return sets.reduce((size, set) => size + set.size, 0);\n }\n add(key, value) {\n add(this.valuesByKey, key, value);\n }\n delete(key, value) {\n del(this.valuesByKey, key, value);\n }\n has(key, value) {\n const values = this.valuesByKey.get(key);\n return values != null && values.has(value);\n }\n hasKey(key) {\n return this.valuesByKey.has(key);\n }\n hasValue(value) {\n const sets = Array.from(this.valuesByKey.values());\n return sets.some((set) => set.has(value));\n }\n getValuesForKey(key) {\n const values = this.valuesByKey.get(key);\n return values ? Array.from(values) : [];\n }\n getKeysForValue(value) {\n return Array.from(this.valuesByKey)\n .filter(([_key, values]) => values.has(value))\n .map(([key, _values]) => key);\n }\n}\n\nclass IndexedMultimap extends Multimap {\n constructor() {\n super();\n this.keysByValue = new Map();\n }\n get values() {\n return Array.from(this.keysByValue.keys());\n }\n add(key, value) {\n super.add(key, value);\n add(this.keysByValue, value, key);\n }\n delete(key, value) {\n super.delete(key, value);\n del(this.keysByValue, value, key);\n }\n hasValue(value) {\n return this.keysByValue.has(value);\n }\n getKeysForValue(value) {\n const set = this.keysByValue.get(value);\n return set ? Array.from(set) : [];\n }\n}\n\nclass SelectorObserver {\n constructor(element, selector, delegate, details) {\n this._selector = selector;\n this.details = details;\n this.elementObserver = new ElementObserver(element, this);\n this.delegate = delegate;\n this.matchesByElement = new Multimap();\n }\n get started() {\n return this.elementObserver.started;\n }\n get selector() {\n return this._selector;\n }\n set selector(selector) {\n this._selector = selector;\n this.refresh();\n }\n start() {\n this.elementObserver.start();\n }\n pause(callback) {\n this.elementObserver.pause(callback);\n }\n stop() {\n this.elementObserver.stop();\n }\n refresh() {\n this.elementObserver.refresh();\n }\n get element() {\n return this.elementObserver.element;\n }\n matchElement(element) {\n const { selector } = this;\n if (selector) {\n const matches = element.matches(selector);\n if (this.delegate.selectorMatchElement) {\n return matches && this.delegate.selectorMatchElement(element, this.details);\n }\n return matches;\n }\n else {\n return false;\n }\n }\n matchElementsInTree(tree) {\n const { selector } = this;\n if (selector) {\n const match = this.matchElement(tree) ? [tree] : [];\n const matches = Array.from(tree.querySelectorAll(selector)).filter((match) => this.matchElement(match));\n return match.concat(matches);\n }\n else {\n return [];\n }\n }\n elementMatched(element) {\n const { selector } = this;\n if (selector) {\n this.selectorMatched(element, selector);\n }\n }\n elementUnmatched(element) {\n const selectors = this.matchesByElement.getKeysForValue(element);\n for (const selector of selectors) {\n this.selectorUnmatched(element, selector);\n }\n }\n elementAttributeChanged(element, _attributeName) {\n const { selector } = this;\n if (selector) {\n const matches = this.matchElement(element);\n const matchedBefore = this.matchesByElement.has(selector, element);\n if (matches && !matchedBefore) {\n this.selectorMatched(element, selector);\n }\n else if (!matches && matchedBefore) {\n this.selectorUnmatched(element, selector);\n }\n }\n }\n selectorMatched(element, selector) {\n this.delegate.selectorMatched(element, selector, this.details);\n this.matchesByElement.add(selector, element);\n }\n selectorUnmatched(element, selector) {\n this.delegate.selectorUnmatched(element, selector, this.details);\n this.matchesByElement.delete(selector, element);\n }\n}\n\nclass StringMapObserver {\n constructor(element, delegate) {\n this.element = element;\n this.delegate = delegate;\n this.started = false;\n this.stringMap = new Map();\n this.mutationObserver = new MutationObserver((mutations) => this.processMutations(mutations));\n }\n start() {\n if (!this.started) {\n this.started = true;\n this.mutationObserver.observe(this.element, { attributes: true, attributeOldValue: true });\n this.refresh();\n }\n }\n stop() {\n if (this.started) {\n this.mutationObserver.takeRecords();\n this.mutationObserver.disconnect();\n this.started = false;\n }\n }\n refresh() {\n if (this.started) {\n for (const attributeName of this.knownAttributeNames) {\n this.refreshAttribute(attributeName, null);\n }\n }\n }\n processMutations(mutations) {\n if (this.started) {\n for (const mutation of mutations) {\n this.processMutation(mutation);\n }\n }\n }\n processMutation(mutation) {\n const attributeName = mutation.attributeName;\n if (attributeName) {\n this.refreshAttribute(attributeName, mutation.oldValue);\n }\n }\n refreshAttribute(attributeName, oldValue) {\n const key = this.delegate.getStringMapKeyForAttribute(attributeName);\n if (key != null) {\n if (!this.stringMap.has(attributeName)) {\n this.stringMapKeyAdded(key, attributeName);\n }\n const value = this.element.getAttribute(attributeName);\n if (this.stringMap.get(attributeName) != value) {\n this.stringMapValueChanged(value, key, oldValue);\n }\n if (value == null) {\n const oldValue = this.stringMap.get(attributeName);\n this.stringMap.delete(attributeName);\n if (oldValue)\n this.stringMapKeyRemoved(key, attributeName, oldValue);\n }\n else {\n this.stringMap.set(attributeName, value);\n }\n }\n }\n stringMapKeyAdded(key, attributeName) {\n if (this.delegate.stringMapKeyAdded) {\n this.delegate.stringMapKeyAdded(key, attributeName);\n }\n }\n stringMapValueChanged(value, key, oldValue) {\n if (this.delegate.stringMapValueChanged) {\n this.delegate.stringMapValueChanged(value, key, oldValue);\n }\n }\n stringMapKeyRemoved(key, attributeName, oldValue) {\n if (this.delegate.stringMapKeyRemoved) {\n this.delegate.stringMapKeyRemoved(key, attributeName, oldValue);\n }\n }\n get knownAttributeNames() {\n return Array.from(new Set(this.currentAttributeNames.concat(this.recordedAttributeNames)));\n }\n get currentAttributeNames() {\n return Array.from(this.element.attributes).map((attribute) => attribute.name);\n }\n get recordedAttributeNames() {\n return Array.from(this.stringMap.keys());\n }\n}\n\nclass TokenListObserver {\n constructor(element, attributeName, delegate) {\n this.attributeObserver = new AttributeObserver(element, attributeName, this);\n this.delegate = delegate;\n this.tokensByElement = new Multimap();\n }\n get started() {\n return this.attributeObserver.started;\n }\n start() {\n this.attributeObserver.start();\n }\n pause(callback) {\n this.attributeObserver.pause(callback);\n }\n stop() {\n this.attributeObserver.stop();\n }\n refresh() {\n this.attributeObserver.refresh();\n }\n get element() {\n return this.attributeObserver.element;\n }\n get attributeName() {\n return this.attributeObserver.attributeName;\n }\n elementMatchedAttribute(element) {\n this.tokensMatched(this.readTokensForElement(element));\n }\n elementAttributeValueChanged(element) {\n const [unmatchedTokens, matchedTokens] = this.refreshTokensForElement(element);\n this.tokensUnmatched(unmatchedTokens);\n this.tokensMatched(matchedTokens);\n }\n elementUnmatchedAttribute(element) {\n this.tokensUnmatched(this.tokensByElement.getValuesForKey(element));\n }\n tokensMatched(tokens) {\n tokens.forEach((token) => this.tokenMatched(token));\n }\n tokensUnmatched(tokens) {\n tokens.forEach((token) => this.tokenUnmatched(token));\n }\n tokenMatched(token) {\n this.delegate.tokenMatched(token);\n this.tokensByElement.add(token.element, token);\n }\n tokenUnmatched(token) {\n this.delegate.tokenUnmatched(token);\n this.tokensByElement.delete(token.element, token);\n }\n refreshTokensForElement(element) {\n const previousTokens = this.tokensByElement.getValuesForKey(element);\n const currentTokens = this.readTokensForElement(element);\n const firstDifferingIndex = zip(previousTokens, currentTokens).findIndex(([previousToken, currentToken]) => !tokensAreEqual(previousToken, currentToken));\n if (firstDifferingIndex == -1) {\n return [[], []];\n }\n else {\n return [previousTokens.slice(firstDifferingIndex), currentTokens.slice(firstDifferingIndex)];\n }\n }\n readTokensForElement(element) {\n const attributeName = this.attributeName;\n const tokenString = element.getAttribute(attributeName) || \"\";\n return parseTokenString(tokenString, element, attributeName);\n }\n}\nfunction parseTokenString(tokenString, element, attributeName) {\n return tokenString\n .trim()\n .split(/\\s+/)\n .filter((content) => content.length)\n .map((content, index) => ({ element, attributeName, content, index }));\n}\nfunction zip(left, right) {\n const length = Math.max(left.length, right.length);\n return Array.from({ length }, (_, index) => [left[index], right[index]]);\n}\nfunction tokensAreEqual(left, right) {\n return left && right && left.index == right.index && left.content == right.content;\n}\n\nclass ValueListObserver {\n constructor(element, attributeName, delegate) {\n this.tokenListObserver = new TokenListObserver(element, attributeName, this);\n this.delegate = delegate;\n this.parseResultsByToken = new WeakMap();\n this.valuesByTokenByElement = new WeakMap();\n }\n get started() {\n return this.tokenListObserver.started;\n }\n start() {\n this.tokenListObserver.start();\n }\n stop() {\n this.tokenListObserver.stop();\n }\n refresh() {\n this.tokenListObserver.refresh();\n }\n get element() {\n return this.tokenListObserver.element;\n }\n get attributeName() {\n return this.tokenListObserver.attributeName;\n }\n tokenMatched(token) {\n const { element } = token;\n const { value } = this.fetchParseResultForToken(token);\n if (value) {\n this.fetchValuesByTokenForElement(element).set(token, value);\n this.delegate.elementMatchedValue(element, value);\n }\n }\n tokenUnmatched(token) {\n const { element } = token;\n const { value } = this.fetchParseResultForToken(token);\n if (value) {\n this.fetchValuesByTokenForElement(element).delete(token);\n this.delegate.elementUnmatchedValue(element, value);\n }\n }\n fetchParseResultForToken(token) {\n let parseResult = this.parseResultsByToken.get(token);\n if (!parseResult) {\n parseResult = this.parseToken(token);\n this.parseResultsByToken.set(token, parseResult);\n }\n return parseResult;\n }\n fetchValuesByTokenForElement(element) {\n let valuesByToken = this.valuesByTokenByElement.get(element);\n if (!valuesByToken) {\n valuesByToken = new Map();\n this.valuesByTokenByElement.set(element, valuesByToken);\n }\n return valuesByToken;\n }\n parseToken(token) {\n try {\n const value = this.delegate.parseValueForToken(token);\n return { value };\n }\n catch (error) {\n return { error };\n }\n }\n}\n\nclass BindingObserver {\n constructor(context, delegate) {\n this.context = context;\n this.delegate = delegate;\n this.bindingsByAction = new Map();\n }\n start() {\n if (!this.valueListObserver) {\n this.valueListObserver = new ValueListObserver(this.element, this.actionAttribute, this);\n this.valueListObserver.start();\n }\n }\n stop() {\n if (this.valueListObserver) {\n this.valueListObserver.stop();\n delete this.valueListObserver;\n this.disconnectAllActions();\n }\n }\n get element() {\n return this.context.element;\n }\n get identifier() {\n return this.context.identifier;\n }\n get actionAttribute() {\n return this.schema.actionAttribute;\n }\n get schema() {\n return this.context.schema;\n }\n get bindings() {\n return Array.from(this.bindingsByAction.values());\n }\n connectAction(action) {\n const binding = new Binding(this.context, action);\n this.bindingsByAction.set(action, binding);\n this.delegate.bindingConnected(binding);\n }\n disconnectAction(action) {\n const binding = this.bindingsByAction.get(action);\n if (binding) {\n this.bindingsByAction.delete(action);\n this.delegate.bindingDisconnected(binding);\n }\n }\n disconnectAllActions() {\n this.bindings.forEach((binding) => this.delegate.bindingDisconnected(binding, true));\n this.bindingsByAction.clear();\n }\n parseValueForToken(token) {\n const action = Action.forToken(token, this.schema);\n if (action.identifier == this.identifier) {\n return action;\n }\n }\n elementMatchedValue(element, action) {\n this.connectAction(action);\n }\n elementUnmatchedValue(element, action) {\n this.disconnectAction(action);\n }\n}\n\nclass ValueObserver {\n constructor(context, receiver) {\n this.context = context;\n this.receiver = receiver;\n this.stringMapObserver = new StringMapObserver(this.element, this);\n this.valueDescriptorMap = this.controller.valueDescriptorMap;\n }\n start() {\n this.stringMapObserver.start();\n this.invokeChangedCallbacksForDefaultValues();\n }\n stop() {\n this.stringMapObserver.stop();\n }\n get element() {\n return this.context.element;\n }\n get controller() {\n return this.context.controller;\n }\n getStringMapKeyForAttribute(attributeName) {\n if (attributeName in this.valueDescriptorMap) {\n return this.valueDescriptorMap[attributeName].name;\n }\n }\n stringMapKeyAdded(key, attributeName) {\n const descriptor = this.valueDescriptorMap[attributeName];\n if (!this.hasValue(key)) {\n this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), descriptor.writer(descriptor.defaultValue));\n }\n }\n stringMapValueChanged(value, name, oldValue) {\n const descriptor = this.valueDescriptorNameMap[name];\n if (value === null)\n return;\n if (oldValue === null) {\n oldValue = descriptor.writer(descriptor.defaultValue);\n }\n this.invokeChangedCallback(name, value, oldValue);\n }\n stringMapKeyRemoved(key, attributeName, oldValue) {\n const descriptor = this.valueDescriptorNameMap[key];\n if (this.hasValue(key)) {\n this.invokeChangedCallback(key, descriptor.writer(this.receiver[key]), oldValue);\n }\n else {\n this.invokeChangedCallback(key, descriptor.writer(descriptor.defaultValue), oldValue);\n }\n }\n invokeChangedCallbacksForDefaultValues() {\n for (const { key, name, defaultValue, writer } of this.valueDescriptors) {\n if (defaultValue != undefined && !this.controller.data.has(key)) {\n this.invokeChangedCallback(name, writer(defaultValue), undefined);\n }\n }\n }\n invokeChangedCallback(name, rawValue, rawOldValue) {\n const changedMethodName = `${name}Changed`;\n const changedMethod = this.receiver[changedMethodName];\n if (typeof changedMethod == \"function\") {\n const descriptor = this.valueDescriptorNameMap[name];\n try {\n const value = descriptor.reader(rawValue);\n let oldValue = rawOldValue;\n if (rawOldValue) {\n oldValue = descriptor.reader(rawOldValue);\n }\n changedMethod.call(this.receiver, value, oldValue);\n }\n catch (error) {\n if (error instanceof TypeError) {\n error.message = `Stimulus Value \"${this.context.identifier}.${descriptor.name}\" - ${error.message}`;\n }\n throw error;\n }\n }\n }\n get valueDescriptors() {\n const { valueDescriptorMap } = this;\n return Object.keys(valueDescriptorMap).map((key) => valueDescriptorMap[key]);\n }\n get valueDescriptorNameMap() {\n const descriptors = {};\n Object.keys(this.valueDescriptorMap).forEach((key) => {\n const descriptor = this.valueDescriptorMap[key];\n descriptors[descriptor.name] = descriptor;\n });\n return descriptors;\n }\n hasValue(attributeName) {\n const descriptor = this.valueDescriptorNameMap[attributeName];\n const hasMethodName = `has${capitalize(descriptor.name)}`;\n return this.receiver[hasMethodName];\n }\n}\n\nclass TargetObserver {\n constructor(context, delegate) {\n this.context = context;\n this.delegate = delegate;\n this.targetsByName = new Multimap();\n }\n start() {\n if (!this.tokenListObserver) {\n this.tokenListObserver = new TokenListObserver(this.element, this.attributeName, this);\n this.tokenListObserver.start();\n }\n }\n stop() {\n if (this.tokenListObserver) {\n this.disconnectAllTargets();\n this.tokenListObserver.stop();\n delete this.tokenListObserver;\n }\n }\n tokenMatched({ element, content: name }) {\n if (this.scope.containsElement(element)) {\n this.connectTarget(element, name);\n }\n }\n tokenUnmatched({ element, content: name }) {\n this.disconnectTarget(element, name);\n }\n connectTarget(element, name) {\n var _a;\n if (!this.targetsByName.has(name, element)) {\n this.targetsByName.add(name, element);\n (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetConnected(element, name));\n }\n }\n disconnectTarget(element, name) {\n var _a;\n if (this.targetsByName.has(name, element)) {\n this.targetsByName.delete(name, element);\n (_a = this.tokenListObserver) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.targetDisconnected(element, name));\n }\n }\n disconnectAllTargets() {\n for (const name of this.targetsByName.keys) {\n for (const element of this.targetsByName.getValuesForKey(name)) {\n this.disconnectTarget(element, name);\n }\n }\n }\n get attributeName() {\n return `data-${this.context.identifier}-target`;\n }\n get element() {\n return this.context.element;\n }\n get scope() {\n return this.context.scope;\n }\n}\n\nfunction readInheritableStaticArrayValues(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return Array.from(ancestors.reduce((values, constructor) => {\n getOwnStaticArrayValues(constructor, propertyName).forEach((name) => values.add(name));\n return values;\n }, new Set()));\n}\nfunction readInheritableStaticObjectPairs(constructor, propertyName) {\n const ancestors = getAncestorsForConstructor(constructor);\n return ancestors.reduce((pairs, constructor) => {\n pairs.push(...getOwnStaticObjectPairs(constructor, propertyName));\n return pairs;\n }, []);\n}\nfunction getAncestorsForConstructor(constructor) {\n const ancestors = [];\n while (constructor) {\n ancestors.push(constructor);\n constructor = Object.getPrototypeOf(constructor);\n }\n return ancestors.reverse();\n}\nfunction getOwnStaticArrayValues(constructor, propertyName) {\n const definition = constructor[propertyName];\n return Array.isArray(definition) ? definition : [];\n}\nfunction getOwnStaticObjectPairs(constructor, propertyName) {\n const definition = constructor[propertyName];\n return definition ? Object.keys(definition).map((key) => [key, definition[key]]) : [];\n}\n\nclass OutletObserver {\n constructor(context, delegate) {\n this.started = false;\n this.context = context;\n this.delegate = delegate;\n this.outletsByName = new Multimap();\n this.outletElementsByName = new Multimap();\n this.selectorObserverMap = new Map();\n this.attributeObserverMap = new Map();\n }\n start() {\n if (!this.started) {\n this.outletDefinitions.forEach((outletName) => {\n this.setupSelectorObserverForOutlet(outletName);\n this.setupAttributeObserverForOutlet(outletName);\n });\n this.started = true;\n this.dependentContexts.forEach((context) => context.refresh());\n }\n }\n refresh() {\n this.selectorObserverMap.forEach((observer) => observer.refresh());\n this.attributeObserverMap.forEach((observer) => observer.refresh());\n }\n stop() {\n if (this.started) {\n this.started = false;\n this.disconnectAllOutlets();\n this.stopSelectorObservers();\n this.stopAttributeObservers();\n }\n }\n stopSelectorObservers() {\n if (this.selectorObserverMap.size > 0) {\n this.selectorObserverMap.forEach((observer) => observer.stop());\n this.selectorObserverMap.clear();\n }\n }\n stopAttributeObservers() {\n if (this.attributeObserverMap.size > 0) {\n this.attributeObserverMap.forEach((observer) => observer.stop());\n this.attributeObserverMap.clear();\n }\n }\n selectorMatched(element, _selector, { outletName }) {\n const outlet = this.getOutlet(element, outletName);\n if (outlet) {\n this.connectOutlet(outlet, element, outletName);\n }\n }\n selectorUnmatched(element, _selector, { outletName }) {\n const outlet = this.getOutletFromMap(element, outletName);\n if (outlet) {\n this.disconnectOutlet(outlet, element, outletName);\n }\n }\n selectorMatchElement(element, { outletName }) {\n const selector = this.selector(outletName);\n const hasOutlet = this.hasOutlet(element, outletName);\n const hasOutletController = element.matches(`[${this.schema.controllerAttribute}~=${outletName}]`);\n if (selector) {\n return hasOutlet && hasOutletController && element.matches(selector);\n }\n else {\n return false;\n }\n }\n elementMatchedAttribute(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n elementAttributeValueChanged(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n elementUnmatchedAttribute(_element, attributeName) {\n const outletName = this.getOutletNameFromOutletAttributeName(attributeName);\n if (outletName) {\n this.updateSelectorObserverForOutlet(outletName);\n }\n }\n connectOutlet(outlet, element, outletName) {\n var _a;\n if (!this.outletElementsByName.has(outletName, element)) {\n this.outletsByName.add(outletName, outlet);\n this.outletElementsByName.add(outletName, element);\n (_a = this.selectorObserverMap.get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletConnected(outlet, element, outletName));\n }\n }\n disconnectOutlet(outlet, element, outletName) {\n var _a;\n if (this.outletElementsByName.has(outletName, element)) {\n this.outletsByName.delete(outletName, outlet);\n this.outletElementsByName.delete(outletName, element);\n (_a = this.selectorObserverMap\n .get(outletName)) === null || _a === void 0 ? void 0 : _a.pause(() => this.delegate.outletDisconnected(outlet, element, outletName));\n }\n }\n disconnectAllOutlets() {\n for (const outletName of this.outletElementsByName.keys) {\n for (const element of this.outletElementsByName.getValuesForKey(outletName)) {\n for (const outlet of this.outletsByName.getValuesForKey(outletName)) {\n this.disconnectOutlet(outlet, element, outletName);\n }\n }\n }\n }\n updateSelectorObserverForOutlet(outletName) {\n const observer = this.selectorObserverMap.get(outletName);\n if (observer) {\n observer.selector = this.selector(outletName);\n }\n }\n setupSelectorObserverForOutlet(outletName) {\n const selector = this.selector(outletName);\n const selectorObserver = new SelectorObserver(document.body, selector, this, { outletName });\n this.selectorObserverMap.set(outletName, selectorObserver);\n selectorObserver.start();\n }\n setupAttributeObserverForOutlet(outletName) {\n const attributeName = this.attributeNameForOutletName(outletName);\n const attributeObserver = new AttributeObserver(this.scope.element, attributeName, this);\n this.attributeObserverMap.set(outletName, attributeObserver);\n attributeObserver.start();\n }\n selector(outletName) {\n return this.scope.outlets.getSelectorForOutletName(outletName);\n }\n attributeNameForOutletName(outletName) {\n return this.scope.schema.outletAttributeForScope(this.identifier, outletName);\n }\n getOutletNameFromOutletAttributeName(attributeName) {\n return this.outletDefinitions.find((outletName) => this.attributeNameForOutletName(outletName) === attributeName);\n }\n get outletDependencies() {\n const dependencies = new Multimap();\n this.router.modules.forEach((module) => {\n const constructor = module.definition.controllerConstructor;\n const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n outlets.forEach((outlet) => dependencies.add(outlet, module.identifier));\n });\n return dependencies;\n }\n get outletDefinitions() {\n return this.outletDependencies.getKeysForValue(this.identifier);\n }\n get dependentControllerIdentifiers() {\n return this.outletDependencies.getValuesForKey(this.identifier);\n }\n get dependentContexts() {\n const identifiers = this.dependentControllerIdentifiers;\n return this.router.contexts.filter((context) => identifiers.includes(context.identifier));\n }\n hasOutlet(element, outletName) {\n return !!this.getOutlet(element, outletName) || !!this.getOutletFromMap(element, outletName);\n }\n getOutlet(element, outletName) {\n return this.application.getControllerForElementAndIdentifier(element, outletName);\n }\n getOutletFromMap(element, outletName) {\n return this.outletsByName.getValuesForKey(outletName).find((outlet) => outlet.element === element);\n }\n get scope() {\n return this.context.scope;\n }\n get schema() {\n return this.context.schema;\n }\n get identifier() {\n return this.context.identifier;\n }\n get application() {\n return this.context.application;\n }\n get router() {\n return this.application.router;\n }\n}\n\nclass Context {\n constructor(module, scope) {\n this.logDebugActivity = (functionName, detail = {}) => {\n const { identifier, controller, element } = this;\n detail = Object.assign({ identifier, controller, element }, detail);\n this.application.logDebugActivity(this.identifier, functionName, detail);\n };\n this.module = module;\n this.scope = scope;\n this.controller = new module.controllerConstructor(this);\n this.bindingObserver = new BindingObserver(this, this.dispatcher);\n this.valueObserver = new ValueObserver(this, this.controller);\n this.targetObserver = new TargetObserver(this, this);\n this.outletObserver = new OutletObserver(this, this);\n try {\n this.controller.initialize();\n this.logDebugActivity(\"initialize\");\n }\n catch (error) {\n this.handleError(error, \"initializing controller\");\n }\n }\n connect() {\n this.bindingObserver.start();\n this.valueObserver.start();\n this.targetObserver.start();\n this.outletObserver.start();\n try {\n this.controller.connect();\n this.logDebugActivity(\"connect\");\n }\n catch (error) {\n this.handleError(error, \"connecting controller\");\n }\n }\n refresh() {\n this.outletObserver.refresh();\n }\n disconnect() {\n try {\n this.controller.disconnect();\n this.logDebugActivity(\"disconnect\");\n }\n catch (error) {\n this.handleError(error, \"disconnecting controller\");\n }\n this.outletObserver.stop();\n this.targetObserver.stop();\n this.valueObserver.stop();\n this.bindingObserver.stop();\n }\n get application() {\n return this.module.application;\n }\n get identifier() {\n return this.module.identifier;\n }\n get schema() {\n return this.application.schema;\n }\n get dispatcher() {\n return this.application.dispatcher;\n }\n get element() {\n return this.scope.element;\n }\n get parentElement() {\n return this.element.parentElement;\n }\n handleError(error, message, detail = {}) {\n const { identifier, controller, element } = this;\n detail = Object.assign({ identifier, controller, element }, detail);\n this.application.handleError(error, `Error ${message}`, detail);\n }\n targetConnected(element, name) {\n this.invokeControllerMethod(`${name}TargetConnected`, element);\n }\n targetDisconnected(element, name) {\n this.invokeControllerMethod(`${name}TargetDisconnected`, element);\n }\n outletConnected(outlet, element, name) {\n this.invokeControllerMethod(`${namespaceCamelize(name)}OutletConnected`, outlet, element);\n }\n outletDisconnected(outlet, element, name) {\n this.invokeControllerMethod(`${namespaceCamelize(name)}OutletDisconnected`, outlet, element);\n }\n invokeControllerMethod(methodName, ...args) {\n const controller = this.controller;\n if (typeof controller[methodName] == \"function\") {\n controller[methodName](...args);\n }\n }\n}\n\nfunction bless(constructor) {\n return shadow(constructor, getBlessedProperties(constructor));\n}\nfunction shadow(constructor, properties) {\n const shadowConstructor = extend(constructor);\n const shadowProperties = getShadowProperties(constructor.prototype, properties);\n Object.defineProperties(shadowConstructor.prototype, shadowProperties);\n return shadowConstructor;\n}\nfunction getBlessedProperties(constructor) {\n const blessings = readInheritableStaticArrayValues(constructor, \"blessings\");\n return blessings.reduce((blessedProperties, blessing) => {\n const properties = blessing(constructor);\n for (const key in properties) {\n const descriptor = blessedProperties[key] || {};\n blessedProperties[key] = Object.assign(descriptor, properties[key]);\n }\n return blessedProperties;\n }, {});\n}\nfunction getShadowProperties(prototype, properties) {\n return getOwnKeys(properties).reduce((shadowProperties, key) => {\n const descriptor = getShadowedDescriptor(prototype, properties, key);\n if (descriptor) {\n Object.assign(shadowProperties, { [key]: descriptor });\n }\n return shadowProperties;\n }, {});\n}\nfunction getShadowedDescriptor(prototype, properties, key) {\n const shadowingDescriptor = Object.getOwnPropertyDescriptor(prototype, key);\n const shadowedByValue = shadowingDescriptor && \"value\" in shadowingDescriptor;\n if (!shadowedByValue) {\n const descriptor = Object.getOwnPropertyDescriptor(properties, key).value;\n if (shadowingDescriptor) {\n descriptor.get = shadowingDescriptor.get || descriptor.get;\n descriptor.set = shadowingDescriptor.set || descriptor.set;\n }\n return descriptor;\n }\n}\nconst getOwnKeys = (() => {\n if (typeof Object.getOwnPropertySymbols == \"function\") {\n return (object) => [...Object.getOwnPropertyNames(object), ...Object.getOwnPropertySymbols(object)];\n }\n else {\n return Object.getOwnPropertyNames;\n }\n})();\nconst extend = (() => {\n function extendWithReflect(constructor) {\n function extended() {\n return Reflect.construct(constructor, arguments, new.target);\n }\n extended.prototype = Object.create(constructor.prototype, {\n constructor: { value: extended },\n });\n Reflect.setPrototypeOf(extended, constructor);\n return extended;\n }\n function testReflectExtension() {\n const a = function () {\n this.a.call(this);\n };\n const b = extendWithReflect(a);\n b.prototype.a = function () { };\n return new b();\n }\n try {\n testReflectExtension();\n return extendWithReflect;\n }\n catch (error) {\n return (constructor) => class extended extends constructor {\n };\n }\n})();\n\nfunction blessDefinition(definition) {\n return {\n identifier: definition.identifier,\n controllerConstructor: bless(definition.controllerConstructor),\n };\n}\n\nclass Module {\n constructor(application, definition) {\n this.application = application;\n this.definition = blessDefinition(definition);\n this.contextsByScope = new WeakMap();\n this.connectedContexts = new Set();\n }\n get identifier() {\n return this.definition.identifier;\n }\n get controllerConstructor() {\n return this.definition.controllerConstructor;\n }\n get contexts() {\n return Array.from(this.connectedContexts);\n }\n connectContextForScope(scope) {\n const context = this.fetchContextForScope(scope);\n this.connectedContexts.add(context);\n context.connect();\n }\n disconnectContextForScope(scope) {\n const context = this.contextsByScope.get(scope);\n if (context) {\n this.connectedContexts.delete(context);\n context.disconnect();\n }\n }\n fetchContextForScope(scope) {\n let context = this.contextsByScope.get(scope);\n if (!context) {\n context = new Context(this, scope);\n this.contextsByScope.set(scope, context);\n }\n return context;\n }\n}\n\nclass ClassMap {\n constructor(scope) {\n this.scope = scope;\n }\n has(name) {\n return this.data.has(this.getDataKey(name));\n }\n get(name) {\n return this.getAll(name)[0];\n }\n getAll(name) {\n const tokenString = this.data.get(this.getDataKey(name)) || \"\";\n return tokenize(tokenString);\n }\n getAttributeName(name) {\n return this.data.getAttributeNameForKey(this.getDataKey(name));\n }\n getDataKey(name) {\n return `${name}-class`;\n }\n get data() {\n return this.scope.data;\n }\n}\n\nclass DataMap {\n constructor(scope) {\n this.scope = scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get(key) {\n const name = this.getAttributeNameForKey(key);\n return this.element.getAttribute(name);\n }\n set(key, value) {\n const name = this.getAttributeNameForKey(key);\n this.element.setAttribute(name, value);\n return this.get(key);\n }\n has(key) {\n const name = this.getAttributeNameForKey(key);\n return this.element.hasAttribute(name);\n }\n delete(key) {\n if (this.has(key)) {\n const name = this.getAttributeNameForKey(key);\n this.element.removeAttribute(name);\n return true;\n }\n else {\n return false;\n }\n }\n getAttributeNameForKey(key) {\n return `data-${this.identifier}-${dasherize(key)}`;\n }\n}\n\nclass Guide {\n constructor(logger) {\n this.warnedKeysByObject = new WeakMap();\n this.logger = logger;\n }\n warn(object, key, message) {\n let warnedKeys = this.warnedKeysByObject.get(object);\n if (!warnedKeys) {\n warnedKeys = new Set();\n this.warnedKeysByObject.set(object, warnedKeys);\n }\n if (!warnedKeys.has(key)) {\n warnedKeys.add(key);\n this.logger.warn(message, object);\n }\n }\n}\n\nfunction attributeValueContainsToken(attributeName, token) {\n return `[${attributeName}~=\"${token}\"]`;\n}\n\nclass TargetSet {\n constructor(scope) {\n this.scope = scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get schema() {\n return this.scope.schema;\n }\n has(targetName) {\n return this.find(targetName) != null;\n }\n find(...targetNames) {\n return targetNames.reduce((target, targetName) => target || this.findTarget(targetName) || this.findLegacyTarget(targetName), undefined);\n }\n findAll(...targetNames) {\n return targetNames.reduce((targets, targetName) => [\n ...targets,\n ...this.findAllTargets(targetName),\n ...this.findAllLegacyTargets(targetName),\n ], []);\n }\n findTarget(targetName) {\n const selector = this.getSelectorForTargetName(targetName);\n return this.scope.findElement(selector);\n }\n findAllTargets(targetName) {\n const selector = this.getSelectorForTargetName(targetName);\n return this.scope.findAllElements(selector);\n }\n getSelectorForTargetName(targetName) {\n const attributeName = this.schema.targetAttributeForScope(this.identifier);\n return attributeValueContainsToken(attributeName, targetName);\n }\n findLegacyTarget(targetName) {\n const selector = this.getLegacySelectorForTargetName(targetName);\n return this.deprecate(this.scope.findElement(selector), targetName);\n }\n findAllLegacyTargets(targetName) {\n const selector = this.getLegacySelectorForTargetName(targetName);\n return this.scope.findAllElements(selector).map((element) => this.deprecate(element, targetName));\n }\n getLegacySelectorForTargetName(targetName) {\n const targetDescriptor = `${this.identifier}.${targetName}`;\n return attributeValueContainsToken(this.schema.targetAttribute, targetDescriptor);\n }\n deprecate(element, targetName) {\n if (element) {\n const { identifier } = this;\n const attributeName = this.schema.targetAttribute;\n const revisedAttributeName = this.schema.targetAttributeForScope(identifier);\n this.guide.warn(element, `target:${targetName}`, `Please replace ${attributeName}=\"${identifier}.${targetName}\" with ${revisedAttributeName}=\"${targetName}\". ` +\n `The ${attributeName} attribute is deprecated and will be removed in a future version of Stimulus.`);\n }\n return element;\n }\n get guide() {\n return this.scope.guide;\n }\n}\n\nclass OutletSet {\n constructor(scope, controllerElement) {\n this.scope = scope;\n this.controllerElement = controllerElement;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get schema() {\n return this.scope.schema;\n }\n has(outletName) {\n return this.find(outletName) != null;\n }\n find(...outletNames) {\n return outletNames.reduce((outlet, outletName) => outlet || this.findOutlet(outletName), undefined);\n }\n findAll(...outletNames) {\n return outletNames.reduce((outlets, outletName) => [...outlets, ...this.findAllOutlets(outletName)], []);\n }\n getSelectorForOutletName(outletName) {\n const attributeName = this.schema.outletAttributeForScope(this.identifier, outletName);\n return this.controllerElement.getAttribute(attributeName);\n }\n findOutlet(outletName) {\n const selector = this.getSelectorForOutletName(outletName);\n if (selector)\n return this.findElement(selector, outletName);\n }\n findAllOutlets(outletName) {\n const selector = this.getSelectorForOutletName(outletName);\n return selector ? this.findAllElements(selector, outletName) : [];\n }\n findElement(selector, outletName) {\n const elements = this.scope.queryElements(selector);\n return elements.filter((element) => this.matchesElement(element, selector, outletName))[0];\n }\n findAllElements(selector, outletName) {\n const elements = this.scope.queryElements(selector);\n return elements.filter((element) => this.matchesElement(element, selector, outletName));\n }\n matchesElement(element, selector, outletName) {\n const controllerAttribute = element.getAttribute(this.scope.schema.controllerAttribute) || \"\";\n return element.matches(selector) && controllerAttribute.split(\" \").includes(outletName);\n }\n}\n\nclass Scope {\n constructor(schema, element, identifier, logger) {\n this.targets = new TargetSet(this);\n this.classes = new ClassMap(this);\n this.data = new DataMap(this);\n this.containsElement = (element) => {\n return element.closest(this.controllerSelector) === this.element;\n };\n this.schema = schema;\n this.element = element;\n this.identifier = identifier;\n this.guide = new Guide(logger);\n this.outlets = new OutletSet(this.documentScope, element);\n }\n findElement(selector) {\n return this.element.matches(selector) ? this.element : this.queryElements(selector).find(this.containsElement);\n }\n findAllElements(selector) {\n return [\n ...(this.element.matches(selector) ? [this.element] : []),\n ...this.queryElements(selector).filter(this.containsElement),\n ];\n }\n queryElements(selector) {\n return Array.from(this.element.querySelectorAll(selector));\n }\n get controllerSelector() {\n return attributeValueContainsToken(this.schema.controllerAttribute, this.identifier);\n }\n get isDocumentScope() {\n return this.element === document.documentElement;\n }\n get documentScope() {\n return this.isDocumentScope\n ? this\n : new Scope(this.schema, document.documentElement, this.identifier, this.guide.logger);\n }\n}\n\nclass ScopeObserver {\n constructor(element, schema, delegate) {\n this.element = element;\n this.schema = schema;\n this.delegate = delegate;\n this.valueListObserver = new ValueListObserver(this.element, this.controllerAttribute, this);\n this.scopesByIdentifierByElement = new WeakMap();\n this.scopeReferenceCounts = new WeakMap();\n }\n start() {\n this.valueListObserver.start();\n }\n stop() {\n this.valueListObserver.stop();\n }\n get controllerAttribute() {\n return this.schema.controllerAttribute;\n }\n parseValueForToken(token) {\n const { element, content: identifier } = token;\n return this.parseValueForElementAndIdentifier(element, identifier);\n }\n parseValueForElementAndIdentifier(element, identifier) {\n const scopesByIdentifier = this.fetchScopesByIdentifierForElement(element);\n let scope = scopesByIdentifier.get(identifier);\n if (!scope) {\n scope = this.delegate.createScopeForElementAndIdentifier(element, identifier);\n scopesByIdentifier.set(identifier, scope);\n }\n return scope;\n }\n elementMatchedValue(element, value) {\n const referenceCount = (this.scopeReferenceCounts.get(value) || 0) + 1;\n this.scopeReferenceCounts.set(value, referenceCount);\n if (referenceCount == 1) {\n this.delegate.scopeConnected(value);\n }\n }\n elementUnmatchedValue(element, value) {\n const referenceCount = this.scopeReferenceCounts.get(value);\n if (referenceCount) {\n this.scopeReferenceCounts.set(value, referenceCount - 1);\n if (referenceCount == 1) {\n this.delegate.scopeDisconnected(value);\n }\n }\n }\n fetchScopesByIdentifierForElement(element) {\n let scopesByIdentifier = this.scopesByIdentifierByElement.get(element);\n if (!scopesByIdentifier) {\n scopesByIdentifier = new Map();\n this.scopesByIdentifierByElement.set(element, scopesByIdentifier);\n }\n return scopesByIdentifier;\n }\n}\n\nclass Router {\n constructor(application) {\n this.application = application;\n this.scopeObserver = new ScopeObserver(this.element, this.schema, this);\n this.scopesByIdentifier = new Multimap();\n this.modulesByIdentifier = new Map();\n }\n get element() {\n return this.application.element;\n }\n get schema() {\n return this.application.schema;\n }\n get logger() {\n return this.application.logger;\n }\n get controllerAttribute() {\n return this.schema.controllerAttribute;\n }\n get modules() {\n return Array.from(this.modulesByIdentifier.values());\n }\n get contexts() {\n return this.modules.reduce((contexts, module) => contexts.concat(module.contexts), []);\n }\n start() {\n this.scopeObserver.start();\n }\n stop() {\n this.scopeObserver.stop();\n }\n loadDefinition(definition) {\n this.unloadIdentifier(definition.identifier);\n const module = new Module(this.application, definition);\n this.connectModule(module);\n const afterLoad = definition.controllerConstructor.afterLoad;\n if (afterLoad) {\n afterLoad.call(definition.controllerConstructor, definition.identifier, this.application);\n }\n }\n unloadIdentifier(identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n this.disconnectModule(module);\n }\n }\n getContextForElementAndIdentifier(element, identifier) {\n const module = this.modulesByIdentifier.get(identifier);\n if (module) {\n return module.contexts.find((context) => context.element == element);\n }\n }\n proposeToConnectScopeForElementAndIdentifier(element, identifier) {\n const scope = this.scopeObserver.parseValueForElementAndIdentifier(element, identifier);\n if (scope) {\n this.scopeObserver.elementMatchedValue(scope.element, scope);\n }\n else {\n console.error(`Couldn't find or create scope for identifier: \"${identifier}\" and element:`, element);\n }\n }\n handleError(error, message, detail) {\n this.application.handleError(error, message, detail);\n }\n createScopeForElementAndIdentifier(element, identifier) {\n return new Scope(this.schema, element, identifier, this.logger);\n }\n scopeConnected(scope) {\n this.scopesByIdentifier.add(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.connectContextForScope(scope);\n }\n }\n scopeDisconnected(scope) {\n this.scopesByIdentifier.delete(scope.identifier, scope);\n const module = this.modulesByIdentifier.get(scope.identifier);\n if (module) {\n module.disconnectContextForScope(scope);\n }\n }\n connectModule(module) {\n this.modulesByIdentifier.set(module.identifier, module);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach((scope) => module.connectContextForScope(scope));\n }\n disconnectModule(module) {\n this.modulesByIdentifier.delete(module.identifier);\n const scopes = this.scopesByIdentifier.getValuesForKey(module.identifier);\n scopes.forEach((scope) => module.disconnectContextForScope(scope));\n }\n}\n\nconst defaultSchema = {\n controllerAttribute: \"data-controller\",\n actionAttribute: \"data-action\",\n targetAttribute: \"data-target\",\n targetAttributeForScope: (identifier) => `data-${identifier}-target`,\n outletAttributeForScope: (identifier, outlet) => `data-${identifier}-${outlet}-outlet`,\n keyMappings: Object.assign(Object.assign({ enter: \"Enter\", tab: \"Tab\", esc: \"Escape\", space: \" \", up: \"ArrowUp\", down: \"ArrowDown\", left: \"ArrowLeft\", right: \"ArrowRight\", home: \"Home\", end: \"End\", page_up: \"PageUp\", page_down: \"PageDown\" }, objectFromEntries(\"abcdefghijklmnopqrstuvwxyz\".split(\"\").map((c) => [c, c]))), objectFromEntries(\"0123456789\".split(\"\").map((n) => [n, n]))),\n};\nfunction objectFromEntries(array) {\n return array.reduce((memo, [k, v]) => (Object.assign(Object.assign({}, memo), { [k]: v })), {});\n}\n\nclass Application {\n constructor(element = document.documentElement, schema = defaultSchema) {\n this.logger = console;\n this.debug = false;\n this.logDebugActivity = (identifier, functionName, detail = {}) => {\n if (this.debug) {\n this.logFormattedMessage(identifier, functionName, detail);\n }\n };\n this.element = element;\n this.schema = schema;\n this.dispatcher = new Dispatcher(this);\n this.router = new Router(this);\n this.actionDescriptorFilters = Object.assign({}, defaultActionDescriptorFilters);\n }\n static start(element, schema) {\n const application = new this(element, schema);\n application.start();\n return application;\n }\n async start() {\n await domReady();\n this.logDebugActivity(\"application\", \"starting\");\n this.dispatcher.start();\n this.router.start();\n this.logDebugActivity(\"application\", \"start\");\n }\n stop() {\n this.logDebugActivity(\"application\", \"stopping\");\n this.dispatcher.stop();\n this.router.stop();\n this.logDebugActivity(\"application\", \"stop\");\n }\n register(identifier, controllerConstructor) {\n this.load({ identifier, controllerConstructor });\n }\n registerActionOption(name, filter) {\n this.actionDescriptorFilters[name] = filter;\n }\n load(head, ...rest) {\n const definitions = Array.isArray(head) ? head : [head, ...rest];\n definitions.forEach((definition) => {\n if (definition.controllerConstructor.shouldLoad) {\n this.router.loadDefinition(definition);\n }\n });\n }\n unload(head, ...rest) {\n const identifiers = Array.isArray(head) ? head : [head, ...rest];\n identifiers.forEach((identifier) => this.router.unloadIdentifier(identifier));\n }\n get controllers() {\n return this.router.contexts.map((context) => context.controller);\n }\n getControllerForElementAndIdentifier(element, identifier) {\n const context = this.router.getContextForElementAndIdentifier(element, identifier);\n return context ? context.controller : null;\n }\n handleError(error, message, detail) {\n var _a;\n this.logger.error(`%s\\n\\n%o\\n\\n%o`, message, error, detail);\n (_a = window.onerror) === null || _a === void 0 ? void 0 : _a.call(window, message, \"\", 0, 0, error);\n }\n logFormattedMessage(identifier, functionName, detail = {}) {\n detail = Object.assign({ application: this }, detail);\n this.logger.groupCollapsed(`${identifier} #${functionName}`);\n this.logger.log(\"details:\", Object.assign({}, detail));\n this.logger.groupEnd();\n }\n}\nfunction domReady() {\n return new Promise((resolve) => {\n if (document.readyState == \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", () => resolve());\n }\n else {\n resolve();\n }\n });\n}\n\nfunction ClassPropertiesBlessing(constructor) {\n const classes = readInheritableStaticArrayValues(constructor, \"classes\");\n return classes.reduce((properties, classDefinition) => {\n return Object.assign(properties, propertiesForClassDefinition(classDefinition));\n }, {});\n}\nfunction propertiesForClassDefinition(key) {\n return {\n [`${key}Class`]: {\n get() {\n const { classes } = this;\n if (classes.has(key)) {\n return classes.get(key);\n }\n else {\n const attribute = classes.getAttributeName(key);\n throw new Error(`Missing attribute \"${attribute}\"`);\n }\n },\n },\n [`${key}Classes`]: {\n get() {\n return this.classes.getAll(key);\n },\n },\n [`has${capitalize(key)}Class`]: {\n get() {\n return this.classes.has(key);\n },\n },\n };\n}\n\nfunction OutletPropertiesBlessing(constructor) {\n const outlets = readInheritableStaticArrayValues(constructor, \"outlets\");\n return outlets.reduce((properties, outletDefinition) => {\n return Object.assign(properties, propertiesForOutletDefinition(outletDefinition));\n }, {});\n}\nfunction getOutletController(controller, element, identifier) {\n return controller.application.getControllerForElementAndIdentifier(element, identifier);\n}\nfunction getControllerAndEnsureConnectedScope(controller, element, outletName) {\n let outletController = getOutletController(controller, element, outletName);\n if (outletController)\n return outletController;\n controller.application.router.proposeToConnectScopeForElementAndIdentifier(element, outletName);\n outletController = getOutletController(controller, element, outletName);\n if (outletController)\n return outletController;\n}\nfunction propertiesForOutletDefinition(name) {\n const camelizedName = namespaceCamelize(name);\n return {\n [`${camelizedName}Outlet`]: {\n get() {\n const outletElement = this.outlets.find(name);\n const selector = this.outlets.getSelectorForOutletName(name);\n if (outletElement) {\n const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n if (outletController)\n return outletController;\n throw new Error(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`);\n }\n throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n },\n },\n [`${camelizedName}Outlets`]: {\n get() {\n const outlets = this.outlets.findAll(name);\n if (outlets.length > 0) {\n return outlets\n .map((outletElement) => {\n const outletController = getControllerAndEnsureConnectedScope(this, outletElement, name);\n if (outletController)\n return outletController;\n console.warn(`The provided outlet element is missing an outlet controller \"${name}\" instance for host controller \"${this.identifier}\"`, outletElement);\n })\n .filter((controller) => controller);\n }\n return [];\n },\n },\n [`${camelizedName}OutletElement`]: {\n get() {\n const outletElement = this.outlets.find(name);\n const selector = this.outlets.getSelectorForOutletName(name);\n if (outletElement) {\n return outletElement;\n }\n else {\n throw new Error(`Missing outlet element \"${name}\" for host controller \"${this.identifier}\". Stimulus couldn't find a matching outlet element using selector \"${selector}\".`);\n }\n },\n },\n [`${camelizedName}OutletElements`]: {\n get() {\n return this.outlets.findAll(name);\n },\n },\n [`has${capitalize(camelizedName)}Outlet`]: {\n get() {\n return this.outlets.has(name);\n },\n },\n };\n}\n\nfunction TargetPropertiesBlessing(constructor) {\n const targets = readInheritableStaticArrayValues(constructor, \"targets\");\n return targets.reduce((properties, targetDefinition) => {\n return Object.assign(properties, propertiesForTargetDefinition(targetDefinition));\n }, {});\n}\nfunction propertiesForTargetDefinition(name) {\n return {\n [`${name}Target`]: {\n get() {\n const target = this.targets.find(name);\n if (target) {\n return target;\n }\n else {\n throw new Error(`Missing target element \"${name}\" for \"${this.identifier}\" controller`);\n }\n },\n },\n [`${name}Targets`]: {\n get() {\n return this.targets.findAll(name);\n },\n },\n [`has${capitalize(name)}Target`]: {\n get() {\n return this.targets.has(name);\n },\n },\n };\n}\n\nfunction ValuePropertiesBlessing(constructor) {\n const valueDefinitionPairs = readInheritableStaticObjectPairs(constructor, \"values\");\n const propertyDescriptorMap = {\n valueDescriptorMap: {\n get() {\n return valueDefinitionPairs.reduce((result, valueDefinitionPair) => {\n const valueDescriptor = parseValueDefinitionPair(valueDefinitionPair, this.identifier);\n const attributeName = this.data.getAttributeNameForKey(valueDescriptor.key);\n return Object.assign(result, { [attributeName]: valueDescriptor });\n }, {});\n },\n },\n };\n return valueDefinitionPairs.reduce((properties, valueDefinitionPair) => {\n return Object.assign(properties, propertiesForValueDefinitionPair(valueDefinitionPair));\n }, propertyDescriptorMap);\n}\nfunction propertiesForValueDefinitionPair(valueDefinitionPair, controller) {\n const definition = parseValueDefinitionPair(valueDefinitionPair, controller);\n const { key, name, reader: read, writer: write } = definition;\n return {\n [name]: {\n get() {\n const value = this.data.get(key);\n if (value !== null) {\n return read(value);\n }\n else {\n return definition.defaultValue;\n }\n },\n set(value) {\n if (value === undefined) {\n this.data.delete(key);\n }\n else {\n this.data.set(key, write(value));\n }\n },\n },\n [`has${capitalize(name)}`]: {\n get() {\n return this.data.has(key) || definition.hasCustomDefaultValue;\n },\n },\n };\n}\nfunction parseValueDefinitionPair([token, typeDefinition], controller) {\n return valueDescriptorForTokenAndTypeDefinition({\n controller,\n token,\n typeDefinition,\n });\n}\nfunction parseValueTypeConstant(constant) {\n switch (constant) {\n case Array:\n return \"array\";\n case Boolean:\n return \"boolean\";\n case Number:\n return \"number\";\n case Object:\n return \"object\";\n case String:\n return \"string\";\n }\n}\nfunction parseValueTypeDefault(defaultValue) {\n switch (typeof defaultValue) {\n case \"boolean\":\n return \"boolean\";\n case \"number\":\n return \"number\";\n case \"string\":\n return \"string\";\n }\n if (Array.isArray(defaultValue))\n return \"array\";\n if (Object.prototype.toString.call(defaultValue) === \"[object Object]\")\n return \"object\";\n}\nfunction parseValueTypeObject(payload) {\n const { controller, token, typeObject } = payload;\n const hasType = isSomething(typeObject.type);\n const hasDefault = isSomething(typeObject.default);\n const fullObject = hasType && hasDefault;\n const onlyType = hasType && !hasDefault;\n const onlyDefault = !hasType && hasDefault;\n const typeFromObject = parseValueTypeConstant(typeObject.type);\n const typeFromDefaultValue = parseValueTypeDefault(payload.typeObject.default);\n if (onlyType)\n return typeFromObject;\n if (onlyDefault)\n return typeFromDefaultValue;\n if (typeFromObject !== typeFromDefaultValue) {\n const propertyPath = controller ? `${controller}.${token}` : token;\n throw new Error(`The specified default value for the Stimulus Value \"${propertyPath}\" must match the defined type \"${typeFromObject}\". The provided default value of \"${typeObject.default}\" is of type \"${typeFromDefaultValue}\".`);\n }\n if (fullObject)\n return typeFromObject;\n}\nfunction parseValueTypeDefinition(payload) {\n const { controller, token, typeDefinition } = payload;\n const typeObject = { controller, token, typeObject: typeDefinition };\n const typeFromObject = parseValueTypeObject(typeObject);\n const typeFromDefaultValue = parseValueTypeDefault(typeDefinition);\n const typeFromConstant = parseValueTypeConstant(typeDefinition);\n const type = typeFromObject || typeFromDefaultValue || typeFromConstant;\n if (type)\n return type;\n const propertyPath = controller ? `${controller}.${typeDefinition}` : token;\n throw new Error(`Unknown value type \"${propertyPath}\" for \"${token}\" value`);\n}\nfunction defaultValueForDefinition(typeDefinition) {\n const constant = parseValueTypeConstant(typeDefinition);\n if (constant)\n return defaultValuesByType[constant];\n const hasDefault = hasProperty(typeDefinition, \"default\");\n const hasType = hasProperty(typeDefinition, \"type\");\n const typeObject = typeDefinition;\n if (hasDefault)\n return typeObject.default;\n if (hasType) {\n const { type } = typeObject;\n const constantFromType = parseValueTypeConstant(type);\n if (constantFromType)\n return defaultValuesByType[constantFromType];\n }\n return typeDefinition;\n}\nfunction valueDescriptorForTokenAndTypeDefinition(payload) {\n const { token, typeDefinition } = payload;\n const key = `${dasherize(token)}-value`;\n const type = parseValueTypeDefinition(payload);\n return {\n type,\n key,\n name: camelize(key),\n get defaultValue() {\n return defaultValueForDefinition(typeDefinition);\n },\n get hasCustomDefaultValue() {\n return parseValueTypeDefault(typeDefinition) !== undefined;\n },\n reader: readers[type],\n writer: writers[type] || writers.default,\n };\n}\nconst defaultValuesByType = {\n get array() {\n return [];\n },\n boolean: false,\n number: 0,\n get object() {\n return {};\n },\n string: \"\",\n};\nconst readers = {\n array(value) {\n const array = JSON.parse(value);\n if (!Array.isArray(array)) {\n throw new TypeError(`expected value of type \"array\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(array)}\"`);\n }\n return array;\n },\n boolean(value) {\n return !(value == \"0\" || String(value).toLowerCase() == \"false\");\n },\n number(value) {\n return Number(value.replace(/_/g, \"\"));\n },\n object(value) {\n const object = JSON.parse(value);\n if (object === null || typeof object != \"object\" || Array.isArray(object)) {\n throw new TypeError(`expected value of type \"object\" but instead got value \"${value}\" of type \"${parseValueTypeDefault(object)}\"`);\n }\n return object;\n },\n string(value) {\n return value;\n },\n};\nconst writers = {\n default: writeString,\n array: writeJSON,\n object: writeJSON,\n};\nfunction writeJSON(value) {\n return JSON.stringify(value);\n}\nfunction writeString(value) {\n return `${value}`;\n}\n\nclass Controller {\n constructor(context) {\n this.context = context;\n }\n static get shouldLoad() {\n return true;\n }\n static afterLoad(_identifier, _application) {\n return;\n }\n get application() {\n return this.context.application;\n }\n get scope() {\n return this.context.scope;\n }\n get element() {\n return this.scope.element;\n }\n get identifier() {\n return this.scope.identifier;\n }\n get targets() {\n return this.scope.targets;\n }\n get outlets() {\n return this.scope.outlets;\n }\n get classes() {\n return this.scope.classes;\n }\n get data() {\n return this.scope.data;\n }\n initialize() {\n }\n connect() {\n }\n disconnect() {\n }\n dispatch(eventName, { target = this.element, detail = {}, prefix = this.identifier, bubbles = true, cancelable = true, } = {}) {\n const type = prefix ? `${prefix}:${eventName}` : eventName;\n const event = new CustomEvent(type, { detail, bubbles, cancelable });\n target.dispatchEvent(event);\n return event;\n }\n}\nController.blessings = [\n ClassPropertiesBlessing,\n TargetPropertiesBlessing,\n ValuePropertiesBlessing,\n OutletPropertiesBlessing,\n];\nController.targets = [];\nController.outlets = [];\nController.values = {};\n\nexport { Application, AttributeObserver, Context, Controller, ElementObserver, IndexedMultimap, Multimap, SelectorObserver, StringMapObserver, TokenListObserver, ValueListObserver, add, defaultSchema, del, fetch, prune };\n", "import {\n isFunction,\n isPlainObject,\n isString,\n isNumber,\n} from '@segment/analytics-core'\nimport { Context } from '../context'\nimport {\n Callback,\n JSONObject,\n Options,\n EventProperties,\n SegmentEvent,\n Traits,\n GroupTraits,\n UserTraits,\n} from '../events'\nimport { ID, WithId } from '../user'\n\n/**\n * Helper for the track method\n */\nexport function resolveArguments(\n eventName: string | SegmentEvent,\n properties?: EventProperties | Callback,\n options?: Options | Callback,\n callback?: Callback\n): [string, EventProperties | Callback, Options, Callback | undefined] {\n const args = [eventName, properties, options, callback]\n\n const name = isPlainObject(eventName) ? eventName.event : eventName\n if (!name || !isString(name)) {\n throw new Error('Event missing')\n }\n\n const data = isPlainObject(eventName)\n ? eventName.properties ?? {}\n : isPlainObject(properties)\n ? properties\n : {}\n\n let opts: Options = {}\n if (!isFunction(options)) {\n opts = options ?? {}\n }\n\n if (isPlainObject(eventName) && !isFunction(properties)) {\n opts = properties ?? {}\n }\n\n const cb = args.find(isFunction) as Callback | undefined\n return [name, data, opts, cb]\n}\n\n/**\n * Helper for page, screen methods\n */\nexport function resolvePageArguments(\n category?: string | object,\n name?: string | object | Callback,\n properties?: EventProperties | Options | Callback | null,\n options?: Options | Callback,\n callback?: Callback\n): [\n string | null,\n string | null,\n EventProperties,\n Options,\n Callback | undefined\n] {\n let resolvedCategory: string | undefined | null = null\n let resolvedName: string | undefined | null = null\n const args = [category, name, properties, options, callback]\n\n const strings = args.filter(isString)\n if (strings[0] !== undefined && strings[1] !== undefined) {\n resolvedCategory = strings[0]\n resolvedName = strings[1]\n }\n\n if (strings.length === 1) {\n resolvedCategory = null\n resolvedName = strings[0]\n }\n\n const resolvedCallback = args.find(isFunction) as Callback | undefined\n\n const objects = args.filter((obj) => {\n if (resolvedName === null) {\n return isPlainObject(obj)\n }\n return isPlainObject(obj) || obj === null\n }) as Array\n\n const resolvedProperties = (objects[0] ?? {}) as EventProperties\n const resolvedOptions = (objects[1] ?? {}) as Options\n\n return [\n resolvedCategory,\n resolvedName,\n resolvedProperties,\n resolvedOptions,\n resolvedCallback,\n ]\n}\n\n/**\n * Helper for group, identify methods\n */\nexport const resolveUserArguments = (\n user: U\n): ResolveUser => {\n return (...args): ReturnType> => {\n const values: {\n id?: ID\n traits?: T | null\n options?: Options\n callback?: Callback\n } = {}\n // It's a stack so it's reversed so that we go through each of the expected arguments\n const orderStack: Array = [\n 'callback',\n 'options',\n 'traits',\n 'id',\n ]\n\n // Read each argument and eval the possible values here\n for (const arg of args) {\n let current = orderStack.pop()\n if (current === 'id') {\n if (isString(arg) || isNumber(arg)) {\n values.id = arg.toString()\n continue\n }\n if (arg === null || arg === undefined) {\n continue\n }\n // First argument should always be the id, if it is not a valid value we can skip it\n current = orderStack.pop()\n }\n\n // Traits and Options\n if (\n (current === 'traits' || current === 'options') &&\n (arg === null || arg === undefined || isPlainObject(arg))\n ) {\n values[current] = arg as T\n }\n\n // Callback\n if (isFunction(arg)) {\n values.callback = arg as Callback\n break // This is always the last argument\n }\n }\n\n return [\n values.id ?? user.id(),\n (values.traits ?? {}) as T,\n values.options ?? {},\n values.callback,\n ]\n }\n}\n\n/**\n * Helper for alias method\n */\nexport function resolveAliasArguments(\n to: string | number,\n from?: string | number | Options,\n options?: Options | Callback,\n callback?: Callback\n): [string, string | null, Options, Callback | undefined] {\n if (isNumber(to)) to = to.toString() // Legacy behaviour - allow integers for alias calls\n if (isNumber(from)) from = from.toString()\n const args = [to, from, options, callback]\n\n const [aliasTo = to, aliasFrom = null] = args.filter(isString)\n const [opts = {}] = args.filter(isPlainObject)\n const resolvedCallback = args.find(isFunction) as Callback | undefined\n\n return [aliasTo, aliasFrom, opts, resolvedCallback]\n}\n\ntype ResolveUser = (\n id?: ID | object,\n traits?: T | Callback | null,\n options?: Options | Callback,\n callback?: Callback\n) => [ID, T, Options, Callback | undefined]\n\nexport type IdentifyParams = Parameters>\nexport type GroupParams = Parameters>\nexport type EventParams = Parameters\nexport type PageParams = Parameters\nexport type AliasParams = Parameters\n\nexport type DispatchedEvent = Context\n", "import { v4 as uuid } from '@lukeed/uuid'\nimport { ID, User } from '../user'\nimport {\n Options,\n Integrations,\n EventProperties,\n Traits,\n SegmentEvent,\n} from './interfaces'\nimport { addPageContext, PageContext } from '../page'\nimport { CoreEventFactory } from '@segment/analytics-core'\n\nexport * from './interfaces'\n\nexport class EventFactory extends CoreEventFactory {\n user: User\n constructor(user: User) {\n super({\n createMessageId: () => `ajs-next-${Date.now()}-${uuid()}`,\n onEventMethodCall: ({ options }) => {\n this.maybeUpdateAnonId(options)\n },\n onFinishedEvent: (event) => {\n this.addIdentity(event)\n return event\n },\n })\n this.user = user\n }\n\n /**\n * Updates the anonymousId *globally* if it's provided in the options.\n * This should generally be done in the identify method, but some customers rely on this.\n */\n private maybeUpdateAnonId(options: Options | undefined): void {\n options?.anonymousId && this.user.anonymousId(options.anonymousId)\n }\n\n /**\n * add user id / anonymous id to the event\n */\n private addIdentity(event: SegmentEvent) {\n if (this.user.id()) {\n event.userId = this.user.id()\n }\n\n if (this.user.anonymousId()) {\n event.anonymousId = this.user.anonymousId()\n }\n }\n\n override track(\n event: string,\n properties?: EventProperties,\n options?: Options,\n globalIntegrations?: Integrations,\n pageCtx?: PageContext\n ): SegmentEvent {\n const ev = super.track(event, properties, options, globalIntegrations)\n addPageContext(ev, pageCtx)\n return ev\n }\n\n override page(\n category: string | null,\n page: string | null,\n properties?: EventProperties,\n options?: Options,\n globalIntegrations?: Integrations,\n pageCtx?: PageContext\n ): SegmentEvent {\n const ev = super.page(\n category,\n page,\n properties,\n options,\n globalIntegrations\n )\n addPageContext(ev, pageCtx)\n return ev\n }\n\n override screen(\n category: string | null,\n screen: string | null,\n properties?: EventProperties,\n options?: Options,\n globalIntegrations?: Integrations,\n pageCtx?: PageContext\n ): SegmentEvent {\n const ev = super.screen(\n category,\n screen,\n properties,\n options,\n globalIntegrations\n )\n addPageContext(ev, pageCtx)\n return ev\n }\n\n override identify(\n userId: ID,\n traits?: Traits,\n options?: Options,\n globalIntegrations?: Integrations,\n pageCtx?: PageContext\n ): SegmentEvent {\n const ev = super.identify(userId, traits, options, globalIntegrations)\n addPageContext(ev, pageCtx)\n return ev\n }\n\n override group(\n groupId: ID,\n traits?: Traits,\n options?: Options,\n globalIntegrations?: Integrations,\n pageCtx?: PageContext\n ): SegmentEvent {\n const ev = super.group(groupId, traits, options, globalIntegrations)\n addPageContext(ev, pageCtx)\n return ev\n }\n\n override alias(\n to: string,\n from: string | null,\n options?: Options,\n globalIntegrations?: Integrations,\n pageCtx?: PageContext\n ): SegmentEvent {\n const ev = super.alias(to, from, options, globalIntegrations)\n addPageContext(ev, pageCtx)\n return ev\n }\n}\n", "import { isPlainObject } from '@segment/analytics-core'\n\n/**\n * Final Page Context object expected in the Segment Event context\n */\nexport interface PageContext {\n path: string\n referrer: string\n search: string\n title: string\n url: string\n}\n\ntype CanonicalUrl = string | undefined\n\nexport const BufferedPageContextDiscriminant = 'bpc' as const\n/**\n * Page Context expected to be built by the snippet.\n * Note: The key names are super short because we want to keep the strings in the html snippet short to save bytes.\n */\nexport interface BufferedPageContext {\n __t: typeof BufferedPageContextDiscriminant // for extra uniqeness\n c: CanonicalUrl\n p: PageContext['path']\n u: PageContext['url']\n s: PageContext['search']\n t: PageContext['title']\n r: PageContext['referrer']\n}\n\n/**\n * `BufferedPageContext` object builder\n */\nexport const createBufferedPageContext = (\n url: string,\n canonicalUrl: CanonicalUrl,\n search: string,\n path: string,\n title: string,\n referrer: string\n): BufferedPageContext => ({\n __t: BufferedPageContextDiscriminant,\n c: canonicalUrl,\n p: path,\n u: url,\n s: search,\n t: title,\n r: referrer,\n})\n\n// my clever/dubious way of making sure this type guard does not get out sync with the type definition\nconst BUFFERED_PAGE_CONTEXT_KEYS = Object.keys(\n createBufferedPageContext('', '', '', '', '', '')\n) as (keyof BufferedPageContext)[]\n\nexport function isBufferedPageContext(\n bufferedPageCtx: unknown\n): bufferedPageCtx is BufferedPageContext {\n if (!isPlainObject(bufferedPageCtx)) return false\n if (bufferedPageCtx.__t !== BufferedPageContextDiscriminant) return false\n\n // ensure obj has all the keys we expect, and none we don't.\n for (const k in bufferedPageCtx) {\n if (!BUFFERED_PAGE_CONTEXT_KEYS.includes(k as keyof BufferedPageContext)) {\n return false\n }\n }\n return true\n}\n\n// Legacy logic: we are we appending search parameters to the canonical URL -- I guess the canonical URL is \"not canonical enough\" (lol)\nconst createCanonicalURL = (canonicalUrl: string, searchParams: string) => {\n return canonicalUrl.indexOf('?') > -1\n ? canonicalUrl\n : canonicalUrl + searchParams\n}\n\n/**\n * Strips hash from URL.\n * http://www.segment.local#test -> http://www.segment.local\n */\nconst removeHash = (href: string) => {\n const hashIdx = href.indexOf('#')\n return hashIdx === -1 ? href : href.slice(0, hashIdx)\n}\n\nconst parseCanonicalPath = (canonicalUrl: string): string => {\n try {\n return new URL(canonicalUrl).pathname\n } catch (_e) {\n // this is classic behavior -- we assume that if the canonical URL is invalid, it's a raw path.\n return canonicalUrl[0] === '/' ? canonicalUrl : '/' + canonicalUrl\n }\n}\n\n/**\n * Create a `PageContext` from a `BufferedPageContext`.\n * `BufferedPageContext` keys are minified to save bytes in the snippet.\n */\nexport const createPageContext = ({\n c: canonicalUrl,\n p: pathname,\n s: search,\n u: url,\n r: referrer,\n t: title,\n}: BufferedPageContext): PageContext => {\n const newPath = canonicalUrl ? parseCanonicalPath(canonicalUrl) : pathname\n const newUrl = canonicalUrl\n ? createCanonicalURL(canonicalUrl, search)\n : removeHash(url)\n return {\n path: newPath,\n referrer,\n search,\n title,\n url: newUrl,\n }\n}\n\n/**\n * Get page properties from the browser window/document.\n */\nexport const getDefaultBufferedPageContext = (): BufferedPageContext => {\n const c = document.querySelector(\"link[rel='canonical']\")\n return createBufferedPageContext(\n location.href,\n (c && c.getAttribute('href')) || undefined,\n location.search,\n location.pathname,\n document.title,\n document.referrer\n )\n}\n\n/**\n * Get page properties from the browser window/document.\n */\nexport const getDefaultPageContext = (): PageContext =>\n createPageContext(getDefaultBufferedPageContext())\n", "export function pick, K extends keyof T>(\n object: T,\n keys: readonly K[]\n): Pick\n\nexport function pick>(\n object: T,\n keys: string[]\n): Partial\n\n/**\n * @example\n * pick({ 'a': 1, 'b': '2', 'c': 3 }, ['a', 'c'])\n * => { 'a': 1, 'c': 3 }\n */\nexport function pick, K extends keyof T>(\n object: T,\n keys: string[] | K[] | readonly K[]\n) {\n return Object.assign(\n {},\n ...keys.map((key) => {\n if (object && Object.prototype.hasOwnProperty.call(object, key)) {\n return { [key]: object[key] }\n }\n })\n )\n}\n", "import type { CorePlugin } from '@segment/analytics-core'\nimport type { DestinationMiddlewareFunction } from '../../plugins/middleware'\nimport type { Analytics } from '../analytics'\nimport type { Context } from '../context'\n\nexport interface Plugin extends CorePlugin {}\n\nexport interface InternalPluginWithAddMiddleware extends Plugin {\n addMiddleware: (...fns: DestinationMiddlewareFunction[]) => void\n}\n\nexport interface InternalDestinationPluginWithAddMiddleware\n extends InternalPluginWithAddMiddleware {\n type: 'destination'\n}\n\nexport const isDestinationPluginWithAddMiddleware = (\n plugin: Plugin\n): plugin is InternalDestinationPluginWithAddMiddleware => {\n // FYI: segment's plugin does not currently have an 'addMiddleware' method\n return 'addMiddleware' in plugin && plugin.type === 'destination'\n}\n", "import { PriorityQueue } from '../../lib/priority-queue'\nimport { PersistedPriorityQueue } from '../../lib/priority-queue/persisted'\nimport { Context } from '../context'\nimport { Plugin } from '../plugin'\nimport { CoreEventQueue } from '@segment/analytics-core'\nimport { isOffline } from '../connection'\n\nexport class EventQueue extends CoreEventQueue {\n constructor(name: string)\n constructor(priorityQueue: PriorityQueue)\n constructor(nameOrQueue: string | PriorityQueue) {\n super(\n typeof nameOrQueue === 'string'\n ? new PersistedPriorityQueue(4, nameOrQueue)\n : nameOrQueue\n )\n }\n async flush(): Promise {\n if (isOffline()) return []\n return super.flush()\n }\n}\n", "import { v4 as uuid } from '@lukeed/uuid'\nimport autoBind from '../../lib/bind-all'\nimport { Traits } from '../events'\nimport {\n CookieOptions,\n UniversalStorage,\n MemoryStorage,\n StorageObject,\n StorageSettings,\n StoreType,\n applyCookieOptions,\n initializeStorages,\n isArrayOfStoreType,\n} from '../storage'\n\nexport type ID = string | null | undefined\n\nexport interface UserOptions {\n /**\n * Disables storing any data about the user.\n */\n disable?: boolean\n localStorageFallbackDisabled?: boolean\n persist?: boolean\n\n cookie?: {\n key?: string\n oldKey?: string\n }\n\n localStorage?: {\n key: string\n }\n\n /**\n * Store priority\n * @example stores: [StoreType.Cookie, StoreType.Memory]\n */\n storage?: StorageSettings\n}\n\nconst defaults = {\n persist: true,\n cookie: {\n key: 'ajs_user_id',\n oldKey: 'ajs_user',\n },\n localStorage: {\n key: 'ajs_user_traits',\n },\n}\n\nexport interface WithId {\n id(id?: ID): ID\n}\n\nexport class User implements WithId {\n static defaults = defaults\n\n private idKey: string\n private traitsKey: string\n private anonKey: string\n private cookieOptions?: CookieOptions\n\n private legacyUserStore: UniversalStorage<{\n [k: string]:\n | {\n id?: string\n traits?: Traits\n }\n | string\n }>\n private traitsStore: UniversalStorage<{\n [k: string]: Traits\n }>\n\n private identityStore: UniversalStorage<{\n [k: string]: string\n }>\n\n options: UserOptions = {}\n\n constructor(options: UserOptions = defaults, cookieOptions?: CookieOptions) {\n this.options = { ...defaults, ...options }\n this.cookieOptions = cookieOptions\n\n this.idKey = options.cookie?.key ?? defaults.cookie.key\n this.traitsKey = options.localStorage?.key ?? defaults.localStorage.key\n this.anonKey = 'ajs_anonymous_id'\n\n this.identityStore = this.createStorage(this.options, cookieOptions)\n\n // using only cookies for legacy user store\n this.legacyUserStore = this.createStorage(\n this.options,\n cookieOptions,\n (s) => s === StoreType.Cookie\n )\n\n // using only localStorage / memory for traits store\n this.traitsStore = this.createStorage(\n this.options,\n cookieOptions,\n (s) => s !== StoreType.Cookie\n )\n\n const legacyUser = this.legacyUserStore.get(defaults.cookie.oldKey)\n if (legacyUser && typeof legacyUser === 'object') {\n legacyUser.id && this.id(legacyUser.id)\n legacyUser.traits && this.traits(legacyUser.traits)\n }\n autoBind(this)\n }\n\n id = (id?: ID): ID => {\n if (this.options.disable) {\n return null\n }\n\n const prevId = this.identityStore.getAndSync(this.idKey)\n\n if (id !== undefined) {\n this.identityStore.set(this.idKey, id)\n\n const changingIdentity = id !== prevId && prevId !== null && id !== null\n if (changingIdentity) {\n this.anonymousId(null)\n }\n }\n\n const retId = this.identityStore.getAndSync(this.idKey)\n if (retId) return retId\n\n const retLeg = this.legacyUserStore.get(defaults.cookie.oldKey)\n return retLeg ? (typeof retLeg === 'object' ? retLeg.id : retLeg) : null\n }\n\n private legacySIO(): [string, string] | null {\n const val = this.legacyUserStore.get('_sio') as string\n if (!val) {\n return null\n }\n const [anon, user] = val.split('----')\n return [anon, user]\n }\n\n anonymousId = (id?: ID): ID => {\n if (this.options.disable) {\n return null\n }\n\n if (id === undefined) {\n const val =\n this.identityStore.getAndSync(this.anonKey) ?? this.legacySIO()?.[0]\n\n if (val) {\n return val\n }\n }\n\n if (id === null) {\n this.identityStore.set(this.anonKey, null)\n return this.identityStore.getAndSync(this.anonKey)\n }\n\n this.identityStore.set(this.anonKey, id ?? uuid())\n return this.identityStore.getAndSync(this.anonKey)\n }\n\n traits = (traits?: Traits | null): Traits | undefined => {\n if (this.options.disable) {\n return\n }\n\n if (traits === null) {\n traits = {}\n }\n\n if (traits) {\n this.traitsStore.set(this.traitsKey, traits ?? {})\n }\n\n return this.traitsStore.get(this.traitsKey) ?? {}\n }\n\n identify(id?: ID, traits?: Traits): void {\n if (this.options.disable) {\n return\n }\n\n traits = traits ?? {}\n const currentId = this.id()\n\n if (currentId === null || currentId === id) {\n traits = {\n ...this.traits(),\n ...traits,\n }\n }\n\n if (id) {\n this.id(id)\n }\n\n this.traits(traits)\n }\n\n logout(): void {\n this.anonymousId(null)\n this.id(null)\n this.traits({})\n }\n\n reset(): void {\n this.logout()\n this.identityStore.clear(this.idKey)\n this.identityStore.clear(this.anonKey)\n this.traitsStore.clear(this.traitsKey)\n }\n\n load(): User {\n return new User(this.options, this.cookieOptions)\n }\n\n save(): boolean {\n return true\n }\n\n /**\n * Creates the right storage system applying all the user options, cookie options and particular filters\n * @param options UserOptions\n * @param cookieOpts CookieOptions\n * @param filterStores filter function to apply to any StoreTypes (skipped if options specify using a custom storage)\n * @returns a Storage object\n */\n private createStorage(\n options: UserOptions,\n cookieOpts?: CookieOptions,\n filterStores?: (value: StoreType) => boolean\n ): UniversalStorage {\n let stores: StoreType[] = [\n StoreType.LocalStorage,\n StoreType.Cookie,\n StoreType.Memory,\n ]\n\n // If disabled we won't have any storage functionality\n if (options.disable) {\n return new UniversalStorage([])\n }\n\n // If persistance is disabled we will always fallback to Memory Storage\n if (!options.persist) {\n return new UniversalStorage([new MemoryStorage()])\n }\n\n if (options.storage !== undefined && options.storage !== null) {\n if (isArrayOfStoreType(options.storage)) {\n // If the user only specified order of stores we will still apply filters and transformations e.g. not using localStorage if localStorageFallbackDisabled\n stores = options.storage.stores\n }\n }\n\n // Disable LocalStorage\n if (options.localStorageFallbackDisabled) {\n stores = stores.filter((s) => s !== StoreType.LocalStorage)\n }\n\n // Apply Additional filters\n if (filterStores) {\n stores = stores.filter(filterStores)\n }\n\n return new UniversalStorage(\n initializeStorages(applyCookieOptions(stores, cookieOpts))\n )\n }\n}\n\nconst groupDefaults: UserOptions = {\n persist: true,\n cookie: {\n key: 'ajs_group_id',\n },\n localStorage: {\n key: 'ajs_group_properties',\n },\n}\n\nexport class Group extends User {\n constructor(options: UserOptions = groupDefaults, cookie?: CookieOptions) {\n super({ ...groupDefaults, ...options }, cookie)\n autoBind(this)\n }\n\n anonymousId = (_id?: ID): ID => {\n return undefined\n }\n}\n", "export default function bindAll<\n ObjType extends { [key: string]: any },\n KeyType extends keyof ObjType\n>(obj: ObjType): ObjType {\n const proto = obj.constructor.prototype\n for (const key of Object.getOwnPropertyNames(proto)) {\n if (key !== 'constructor') {\n const desc = Object.getOwnPropertyDescriptor(\n obj.constructor.prototype,\n key\n )\n if (!!desc && typeof desc.value === 'function') {\n obj[key as KeyType] = obj[key].bind(obj)\n }\n }\n }\n\n return obj\n}\n", "/*! js-cookie v3.0.1 | MIT */\n/* eslint-disable no-var */\nfunction assign (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n for (var key in source) {\n target[key] = source[key];\n }\n }\n return target\n}\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\nvar defaultConverter = {\n read: function (value) {\n if (value[0] === '\"') {\n value = value.slice(1, -1);\n }\n return value.replace(/(%[\\dA-F]{2})+/gi, decodeURIComponent)\n },\n write: function (value) {\n return encodeURIComponent(value).replace(\n /%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,\n decodeURIComponent\n )\n }\n};\n/* eslint-enable no-var */\n\n/* eslint-disable no-var */\n\nfunction init (converter, defaultAttributes) {\n function set (key, value, attributes) {\n if (typeof document === 'undefined') {\n return\n }\n\n attributes = assign({}, defaultAttributes, attributes);\n\n if (typeof attributes.expires === 'number') {\n attributes.expires = new Date(Date.now() + attributes.expires * 864e5);\n }\n if (attributes.expires) {\n attributes.expires = attributes.expires.toUTCString();\n }\n\n key = encodeURIComponent(key)\n .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)\n .replace(/[()]/g, escape);\n\n var stringifiedAttributes = '';\n for (var attributeName in attributes) {\n if (!attributes[attributeName]) {\n continue\n }\n\n stringifiedAttributes += '; ' + attributeName;\n\n if (attributes[attributeName] === true) {\n continue\n }\n\n // Considers RFC 6265 section 5.2:\n // ...\n // 3. If the remaining unparsed-attributes contains a %x3B (\";\")\n // character:\n // Consume the characters of the unparsed-attributes up to,\n // not including, the first %x3B (\";\") character.\n // ...\n stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];\n }\n\n return (document.cookie =\n key + '=' + converter.write(value, key) + stringifiedAttributes)\n }\n\n function get (key) {\n if (typeof document === 'undefined' || (arguments.length && !key)) {\n return\n }\n\n // To prevent the for loop in the first place assign an empty array\n // in case there are no cookies at all.\n var cookies = document.cookie ? document.cookie.split('; ') : [];\n var jar = {};\n for (var i = 0; i < cookies.length; i++) {\n var parts = cookies[i].split('=');\n var value = parts.slice(1).join('=');\n\n try {\n var foundKey = decodeURIComponent(parts[0]);\n jar[foundKey] = converter.read(value, foundKey);\n\n if (key === foundKey) {\n break\n }\n } catch (e) {}\n }\n\n return key ? jar[key] : jar\n }\n\n return Object.create(\n {\n set: set,\n get: get,\n remove: function (key, attributes) {\n set(\n key,\n '',\n assign({}, attributes, {\n expires: -1\n })\n );\n },\n withAttributes: function (attributes) {\n return init(this.converter, assign({}, this.attributes, attributes))\n },\n withConverter: function (converter) {\n return init(assign({}, this.converter, converter), this.attributes)\n }\n },\n {\n attributes: { value: Object.freeze(defaultAttributes) },\n converter: { value: Object.freeze(converter) }\n }\n )\n}\n\nvar api = init(defaultConverter, { path: '/' });\n/* eslint-enable no-var */\n\nexport default api;\n", "import cookie from 'js-cookie'\n\n/**\n * Levels returns all levels of the given url.\n *\n * @param {string} url\n * @return {Array}\n * @api public\n */\nfunction levels(url: URL): string[] {\n const host = url.hostname\n const parts = host.split('.')\n const last = parts[parts.length - 1]\n const levels: string[] = []\n\n // Ip address.\n if (parts.length === 4 && parseInt(last, 10) > 0) {\n return levels\n }\n\n // Localhost.\n if (parts.length <= 1) {\n return levels\n }\n\n // Create levels.\n for (let i = parts.length - 2; i >= 0; --i) {\n levels.push(parts.slice(i).join('.'))\n }\n\n return levels\n}\n\nfunction parseUrl(url: string): URL | undefined {\n try {\n return new URL(url)\n } catch {\n return\n }\n}\n\nexport function tld(url: string): string | undefined {\n const parsedUrl = parseUrl(url)\n if (!parsedUrl) return\n\n const lvls = levels(parsedUrl)\n\n // Lookup the real top level one.\n for (let i = 0; i < lvls.length; ++i) {\n const cname = '__tld__'\n const domain = lvls[i]\n const opts = { domain: '.' + domain }\n\n try {\n // cookie access throw an error if the library is ran inside a sandboxed environment (e.g. sandboxed iframe)\n cookie.set(cname, '1', opts)\n if (cookie.get(cname)) {\n cookie.remove(cname, opts)\n return domain\n }\n } catch (_) {\n return\n }\n }\n}\n", "import { StorageObject, Store } from './types'\n\n/**\n * Data storage using browser's localStorage\n */\nexport class LocalStorage\n implements Store\n{\n private localStorageWarning(key: keyof Data, state: 'full' | 'unavailable') {\n console.warn(`Unable to access ${key}, localStorage may be ${state}`)\n }\n\n get(key: K): Data[K] | null {\n try {\n const val = localStorage.getItem(key)\n if (val === null) {\n return null\n }\n try {\n return JSON.parse(val) ?? null\n } catch (e) {\n return (val ?? null) as unknown as Data[K] | null\n }\n } catch (err) {\n this.localStorageWarning(key, 'unavailable')\n return null\n }\n }\n\n set(key: K, value: Data[K] | null): void {\n try {\n localStorage.setItem(key, JSON.stringify(value))\n } catch {\n this.localStorageWarning(key, 'full')\n }\n }\n\n remove(key: K): void {\n try {\n return localStorage.removeItem(key)\n } catch (err) {\n this.localStorageWarning(key, 'unavailable')\n }\n }\n}\n", "import { Store, StorageObject } from './types'\n\n/**\n * Data Storage using in memory object\n */\nexport class MemoryStorage\n implements Store\n{\n private cache: Record = {}\n\n get(key: K): Data[K] | null {\n return (this.cache[key] ?? null) as Data[K] | null\n }\n\n set(key: K, value: Data[K] | null): void {\n this.cache[key] = value\n }\n\n remove(key: K): void {\n delete this.cache[key]\n }\n}\n", "import { CookieOptions } from './cookieStorage'\n\nexport const StoreType = {\n Cookie: 'cookie',\n LocalStorage: 'localStorage',\n Memory: 'memory',\n} as const\n\n/**\n * Known Storage Types\n *\n * Convenience settings for storage systems that AJS includes support for\n */\nexport type StoreType = typeof StoreType[keyof typeof StoreType]\n\nexport type StorageObject = Record\n\n/**\n * Defines a Storage object for use in AJS Client.\n */\nexport interface Store {\n /**\n * get value for the key from the stores. it will return the first value found in the stores\n * @param key key for the value to be retrieved\n * @returns value for the key or null if not found\n */\n get(key: K): Data[K] | null\n\n /**\n * it will set the value for the key in all the stores\n * @param key key for the value to be stored\n * @param value value to be stored\n * @returns value that was stored\n */\n set(key: K, value: Data[K] | null): void\n /**\n * remove the value for the key from all the stores\n * @param key key for the value to be removed\n * @param storeTypes optional array of store types to be used for removing the value\n */\n remove(key: K): void\n}\n\nexport interface StoreTypeWithSettings {\n name: T\n settings?: T extends 'cookie' ? CookieOptions : never\n}\n\nexport type InitializeStorageArgs = (StoreTypeWithSettings | StoreType)[]\n", "import { StoreType, StoreTypeWithSettings } from './types'\n\nexport type UniversalStorageSettings = { stores: StoreType[] }\n\n// This is setup this way to permit eventually a different set of settings for custom storage\nexport type StorageSettings = UniversalStorageSettings\n\nexport function isArrayOfStoreType(\n s: StorageSettings\n): s is UniversalStorageSettings {\n return (\n s &&\n s.stores &&\n Array.isArray(s.stores) &&\n s.stores.every((e) => Object.values(StoreType).includes(e))\n )\n}\n\nexport function isStoreTypeWithSettings(\n s: StoreTypeWithSettings | StoreType\n): s is StoreTypeWithSettings {\n return typeof s === 'object' && s.name !== undefined\n}\n", "import { Store, StorageObject } from './types'\n\n// not adding to private method because those method names do not get minified atm, and does not use 'this'\nconst _logStoreKeyError = (\n store: Store,\n action: 'set' | 'get' | 'remove',\n key: string,\n err: unknown\n) => {\n console.warn(\n `${store.constructor.name}: Can't ${action} key \"${key}\" | Err: ${err}`\n )\n}\n\n/**\n * Uses multiple storages in a priority list to get/set values in the order they are specified.\n */\nexport class UniversalStorage {\n private stores: Store[]\n\n constructor(stores: Store[]) {\n this.stores = stores\n }\n\n get(key: K): Data[K] | null {\n let val: Data[K] | null = null\n\n for (const store of this.stores) {\n try {\n val = store.get(key) as Data[K] | null\n if (val !== undefined && val !== null) {\n return val\n }\n } catch (e) {\n _logStoreKeyError(store, 'get', key, e)\n }\n }\n return null\n }\n\n set(key: K, value: Data[K] | null): void {\n this.stores.forEach((store) => {\n try {\n store.set(key, value)\n } catch (e) {\n _logStoreKeyError(store, 'set', key, e)\n }\n })\n }\n\n clear(key: K): void {\n this.stores.forEach((store) => {\n try {\n store.remove(key)\n } catch (e) {\n _logStoreKeyError(store, 'remove', key, e)\n }\n })\n }\n\n /*\n This is to support few scenarios where:\n - value exist in one of the stores ( as a result of other stores being cleared from browser ) and we want to resync them\n - read values in AJS 1.0 format ( for customers after 1.0 --> 2.0 migration ) and then re-write them in AJS 2.0 format\n */\n getAndSync(key: K): Data[K] | null {\n const val = this.get(key)\n\n // legacy behavior, getAndSync can change the type of a value from number to string (AJS 1.0 stores numerical values as a number)\n const coercedValue = (typeof val === 'number' ? val.toString() : val) as\n | Data[K]\n | null\n\n this.set(key, coercedValue)\n\n return coercedValue\n }\n}\n", "import { CookieOptions, CookieStorage } from './cookieStorage'\nimport { LocalStorage } from './localStorage'\nimport { MemoryStorage } from './memoryStorage'\nimport { isStoreTypeWithSettings } from './settings'\nimport { StoreType, Store, InitializeStorageArgs } from './types'\n\nexport * from './types'\nexport * from './localStorage'\nexport * from './cookieStorage'\nexport * from './memoryStorage'\nexport * from './universalStorage'\nexport * from './settings'\n\n/**\n * Creates multiple storage systems from an array of StoreType and options\n * @param args StoreType and options\n * @returns Storage array\n */\nexport function initializeStorages(args: InitializeStorageArgs): Store[] {\n const storages = args.map((s) => {\n let type: StoreType\n let settings\n\n if (isStoreTypeWithSettings(s)) {\n type = s.name\n settings = s.settings\n } else {\n type = s\n }\n\n switch (type) {\n case StoreType.Cookie:\n return new CookieStorage(settings)\n case StoreType.LocalStorage:\n return new LocalStorage()\n case StoreType.Memory:\n return new MemoryStorage()\n default:\n throw new Error(`Unknown Store Type: ${s}`)\n }\n })\n return storages\n}\n\n/**\n * Injects the CookieOptions into a the arguments for initializeStorage\n * @param storeTypes list of storeType\n * @param cookieOptions cookie Options\n * @returns arguments for initializeStorage\n */\nexport function applyCookieOptions(\n storeTypes: StoreType[],\n cookieOptions?: CookieOptions\n): InitializeStorageArgs {\n return storeTypes.map((s) => {\n if (cookieOptions && s === StoreType.Cookie) {\n return {\n name: s,\n settings: cookieOptions,\n }\n }\n return s\n })\n}\n", "/**\n * Check if thenable\n * (instanceof Promise doesn't respect realms)\n */\nexport const isThenable = (value: unknown): boolean =>\n typeof value === 'object' &&\n value !== null &&\n 'then' in value &&\n typeof (value as any).then === 'function'\n", "/**\n * Returns `process.env` if it is available in the environment.\n * Always returns an object make it similarly easy to use as `process.env`.\n */\nexport function getProcessEnv(): { [key: string]: string | undefined } {\n if (typeof process === 'undefined' || !process.env) {\n return {}\n }\n\n return process.env\n}\n", "import { HighEntropyHint, NavigatorUAData, UADataValues } from './interfaces'\n\nexport async function clientHints(\n hints?: HighEntropyHint[]\n): Promise {\n const userAgentData = (navigator as any).userAgentData as\n | NavigatorUAData\n | undefined\n\n if (!userAgentData) return undefined\n\n if (!hints) return userAgentData.toJSON()\n return userAgentData\n .getHighEntropyValues(hints)\n .catch(() => userAgentData.toJSON())\n}\n", "import type { Integrations } from '../../core/events/interfaces'\nimport { CDNSettings } from '../../browser'\nimport { JSONObject, JSONValue } from '../../core/events'\nimport { Plugin, InternalPluginWithAddMiddleware } from '../../core/plugin'\nimport { loadScript } from '../../lib/load-script'\nimport { getCDN } from '../../lib/parse-cdn'\nimport {\n applyDestinationMiddleware,\n DestinationMiddlewareFunction,\n} from '../middleware'\nimport { Context, ContextCancelation } from '../../core/context'\nimport { recordIntegrationMetric } from '../../core/stats/metric-helpers'\nimport { Analytics, InitOptions } from '../../core/analytics'\nimport { createDeferred } from '@segment/analytics-generic-utils'\n\nexport interface RemotePlugin {\n /** The name of the remote plugin */\n name: string\n /** The creation name of the remote plugin */\n creationName: string\n /** The url of the javascript file to load */\n url: string\n /** The UMD/global name the plugin uses. Plugins are expected to exist here with the `PluginFactory` method signature */\n libraryName: string\n /** The settings related to this plugin. */\n settings: JSONObject\n}\n\nexport class ActionDestination implements InternalPluginWithAddMiddleware {\n name: string // destination name\n version = '1.0.0'\n /**\n * The lifecycle name of the wrapped plugin.\n * This does not need to be 'destination', and can be 'enrichment', etc.\n */\n type: Plugin['type']\n\n alternativeNames: string[] = []\n\n private loadPromise = createDeferred()\n\n middleware: DestinationMiddlewareFunction[] = []\n\n action: Plugin\n\n constructor(name: string, action: Plugin) {\n this.action = action\n this.name = name\n this.type = action.type\n this.alternativeNames.push(action.name)\n }\n\n addMiddleware(...fn: DestinationMiddlewareFunction[]): void {\n /** Make sure we only apply destination filters to actions of the \"destination\" type to avoid causing issues for hybrid destinations */\n if (this.type === 'destination') {\n this.middleware.push(...fn)\n }\n }\n\n private async transform(ctx: Context): Promise {\n const modifiedEvent = await applyDestinationMiddleware(\n this.name,\n ctx.event,\n this.middleware\n )\n\n if (modifiedEvent === null) {\n ctx.cancel(\n new ContextCancelation({\n retry: false,\n reason: 'dropped by destination middleware',\n })\n )\n }\n\n return new Context(modifiedEvent!)\n }\n\n private _createMethod(\n methodName: 'track' | 'page' | 'identify' | 'alias' | 'group' | 'screen'\n ) {\n return async (ctx: Context): Promise => {\n if (!this.action[methodName]) return ctx\n\n let transformedContext: Context = ctx\n // Transformations only allowed for destination plugins. Other plugin types support mutating events.\n if (this.type === 'destination') {\n transformedContext = await this.transform(ctx)\n }\n\n try {\n if (!(await this.ready())) {\n throw new Error(\n 'Something prevented the destination from getting ready'\n )\n }\n\n recordIntegrationMetric(ctx, {\n integrationName: this.action.name,\n methodName,\n type: 'action',\n })\n\n await this.action[methodName]!(transformedContext)\n } catch (error) {\n recordIntegrationMetric(ctx, {\n integrationName: this.action.name,\n methodName,\n type: 'action',\n didError: true,\n })\n throw error\n }\n\n return ctx\n }\n }\n\n alias = this._createMethod('alias')\n group = this._createMethod('group')\n identify = this._createMethod('identify')\n page = this._createMethod('page')\n screen = this._createMethod('screen')\n track = this._createMethod('track')\n\n /* --- PASSTHROUGH METHODS --- */\n isLoaded(): boolean {\n return this.action.isLoaded()\n }\n\n async ready(): Promise {\n try {\n await this.loadPromise.promise\n return true\n } catch {\n return false\n }\n }\n\n async load(ctx: Context, analytics: Analytics): Promise {\n if (this.loadPromise.isSettled()) {\n return this.loadPromise.promise\n }\n\n try {\n recordIntegrationMetric(ctx, {\n integrationName: this.action.name,\n methodName: 'load',\n type: 'action',\n })\n\n const loadP = this.action.load(ctx, analytics)\n\n this.loadPromise.resolve(await loadP)\n return loadP\n } catch (error) {\n recordIntegrationMetric(ctx, {\n integrationName: this.action.name,\n methodName: 'load',\n type: 'action',\n didError: true,\n })\n\n this.loadPromise.reject(error)\n throw error\n }\n }\n\n unload(ctx: Context, analytics: Analytics): Promise | unknown {\n return this.action.unload?.(ctx, analytics)\n }\n}\n\nexport type PluginFactory = {\n (settings: JSONValue): Plugin | Plugin[] | Promise\n pluginName: string\n}\n\nfunction validate(pluginLike: unknown): pluginLike is Plugin[] {\n if (!Array.isArray(pluginLike)) {\n throw new Error('Not a valid list of plugins')\n }\n\n const required = ['load', 'isLoaded', 'name', 'version', 'type']\n pluginLike.forEach((plugin) => {\n required.forEach((method) => {\n if (plugin[method] === undefined) {\n throw new Error(\n `Plugin: ${\n plugin.name ?? 'unknown'\n } missing required function ${method}`\n )\n }\n })\n })\n\n return true\n}\n\nfunction isPluginDisabled(\n userIntegrations: Integrations,\n remotePlugin: RemotePlugin\n) {\n const creationNameEnabled = userIntegrations[remotePlugin.creationName]\n const currentNameEnabled = userIntegrations[remotePlugin.name]\n\n // Check that the plugin isn't explicitly enabled when All: false\n if (\n userIntegrations.All === false &&\n !creationNameEnabled &&\n !currentNameEnabled\n ) {\n return true\n }\n\n // Check that the plugin isn't explicitly disabled\n if (creationNameEnabled === false || currentNameEnabled === false) {\n return true\n }\n\n return false\n}\n\nasync function loadPluginFactory(\n remotePlugin: RemotePlugin,\n obfuscate?: boolean\n): Promise {\n const defaultCdn = new RegExp('https://cdn.segment.(com|build)')\n const cdn = getCDN()\n\n if (obfuscate) {\n const urlSplit = remotePlugin.url.split('/')\n const name = urlSplit[urlSplit.length - 2]\n const obfuscatedURL = remotePlugin.url.replace(\n name,\n btoa(name).replace(/=/g, '')\n )\n try {\n await loadScript(obfuscatedURL.replace(defaultCdn, cdn))\n } catch (error) {\n // Due to syncing concerns it is possible that the obfuscated action destination (or requested version) might not exist.\n // We should use the unobfuscated version as a fallback.\n await loadScript(remotePlugin.url.replace(defaultCdn, cdn))\n }\n } else {\n await loadScript(remotePlugin.url.replace(defaultCdn, cdn))\n }\n\n // @ts-expect-error\n if (typeof window[remotePlugin.libraryName] === 'function') {\n // @ts-expect-error\n return window[remotePlugin.libraryName] as PluginFactory\n }\n}\n\nexport async function remoteLoader(\n settings: CDNSettings,\n userIntegrations: Integrations,\n mergedIntegrations: Record,\n options?: InitOptions,\n routingMiddleware?: DestinationMiddlewareFunction,\n pluginSources?: PluginFactory[]\n): Promise {\n const allPlugins: Plugin[] = []\n\n const routingRules = settings.middlewareSettings?.routingRules ?? []\n\n const pluginPromises = (settings.remotePlugins ?? []).map(\n async (remotePlugin) => {\n if (isPluginDisabled(userIntegrations, remotePlugin)) return\n\n try {\n const pluginFactory =\n pluginSources?.find(\n ({ pluginName }) => pluginName === remotePlugin.name\n ) || (await loadPluginFactory(remotePlugin, options?.obfuscate))\n\n if (pluginFactory) {\n const plugin = await pluginFactory({\n ...remotePlugin.settings,\n ...mergedIntegrations[remotePlugin.name],\n })\n const plugins = Array.isArray(plugin) ? plugin : [plugin]\n\n validate(plugins)\n\n const routing = routingRules.filter(\n (rule) => rule.destinationName === remotePlugin.creationName\n )\n\n plugins.forEach((plugin) => {\n const wrapper = new ActionDestination(\n remotePlugin.creationName,\n plugin\n )\n\n if (routing.length && routingMiddleware) {\n wrapper.addMiddleware(routingMiddleware)\n }\n\n allPlugins.push(wrapper)\n })\n }\n } catch (error) {\n console.warn('Failed to load Remote Plugin', error)\n }\n }\n )\n\n await Promise.all(pluginPromises)\n return allPlugins.filter(Boolean)\n}\n", "import { Facade } from '@segment/facade'\nimport { Analytics } from '../../core/analytics'\nimport { CDNSettings } from '../../browser'\nimport { isOffline } from '../../core/connection'\nimport { Context } from '../../core/context'\nimport { Plugin } from '../../core/plugin'\nimport { PriorityQueue } from '../../lib/priority-queue'\nimport { PersistedPriorityQueue } from '../../lib/priority-queue/persisted'\nimport { toFacade } from '../../lib/to-facade'\nimport batch, { BatchingDispatchConfig } from './batched-dispatcher'\nimport standard, { StandardDispatcherConfig } from './fetch-dispatcher'\nimport { normalize } from './normalize'\nimport { scheduleFlush } from './schedule-flush'\nimport { SEGMENT_API_HOST } from '../../core/constants'\n\ntype DeliveryStrategy =\n | {\n strategy?: 'standard'\n config?: StandardDispatcherConfig\n }\n | {\n strategy?: 'batching'\n config?: BatchingDispatchConfig\n }\n\nexport type SegmentioSettings = {\n apiKey: string\n apiHost?: string\n protocol?: 'http' | 'https'\n\n addBundledMetadata?: boolean\n unbundledIntegrations?: string[]\n bundledConfigIds?: string[]\n unbundledConfigIds?: string[]\n\n maybeBundledConfigIds?: Record\n\n deliveryStrategy?: DeliveryStrategy\n}\n\ntype JSON = ReturnType\n\nfunction onAlias(analytics: Analytics, json: JSON): JSON {\n const user = analytics.user()\n json.previousId =\n json.previousId ?? json.from ?? user.id() ?? user.anonymousId()\n json.userId = json.userId ?? json.to\n delete json.from\n delete json.to\n return json\n}\n\nexport function segmentio(\n analytics: Analytics,\n settings?: SegmentioSettings,\n integrations?: CDNSettings['integrations']\n): Plugin {\n // Attach `pagehide` before buffer is created so that inflight events are added\n // to the buffer before the buffer persists events in its own `pagehide` handler.\n window.addEventListener('pagehide', () => {\n buffer.push(...Array.from(inflightEvents))\n inflightEvents.clear()\n })\n\n const writeKey = settings?.apiKey ?? ''\n\n const buffer = analytics.options.disableClientPersistence\n ? new PriorityQueue(analytics.queue.queue.maxAttempts, [])\n : new PersistedPriorityQueue(\n analytics.queue.queue.maxAttempts,\n `${writeKey}:dest-Segment.io`\n )\n\n const inflightEvents = new Set()\n const flushing = false\n\n const apiHost = settings?.apiHost ?? SEGMENT_API_HOST\n const protocol = settings?.protocol ?? 'https'\n const remote = `${protocol}://${apiHost}`\n\n const deliveryStrategy = settings?.deliveryStrategy\n const client =\n deliveryStrategy?.strategy === 'batching'\n ? batch(apiHost, deliveryStrategy.config)\n : standard(deliveryStrategy?.config as StandardDispatcherConfig)\n\n async function send(ctx: Context): Promise {\n if (isOffline()) {\n buffer.push(ctx)\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n scheduleFlush(flushing, buffer, segmentio, scheduleFlush)\n return ctx\n }\n\n inflightEvents.add(ctx)\n\n const path = ctx.event.type.charAt(0)\n\n let json = toFacade(ctx.event).json()\n\n if (ctx.event.type === 'track') {\n delete json.traits\n }\n\n if (ctx.event.type === 'alias') {\n json = onAlias(analytics, json)\n }\n\n return client\n .dispatch(\n `${remote}/${path}`,\n normalize(analytics, json, settings, integrations)\n )\n .then(() => ctx)\n .catch(() => {\n buffer.pushWithBackoff(ctx)\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n scheduleFlush(flushing, buffer, segmentio, scheduleFlush)\n return ctx\n })\n .finally(() => {\n inflightEvents.delete(ctx)\n })\n }\n\n const segmentio: Plugin = {\n name: 'Segment.io',\n type: 'destination',\n version: '0.1.0',\n isLoaded: (): boolean => true,\n load: (): Promise => Promise.resolve(),\n track: send,\n identify: send,\n page: send,\n alias: send,\n group: send,\n screen: send,\n }\n\n // Buffer may already have items if they were previously stored in localStorage.\n // Start flushing them immediately.\n if (buffer.todo) {\n scheduleFlush(flushing, buffer, segmentio, scheduleFlush)\n }\n\n return segmentio\n}\n", "import { SegmentEvent } from '../../core/events'\nimport { fetch } from '../../lib/fetch'\nimport { onPageChange } from '../../lib/on-page-change'\n\nexport type BatchingDispatchConfig = {\n size?: number\n timeout?: number\n keepalive?: boolean\n}\n\nconst MAX_PAYLOAD_SIZE = 500\nconst MAX_KEEPALIVE_SIZE = 64\n\nfunction kilobytes(buffer: unknown): number {\n const size = encodeURI(JSON.stringify(buffer)).split(/%..|./).length - 1\n return size / 1024\n}\n\n/**\n * Checks if the payload is over or close to\n * the maximum payload size allowed by tracking\n * API.\n */\nfunction approachingTrackingAPILimit(buffer: unknown): boolean {\n return kilobytes(buffer) >= MAX_PAYLOAD_SIZE - 50\n}\n\n/**\n * Checks if payload is over or approaching the limit for keepalive\n * requests. If keepalive is enabled we want to avoid\n * going over this to prevent data loss.\n */\nfunction passedKeepaliveLimit(buffer: unknown): boolean {\n return kilobytes(buffer) >= MAX_KEEPALIVE_SIZE - 10\n}\n\nfunction chunks(batch: object[]): Array {\n const result: object[][] = []\n let index = 0\n\n batch.forEach((item) => {\n const size = kilobytes(result[index])\n if (size >= 64) {\n index++\n }\n\n if (result[index]) {\n result[index].push(item)\n } else {\n result[index] = [item]\n }\n })\n\n return result\n}\n\nexport default function batch(\n apiHost: string,\n config?: BatchingDispatchConfig\n) {\n let buffer: object[] = []\n let pageUnloaded = false\n\n const limit = config?.size ?? 10\n const timeout = config?.timeout ?? 5000\n\n function sendBatch(batch: object[]) {\n if (batch.length === 0) {\n return\n }\n\n const writeKey = (batch[0] as SegmentEvent)?.writeKey\n\n // Remove sentAt from every event as batching only needs a single timestamp\n const updatedBatch = batch.map((event) => {\n const { sentAt, ...newEvent } = event as SegmentEvent\n return newEvent\n })\n\n return fetch(`https://${apiHost}/b`, {\n keepalive: config?.keepalive || pageUnloaded,\n headers: {\n 'Content-Type': 'text/plain',\n },\n method: 'post',\n body: JSON.stringify({\n writeKey,\n batch: updatedBatch,\n sentAt: new Date().toISOString(),\n }),\n })\n }\n\n async function flush(): Promise {\n if (buffer.length) {\n const batch = buffer\n buffer = []\n return sendBatch(batch)\n }\n }\n\n let schedule: NodeJS.Timeout | undefined\n\n function scheduleFlush(): void {\n if (schedule) {\n return\n }\n\n schedule = setTimeout(() => {\n schedule = undefined\n flush().catch(console.error)\n }, timeout)\n }\n\n onPageChange((unloaded) => {\n pageUnloaded = unloaded\n\n if (pageUnloaded && buffer.length) {\n const reqs = chunks(buffer).map(sendBatch)\n Promise.all(reqs).catch(console.error)\n }\n })\n\n async function dispatch(_url: string, body: object): Promise {\n buffer.push(body)\n\n const bufferOverflow =\n buffer.length >= limit ||\n approachingTrackingAPILimit(buffer) ||\n (config?.keepalive && passedKeepaliveLimit(buffer))\n\n return bufferOverflow || pageUnloaded ? flush() : scheduleFlush()\n }\n\n return {\n dispatch,\n }\n}\n", "/**\n * Register event listener on document that fires when:\n * * tab change or tab close (in mobile or desktop)\n * * click back / forward button\n * * click any link or perform any other navigation action\n * * soft refresh / hard refresh\n *\n * adapted from https://stackoverflow.com/questions/3239834/window-onbeforeunload-not-working-on-the-ipad/52864508#52864508,\n */\nexport const onPageChange = (cb: (unloaded: boolean) => void) => {\n let unloaded = false // prevents double firing if both are supported\n\n window.addEventListener('pagehide', () => {\n if (unloaded) return\n unloaded = true\n cb(unloaded)\n })\n\n // using document instead of window because of bug affecting browsers before safari 14 (detail in footnotes https://caniuse.com/?search=visibilitychange)\n document.addEventListener('visibilitychange', () => {\n if (document.visibilityState == 'hidden') {\n if (unloaded) return\n unloaded = true\n } else {\n unloaded = false\n }\n cb(unloaded)\n })\n}\n", "import { fetch } from '../../lib/fetch'\n\nexport type Dispatcher = (url: string, body: object) => Promise\n\nexport type StandardDispatcherConfig = {\n keepalive?: boolean\n}\n\nexport default function (config?: StandardDispatcherConfig): {\n dispatch: Dispatcher\n} {\n function dispatch(url: string, body: object): Promise {\n return fetch(url, {\n keepalive: config?.keepalive,\n headers: { 'Content-Type': 'text/plain' },\n method: 'post',\n body: JSON.stringify(body),\n })\n }\n\n return {\n dispatch,\n }\n}\n", "import { Analytics } from '../../core/analytics'\nimport { CDNSettings } from '../../browser'\nimport { SegmentFacade } from '../../lib/to-facade'\nimport { SegmentioSettings } from './index'\n\nexport function normalize(\n analytics: Analytics,\n json: ReturnType,\n settings?: SegmentioSettings,\n integrations?: CDNSettings['integrations']\n): object {\n const user = analytics.user()\n\n delete json.options\n\n json.writeKey = settings?.apiKey\n\n json.userId = json.userId || user.id()\n json.anonymousId = json.anonymousId || user.anonymousId()\n\n json.sentAt = new Date()\n\n const failed = analytics.queue.failedInitializations || []\n if (failed.length > 0) {\n json._metadata = { failedInitializations: failed }\n }\n\n const bundled: string[] = []\n const unbundled: string[] = []\n\n for (const key in integrations) {\n const integration = integrations[key]\n if (key === 'Segment.io') {\n bundled.push(key)\n }\n if (integration.bundlingStatus === 'bundled') {\n bundled.push(key)\n }\n if (integration.bundlingStatus === 'unbundled') {\n unbundled.push(key)\n }\n }\n\n // This will make sure that the disabled cloud mode destinations will be\n // included in the unbundled list.\n for (const settingsUnbundled of settings?.unbundledIntegrations || []) {\n if (!unbundled.includes(settingsUnbundled)) {\n unbundled.push(settingsUnbundled)\n }\n }\n\n const configIds = settings?.maybeBundledConfigIds ?? {}\n const bundledConfigIds: string[] = []\n\n bundled.sort().forEach((name) => {\n ;(configIds[name] ?? []).forEach((id) => {\n bundledConfigIds.push(id)\n })\n })\n\n if (settings?.addBundledMetadata !== false) {\n json._metadata = {\n ...json._metadata,\n bundled: bundled.sort(),\n unbundled: unbundled.sort(),\n bundledIds: bundledConfigIds,\n }\n }\n\n return json\n}\n", "import { isOffline } from '../../core/connection'\nimport { Context } from '../../core/context'\nimport { Plugin } from '../../core/plugin'\nimport { attempt } from '@segment/analytics-core'\nimport { pWhile } from '../../lib/p-while'\nimport { PriorityQueue } from '../../lib/priority-queue'\n\nasync function flushQueue(\n xt: Plugin,\n queue: PriorityQueue\n): Promise> {\n const failedQueue: Context[] = []\n if (isOffline()) {\n return queue\n }\n\n await pWhile(\n () => queue.length > 0 && !isOffline(),\n async () => {\n const ctx = queue.pop()\n if (!ctx) {\n return\n }\n\n const result = await attempt(ctx, xt)\n const success = result instanceof Context\n if (!success) {\n failedQueue.push(ctx)\n }\n }\n )\n // re-add failed tasks\n failedQueue.map((failed) => queue.pushWithBackoff(failed))\n return queue\n}\n\nexport function scheduleFlush(\n flushing: boolean,\n buffer: PriorityQueue,\n xt: Plugin,\n scheduleFlush: Function\n): void {\n if (flushing) {\n return\n }\n\n // eslint-disable-next-line @typescript-eslint/no-misused-promises\n setTimeout(async () => {\n let isFlushing = true\n // eslint-disable-next-line @typescript-eslint/no-use-before-define\n const newBuffer = await flushQueue(xt, buffer)\n isFlushing = false\n\n if (buffer.todo > 0) {\n scheduleFlush(isFlushing, newBuffer, xt, scheduleFlush)\n }\n }, Math.random() * 5000)\n}\n", "import { getGlobal } from '../../lib/get-global'\nimport type { Analytics } from '../analytics'\n\nconst env = getGlobal()\n\n// The code below assumes the inspector extension will use Object.assign\n// to add the inspect interface on to this object reference (unless the\n// extension code ran first and has already set up the variable)\nconst inspectorHost: {\n attach: (analytics: Analytics) => void\n} = ((env as any)['__SEGMENT_INSPECTOR__'] ??= {})\n\nexport const attachInspector = (analytics: Analytics) =>\n inspectorHost.attach?.(analytics as any)\n", "export { Analytics, AnalyticsSettings, InitOptions } from './core/analytics'\nexport {\n AnalyticsBrowser,\n AnalyticsBrowserSettings,\n CDNSettings,\n RemoteIntegrationSettings,\n} from './browser'\nexport * from './node'\n\nexport * from './core/context'\nexport * from './core/events'\nexport * from './core/plugin'\nexport * from './core/user'\n\nexport type { AnalyticsSnippet } from './browser/standalone-interface'\nexport type { MiddlewareFunction } from './plugins/middleware'\nexport { getGlobalAnalytics } from './lib/global-analytics-helper'\nexport { UniversalStorage, Store, StorageObject } from './core/storage'\nexport { segmentio } from './plugins/segmentio'\nexport {\n resolveAliasArguments,\n resolveArguments,\n resolvePageArguments,\n resolveUserArguments,\n} from './core/arguments-resolver'\n", "/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n", "/******************************************************************************\nCopyright (c) Microsoft Corporation.\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\nPERFORMANCE OF THIS SOFTWARE.\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\n\nvar extendStatics = function(d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\n return extendStatics(d, b);\n};\n\nexport function __extends(d, b) {\n if (typeof b !== \"function\" && b !== null)\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\n\nexport var __assign = function() {\n __assign = Object.assign || function __assign(t) {\n for (var s, i = 1, n = arguments.length; i < n; i++) {\n s = arguments[i];\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\n }\n return t;\n }\n return __assign.apply(this, arguments);\n}\n\nexport function __rest(s, e) {\n var t = {};\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\n t[p] = s[p];\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\n t[p[i]] = s[p[i]];\n }\n return t;\n}\n\nexport function __decorate(decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n}\n\nexport function __param(paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n}\n\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\n var _, done = false;\n for (var i = decorators.length - 1; i >= 0; i--) {\n var context = {};\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\n if (kind === \"accessor\") {\n if (result === void 0) continue;\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\n if (_ = accept(result.get)) descriptor.get = _;\n if (_ = accept(result.set)) descriptor.set = _;\n if (_ = accept(result.init)) initializers.unshift(_);\n }\n else if (_ = accept(result)) {\n if (kind === \"field\") initializers.unshift(_);\n else descriptor[key] = _;\n }\n }\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\n done = true;\n};\n\nexport function __runInitializers(thisArg, initializers, value) {\n var useValue = arguments.length > 2;\n for (var i = 0; i < initializers.length; i++) {\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\n }\n return useValue ? value : void 0;\n};\n\nexport function __propKey(x) {\n return typeof x === \"symbol\" ? x : \"\".concat(x);\n};\n\nexport function __setFunctionName(f, name, prefix) {\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\n};\n\nexport function __metadata(metadataKey, metadataValue) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\n}\n\nexport function __awaiter(thisArg, _arguments, P, generator) {\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments || [])).next());\n });\n}\n\nexport function __generator(thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n}\n\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n});\n\nexport function __exportStar(m, o) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\n}\n\nexport function __values(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n}\n\nexport function __read(o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n}\n\n/** @deprecated */\nexport function __spread() {\n for (var ar = [], i = 0; i < arguments.length; i++)\n ar = ar.concat(__read(arguments[i]));\n return ar;\n}\n\n/** @deprecated */\nexport function __spreadArrays() {\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\n r[k] = a[j];\n return r;\n}\n\nexport function __spreadArray(to, from, pack) {\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\n if (ar || !(i in from)) {\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\n ar[i] = from[i];\n }\n }\n return to.concat(ar || Array.prototype.slice.call(from));\n}\n\nexport function __await(v) {\n return this instanceof __await ? (this.v = v, this) : new __await(v);\n}\n\nexport function __asyncGenerator(thisArg, _arguments, generator) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\n function fulfill(value) { resume(\"next\", value); }\n function reject(value) { resume(\"throw\", value); }\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\n}\n\nexport function __asyncDelegator(o) {\n var i, p;\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\n}\n\nexport function __asyncValues(o) {\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\n var m = o[Symbol.asyncIterator], i;\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\n}\n\nexport function __makeTemplateObject(cooked, raw) {\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\n return cooked;\n};\n\nvar __setModuleDefault = Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n};\n\nvar ownKeys = function(o) {\n ownKeys = Object.getOwnPropertyNames || function (o) {\n var ar = [];\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\n return ar;\n };\n return ownKeys(o);\n};\n\nexport function __importStar(mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\n __setModuleDefault(result, mod);\n return result;\n}\n\nexport function __importDefault(mod) {\n return (mod && mod.__esModule) ? mod : { default: mod };\n}\n\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n}\n\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n}\n\nexport function __classPrivateFieldIn(state, receiver) {\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\n}\n\nexport function __addDisposableResource(env, value, async) {\n if (value !== null && value !== void 0) {\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\n var dispose, inner;\n if (async) {\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\n dispose = value[Symbol.asyncDispose];\n }\n if (dispose === void 0) {\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\n dispose = value[Symbol.dispose];\n if (async) inner = dispose;\n }\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\n env.stack.push({ value: value, dispose: dispose, async: async });\n }\n else if (async) {\n env.stack.push({ async: true });\n }\n return value;\n}\n\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nexport function __disposeResources(env) {\n function fail(e) {\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\n env.hasError = true;\n }\n var r, s = 0;\n function next() {\n while (r = env.stack.pop()) {\n try {\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\n if (r.dispose) {\n var result = r.dispose.call(r.value);\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\n }\n else s |= 1;\n }\n catch (e) {\n fail(e);\n }\n }\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\n if (env.hasError) throw env.error;\n }\n return next();\n}\n\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n}\n\nexport default {\n __extends,\n __assign,\n __rest,\n __decorate,\n __param,\n __esDecorate,\n __runInitializers,\n __propKey,\n __setFunctionName,\n __metadata,\n __awaiter,\n __generator,\n __createBinding,\n __exportStar,\n __values,\n __read,\n __spread,\n __spreadArrays,\n __spreadArray,\n __await,\n __asyncGenerator,\n __asyncDelegator,\n __asyncValues,\n __makeTemplateObject,\n __importStar,\n __importDefault,\n __classPrivateFieldGet,\n __classPrivateFieldSet,\n __classPrivateFieldIn,\n __addDisposableResource,\n __disposeResources,\n __rewriteRelativeImportExtension,\n};\n", "/**\n * Taken from from https://github.com/reduxjs/redux\n *\n * (This file used to be a TypeScript port of the `compose` function, but since\n * Redux has been ported to TypeScript, it's now an exact copy)\n */\n\ntype Func = (...a: T) => R\n\n/**\n * Composes single-argument functions from right to left. The rightmost\n * function can take multiple arguments as it provides the signature for the\n * resulting composite function.\n *\n * @param funcs The functions to compose.\n * @returns A function obtained by composing the argument functions from right\n * to left. For example, `compose(f, g, h)` is identical to doing\n * `(...args) => f(g(h(...args)))`.\n */\nexport function compose(): (a: R) => R\n\nexport function compose(f: F): F\n\n/* two functions */\nexport function compose(\n f1: (a: A) => R,\n f2: Func\n): Func\n\n/* three functions */\nexport function compose(\n f1: (b: B) => R,\n f2: (a: A) => B,\n f3: Func\n): Func\n\n/* four functions */\nexport function compose(\n f1: (c: C) => R,\n f2: (b: B) => C,\n f3: (a: A) => B,\n f4: Func\n): Func\n\n/* rest */\nexport function compose(\n f1: (a: any) => R,\n ...funcs: Function[]\n): (...args: any[]) => R\n\nexport function compose(...funcs: Function[]): (...args: any[]) => R\n\nexport function compose(...funcs: Function[]) {\n if (funcs.length === 0) {\n // infer the argument type so it is usable in inference down the line\n return (arg: T) => arg\n }\n\n if (funcs.length === 1) {\n return funcs[0]\n }\n\n return funcs.reduce((a, b) => (...args: any) => a(b(...args)))\n}\n", "import type { HashMap, HashMapValue } from \"@appsignal/types\"\n\n/**\n * Converts all values in a flat object to a string.\n *\n * Adapted from https://stackoverflow.com/questions/46982698/how-do-i-convert-all-property-values-in-an-object-to-type-string\n */\nexport function toHashMapString(\n obj?: HashMap\n): HashMap | undefined {\n if (!obj) return\n\n const hm: HashMap = {}\n\n Object.keys(obj).forEach(k => {\n if (typeof obj[k] === \"object\") {\n hm[k] = JSON.stringify(obj[k])\n } else {\n hm[k] = String(obj[k])\n }\n })\n\n return hm\n}\n\n/**\n * Converts any non-string, boolean or number value in an object to a string\n */\nexport function toHashMap(\n obj?: HashMap\n): HashMap | undefined {\n if (!obj) return\n\n const hm: HashMap = {}\n\n Object.keys(obj).forEach(k => {\n if (\n typeof obj[k] === \"string\" ||\n typeof obj[k] === \"boolean\" ||\n typeof obj[k] === \"number\"\n ) {\n hm[k] = obj[k]\n } else {\n hm[k] = JSON.stringify(obj[k])\n }\n })\n\n return hm\n}\n", "/**\n * Check if the given object is an error-like object.\n *\n * @param {Error | T} error An `Error` object or an error-like object\n *\n * @return {boolean}\n */\nexport function isError(error: Error | T): boolean {\n return (\n typeof error === \"object\" && typeof (error as any).message !== \"undefined\"\n )\n}\n\n/**\n * Get backtrace from an `Error` object, or an error-like object\n *\n * @param {Error | T} error An `Error` object or an error-like object\n *\n * @return {string[]} A backtrace\n */\nexport function getStacktrace(error: Error | T): string[] {\n if (\n typeof (error as any).stacktrace !== \"undefined\" ||\n typeof (error as any)[\"opera#sourceloc\"] !== \"undefined\"\n ) {\n // probably opera\n const { stacktrace = \"\" } = error as any\n return stacktrace\n .split(\"\\n\")\n .filter((line: string | undefined) => line !== \"\")\n } else if (error.stack) {\n // an Error or a plain object that resembles an error\n const { stack = \"\" } = error\n return stack.split(\"\\n\").filter(line => line !== \"\")\n } else {\n // probably IE9 :(\n return [\"No stacktrace available\"]\n }\n}\n", "/**\n * Encodes given object into url-friendly format\n *\n * @param {object} object: [object: An object that contains serializable values]\n *\n * @return {string} [Encoded URI params]\n */\nexport function urlEncode(object: { [key: string]: any }): string {\n return Object.keys(object)\n .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`)\n .join(\"&\")\n}\n", "/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * Originally from https://github.com/getsentry/sentry-javascript/\n */\n\nexport function isNodeEnv(): boolean {\n return (\n Object.prototype.toString.call(\n typeof process !== \"undefined\" ? process : 0\n ) === \"[object process]\"\n )\n}\n\n/**\n * Safely get global scope object\n *\n * Originally from https://github.com/getsentry/sentry-javascript/\n */\nexport function getGlobalObject(): T {\n return (isNodeEnv()\n ? global\n : typeof window !== \"undefined\"\n ? window\n : typeof self !== \"undefined\"\n ? self\n : {}) as T\n}\n", "export class Serializable {\n protected _data: T\n\n constructor(data: T) {\n this._data = data\n }\n\n public toJSON(): string {\n return JSON.stringify(this._data)\n }\n\n public serialize(): T {\n return this._data\n }\n}\n", "// Do not touch this file, auto-generated by scripts/create-version\nexport const VERSION = \"1.4.1\"\n", "import { getGlobalObject, isNodeEnv } from \"@appsignal/core\"\n\nexport class Environment {\n /**\n * Serializes the current browser environment into an object.\n */\n public static serialize(): { [key: string]: string } {\n return {\n transport: this.transport(),\n origin: this.origin()\n }\n }\n\n /**\n * Returns the origin of the current context.\n *\n * @return {string} The origin URL\n */\n public static origin(): string {\n const globals = getGlobalObject()\n\n // environments like nodejs or react native where an origin isn't relavent\n if (!globals.location) {\n return \"\"\n }\n\n return (\n globals.location.origin ||\n `${globals.location.protocol}//${globals.location.hostname}`\n )\n }\n\n /**\n * Returns the best currently available API that the current browser supports\n * for making HTTP requests.\n *\n * @return {string} The name of the best availble HTTP transport\n */\n public static transport(): string {\n // we throw out the typechecking here as the transports aren't exported\n // using TS' `Window` type\n const globals = getGlobalObject() as any\n\n // we ignore jest here, as it's a false positive for a node\n // environment and breaks the tests\n if (isNodeEnv() && typeof jest === \"undefined\") {\n return \"NodeHTTP\"\n } else if (globals.XDomainRequest) {\n return \"XDomainRequest\"\n } else if (globals.XMLHttpRequest && !globals.fetch) {\n return \"XMLHttpRequest\"\n } else {\n return \"fetch\"\n }\n }\n\n /**\n * Indicates whether promises are available in the current browser\n * or environment.\n *\n * Adapted from https://github.com/Modernizr/Modernizr/blob/master/feature-detects/es6/promises.js\n *\n * @return {boolean} A value indicating if Promises are supported\n */\n public static supportsPromises(): boolean {\n // we throw out the typechecking here as the transports aren't exported\n // using TS' `Window` type\n const globals = getGlobalObject() as any\n\n return (\n \"Promise\" in globals &&\n // Some of these methods are missing from\n // Firefox/Chrome experimental implementations\n \"resolve\" in globals.Promise &&\n \"reject\" in globals.Promise &&\n \"all\" in globals.Promise &&\n \"race\" in globals.Promise &&\n // Older version of the spec had a resolver object\n // as the arg rather than a function\n (function () {\n var resolve\n new globals.Promise(function (r: any) {\n resolve = r\n })\n return typeof resolve === \"function\"\n })()\n )\n }\n}\n", "import { Transport } from \"../interfaces/transport\"\n\n// Fixes TypeScript complaining about this class\n// not existing\ndeclare var XDomainRequest: any\n\nexport class XDomainTransport implements Transport {\n public url: string\n\n constructor(url: string) {\n this.url = url\n }\n\n public send(data: string): Promise {\n return new Promise((resolve, reject) => {\n const req = new XDomainRequest()\n const rx = new RegExp(\"^https?:\")\n\n req.onload = () => resolve({})\n\n // XDomainRequest will only make a request to a URL with\n // the same protocol\n req.open(\"POST\", this.url.replace(rx, window?.location?.protocol))\n\n setTimeout(() => {\n try {\n req.send(data)\n } catch (e) {\n reject(e)\n }\n }, 0)\n })\n }\n}\n", "import { Transport } from \"../interfaces/transport\"\n\nexport class XHRTransport implements Transport {\n public url: string\n\n constructor(url: string) {\n this.url = url\n }\n\n public send(data: string): Promise {\n return new Promise((resolve, reject) => {\n try {\n const req = new XMLHttpRequest()\n\n req.onreadystatechange = () => {\n if (req.readyState === XMLHttpRequest.DONE) {\n resolve({})\n }\n }\n\n req.open(\"POST\", this.url)\n req.send(data)\n } catch (e) {\n reject(e)\n }\n })\n }\n}\n", "import { Transport } from \"../interfaces/transport\"\n\nexport class FetchTransport implements Transport {\n public url: string\n\n constructor(url: string, headers?: { [key: string]: string }) {\n this.url = url\n }\n\n public async send(data: string): Promise {\n const res = await fetch(this.url, {\n method: \"POST\",\n body: data\n })\n\n const { statusText, ok } = res\n\n return ok ? Promise.resolve({}) : Promise.reject({ statusText })\n }\n}\n", "import { Transport } from \"../interfaces/transport\"\nimport type https from \"https\"\nexport class NodeTransport implements Transport {\n public url: string\n private https: Promise\n\n constructor(url: string) {\n this.url = url\n this.https = import(\"https\")\n }\n\n public send(data: string): Promise {\n const options = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": data.length\n }\n }\n\n return new Promise((resolve, reject) => {\n this.https\n .then(https => {\n const req = https\n .request(this.url, options, () => {})\n .on(\"error\", error => reject(error))\n\n req.write(data)\n req.end()\n\n resolve({})\n })\n .catch(reason => {\n console.warn(\n \"NodeTransport is being used, but the HTTPS module could not be imported. No data will be sent to AppSignal.\"\n )\n reject(reason)\n })\n })\n }\n}\n", "import { urlEncode } from \"@appsignal/core\"\n\nimport { Environment } from \"./environment\"\nimport { Span } from \"./span\"\n\nimport { XDomainTransport } from \"./transports/xdomain\"\nimport { XHRTransport } from \"./transports/xhr\"\nimport { FetchTransport } from \"./transports/fetch\"\nimport { NodeTransport } from \"./transports/node\"\n\nimport { PushApiOptions } from \"./interfaces/options\"\nimport { Transport } from \"./interfaces/transport\"\n\nexport class PushApi {\n private _uri: string\n private _apiKey: string\n private _clientVersion: string\n private _transport: Transport\n\n /**\n * Creates a new instance of the Push API client.\n *\n * @constructor\n *\n * @param {object} options An object of options to configure the Push API client\n */\n constructor(options: PushApiOptions) {\n this._uri = options.uri || \"https://appsignal-endpoint.net/collect\"\n this._apiKey = options.key\n this._clientVersion = options.version\n\n this._transport = this._createTransport(this._url())\n }\n\n /**\n * Pushes a transaction to the Push API.\n *\n * @param {Span} span A single API `Span`\n *\n * @return {Promise} A single API `Span`\n */\n public async push(span: Span): Promise {\n await this._transport.send(span.toJSON())\n return span\n }\n\n /**\n * Creates an instance of a new `Transport` object. A `Transport` is a\n * browser API that is able to sent HTTP requests to an endpoint. A\n * transport is selected based on the best available in the current\n * environment.\n *\n * @return {ITransport} A Transport object\n */\n private _createTransport(url: string): Transport {\n switch (Environment.transport()) {\n case \"XDomainRequest\":\n return new XDomainTransport(url)\n case \"XMLHttpRequest\":\n return new XHRTransport(url)\n case \"NodeHTTP\":\n return new NodeTransport(url)\n default:\n return new FetchTransport(url)\n }\n }\n\n /**\n * Constructs a complete URL for accessing the Push API.\n *\n * @return {string} A Push API URL string\n */\n private _url(): string {\n const auth = this._authorization()\n return `${this._uri}?${urlEncode(auth)}`\n }\n\n /**\n * Creates an object of API credentials.\n *\n * @return {object} API credentials\n */\n private _authorization(): object {\n return {\n api_key: this._apiKey,\n version: this._clientVersion\n }\n }\n}\n", "import {\n Serializable,\n getStacktrace,\n toHashMapString,\n isError\n} from \"@appsignal/core\"\nimport type {\n JSSpanData,\n Breadcrumb,\n HashMap,\n HashMapValue\n} from \"@appsignal/types\"\n\nexport class Span extends Serializable {\n constructor(span?: Partial) {\n super({\n timestamp: Math.round(new Date().getTime() / 1000),\n namespace: \"frontend\",\n error: {\n name: \"NullError\",\n message: \"No error has been set\",\n backtrace: []\n },\n ...span\n })\n }\n\n public setAction(name: string): this {\n if (!name || typeof name !== \"string\") {\n return this\n }\n\n this._data.action = name\n return this\n }\n\n public setNamespace(name: string): this {\n if (!name || typeof name !== \"string\") {\n return this\n }\n\n this._data.namespace = name\n return this\n }\n\n public setError(error: Error | T): this {\n if (!error || !isError(error)) return this\n\n this._data.error = {\n name: error.name || \"[unknown]\",\n message: error.message,\n backtrace: getStacktrace(error)\n }\n\n return this\n }\n\n public setTags(tags: HashMap): this {\n this._data.tags = { ...this._data.tags, ...toHashMapString(tags) }\n return this\n }\n\n public setParams(params: HashMap): this {\n this._data.params = { ...this._data.params, ...params }\n return this\n }\n\n public setBreadcrumbs(breadcrumbs: Breadcrumb[]): this {\n this._data.breadcrumbs = breadcrumbs\n return this\n }\n\n public setEnvironment(environment: HashMap): this {\n this._data.environment = { ...this._data.environment, ...environment }\n return this\n }\n\n // @private\n // Do not use this function directly. Instead, set the `matchBacktracePaths`\n // configuration option when initializing AppSignal.\n public cleanBacktracePath(matchBacktracePaths: RegExp[]): this {\n if (matchBacktracePaths.length === 0) {\n return this\n }\n\n if (!this._data.error || !this._data.error.backtrace) {\n return this\n }\n\n let linesMatched = 0\n\n this._data.error.backtrace = this._data.error.backtrace.map(line => {\n const path = extractPath(line)\n if (!path) {\n return line\n }\n\n for (const matcher of matchBacktracePaths as RegExp[]) {\n const match = path.match(matcher)\n if (!match || match.length < 2) {\n continue\n }\n\n const relevantPath = match.slice(1).join(\"\")\n if (relevantPath) {\n linesMatched++\n return line.replace(path, relevantPath)\n }\n }\n\n return line\n })\n\n if (linesMatched > 0) {\n this.setEnvironment({\n backtrace_paths_matched: linesMatched.toString()\n })\n }\n\n return this\n }\n}\n\n// Backtrace formats are different between browsers, and generally not\n// meant to be parsed by machines. This function does a best-effort to\n// extract whatever is at the location in the line where the path\n// usually appears.\n//\n// If it returns `undefined`, it means that it could not find where the\n// path is located in the backtrace line. If it returns a string, that\n// string _may_ be a path, but it may contain non-path elements as well.\nfunction extractPath(backtraceLine: string): string | undefined {\n // A Chrome backtrace line always contains `at` near the beginning,\n // preceded by space characters and followed by one space.\n const IS_CHROME = /^\\s*at\\s/\n // In a Chrome backtrace line, the path (if it is available)\n // is located, usually within parentheses, after the \"@\" towards the\n // end of the line, along with the line number and column number,\n // separated by colons. We check for those to reject clear non-paths.\n const CHROME_PATH = /at(?:\\s.*)?\\s\\(?(.*):\\d*:\\d*\\)?$/i\n\n if (backtraceLine.match(IS_CHROME)) {\n const match = backtraceLine.match(CHROME_PATH)\n return match ? match[1] : undefined\n }\n\n // A Safari or Firefox backtrace line always contains `@` after the first\n // term in the line.\n const IS_SAFARI_FF = /^.*@/\n\n // In a Safari or Firefox backtrace line, the path (if it is available)\n // is located after the \"@\" at the towards end of the line, followed by\n // the line number and column number, separated by colons. We check for\n // those to reject clear non-paths.\n const SAFARI_FF_PATH = /@\\s?(.*):\\d*:\\d*$/i\n\n if (backtraceLine.match(IS_SAFARI_FF)) {\n const match = backtraceLine.match(SAFARI_FF_PATH)\n return match ? match[1] : undefined\n }\n}\n", "import { Span } from \"./span\"\n\nexport class Queue {\n private _data: Span[]\n\n constructor(data?: Span[]) {\n this._data = data || []\n }\n\n public clear() {\n this._data = []\n }\n\n public values(): Span[] {\n return this._data\n }\n\n public push(item: Span | Span[]) {\n return Array.isArray(item)\n ? this._data.push(...item)\n : this._data.push(item)\n }\n\n public *drain() {\n while (this._data.length > 0) {\n yield this._data.shift()\n }\n }\n}\n", "import { getGlobalObject } from \"@appsignal/core\"\n\nimport { Queue } from \"./queue\"\nimport { PushApi } from \"./api\"\n\ntype DispatcherOptions = { limit: number; initialDuration: number }\n\nexport class Dispatcher {\n public options: DispatcherOptions\n\n private _queue: Queue\n private _api: PushApi\n private _retries = 0\n private _timerID = 0\n private _duration = 0\n\n constructor(\n queue: Queue,\n api: PushApi,\n options?: Partial\n ) {\n this._api = api\n this._queue = queue\n\n this.options = {\n limit: 5,\n initialDuration: 1000,\n ...options\n }\n\n this.reset()\n }\n\n public schedule(time = this._duration): number {\n const globals = getGlobalObject()\n\n // @TODO: make this configurable?\n const BACKOFF_FACTOR = 1.3\n\n const cb = async () => {\n for (let span of this._queue.drain()) {\n if (!span) return\n\n try {\n await this._api.push(span)\n } catch (e) {\n // when the first promise fails, reschedule a timer\n const expDuration = Math.floor(Math.pow(time, BACKOFF_FACTOR))\n\n this._retries = this._retries - 1\n\n if (this._retries === 0) {\n this.reset()\n } else {\n this._queue.push(span)\n this._timerID = this.schedule(expDuration)\n }\n\n return\n }\n }\n\n // reset once all promises are cleared\n this.reset()\n }\n\n return globals.setTimeout(cb, time)\n }\n\n public reset() {\n const { limit, initialDuration } = this.options\n this._retries = limit\n this._duration = initialDuration\n }\n}\n", "/**\n * The AppSignal client.\n * @module Appsignal\n */\n\nimport { compose, toHashMap } from \"@appsignal/core\"\nimport type { Breadcrumb, JSClient, Hook, HashMap } from \"@appsignal/types\"\n\nimport { VERSION } from \"./version\"\nimport { PushApi } from \"./api\"\nimport { Environment } from \"./environment\"\nimport { Span } from \"./span\"\nimport { Queue } from \"./queue\"\nimport { Dispatcher } from \"./dispatcher\"\n\nimport { AppsignalOptions } from \"./interfaces/options\"\n\nexport default class Appsignal implements JSClient {\n public VERSION = VERSION\n public ignored: RegExp[] = []\n private matchBacktracePaths: RegExp[] = []\n\n private _dispatcher: Dispatcher\n private _options: AppsignalOptions\n private _api: PushApi\n private _breadcrumbs: Breadcrumb[] = []\n\n private _hooks = {\n decorators: Array(),\n overrides: Array()\n }\n\n private _env = Environment.serialize()\n private _queue = new Queue([])\n\n /**\n * Creates a new instance of the AppSignal client.\n *\n * @constructor\n *\n * @param {AppsignalOptions} options An object of options to configure the AppSignal client\n */\n constructor(options: AppsignalOptions) {\n const {\n key = \"\",\n uri,\n revision,\n ignoreErrors,\n matchBacktracePaths\n } = options\n\n // `revision` should be a `string`, but we attempt to\n // normalise to one anyway\n if (revision && typeof revision !== \"string\") {\n options.revision = String(revision)\n }\n\n // starting with no key means nothing will be sent to the API\n if (key === \"\") {\n console.info(\n \"[APPSIGNAL]: No API key provided. Started in development mode. No data will be sent.\"\n )\n }\n\n this._api = new PushApi({\n key,\n uri,\n version: this.VERSION\n })\n\n // ignored exceptions are checked against the `message`\n // property of a given `Error`\n if (ignoreErrors && Array.isArray(ignoreErrors)) {\n this.ignored = ignoreErrors\n .filter(value => value instanceof RegExp)\n .map(unglobalize)\n }\n\n if (matchBacktracePaths) {\n if (Array.isArray(matchBacktracePaths)) {\n this.matchBacktracePaths = matchBacktracePaths\n } else {\n this.matchBacktracePaths = [matchBacktracePaths]\n }\n\n this.matchBacktracePaths = this.matchBacktracePaths\n .filter(value => value instanceof RegExp)\n .map(unglobalize)\n }\n\n this._dispatcher = new Dispatcher(this._queue, this._api)\n\n this._options = options\n }\n\n /**\n * Records and sends a browser `Error` to AppSignal.\n *\n * @param {Error | ErrorEvent} error A JavaScript Error object\n * @param {Function | void} fn Optional callback function to modify span before it's sent.\n *\n * @return {Promise | void} An API response, or `void` if `Promise` is unsupported.\n */\n public send(error: Error, fn?: (span: Span) => T): Promise | void\n\n /**\n * Records and sends a browser `Error` to AppSignal.\n *\n * @param {Error | ErrorEvent} error A JavaScript Error object\n * @param {object} tags An key, value object of tags\n * @param {string} namespace An optional namespace name\n *\n * @return {Promise | void} An API response, or `void` if `Promise` is unsupported.\n */\n public send(\n error: Error | ErrorEvent,\n tags?: object,\n namespace?: string\n ): Promise | void\n\n /**\n * Records and sends an Appsignal `Span` object to AppSignal.\n *\n * @param {Span} span An Appsignal Span object\n *\n * @return {Promise} An API response, or `void` if `Promise` is unsupported.\n */\n public send(span: Span): Promise | void\n\n /**\n *\n * @param {Error | Span | ErrorEvent} data A JavaScript Error or Appsignal Span object\n * @param {object | Function} tagsOrFn An key-value object of tags or a callback function to customize the span before it is sent.\n * @param {string} namespace DEPRECATED: An optional namespace name.\n *\n * @return {Promise | void} An API response, or `void` if `Promise` is unsupported.\n */\n public send(\n data: Error | Span | ErrorEvent,\n tagsOrFn?: object | ((span: Span) => T),\n namespace?: string\n ): Promise | void {\n if (\n !(data instanceof Error) &&\n !(data instanceof Span) &&\n !(data && data.error instanceof Error)\n ) {\n // @TODO: route this through a central logger\n console.error(\n \"[APPSIGNAL]: Can't send error, given error is not a valid type\"\n )\n return\n }\n\n let error: Error | Span\n\n if (\"error\" in data) {\n error = data.error as Error // handle ErrorEvent\n } else {\n error = data\n }\n\n // handle user defined ignores\n if (this.ignored.length !== 0) {\n if (error && \"message\" in error) {\n if (\n this.ignored.some(el =>\n el.test((error as { message: string }).message)\n )\n ) {\n console.warn(`[APPSIGNAL]: Ignored an error: ${error.message}`)\n return\n }\n }\n\n if (error instanceof Span) {\n const serializedError = error.serialize().error\n\n if (\n serializedError.message &&\n this.ignored.some(el => el.test(serializedError.message!))\n ) {\n console.warn(\n `[APPSIGNAL]: Ignored a span: ${serializedError.message}`\n )\n return\n }\n }\n }\n\n // a \"span\" currently refers to a fixed point in time, as opposed to\n // a range or length in time. this may change in future!\n const span =\n error instanceof Span ? error : this._createSpanFromError(error)\n\n // A Span can be \"decorated\" with metadata after it has been created,\n // but before it is sent to the API and before metadata provided\n // as arguments is added\n if (this._hooks.decorators.length > 0) {\n compose(...this._hooks.decorators)(span)\n }\n\n if (tagsOrFn) {\n if (typeof tagsOrFn === \"function\") {\n const callback = tagsOrFn\n callback(span)\n } else {\n console.warn(\n \"[APPSIGNAL]: DEPRECATED: Calling the `send`/`sendError` function with a tags object is deprecated. Use the callback argument instead.\"\n )\n const tags = (toHashMap(tagsOrFn) || {}) as HashMap\n span.setTags(tags)\n }\n }\n if (namespace) {\n console.warn(\n \"[APPSIGNAL]: DEPRECATED: Calling the `send`/`sendError` function with a namespace is deprecated. Use the callback argument instead.\"\n )\n span.setNamespace(namespace)\n }\n\n if (this._breadcrumbs.length > 0) span.setBreadcrumbs(this._breadcrumbs)\n\n // A Span can be \"overridden\" with metadata after it has been created,\n // but before it is sent to the API and after metadata provided\n // as arguments is added\n if (this._hooks.overrides.length > 0) {\n compose(...this._hooks.overrides)(span)\n }\n\n span.cleanBacktracePath(this.matchBacktracePaths)\n\n if (Environment.supportsPromises()) {\n // clear breadcrumbs as they are now loaded into the span,\n // and we are sure that it's possible to send them\n this._breadcrumbs = []\n\n // if no key is supplied, we just output the span to the console\n if (!this._options.key) {\n // @TODO: route this through a central logger\n console.warn(\n \"[APPSIGNAL]: Span not sent because we're in development mode:\",\n span\n )\n } else {\n // attempt to push to the API\n return this._api.push(span).catch(() => {\n this._queue.push(span)\n\n // schedule on next tick\n setTimeout(() => this._dispatcher.schedule(), 0)\n })\n }\n } else {\n // @TODO: route this through a central logger\n console.error(\n \"[APPSIGNAL]: Error not sent. A Promise polyfill is required.\"\n )\n return\n }\n }\n\n sendError(error: Error | ErrorEvent): Promise | void\n sendError(\n error: Error | ErrorEvent,\n callback: (span: Span) => T\n ): Promise | void\n sendError(\n error: Error | ErrorEvent,\n tags?: object,\n namespace?: string\n ): Promise | void\n\n /**\n * Records and sends a browser `Error` to AppSignal. An alias to `#send()`\n * to maintain compatibility.\n *\n * @param {Error | ErrorEvent} error A JavaScript Error object\n * @param {object | Function} tagsOrFn An key-value object of tags or callback function to customize the span before it is sent.\n * @param {string} namespace DEPRECATED: An optional namespace name\n *\n * @return {Promise | void} An API response, or `void` if `Promise` is unsupported.\n */\n public sendError(\n error: Error | ErrorEvent,\n tagsOrFn?: object | ((span: Span) => T),\n namespace?: string\n ): Promise | void {\n return this.send(error, tagsOrFn, namespace)\n }\n\n /**\n * Registers and installs a valid plugin.\n *\n * A plugin is typically a function that can be used to provide a\n * reference to the `Appsignal` instance via returning a function\n * that can be bound to `this`.\n *\n * @param {Plugin} plugin A JavaScript Error object\n *\n * @return {void}\n */\n public use(plugin: Function): void {\n plugin.call(this)\n }\n\n /**\n * Creates a new `Span`, augmented with the current environment.\n *\n * @param {Function | void} fn Optional function to modify span\n *\n * @return {Span} An AppSignal `Span` object\n */\n public createSpan(fn?: (span: Span) => void): Span {\n const { revision = \"\", namespace } = this._options\n\n const span = new Span({\n environment: this._env,\n revision\n })\n\n // set default namespace from constructor if none is set\n if (namespace) span.setNamespace(namespace)\n\n if (fn && typeof fn === \"function\") fn(span)\n\n return span\n }\n\n /**\n * Wraps and catches errors within a given function. If the function throws an\n * error, a rejected `Promise` will be returned and the error thrown will be\n * logged to AppSignal.\n */\n public async wrap(fn: () => T, callbackFn?: (span: Span) => T): Promise\n\n /**\n * Wraps and catches errors within a given function. If the function throws an\n * error, a rejected `Promise` will be returned and the error thrown will be\n * logged to AppSignal.\n */\n public async wrap(\n fn: () => T,\n tags?: object,\n namespace?: string\n ): Promise\n\n /**\n * Wraps and catches errors within a given function. If the function throws an\n * error, a rejected `Promise` will be returned and the error thrown will be\n * logged to AppSignal.\n *\n * @param {Function} fn A function to wrap\n * @param {object | Function} tagsOrFn An key-value object of tags or a callback function to customize the span before it is sent.\n * @param {string} namespace DEPRECATED: An optional namespace name\n *\n * @return {Promise} A Promise containing the return value of the function, or a `Span` if an error was thrown.\n */\n public async wrap(\n fn: () => T,\n tagsOrFn?: object | ((span: Span) => T),\n namespace?: string\n ): Promise {\n try {\n return await fn()\n } catch (e) {\n if (e instanceof Error || e instanceof ErrorEvent) {\n await this.sendError(e, tagsOrFn, namespace)\n }\n return Promise.reject(e)\n }\n }\n\n /**\n * Registers a span decorator to be applied every time a Span\n * is sent to the Push API\n *\n * @param {Function} decorator A decorator function, returning `Span`\n *\n * @return {void}\n */\n public addDecorator(decorator: T): void {\n this._hooks.decorators.push(decorator)\n }\n\n /**\n * Registers a span override to be applied every time a Span\n * is sent to the Push API\n *\n * @param {Function} override An override function, returning `Span`\n *\n * @return {void}\n */\n public addOverride(override: T): void {\n this._hooks.overrides.push(override)\n }\n\n /**\n * Sends a demonstration error to AppSignal.\n *\n * @return {void}\n */\n public demo(): void {\n const span = this._createSpanFromError(\n new Error(\n \"Hello world! This is an error used for demonstration purposes.\"\n )\n )\n\n span\n .setAction(\"TestAction\")\n .setParams({\n path: \"/hello\",\n method: \"GET\"\n })\n .setTags({\n demo_sample: \"true\"\n })\n\n this.send(span)\n }\n\n /**\n * Adds a breadcrumb.\n *\n * @param {Breadcrumb} breadcrumb A valid breadcrumb\n *\n * @return {void}\n */\n public addBreadcrumb(breadcrumb: Omit): void {\n const crumb: Breadcrumb = {\n timestamp: Math.round(new Date().getTime() / 1000),\n ...breadcrumb,\n metadata: toHashMap(breadcrumb.metadata)\n }\n\n if (!crumb.category) {\n console.warn(\"[APPSIGNAL]: Breadcrumb not added. `category` is missing.\")\n return\n }\n\n if (!crumb.action) {\n console.warn(\"[APPSIGNAL]: Breadcrumb not added. `action` is missing.\")\n return\n }\n\n if (this._breadcrumbs.length === 20) {\n this._breadcrumbs.pop()\n }\n\n this._breadcrumbs.unshift(crumb)\n }\n\n /**\n * Creates a valid AppSignal `Span` from a JavaScript `Error`\n * object.\n *\n * @param {Error} error A JavaScript error\n *\n * @return {Span} An AppSignal event\n */\n private _createSpanFromError(error: Error): Span {\n const event = this.createSpan()\n event.setError(error)\n\n return event\n }\n}\n\n// Returns a new `RegExp` object with the global flag removed.\n// This fixes issues where using global regexes repeatedly with `test` against\n// different strings will return unexpected results, due to the regex object\n// storing the location of its last match and resuming the search from there.\nfunction unglobalize(regexp: RegExp): RegExp {\n return new RegExp(regexp.source, regexp.flags.replace(\"g\", \"\"))\n}\n", "import type { JSClient } from \"@appsignal/types\"\nimport { isError } from \"@appsignal/core\"\n\nfunction windowEventsPlugin(options?: { [key: string]: any }) {\n const ctx = window as Window\n\n const opts = {\n onerror: true,\n onunhandledrejection: true,\n ...options\n }\n\n return function (this: JSClient) {\n const self = this\n\n const prev = {\n onError: ctx.onerror,\n unhandledRejection: ctx.onunhandledrejection\n }\n\n function _onErrorHandler(\n this: WindowEventHandlers,\n event: Event | string,\n source?: string,\n lineno?: number,\n colno?: number,\n error?: Error\n ): void {\n const span = self.createSpan()\n\n // handles \"Script error.\" message in some browsers when script is loaded\n // cross origin.\n // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#Notes\n if (\n typeof event === \"string\" &&\n lineno === 0 &&\n /Script error\\.?/.test(event)\n ) {\n console.warn(\n \"[APPSIGNAL]: Cross-domain or eval script error detected, error ignored\"\n )\n } else {\n if (error) {\n span.setError(error)\n } else {\n // handle browsers that don't supply an `error` argument\n // or don't return a stacktrace\n span.setError({\n name: \"Error\",\n // `event` shoiuld be the message in most browsers\n message:\n typeof event === \"string\"\n ? event\n : 'An HTML onerror=\"\" handler failed to execute',\n stack: `at ${source}:${lineno}${colno ? `:${colno}` : \"\"}`\n })\n }\n\n self.send(span)\n }\n\n if (typeof prev.onError === \"function\") {\n prev.onError.apply(this, arguments as any)\n }\n }\n\n function _onUnhandledRejectionHandler(\n this: WindowEventHandlers,\n event: PromiseRejectionEvent\n ): void {\n const span = self.createSpan()\n\n let error: Error\n\n if (event && event.reason && isError(event.reason)) {\n error = event.reason\n } else {\n error = {\n name: \"UnhandledPromiseRejectionError\",\n message: _reasonFromEvent(event)\n }\n }\n\n span.setError(error)\n\n self.send(span)\n\n if (typeof prev.unhandledRejection === \"function\") {\n prev.unhandledRejection.apply(this, arguments as any)\n }\n }\n\n if (opts.onerror) {\n ctx.onerror = _onErrorHandler\n }\n\n if (opts.onunhandledrejection) {\n ctx.onunhandledrejection = _onUnhandledRejectionHandler\n }\n }\n\n function _reasonFromEvent(event: PromiseRejectionEvent): string {\n if (!event || !event.reason) {\n return \"\"\n }\n\n if (typeof event.reason === \"string\") {\n return event.reason\n }\n\n return JSON.stringify(event.reason, circularReplacer())\n }\n\n function circularReplacer() {\n const seenValue: any[] = []\n const seenKey: string[] = []\n return (key: string, value: any) => {\n if (typeof value === \"object\" && value !== null) {\n const i = seenValue.indexOf(value)\n if (i !== -1) {\n return `[cyclic value: ${seenKey[i] || \"root object\"}]`\n } else {\n seenValue.push(value)\n seenKey.push(key)\n }\n }\n\n return value\n }\n }\n}\n\nexport const plugin = windowEventsPlugin\n", "import Appsignal from '@appsignal/javascript'\nimport { plugin } from '@appsignal/plugin-window-events'\n\n/**\n * Call at page initialization to initialize Appsignal logging\n *\n * @param {Object} [config] - Configuration options\n * @param {boolean} [config.reportErrors] - Whether to report all unhandled errors to our error monitoring service.\n Note we avoid enabling it in Platform because we are afraid of being flooded with all sort of errors from Retailers websites.\n*/\nexport function initLogging ({ reportErrors = false } = {}) {\n const globals = window.provenance\n if (!globals) return\n if (\n typeof globals.appsignalApiKey !== 'undefined' ||\n typeof globals.applicationEnvironment !== 'undefined'\n ) {\n const appsignal = new Appsignal({\n key: globals.appsignalApiKey,\n revision: globals.revision\n })\n\n if (reportErrors) {\n appsignal.use(plugin())\n }\n\n globals.appsignal = appsignal\n }\n}\n\n// Log an error to Appsignal only\nexport function internalLog (err) {\n const appsignal = window.provenance.appsignal\n if (appsignal) {\n appsignal.sendError(err)\n }\n}\n\n// Log an error to Appsignal and the JS console\nexport function log (err) {\n // eslint-disable-next-line no-console\n console.log(err.message)\n\n internalLog(err)\n}\n", "import { AnalyticsBrowser } from '@segment/analytics-next'\n\nimport { internalLog, log } from './logger'\n\n// IP addresses are anonymised in Segment calls (identify and track) to avoid any PII being captured\n// See https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/identity/#anonymizing-ip for info.\n\nlet segmentAnalytics\nif (window.provenance && window.provenance.segmentWriteKey) {\n segmentAnalytics = AnalyticsBrowser.load({ writeKey: window.provenance.segmentWriteKey })\n // The Segment user is defined as an account identifier\n console.debug('Init Segment', window.provenance.segmentWriteKey)\n if (window.provenance.segmentUserId) {\n segmentAnalytics.identify(window.provenance.segmentUserId, {}, { context: { ip: '0.0.0.0' } })\n }\n}\n\nconst postEventToGTM = (event, properties) => {\n // console.log('Track event: GTM', event, properties)\n\n properties.eventCategory = properties.eventCategory ? `provenance:${properties.eventCategory}` : event\n\n try {\n // Old-style IFrame tracking\n if (window.xprops && window.xprops.track) {\n window.xprops.track(event, properties)\n }\n\n const eventData = properties\n eventData.event = event\n\n // New-style IFrame tracking\n if (window.xprops && window.xprops.onChildEvent) {\n const event = {\n name: 'analytics_event',\n data: {\n details: eventData\n }\n }\n window.xprops.onChildEvent(event)\n }\n\n // Also push to the data layer of the iFrame, for internal capture\n window.dataLayer = window.dataLayer || []\n window.dataLayer.push(eventData)\n } catch (error) {\n log(error)\n }\n}\n\nconst postEventToSegment = (event, properties) => {\n if (window.provenance.segmentWriteKey) {\n // console.log('Track event: Segment', event, properties)\n segmentAnalytics.track(event, properties, { context: { ip: '0.0.0.0' } })\n }\n}\n\n// For tracking events on platform embedded content\nconst track = (event, properties, options = {}) => {\n const adapter = options.adapter || 'gtm'\n // Prefix all event names with \"provenance:\"\n event = `provenance:${event}`\n const undefinedProvEventProps = []\n for (const property in properties) {\n if (properties[property] === undefined || properties[property] === '') {\n undefinedProvEventProps.push('Property ' + property + ' undefined')\n }\n }\n if (undefinedProvEventProps.length > 0) {\n internalLog(undefinedProvEventProps, event, properties, adapter)\n }\n\n // TODO: add adapters to gtm track calls and segment tracking (plus adapter) to all track calls\n if (adapter === 'segment') {\n postEventToSegment(event, properties)\n } else {\n postEventToGTM(event, properties)\n }\n}\n\nconst trackInApp = (event, properties) => {\n // Guard against tracking when impersonating in production\n if (properties.impersonating &&\n window.provenance.applicationEnvironment === 'production') {\n console.debug('Skipping tracking while impersonating in production', event, properties)\n return\n }\n\n // Ensure correct in app identity is set\n segmentAnalytics.identify(properties.user_id, {}, { context: { ip: '0.0.0.0' } })\n postEventToSegment(event, properties)\n}\n\nexport { track, trackInApp, segmentAnalytics }\n", "import { Controller } from '@hotwired/stimulus'\n\nimport * as analytics from '../utils/analytics'\n\n// The naming convention is: provenance:objectName_actionName\n// Example event name: provenance:bundleTab_clicked\n// This style is documented: https://davidwells.io/blog/clean-analytics\nexport default class extends Controller {\n // For improved clarity, we should prefer values over plain data attributes.\n // E.g. use data-analytics-label-value=\"Some Label\" over data-label=\"Some Label\"\n // See: https://stimulus.hotwired.dev/reference/values\n static values = {\n // The action name in past tense, e.g. clicked, or scrolled.\n // It is used to construct the event name.\n action: { type: String, default: 'clicked' },\n // The context, which follows a specific format.\n // E.g.: Retailer Name / Beauty brand / Sun Cream\n // TODO: Refactor this to be taken from the top level (more convenient than having to pass it through).\n label: String,\n // The name of the object being tracked.\n // It is used to construct the event name.\n name: String,\n // Subject can contain any useful info, e.g. the name of the PP being clicked.\n subject: String,\n // The version is currently only used to track which UI version of a claim\n // modal is being used, but it could be used for other purposes in the future.\n version: Number\n }\n\n // Use the click() method to track clicks.\n // Assumes that the event.currentTarget has type and label data attributes (for legacy reasons).\n //\n // Example usage:\n //\n // \n // \uD83D\uDC4D\n // \n // \uD83D\uDC4E\n // \n // \n //\n click (event) {\n const { context, label, type: eventType, brandName, subjectName } = event.currentTarget.dataset\n const { channel, type, tabOrder } = this.element.dataset\n let prodOrBrand\n let ppSubjectType\n let bundleType\n let dtc\n\n if (subjectName && brandName) {\n prodOrBrand = (subjectName === brandName) ? 'brand' : 'product'\n }\n if (channel && brandName) {\n dtc = channel === brandName\n }\n \n if (type === 'combined_bundle') {\n bundleType = type\n // If tab order is brand_first, all proof points are brand proof points\n if (tabOrder === 'brand_first') {\n ppSubjectType = 'brand'\n } else {\n // For product_first, first tab is product, second is brand\n const isFirstTab = this.element.querySelector(\"[aria-selected='true']\").id === 'tab-1'\n ppSubjectType = isFirstTab ? 'product' : 'brand'\n }\n } else {\n bundleType = prodOrBrand\n ppSubjectType = prodOrBrand\n }\n\n let eventName = `click_${eventType}`\n if (type) eventName += `_${type}`\n\n if (this.element.nodeName === 'DETAILS') {\n this.actionValue = this.element.open ? 'opened' : 'closed'\n }\n\n if (this.hasNameValue) {\n eventName = `${this.nameValue}_${this.actionValue}`\n }\n\n const eventLabel = channel ? `${channel} / ${context}` : context\n\n analytics.track(eventName, {\n eventAction: this.hasSubjectValue ? this.subjectValue : label,\n eventLabel: this.hasLabelValue ? this.labelValue : eventLabel\n }, { adapter: 'gtm' })\n\n eventName = eventType ? `${eventType}_${this.actionValue}` : eventName\n\n analytics.track(eventName, {\n object: eventType,\n action: this.actionValue,\n type,\n channel,\n brand_name: brandName,\n subject_name: subjectName,\n subject_value: this.hasSubjectValue ? this.subjectValue : label,\n subject_type: ppSubjectType,\n event_label: eventLabel,\n bundle_type: bundleType,\n tab_order: tabOrder,\n dtc,\n ...(this.hasVersionValue && { ui_version: this.versionValue })\n }, { adapter: 'segment' })\n }\n}\n", "import { Controller } from '@hotwired/stimulus'\nimport * as analytics from '../utils/analytics'\n\nexport default class extends Controller {\n static get targets () {\n return ['link']\n }\n\n connect () {\n // Don't run if we're not in an iframe\n if (window.self === window.top) return\n\n if (window.xprops && window.xprops.version) {\n this.setupImpressionTracking()\n }\n }\n\n // this could also be in analytics controller to further unify code\n setupImpressionTracking () {\n this.defineParentEventHandler()\n\n window.xprops.onChildEvent({\n name: 'setup_impression_tracking'\n })\n }\n\n // consider moving this to something like sdkEvents so we can have onParentEvent defined in a single place\n defineParentEventHandler () {\n window.xprops.export({\n onParentEvent: (event) => {\n switch (event.name) {\n case 'impression_detected':\n this.trackImpression()\n break\n default:\n console.warn('[Provenance] Unrecognised parent event:', event)\n }\n }\n })\n }\n\n getCombinedBundlePPsInView () {\n // get tab with aria selected\n const proofPointNames = []\n const tabName = this.element.querySelector(\"[aria-selected='true']\").dataset.name\n const panel = (tabName === 'product-pp-tab')\n ? this.element.querySelector(\"[data-name='product-pp-panel']\")\n : this.element.querySelector(\"[data-name='brand-pp-panel']\")\n const proofPoints = panel.querySelectorAll('button')\n proofPoints.forEach(pp => {\n proofPointNames.push(pp.dataset.name)\n })\n return proofPointNames\n }\n\n // this could also be in analytics controller to further unify code\n trackImpression () {\n const { channel, brandName, resourceId, subjectName, type, tabOrder } = this.element.dataset\n const eventLabel = `${channel} / ${brandName} / ${subjectName}`\n let prodOrBrand\n let dtc\n\n if (subjectName && brandName) {\n prodOrBrand = (subjectName === brandName) ? 'brand' : 'product'\n }\n if (channel && brandName) {\n dtc = channel === brandName\n }\n\n // Determine the subject type for proof points\n let ppType\n if (type === 'combined_bundle') {\n if (tabOrder === 'brand_first') {\n ppType = 'brand'\n } else {\n // For product_first bundles, check which tab is selected\n const selectedTab = this.element.querySelector(\"[aria-selected='true']\")\n ppType = selectedTab.id === 'tab-1' ? 'product' : 'brand'\n }\n } else {\n ppType = prodOrBrand\n }\n\n const bundleType = (type === 'combined_bundle') ? 'combined_bundle' : prodOrBrand\n\n let proofPointNames =\n this.linkTargets.map(link => {\n return link.dataset.name\n })\n\n analytics.track('impression', {\n eventCategory: 'impression_bundle',\n eventAction: proofPointNames.join('|'),\n eventLabel\n }, { adapter: 'gtm' })\n\n analytics.track('bundle_impression', {\n object: 'bundle',\n action: 'impression',\n channel,\n brand_name: brandName,\n subject_name: subjectName,\n subject_value: proofPointNames.join('|'),\n subject_type: bundleType,\n event_label: eventLabel,\n bundle_type: bundleType,\n resource_id: resourceId,\n dtc\n }, { adapter: 'segment' })\n\n // if the bundle is combined, only track proof points that are in view\n if (type === 'combined_bundle') {\n proofPointNames = this.getCombinedBundlePPsInView()\n }\n\n proofPointNames.forEach((name) => {\n analytics.track('impression', {\n eventCategory: 'impression_proofpoint_bundle',\n eventAction: name,\n eventLabel\n }, { adapter: 'gtm' })\n\n analytics.track('proofpoint_impression', {\n object: 'proofpoint',\n action: 'impression',\n channel,\n brand_name: brandName,\n subject_name: subjectName,\n subject_value: name,\n subject_type: ppType,\n bundle_type: bundleType,\n dtc\n }, { adapter: 'segment' })\n })\n }\n}\n", "import { Controller } from '@hotwired/stimulus'\n\nexport default class extends Controller {\n connect () {\n // Prevent reinitialization or don't initialize if we're not in an iframe\n if (window.self === window.top) {\n return\n }\n\n this.initFrame()\n }\n\n initFrame () {\n let variant = 'embed'\n const url = new URL(document.location)\n const modalSize = url.searchParams.get('modal')\n\n if (modalSize && modalSize !== 'true') {\n variant = modalSize\n }\n\n window.provenance.frameFactory.getFrame(variant, document.location.href)\n }\n}\n", "import { Controller } from '@hotwired/stimulus'\nimport * as analytics from '../utils/analytics'\n\n/**\n * This file is responsible for tracking user behaviour when they\n * scroll the Proof Point container horizontally.\n * An analytics event will be fired when any container is scrolled,\n * regardless of whether it contains brand or product Proof Points.\n * However the event(s) will only be sent once per page visit:\n * this behaviour is controlled by `this.scrolled`. In other words,\n * if the user has already scrolled, the scroll handler function will\n * be a no-op.\n */\nexport default class extends Controller {\n initialize () {\n this.element.addEventListener('scroll', this.handleScroll)\n }\n\n handleScroll () {\n if (this.scrolled) return\n\n const bundle = document.querySelector('.Bundle')\n const {\n bundleId, // e.g. 2FfDJv38\n channel, // e.g. A Little Find\n brandName, // e.g. Emma Hardie\n subjectName, // e.g. Brilliance Facial Oil\n style, // e.g. Card\n type // e.g. combined_bundle\n } = bundle.dataset\n const eventLabel = `${channel} / ${brandName} / ${subjectName}`\n\n analytics.track('firstScrolled', {\n eventCategory: 'firstScrolled_bundle',\n eventAction: bundleId,\n eventLabel\n }, { adapter: 'gtm' })\n\n analytics.track('bundle_firstScrolled', {\n object: 'bundle',\n action: 'firstScrolled',\n channel,\n brand_name: brandName,\n subject_name: subjectName,\n event_label: eventLabel,\n bundle_id: bundleId,\n bundle_style: style,\n bundle_type: type\n }, { adapter: 'segment' })\n\n this.scrolled = true\n }\n}\n", "function e(e,t){for(var o=0;oe.length)&&(t=e.length);for(var o=0,n=new Array(t);o0&&this.registerTriggers.apply(this,t(a)),this.onClick=this.onClick.bind(this),this.onKeydown=this.onKeydown.bind(this)}var i,a,r;return i=o,(a=[{key:\"registerTriggers\",value:function(){for(var e=this,t=arguments.length,o=new Array(t),n=0;n0&&void 0!==arguments[0]?arguments[0]:null;if(this.activeElement=document.activeElement,this.modal.setAttribute(\"aria-hidden\",\"false\"),this.modal.classList.add(this.config.openClass),this.scrollBehaviour(\"disable\"),this.addEventListeners(),this.config.awaitOpenAnimation){var o=function t(){e.modal.removeEventListener(\"animationend\",t,!1),e.setFocusToFirstNode()};this.modal.addEventListener(\"animationend\",o,!1)}else this.setFocusToFirstNode();this.config.onShow(this.modal,this.activeElement,t)}},{key:\"closeModal\",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null,t=this.modal;if(this.modal.setAttribute(\"aria-hidden\",\"true\"),this.removeEventListeners(),this.scrollBehaviour(\"enable\"),this.activeElement&&this.activeElement.focus&&this.activeElement.focus(),this.config.onClose(this.modal,this.activeElement,e),this.config.awaitCloseAnimation){var o=this.config.openClass;this.modal.addEventListener(\"animationend\",(function e(){t.classList.remove(o),t.removeEventListener(\"animationend\",e,!1)}),!1)}else t.classList.remove(this.config.openClass)}},{key:\"closeModalById\",value:function(e){this.modal=document.getElementById(e),this.modal&&this.closeModal()}},{key:\"scrollBehaviour\",value:function(e){if(this.config.disableScroll){var t=document.querySelector(\"body\");switch(e){case\"enable\":Object.assign(t.style,{overflow:\"\"});break;case\"disable\":Object.assign(t.style,{overflow:\"hidden\"})}}}},{key:\"addEventListeners\",value:function(){this.modal.addEventListener(\"touchstart\",this.onClick),this.modal.addEventListener(\"click\",this.onClick),document.addEventListener(\"keydown\",this.onKeydown)}},{key:\"removeEventListeners\",value:function(){this.modal.removeEventListener(\"touchstart\",this.onClick),this.modal.removeEventListener(\"click\",this.onClick),document.removeEventListener(\"keydown\",this.onKeydown)}},{key:\"onClick\",value:function(e){(e.target.hasAttribute(this.config.closeTrigger)||e.target.parentNode.hasAttribute(this.config.closeTrigger))&&(e.preventDefault(),e.stopPropagation(),this.closeModal(e))}},{key:\"onKeydown\",value:function(e){27===e.keyCode&&this.closeModal(e),9===e.keyCode&&this.retainFocus(e)}},{key:\"getFocusableNodes\",value:function(){var e=this.modal.querySelectorAll(n);return Array.apply(void 0,t(e))}},{key:\"setFocusToFirstNode\",value:function(){var e=this;if(!this.config.disableFocus){var t=this.getFocusableNodes();if(0!==t.length){var o=t.filter((function(t){return!t.hasAttribute(e.config.closeTrigger)}));o.length>0&&o[0].focus(),0===o.length&&t[0].focus()}}}},{key:\"retainFocus\",value:function(e){var t=this.getFocusableNodes();if(0!==t.length)if(t=t.filter((function(e){return null!==e.offsetParent})),this.modal.contains(document.activeElement)){var o=t.indexOf(document.activeElement);e.shiftKey&&0===o&&(t[t.length-1].focus(),e.preventDefault()),!e.shiftKey&&t.length>0&&o===t.length-1&&(t[0].focus(),e.preventDefault())}else t[0].focus()}}])&&e(i.prototype,a),r&&e(i,r),o}(),a=null,r=function(e){if(!document.getElementById(e))return console.warn(\"MicroModal: \u2757Seems like you have missed %c'\".concat(e,\"'\"),\"background-color: #f8f9fa;color: #50596c;font-weight: bold;\",\"ID somewhere in your code. Refer example below to resolve it.\"),console.warn(\"%cExample:\",\"background-color: #f8f9fa;color: #50596c;font-weight: bold;\",'
')),!1},s=function(e,t){if(function(e){e.length<=0&&(console.warn(\"MicroModal: \u2757Please specify at least one %c'micromodal-trigger'\",\"background-color: #f8f9fa;color: #50596c;font-weight: bold;\",\"data attribute.\"),console.warn(\"%cExample:\",\"background-color: #f8f9fa;color: #50596c;font-weight: bold;\",''))}(e),!t)return!0;for(var o in t)r(o);return!0},{init:function(e){var o=Object.assign({},{openTrigger:\"data-micromodal-trigger\"},e),n=t(document.querySelectorAll(\"[\".concat(o.openTrigger,\"]\"))),r=function(e,t){var o=[];return e.forEach((function(e){var n=e.attributes[t].value;void 0===o[n]&&(o[n]=[]),o[n].push(e)})),o}(n,o.openTrigger);if(!0!==o.debugMode||!1!==s(n,r))for(var l in r){var c=r[l];o.targetModal=l,o.triggers=t(c),a=new i(o)}},show:function(e,t){var o=t||{};o.targetModal=e,!0===o.debugMode&&!1===r(e)||(a&&a.removeEventListeners(),(a=new i(o)).showModal())},close:function(e){e?a.closeModalById(e):a.closeModal()}});\"undefined\"!=typeof window&&(window.MicroModal=l);export default l;\n", "import MicroModal from 'micromodal'\n\nconst openModal = (options) => {\n console.debug('openModal options:', options)\n options.id = options.id || 'provenance-modal'\n options.variant = options.variant || 'full'\n\n if (options.url.includes('/stories') && !options.url.includes('/modal')) {\n options.url += '/modal'\n }\n\n const uri = new URL(options.url, document.location.origin)\n uri.searchParams.set('modal', options.variant)\n options.url = uri.toString()\n\n if (window.xprops && typeof window.xprops.openModal === 'function') {\n openModalFromEmbed(options)\n return\n }\n\n const buildModalElement = ({ id, variant, behavior }) => {\n const template = document.createElement('template')\n template.innerHTML = modalHtml({\n id,\n classes: `ProvenanceModal--${variant}Variant ${behavior ? `ProvenanceModal--${behavior}Behavior` : ''}`\n })\n const modal = template.content.firstElementChild.cloneNode(true)\n return modal\n }\n\n /**\n * Builds the HTML for Micromodal.js to display a modal.\n * It is intended to be added at the bottom of the page, before .\n *\n * @param {string} id - a valid, unique HTML ID (required for Micromodal.js)\n * @param {string} [classes] - additional CSS classes (optional)\n * @returns {string}\n */\n const modalHtml = ({ id, classes }) =>\n `\n
\n
\n
\n \n
\n
\n
\n
\n `\n\n const insertContentInModal = (modal, content) => {\n modal\n .querySelector('.ProvenanceModal-content')\n .insertAdjacentHTML('beforeend', content)\n }\n\n const openDrawer = modal => {\n modal.dataset.state = 'drawer-open'\n }\n\n const closeDrawer = (modal, callback) => {\n modal.dataset.state = 'drawer-closed'\n modal.addEventListener('transitionend', callback)\n }\n\n const showModal = id => {\n MicroModal.show(id, {\n onShow: modal => {\n if (options.behavior === 'drawer') {\n openDrawer(modal)\n }\n },\n onClose: modal => {\n if (options.behavior === 'drawer') {\n closeDrawer(modal, e => {\n modal.remove()\n })\n } else {\n modal.remove()\n }\n },\n disableScroll: true\n })\n }\n\n // Add layout param to URL for modals handled internally\n uri.searchParams.set('layout', false)\n options.url = uri.toString()\n\n const modal = buildModalElement(options)\n document.body.appendChild(modal)\n\n fetch(options.url)\n .then(response => response.text())\n .then(text => {\n insertContentInModal(modal, text)\n showModal(options.id)\n })\n .catch(err => {\n console.error('modalOpen fetch error:', err)\n })\n}\n\nconst openModalFromEmbed = opts => {\n const { xprops } = window\n console.debug('openModalFromEmbed', opts, 'xprops:', xprops)\n\n if (xprops.version) {\n xprops.openModal(opts)\n }\n}\n\nexport default openModal\n", "import { Controller } from '@hotwired/stimulus'\nimport openModal from '../utils/modal'\n\nexport default class extends Controller {\n call (event) {\n event.preventDefault()\n\n let { behavior, href, modalVariant: variant, slug, suffix, type } = this.element.dataset\n\n let url = this.element.getAttribute('href') || href\n url = suffix ? `${url}/${suffix}` : url\n\n if (type === 'proofpoint') {\n behavior = 'drawer'\n variant = 'small'\n }\n const opts = { behavior, slug, url, variant }\n console.debug('[modal_trigger_controller] calling openModal', opts)\n openModal(opts)\n }\n}\n", "import { Controller } from '@hotwired/stimulus'\n\nexport default class extends Controller {\n static targets = ['flag', 'logos']\n\n mouseOver () {\n if (window.screen.width > 1000) {\n this.flagTarget.style.display = 'none'\n this.logosTarget.style.display = 'flex'\n }\n }\n\n mouseOut () {\n if (window.screen.width > 1000) {\n this.flagTarget.style.display = 'flex'\n this.logosTarget.style.display = 'none'\n }\n }\n}\n", "import { Controller } from '@hotwired/stimulus'\n\nconst DELAY = 0 // Tweak this to increase the status change delay. 0 means no delay at all.\n\n/**\n * This controller is solely responsible for updating the Proof Point status\n * for vanity purposes. The status is 'checking' by default and gets updated\n * to either 'evidenced' or 'verified' after a random number of seconds.\n */\nexport default class extends Controller {\n static values = {\n status: String\n }\n\n connect () {\n if (this.statusValue !== 'evidenced' && this.statusValue !== 'verified') return\n\n setTimeout(() => {\n this.element.querySelector('[checking]').dataset.state = 'checked'\n this.element.querySelector(`[${this.statusValue}]`).hidden = false\n }, DELAY)\n }\n}\n", "/**\n * Original code taken from: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles/tab_role\n *\n * Code adapted to follow the general style of a Stimulus controller\n *\n * The tab panels have been readapted to work by scrolling horizontally\n * (original code was making use of the `hidden` attribute instead)\n */\nimport { Controller } from '@hotwired/stimulus'\nimport * as analytics from '../utils/analytics'\n\nexport default class extends Controller {\n static targets = ['tab']\n\n connect () {\n // Enable arrow navigation between tabs in the tab list\n this.tabFocus = 0\n }\n\n switch (e) {\n const { innerText: eventAction } = e.target\n changeTabs(e)\n trackBundleTabClicked(e)\n if (eventAction === 'Brand') {\n trackBrandProofPointImpressions(e)\n }\n }\n\n onTabListKeyDown (e) {\n // Move right\n if (e.keyCode === 39 || e.keyCode === 37) {\n const tabs = this.tabTargets\n\n tabs[this.tabFocus].setAttribute('tabindex', -1)\n if (e.keyCode === 39) {\n this.tabFocus++\n // If we're at the end, go to the start\n if (this.tabFocus >= tabs.length) {\n this.tabFocus = 0\n }\n // Move left\n } else if (e.keyCode === 37) {\n this.tabFocus--\n // If we're at the start, move to the end\n if (this.tabFocus < 0) {\n this.tabFocus = tabs.length - 1\n }\n }\n\n tabs[this.tabFocus].setAttribute('tabindex', 0)\n tabs[this.tabFocus].focus()\n }\n }\n}\n\nfunction changeTabs (e) {\n const target = e.target\n const parent = target.parentNode\n const grandparent = parent.parentNode\n\n // Remove all current selected tabs\n parent\n .querySelectorAll('[aria-selected=\"true\"]')\n .forEach(t => t.setAttribute('aria-selected', false))\n\n // Set this tab as selected\n target.setAttribute('aria-selected', true)\n\n // Show the selected panel\n grandparent.parentNode\n .querySelector(`#${target.getAttribute('aria-controls')}`)\n .scrollIntoView({\n block: 'nearest',\n behavior: /apple/i.test(navigator.vendor) ? 'auto' : 'smooth'\n })\n}\n\nfunction trackBundleTabClicked (e) {\n const { innerText: eventAction } = e.target\n const { channel, brandName, subjectName } = e.target.parentNode.parentNode.dataset\n const eventLabel = channel + ' / ' + brandName + ' / ' + subjectName\n const dtc = channel === brandName\n analytics.track('bundleTab_clicked', {\n eventAction,\n eventLabel\n })\n analytics.track('bundleTab_clicked',\n {\n object: 'bundleTab',\n action: 'clicked',\n channel,\n brand_name: brandName,\n subject_name: subjectName,\n subject_value: eventAction,\n event_label: eventLabel,\n bundle_type: 'combined_bundle',\n dtc\n }, { adapter: 'segment' })\n}\n\nfunction trackBrandProofPointImpressions (e) {\n const { channel, brandName, subjectName } = e.target.parentNode.parentNode.dataset\n const eventLabel = channel + ' / ' + brandName + ' / ' + subjectName\n const brandProofPointNames = getBrandProofPointNames(e)\n const dtc = channel === brandName\n brandProofPointNames.forEach((brandProofPointName) => {\n analytics.track('impression', {\n eventCategory: 'impression_proofpoint_bundle',\n eventAction: brandProofPointName,\n eventLabel\n }, { adapter: 'gtm' })\n\n analytics.track('proofpoint_impression',\n {\n object: 'proofpoint',\n action: 'impression',\n channel,\n brand_name: brandName,\n subject_name: subjectName,\n subject_value: brandProofPointName,\n subject_type: 'brand',\n event_label: eventLabel,\n bundle_type: 'combined_bundle',\n dtc\n }, { adapter: 'segment' })\n }\n )\n}\n\nfunction getBrandProofPointNames (e) {\n const grandParent = e.target.parentNode.parentNode\n const brandProofPointNames = []\n const brandPanel = grandParent.querySelector(\"[data-name='brand-pp-panel']\")\n const brandProofPoints = brandPanel.querySelectorAll('button')\n brandProofPoints\n .forEach((brandPP) => {\n brandProofPointNames.push(brandPP.dataset.name)\n })\n return brandProofPointNames\n}\n", "/* This controller's sole purpose is to fix a minor issue where, when tabbing through\nitems in a tabpanel and jumping to the next tabpanel, the next tab didn't appear\nto be focused/selected. Sorry, I couldn't find a way to do that in CSS. */\nimport { Controller } from '@hotwired/stimulus'\n\nexport default class extends Controller {\n onKeyUp (e) {\n // We only want Tab key presses\n if (e.key !== 'Tab') return\n\n // Remove ARIA selected status from all panels\n this.element.parentElement.querySelectorAll('[aria-selected=\"true\"]')\n .forEach(t => t.setAttribute('aria-selected', false))\n\n const numberOfTabs = this.element.children.length\n\n // Check if the currently focused element is a tabpanel or one of its children. If so, ARIA select it.\n for (let i = 1; i <= numberOfTabs; i++) {\n if (document.activeElement.id === `panel-${i}` || document.activeElement.closest('[role=\"tabpanel\"]').id === `panel-${i}`) {\n document.getElementById(`tab-${i}`).setAttribute('aria-selected', true)\n }\n }\n }\n}\n", "/** Normal hydration that attaches to a DOM tree but does not diff it. */\nexport const MODE_HYDRATE = 1 << 5;\n/** Signifies this VNode suspended on the previous render */\nexport const MODE_SUSPENDED = 1 << 7;\n/** Indicates that this node needs to be inserted while patching children */\nexport const INSERT_VNODE = 1 << 16;\n/** Indicates a VNode has been matched with another VNode in the diff */\nexport const MATCHED = 1 << 17;\n\n/** Reset all mode flags */\nexport const RESET_MODE = ~(MODE_HYDRATE | MODE_SUSPENDED);\n\nexport const EMPTY_OBJ = /** @type {any} */ ({});\nexport const EMPTY_ARR = [];\nexport const IS_NON_DIMENSIONAL =\n\t/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;\n", "import { EMPTY_ARR } from './constants';\n\nexport const isArray = Array.isArray;\n\n/**\n * Assign properties from `props` to `obj`\n * @template O, P The obj and props types\n * @param {O} obj The object to copy properties to\n * @param {P} props The object to copy properties from\n * @returns {O & P}\n */\nexport function assign(obj, props) {\n\t// @ts-expect-error We change the type of `obj` to be `O & P`\n\tfor (let i in props) obj[i] = props[i];\n\treturn /** @type {O & P} */ (obj);\n}\n\n/**\n * Remove a child node from its parent if attached. This is a workaround for\n * IE11 which doesn't support `Element.prototype.remove()`. Using this function\n * is smaller than including a dedicated polyfill.\n * @param {preact.ContainerNode} node The node to remove\n */\nexport function removeNode(node) {\n\tlet parentNode = node.parentNode;\n\tif (parentNode) parentNode.removeChild(node);\n}\n\nexport const slice = EMPTY_ARR.slice;\n", "import { _catchError } from './diff/catch-error';\n\n/**\n * The `option` object can potentially contain callback functions\n * that are called during various stages of our renderer. This is the\n * foundation on which all our addons like `preact/debug`, `preact/compat`,\n * and `preact/hooks` are based on. See the `Options` type in `internal.d.ts`\n * for a full list of available option hooks (most editors/IDEs allow you to\n * ctrl+click or cmd+click on mac the type definition below).\n * @type {Options}\n */\nconst options = {\n\t_catchError\n};\n\nexport default options;\n", "import { slice } from './util';\nimport options from './options';\n\nlet vnodeId = 0;\n\n/**\n * Create an virtual node (used for JSX)\n * @param {VNode[\"type\"]} type The node name or Component constructor for this\n * virtual node\n * @param {object | null | undefined} [props] The properties of the virtual node\n * @param {Array} [children] The children of the\n * virtual node\n * @returns {VNode}\n */\nexport function createElement(type, props, children) {\n\tlet normalizedProps = {},\n\t\tkey,\n\t\tref,\n\t\ti;\n\tfor (i in props) {\n\t\tif (i == 'key') key = props[i];\n\t\telse if (i == 'ref') ref = props[i];\n\t\telse normalizedProps[i] = props[i];\n\t}\n\n\tif (arguments.length > 2) {\n\t\tnormalizedProps.children =\n\t\t\targuments.length > 3 ? slice.call(arguments, 2) : children;\n\t}\n\n\t// If a Component VNode, check for and apply defaultProps\n\t// Note: type may be undefined in development, must never error here.\n\tif (typeof type == 'function' && type.defaultProps != null) {\n\t\tfor (i in type.defaultProps) {\n\t\t\tif (normalizedProps[i] === undefined) {\n\t\t\t\tnormalizedProps[i] = type.defaultProps[i];\n\t\t\t}\n\t\t}\n\t}\n\n\treturn createVNode(type, normalizedProps, key, ref, null);\n}\n\n/**\n * Create a VNode (used internally by Preact)\n * @param {VNode[\"type\"]} type The node name or Component\n * Constructor for this virtual node\n * @param {object | string | number | null} props The properties of this virtual node.\n * If this virtual node represents a text node, this is the text of the node (string or number).\n * @param {string | number | null} key The key for this virtual node, used when\n * diffing it against its children\n * @param {VNode[\"ref\"]} ref The ref property that will\n * receive a reference to its created child\n * @returns {VNode}\n */\nexport function createVNode(type, props, key, ref, original) {\n\t// V8 seems to be better at detecting type shapes if the object is allocated from the same call site\n\t// Do not inline into createElement and coerceToVNode!\n\t/** @type {VNode} */\n\tconst vnode = {\n\t\ttype,\n\t\tprops,\n\t\tkey,\n\t\tref,\n\t\t_children: null,\n\t\t_parent: null,\n\t\t_depth: 0,\n\t\t_dom: null,\n\t\t// _nextDom must be initialized to undefined b/c it will eventually\n\t\t// be set to dom.nextSibling which can return `null` and it is important\n\t\t// to be able to distinguish between an uninitialized _nextDom and\n\t\t// a _nextDom that has been set to `null`\n\t\t_nextDom: undefined,\n\t\t_component: null,\n\t\tconstructor: undefined,\n\t\t_original: original == null ? ++vnodeId : original,\n\t\t_index: -1,\n\t\t_flags: 0\n\t};\n\n\t// Only invoke the vnode hook if this was *not* a direct copy:\n\tif (original == null && options.vnode != null) options.vnode(vnode);\n\n\treturn vnode;\n}\n\nexport function createRef() {\n\treturn { current: null };\n}\n\nexport function Fragment(props) {\n\treturn props.children;\n}\n\n/**\n * Check if a the argument is a valid Preact VNode.\n * @param {*} vnode\n * @returns {vnode is VNode}\n */\nexport const isValidElement = vnode =>\n\tvnode != null && vnode.constructor == undefined;\n", "import { assign } from './util';\nimport { diff, commitRoot } from './diff/index';\nimport options from './options';\nimport { Fragment } from './create-element';\nimport { MODE_HYDRATE } from './constants';\n\n/**\n * Base Component class. Provides `setState()` and `forceUpdate()`, which\n * trigger rendering\n * @param {object} props The initial component props\n * @param {object} context The initial context from parent components'\n * getChildContext\n */\nexport function BaseComponent(props, context) {\n\tthis.props = props;\n\tthis.context = context;\n}\n\n/**\n * Update component state and schedule a re-render.\n * @this {Component}\n * @param {object | ((s: object, p: object) => object)} update A hash of state\n * properties to update with new values or a function that given the current\n * state and props returns a new partial state\n * @param {() => void} [callback] A function to be called once component state is\n * updated\n */\nBaseComponent.prototype.setState = function (update, callback) {\n\t// only clone state when copying to nextState the first time.\n\tlet s;\n\tif (this._nextState != null && this._nextState !== this.state) {\n\t\ts = this._nextState;\n\t} else {\n\t\ts = this._nextState = assign({}, this.state);\n\t}\n\n\tif (typeof update == 'function') {\n\t\t// Some libraries like `immer` mark the current state as readonly,\n\t\t// preventing us from mutating it, so we need to clone it. See #2716\n\t\tupdate = update(assign({}, s), this.props);\n\t}\n\n\tif (update) {\n\t\tassign(s, update);\n\t}\n\n\t// Skip update if updater function returned null\n\tif (update == null) return;\n\n\tif (this._vnode) {\n\t\tif (callback) {\n\t\t\tthis._stateCallbacks.push(callback);\n\t\t}\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Immediately perform a synchronous re-render of the component\n * @this {Component}\n * @param {() => void} [callback] A function to be called after component is\n * re-rendered\n */\nBaseComponent.prototype.forceUpdate = function (callback) {\n\tif (this._vnode) {\n\t\t// Set render mode so that we can differentiate where the render request\n\t\t// is coming from. We need this because forceUpdate should never call\n\t\t// shouldComponentUpdate\n\t\tthis._force = true;\n\t\tif (callback) this._renderCallbacks.push(callback);\n\t\tenqueueRender(this);\n\t}\n};\n\n/**\n * Accepts `props` and `state`, and returns a new Virtual DOM tree to build.\n * Virtual DOM is generally constructed via [JSX](http://jasonformat.com/wtf-is-jsx).\n * @param {object} props Props (eg: JSX attributes) received from parent\n * element/component\n * @param {object} state The component's current state\n * @param {object} context Context object, as returned by the nearest\n * ancestor's `getChildContext()`\n * @returns {ComponentChildren | void}\n */\nBaseComponent.prototype.render = Fragment;\n\n/**\n * @param {VNode} vnode\n * @param {number | null} [childIndex]\n */\nexport function getDomSibling(vnode, childIndex) {\n\tif (childIndex == null) {\n\t\t// Use childIndex==null as a signal to resume the search from the vnode's sibling\n\t\treturn vnode._parent\n\t\t\t? getDomSibling(vnode._parent, vnode._index + 1)\n\t\t\t: null;\n\t}\n\n\tlet sibling;\n\tfor (; childIndex < vnode._children.length; childIndex++) {\n\t\tsibling = vnode._children[childIndex];\n\n\t\tif (sibling != null && sibling._dom != null) {\n\t\t\t// Since updateParentDomPointers keeps _dom pointer correct,\n\t\t\t// we can rely on _dom to tell us if this subtree contains a\n\t\t\t// rendered DOM node, and what the first rendered DOM node is\n\t\t\treturn sibling._dom;\n\t\t}\n\t}\n\n\t// If we get here, we have not found a DOM node in this vnode's children.\n\t// We must resume from this vnode's sibling (in it's parent _children array)\n\t// Only climb up and search the parent if we aren't searching through a DOM\n\t// VNode (meaning we reached the DOM parent of the original vnode that began\n\t// the search)\n\treturn typeof vnode.type == 'function' ? getDomSibling(vnode) : null;\n}\n\n/**\n * Trigger in-place re-rendering of a component.\n * @param {Component} component The component to rerender\n */\nfunction renderComponent(component) {\n\tlet oldVNode = component._vnode,\n\t\toldDom = oldVNode._dom,\n\t\tcommitQueue = [],\n\t\trefQueue = [];\n\n\tif (component._parentDom) {\n\t\tconst newVNode = assign({}, oldVNode);\n\t\tnewVNode._original = oldVNode._original + 1;\n\t\tif (options.vnode) options.vnode(newVNode);\n\n\t\tdiff(\n\t\t\tcomponent._parentDom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tcomponent._globalContext,\n\t\t\tcomponent._parentDom.namespaceURI,\n\t\t\toldVNode._flags & MODE_HYDRATE ? [oldDom] : null,\n\t\t\tcommitQueue,\n\t\t\toldDom == null ? getDomSibling(oldVNode) : oldDom,\n\t\t\t!!(oldVNode._flags & MODE_HYDRATE),\n\t\t\trefQueue\n\t\t);\n\n\t\tnewVNode._original = oldVNode._original;\n\t\tnewVNode._parent._children[newVNode._index] = newVNode;\n\t\tcommitRoot(commitQueue, newVNode, refQueue);\n\n\t\tif (newVNode._dom != oldDom) {\n\t\t\tupdateParentDomPointers(newVNode);\n\t\t}\n\t}\n}\n\n/**\n * @param {VNode} vnode\n */\nfunction updateParentDomPointers(vnode) {\n\tif ((vnode = vnode._parent) != null && vnode._component != null) {\n\t\tvnode._dom = vnode._component.base = null;\n\t\tfor (let i = 0; i < vnode._children.length; i++) {\n\t\t\tlet child = vnode._children[i];\n\t\t\tif (child != null && child._dom != null) {\n\t\t\t\tvnode._dom = vnode._component.base = child._dom;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn updateParentDomPointers(vnode);\n\t}\n}\n\n/**\n * The render queue\n * @type {Array}\n */\nlet rerenderQueue = [];\n\n/*\n * The value of `Component.debounce` must asynchronously invoke the passed in callback. It is\n * important that contributors to Preact can consistently reason about what calls to `setState`, etc.\n * do, and when their effects will be applied. See the links below for some further reading on designing\n * asynchronous APIs.\n * * [Designing APIs for Asynchrony](https://blog.izs.me/2013/08/designing-apis-for-asynchrony)\n * * [Callbacks synchronous and asynchronous](https://blog.ometer.com/2011/07/24/callbacks-synchronous-and-asynchronous/)\n */\n\nlet prevDebounce;\n\nconst defer =\n\ttypeof Promise == 'function'\n\t\t? Promise.prototype.then.bind(Promise.resolve())\n\t\t: setTimeout;\n\n/**\n * Enqueue a rerender of a component\n * @param {Component} c The component to rerender\n */\nexport function enqueueRender(c) {\n\tif (\n\t\t(!c._dirty &&\n\t\t\t(c._dirty = true) &&\n\t\t\trerenderQueue.push(c) &&\n\t\t\t!process._rerenderCount++) ||\n\t\tprevDebounce !== options.debounceRendering\n\t) {\n\t\tprevDebounce = options.debounceRendering;\n\t\t(prevDebounce || defer)(process);\n\t}\n}\n\n/**\n * @param {Component} a\n * @param {Component} b\n */\nconst depthSort = (a, b) => a._vnode._depth - b._vnode._depth;\n\n/** Flush the render queue by rerendering all queued components */\nfunction process() {\n\tlet c;\n\trerenderQueue.sort(depthSort);\n\t// Don't update `renderCount` yet. Keep its value non-zero to prevent unnecessary\n\t// process() calls from getting scheduled while `queue` is still being consumed.\n\twhile ((c = rerenderQueue.shift())) {\n\t\tif (c._dirty) {\n\t\t\tlet renderQueueLength = rerenderQueue.length;\n\t\t\trenderComponent(c);\n\t\t\tif (rerenderQueue.length > renderQueueLength) {\n\t\t\t\t// When i.e. rerendering a provider additional new items can be injected, we want to\n\t\t\t\t// keep the order from top to bottom with those new items so we can handle them in a\n\t\t\t\t// single pass\n\t\t\t\trerenderQueue.sort(depthSort);\n\t\t\t}\n\t\t}\n\t}\n\tprocess._rerenderCount = 0;\n}\n\nprocess._rerenderCount = 0;\n", "import { IS_NON_DIMENSIONAL } from '../constants';\nimport options from '../options';\n\nfunction setStyle(style, key, value) {\n\tif (key[0] === '-') {\n\t\tstyle.setProperty(key, value == null ? '' : value);\n\t} else if (value == null) {\n\t\tstyle[key] = '';\n\t} else if (typeof value != 'number' || IS_NON_DIMENSIONAL.test(key)) {\n\t\tstyle[key] = value;\n\t} else {\n\t\tstyle[key] = value + 'px';\n\t}\n}\n\n// A logical clock to solve issues like https://github.com/preactjs/preact/issues/3927.\n// When the DOM performs an event it leaves micro-ticks in between bubbling up which means that\n// an event can trigger on a newly reated DOM-node while the event bubbles up.\n//\n// Originally inspired by Vue\n// (https://github.com/vuejs/core/blob/caeb8a68811a1b0f79/packages/runtime-dom/src/modules/events.ts#L90-L101),\n// but modified to use a logical clock instead of Date.now() in case event handlers get attached\n// and events get dispatched during the same millisecond.\n//\n// The clock is incremented after each new event dispatch. This allows 1 000 000 new events\n// per second for over 280 years before the value reaches Number.MAX_SAFE_INTEGER (2**53 - 1).\nlet eventClock = 0;\n\n/**\n * Set a property value on a DOM node\n * @param {PreactElement} dom The DOM node to modify\n * @param {string} name The name of the property to set\n * @param {*} value The value to set the property to\n * @param {*} oldValue The old value the property had\n * @param {string} namespace Whether or not this DOM node is an SVG node or not\n */\nexport function setProperty(dom, name, value, oldValue, namespace) {\n\tlet useCapture;\n\n\to: if (name === 'style') {\n\t\tif (typeof value == 'string') {\n\t\t\tdom.style.cssText = value;\n\t\t} else {\n\t\t\tif (typeof oldValue == 'string') {\n\t\t\t\tdom.style.cssText = oldValue = '';\n\t\t\t}\n\n\t\t\tif (oldValue) {\n\t\t\t\tfor (name in oldValue) {\n\t\t\t\t\tif (!(value && name in value)) {\n\t\t\t\t\t\tsetStyle(dom.style, name, '');\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (value) {\n\t\t\t\tfor (name in value) {\n\t\t\t\t\tif (!oldValue || value[name] !== oldValue[name]) {\n\t\t\t\t\t\tsetStyle(dom.style, name, value[name]);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// Benchmark for comparison: https://esbench.com/bench/574c954bdb965b9a00965ac6\n\telse if (name[0] === 'o' && name[1] === 'n') {\n\t\tuseCapture =\n\t\t\tname !== (name = name.replace(/(PointerCapture)$|Capture$/i, '$1'));\n\n\t\t// Infer correct casing for DOM built-in events:\n\t\tif (\n\t\t\tname.toLowerCase() in dom ||\n\t\t\tname === 'onFocusOut' ||\n\t\t\tname === 'onFocusIn'\n\t\t)\n\t\t\tname = name.toLowerCase().slice(2);\n\t\telse name = name.slice(2);\n\n\t\tif (!dom._listeners) dom._listeners = {};\n\t\tdom._listeners[name + useCapture] = value;\n\n\t\tif (value) {\n\t\t\tif (!oldValue) {\n\t\t\t\tvalue._attached = eventClock;\n\t\t\t\tdom.addEventListener(\n\t\t\t\t\tname,\n\t\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\t\tuseCapture\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tvalue._attached = oldValue._attached;\n\t\t\t}\n\t\t} else {\n\t\t\tdom.removeEventListener(\n\t\t\t\tname,\n\t\t\t\tuseCapture ? eventProxyCapture : eventProxy,\n\t\t\t\tuseCapture\n\t\t\t);\n\t\t}\n\t} else {\n\t\tif (namespace == 'http://www.w3.org/2000/svg') {\n\t\t\t// Normalize incorrect prop usage for SVG:\n\t\t\t// - xlink:href / xlinkHref --> href (xlink:href was removed from SVG and isn't needed)\n\t\t\t// - className --> class\n\t\t\tname = name.replace(/xlink(H|:h)/, 'h').replace(/sName$/, 's');\n\t\t} else if (\n\t\t\tname != 'width' &&\n\t\t\tname != 'height' &&\n\t\t\tname != 'href' &&\n\t\t\tname != 'list' &&\n\t\t\tname != 'form' &&\n\t\t\t// Default value in browsers is `-1` and an empty string is\n\t\t\t// cast to `0` instead\n\t\t\tname != 'tabIndex' &&\n\t\t\tname != 'download' &&\n\t\t\tname != 'rowSpan' &&\n\t\t\tname != 'colSpan' &&\n\t\t\tname != 'role' &&\n\t\t\tname != 'popover' &&\n\t\t\tname in dom\n\t\t) {\n\t\t\ttry {\n\t\t\t\tdom[name] = value == null ? '' : value;\n\t\t\t\t// labelled break is 1b smaller here than a return statement (sorry)\n\t\t\t\tbreak o;\n\t\t\t} catch (e) {}\n\t\t}\n\n\t\t// aria- and data- attributes have no boolean representation.\n\t\t// A `false` value is different from the attribute not being\n\t\t// present, so we can't remove it. For non-boolean aria\n\t\t// attributes we could treat false as a removal, but the\n\t\t// amount of exceptions would cost too many bytes. On top of\n\t\t// that other frameworks generally stringify `false`.\n\n\t\tif (typeof value == 'function') {\n\t\t\t// never serialize functions as attribute values\n\t\t} else if (value != null && (value !== false || name[4] === '-')) {\n\t\t\tdom.setAttribute(name, name == 'popover' && value == true ? '' : value);\n\t\t} else {\n\t\t\tdom.removeAttribute(name);\n\t\t}\n\t}\n}\n\n/**\n * Create an event proxy function.\n * @param {boolean} useCapture Is the event handler for the capture phase.\n * @private\n */\nfunction createEventProxy(useCapture) {\n\t/**\n\t * Proxy an event to hooked event handlers\n\t * @param {PreactEvent} e The event object from the browser\n\t * @private\n\t */\n\treturn function (e) {\n\t\tif (this._listeners) {\n\t\t\tconst eventHandler = this._listeners[e.type + useCapture];\n\t\t\tif (e._dispatched == null) {\n\t\t\t\te._dispatched = eventClock++;\n\n\t\t\t\t// When `e._dispatched` is smaller than the time when the targeted event\n\t\t\t\t// handler was attached we know we have bubbled up to an element that was added\n\t\t\t\t// during patching the DOM.\n\t\t\t} else if (e._dispatched < eventHandler._attached) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treturn eventHandler(options.event ? options.event(e) : e);\n\t\t}\n\t};\n}\n\nconst eventProxy = createEventProxy(false);\nconst eventProxyCapture = createEventProxy(true);\n", "import { enqueueRender } from './component';\n\nexport let i = 0;\n\nexport function createContext(defaultValue, contextId) {\n\tcontextId = '__cC' + i++;\n\n\tconst context = {\n\t\t_id: contextId,\n\t\t_defaultValue: defaultValue,\n\t\t/** @type {FunctionComponent} */\n\t\tConsumer(props, contextValue) {\n\t\t\t// return props.children(\n\t\t\t// \tcontext[contextId] ? context[contextId].props.value : defaultValue\n\t\t\t// );\n\t\t\treturn props.children(contextValue);\n\t\t},\n\t\t/** @type {FunctionComponent} */\n\t\tProvider(props) {\n\t\t\tif (!this.getChildContext) {\n\t\t\t\t/** @type {Component[] | null} */\n\t\t\t\tlet subs = [];\n\t\t\t\tlet ctx = {};\n\t\t\t\tctx[contextId] = this;\n\n\t\t\t\tthis.getChildContext = () => ctx;\n\n\t\t\t\tthis.componentWillUnmount = () => {\n\t\t\t\t\tsubs = null;\n\t\t\t\t};\n\n\t\t\t\tthis.shouldComponentUpdate = function (_props) {\n\t\t\t\t\tif (this.props.value !== _props.value) {\n\t\t\t\t\t\tsubs.some(c => {\n\t\t\t\t\t\t\tc._force = true;\n\t\t\t\t\t\t\tenqueueRender(c);\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t};\n\n\t\t\t\tthis.sub = c => {\n\t\t\t\t\tsubs.push(c);\n\t\t\t\t\tlet old = c.componentWillUnmount;\n\t\t\t\t\tc.componentWillUnmount = () => {\n\t\t\t\t\t\tif (subs) {\n\t\t\t\t\t\t\tsubs.splice(subs.indexOf(c), 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (old) old.call(c);\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn props.children;\n\t\t}\n\t};\n\n\t// Devtools needs access to the context object when it\n\t// encounters a Provider. This is necessary to support\n\t// setting `displayName` on the context object instead\n\t// of on the component itself. See:\n\t// https://reactjs.org/docs/context.html#contextdisplayname\n\n\treturn (context.Provider._contextRef = context.Consumer.contextType =\n\t\tcontext);\n}\n", "import { diff, unmount, applyRef } from './index';\nimport { createVNode, Fragment } from '../create-element';\nimport { EMPTY_OBJ, EMPTY_ARR, INSERT_VNODE, MATCHED } from '../constants';\nimport { isArray } from '../util';\nimport { getDomSibling } from '../component';\n\n/**\n * Diff the children of a virtual node\n * @param {PreactElement} parentDom The DOM element whose children are being\n * diffed\n * @param {ComponentChildren[]} renderResult\n * @param {VNode} newParentVNode The new virtual node whose children should be\n * diff'ed against oldParentVNode\n * @param {VNode} oldParentVNode The old virtual node whose children should be\n * diff'ed against newParentVNode\n * @param {object} globalContext The current context object - modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diffChildren(\n\tparentDom,\n\trenderResult,\n\tnewParentVNode,\n\toldParentVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\tlet i,\n\t\t/** @type {VNode} */\n\t\toldVNode,\n\t\t/** @type {VNode} */\n\t\tchildVNode,\n\t\t/** @type {PreactElement} */\n\t\tnewDom,\n\t\t/** @type {PreactElement} */\n\t\tfirstChildDom;\n\n\t// This is a compression of oldParentVNode!=null && oldParentVNode != EMPTY_OBJ && oldParentVNode._children || EMPTY_ARR\n\t// as EMPTY_OBJ._children should be `undefined`.\n\t/** @type {VNode[]} */\n\tlet oldChildren = (oldParentVNode && oldParentVNode._children) || EMPTY_ARR;\n\n\tlet newChildrenLength = renderResult.length;\n\n\tnewParentVNode._nextDom = oldDom;\n\tconstructNewChildrenArray(newParentVNode, renderResult, oldChildren);\n\toldDom = newParentVNode._nextDom;\n\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\tchildVNode = newParentVNode._children[i];\n\t\tif (\n\t\t\tchildVNode == null ||\n\t\t\ttypeof childVNode == 'boolean' ||\n\t\t\ttypeof childVNode == 'function'\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\t// At this point, constructNewChildrenArray has assigned _index to be the\n\t\t// matchingIndex for this VNode's oldVNode (or -1 if there is no oldVNode).\n\t\tif (childVNode._index === -1) {\n\t\t\toldVNode = EMPTY_OBJ;\n\t\t} else {\n\t\t\toldVNode = oldChildren[childVNode._index] || EMPTY_OBJ;\n\t\t}\n\n\t\t// Update childVNode._index to its final index\n\t\tchildVNode._index = i;\n\n\t\t// Morph the old element into the new one, but don't append it to the dom yet\n\t\tdiff(\n\t\t\tparentDom,\n\t\t\tchildVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\toldDom,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\n\t\t// Adjust DOM nodes\n\t\tnewDom = childVNode._dom;\n\t\tif (childVNode.ref && oldVNode.ref != childVNode.ref) {\n\t\t\tif (oldVNode.ref) {\n\t\t\t\tapplyRef(oldVNode.ref, null, childVNode);\n\t\t\t}\n\t\t\trefQueue.push(\n\t\t\t\tchildVNode.ref,\n\t\t\t\tchildVNode._component || newDom,\n\t\t\t\tchildVNode\n\t\t\t);\n\t\t}\n\n\t\tif (firstChildDom == null && newDom != null) {\n\t\t\tfirstChildDom = newDom;\n\t\t}\n\n\t\tif (\n\t\t\tchildVNode._flags & INSERT_VNODE ||\n\t\t\toldVNode._children === childVNode._children\n\t\t) {\n\t\t\toldDom = insert(childVNode, oldDom, parentDom);\n\t\t} else if (\n\t\t\ttypeof childVNode.type == 'function' &&\n\t\t\tchildVNode._nextDom !== undefined\n\t\t) {\n\t\t\t// Since Fragments or components that return Fragment like VNodes can\n\t\t\t// contain multiple DOM nodes as the same level, continue the diff from\n\t\t\t// the sibling of last DOM child of this child VNode\n\t\t\toldDom = childVNode._nextDom;\n\t\t} else if (newDom) {\n\t\t\toldDom = newDom.nextSibling;\n\t\t}\n\n\t\t// Eagerly cleanup _nextDom. We don't need to persist the value because it\n\t\t// is only used by `diffChildren` to determine where to resume the diff\n\t\t// after diffing Components and Fragments. Once we store it the nextDOM\n\t\t// local var, we can clean up the property. Also prevents us hanging on to\n\t\t// DOM nodes that may have been unmounted.\n\t\tchildVNode._nextDom = undefined;\n\n\t\t// Unset diffing flags\n\t\tchildVNode._flags &= ~(INSERT_VNODE | MATCHED);\n\t}\n\n\t// TODO: With new child diffing algo, consider alt ways to diff Fragments.\n\t// Such as dropping oldDom and moving fragments in place\n\t//\n\t// Because the newParentVNode is Fragment-like, we need to set it's\n\t// _nextDom property to the nextSibling of its last child DOM node.\n\t//\n\t// `oldDom` contains the correct value here because if the last child\n\t// is a Fragment-like, then oldDom has already been set to that child's _nextDom.\n\t// If the last child is a DOM VNode, then oldDom will be set to that DOM\n\t// node's nextSibling.\n\tnewParentVNode._nextDom = oldDom;\n\tnewParentVNode._dom = firstChildDom;\n}\n\n/**\n * @param {VNode} newParentVNode\n * @param {ComponentChildren[]} renderResult\n * @param {VNode[]} oldChildren\n */\nfunction constructNewChildrenArray(newParentVNode, renderResult, oldChildren) {\n\t/** @type {number} */\n\tlet i;\n\t/** @type {VNode} */\n\tlet childVNode;\n\t/** @type {VNode} */\n\tlet oldVNode;\n\n\tconst newChildrenLength = renderResult.length;\n\tlet oldChildrenLength = oldChildren.length,\n\t\tremainingOldChildren = oldChildrenLength;\n\n\tlet skew = 0;\n\n\tnewParentVNode._children = [];\n\tfor (i = 0; i < newChildrenLength; i++) {\n\t\t// @ts-expect-error We are reusing the childVNode variable to hold both the\n\t\t// pre and post normalized childVNode\n\t\tchildVNode = renderResult[i];\n\n\t\tif (\n\t\t\tchildVNode == null ||\n\t\t\ttypeof childVNode == 'boolean' ||\n\t\t\ttypeof childVNode == 'function'\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = null;\n\t\t}\n\t\t// If this newVNode is being reused (e.g.
{reuse}{reuse}
) in the same diff,\n\t\t// or we are rendering a component (e.g. setState) copy the oldVNodes so it can have\n\t\t// it's own DOM & etc. pointers\n\t\telse if (\n\t\t\ttypeof childVNode == 'string' ||\n\t\t\ttypeof childVNode == 'number' ||\n\t\t\t// eslint-disable-next-line valid-typeof\n\t\t\ttypeof childVNode == 'bigint' ||\n\t\t\tchildVNode.constructor == String\n\t\t) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tnull,\n\t\t\t\tchildVNode,\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull\n\t\t\t);\n\t\t} else if (isArray(childVNode)) {\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tFragment,\n\t\t\t\t{ children: childVNode },\n\t\t\t\tnull,\n\t\t\t\tnull,\n\t\t\t\tnull\n\t\t\t);\n\t\t} else if (childVNode.constructor === undefined && childVNode._depth > 0) {\n\t\t\t// VNode is already in use, clone it. This can happen in the following\n\t\t\t// scenario:\n\t\t\t// const reuse =
\n\t\t\t//
{reuse}{reuse}
\n\t\t\tchildVNode = newParentVNode._children[i] = createVNode(\n\t\t\t\tchildVNode.type,\n\t\t\t\tchildVNode.props,\n\t\t\t\tchildVNode.key,\n\t\t\t\tchildVNode.ref ? childVNode.ref : null,\n\t\t\t\tchildVNode._original\n\t\t\t);\n\t\t} else {\n\t\t\tchildVNode = newParentVNode._children[i] = childVNode;\n\t\t}\n\n\t\tconst skewedIndex = i + skew;\n\n\t\t// Handle unmounting null placeholders, i.e. VNode => null in unkeyed children\n\t\tif (childVNode == null) {\n\t\t\toldVNode = oldChildren[skewedIndex];\n\t\t\tif (\n\t\t\t\toldVNode &&\n\t\t\t\toldVNode.key == null &&\n\t\t\t\toldVNode._dom &&\n\t\t\t\t(oldVNode._flags & MATCHED) === 0\n\t\t\t) {\n\t\t\t\tif (oldVNode._dom == newParentVNode._nextDom) {\n\t\t\t\t\tnewParentVNode._nextDom = getDomSibling(oldVNode);\n\t\t\t\t}\n\n\t\t\t\tunmount(oldVNode, oldVNode, false);\n\n\t\t\t\t// Explicitly nullify this position in oldChildren instead of just\n\t\t\t\t// setting `_match=true` to prevent other routines (e.g.\n\t\t\t\t// `findMatchingIndex` or `getDomSibling`) from thinking VNodes or DOM\n\t\t\t\t// nodes in this position are still available to be used in diffing when\n\t\t\t\t// they have actually already been unmounted. For example, by only\n\t\t\t\t// setting `_match=true` here, the unmounting loop later would attempt\n\t\t\t\t// to unmount this VNode again seeing `_match==true`. Further,\n\t\t\t\t// getDomSibling doesn't know about _match and so would incorrectly\n\t\t\t\t// assume DOM nodes in this subtree are mounted and usable.\n\t\t\t\toldChildren[skewedIndex] = null;\n\t\t\t\tremainingOldChildren--;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\tchildVNode._parent = newParentVNode;\n\t\tchildVNode._depth = newParentVNode._depth + 1;\n\n\t\tconst matchingIndex = findMatchingIndex(\n\t\t\tchildVNode,\n\t\t\toldChildren,\n\t\t\tskewedIndex,\n\t\t\tremainingOldChildren\n\t\t);\n\n\t\t// Temporarily store the matchingIndex on the _index property so we can pull\n\t\t// out the oldVNode in diffChildren. We'll override this to the VNode's\n\t\t// final index after using this property to get the oldVNode\n\t\tchildVNode._index = matchingIndex;\n\n\t\toldVNode = null;\n\t\tif (matchingIndex !== -1) {\n\t\t\toldVNode = oldChildren[matchingIndex];\n\t\t\tremainingOldChildren--;\n\t\t\tif (oldVNode) {\n\t\t\t\toldVNode._flags |= MATCHED;\n\t\t\t}\n\t\t}\n\n\t\t// Here, we define isMounting for the purposes of the skew diffing\n\t\t// algorithm. Nodes that are unsuspending are considered mounting and we detect\n\t\t// this by checking if oldVNode._original === null\n\t\tconst isMounting = oldVNode == null || oldVNode._original === null;\n\n\t\tif (isMounting) {\n\t\t\tif (matchingIndex == -1) {\n\t\t\t\tskew--;\n\t\t\t}\n\n\t\t\t// If we are mounting a DOM VNode, mark it for insertion\n\t\t\tif (typeof childVNode.type != 'function') {\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t} else if (matchingIndex !== skewedIndex) {\n\t\t\tif (matchingIndex == skewedIndex - 1) {\n\t\t\t\tskew--;\n\t\t\t} else if (matchingIndex == skewedIndex + 1) {\n\t\t\t\tskew++;\n\t\t\t} else if (matchingIndex > skewedIndex) {\n\t\t\t\t// Our matched DOM-node is further in the list of children than\n\t\t\t\t// where it's at now.\n\n\t\t\t\t// When the remaining old children is bigger than the new-children\n\t\t\t\t// minus our skewed index we know we are dealing with a shrinking list\n\t\t\t\t// we have to increase our skew with the matchedIndex - the skewed index\n\t\t\t\tif (remainingOldChildren > newChildrenLength - skewedIndex) {\n\t\t\t\t\tskew += matchingIndex - skewedIndex;\n\t\t\t\t} else {\n\t\t\t\t\t// If we have matched all the children just decrease the skew\n\t\t\t\t\tskew--;\n\t\t\t\t}\n\t\t\t} else if (matchingIndex < skewedIndex) {\n\t\t\t\tif (matchingIndex == skewedIndex - skew) {\n\t\t\t\t\tskew -= matchingIndex - skewedIndex;\n\t\t\t\t} else {\n\t\t\t\t\t// When our new position is in front of our old position than we increase the skew\n\t\t\t\t\tskew++;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Move this VNode's DOM if the original index (matchingIndex) doesn't\n\t\t\t// match the new skew index (i + new skew)\n\t\t\tif (matchingIndex !== i + skew) {\n\t\t\t\tchildVNode._flags |= INSERT_VNODE;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove remaining oldChildren if there are any. Loop forwards so that as we\n\t// unmount DOM from the beginning of the oldChildren, we can adjust oldDom to\n\t// point to the next child, which needs to be the first DOM node that won't be\n\t// unmounted.\n\tif (remainingOldChildren) {\n\t\tfor (i = 0; i < oldChildrenLength; i++) {\n\t\t\toldVNode = oldChildren[i];\n\t\t\tif (oldVNode != null && (oldVNode._flags & MATCHED) === 0) {\n\t\t\t\tif (oldVNode._dom == newParentVNode._nextDom) {\n\t\t\t\t\tnewParentVNode._nextDom = getDomSibling(oldVNode);\n\t\t\t\t}\n\n\t\t\t\tunmount(oldVNode, oldVNode);\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * @param {VNode} parentVNode\n * @param {PreactElement} oldDom\n * @param {PreactElement} parentDom\n * @returns {PreactElement}\n */\nfunction insert(parentVNode, oldDom, parentDom) {\n\t// Note: VNodes in nested suspended trees may be missing _children.\n\n\tif (typeof parentVNode.type == 'function') {\n\t\tlet children = parentVNode._children;\n\t\tfor (let i = 0; children && i < children.length; i++) {\n\t\t\tif (children[i]) {\n\t\t\t\t// If we enter this code path on sCU bailout, where we copy\n\t\t\t\t// oldVNode._children to newVNode._children, we need to update the old\n\t\t\t\t// children's _parent pointer to point to the newVNode (parentVNode\n\t\t\t\t// here).\n\t\t\t\tchildren[i]._parent = parentVNode;\n\t\t\t\toldDom = insert(children[i], oldDom, parentDom);\n\t\t\t}\n\t\t}\n\n\t\treturn oldDom;\n\t} else if (parentVNode._dom != oldDom) {\n\t\tif (oldDom && parentVNode.type && !parentDom.contains(oldDom)) {\n\t\t\toldDom = getDomSibling(parentVNode);\n\t\t}\n\t\tparentDom.insertBefore(parentVNode._dom, oldDom || null);\n\t\toldDom = parentVNode._dom;\n\t}\n\n\tdo {\n\t\toldDom = oldDom && oldDom.nextSibling;\n\t} while (oldDom != null && oldDom.nodeType === 8);\n\n\treturn oldDom;\n}\n\n/**\n * Flatten and loop through the children of a virtual node\n * @param {ComponentChildren} children The unflattened children of a virtual\n * node\n * @returns {VNode[]}\n */\nexport function toChildArray(children, out) {\n\tout = out || [];\n\tif (children == null || typeof children == 'boolean') {\n\t} else if (isArray(children)) {\n\t\tchildren.some(child => {\n\t\t\ttoChildArray(child, out);\n\t\t});\n\t} else {\n\t\tout.push(children);\n\t}\n\treturn out;\n}\n\n/**\n * @param {VNode} childVNode\n * @param {VNode[]} oldChildren\n * @param {number} skewedIndex\n * @param {number} remainingOldChildren\n * @returns {number}\n */\nfunction findMatchingIndex(\n\tchildVNode,\n\toldChildren,\n\tskewedIndex,\n\tremainingOldChildren\n) {\n\tconst key = childVNode.key;\n\tconst type = childVNode.type;\n\tlet x = skewedIndex - 1;\n\tlet y = skewedIndex + 1;\n\tlet oldVNode = oldChildren[skewedIndex];\n\n\t// We only need to perform a search if there are more children\n\t// (remainingOldChildren) to search. However, if the oldVNode we just looked\n\t// at skewedIndex was not already used in this diff, then there must be at\n\t// least 1 other (so greater than 1) remainingOldChildren to attempt to match\n\t// against. So the following condition checks that ensuring\n\t// remainingOldChildren > 1 if the oldVNode is not already used/matched. Else\n\t// if the oldVNode was null or matched, then there could needs to be at least\n\t// 1 (aka `remainingOldChildren > 0`) children to find and compare against.\n\tlet shouldSearch =\n\t\tremainingOldChildren >\n\t\t(oldVNode != null && (oldVNode._flags & MATCHED) === 0 ? 1 : 0);\n\n\tif (\n\t\toldVNode === null ||\n\t\t(oldVNode &&\n\t\t\tkey == oldVNode.key &&\n\t\t\ttype === oldVNode.type &&\n\t\t\t(oldVNode._flags & MATCHED) === 0)\n\t) {\n\t\treturn skewedIndex;\n\t} else if (shouldSearch) {\n\t\twhile (x >= 0 || y < oldChildren.length) {\n\t\t\tif (x >= 0) {\n\t\t\t\toldVNode = oldChildren[x];\n\t\t\t\tif (\n\t\t\t\t\toldVNode &&\n\t\t\t\t\t(oldVNode._flags & MATCHED) === 0 &&\n\t\t\t\t\tkey == oldVNode.key &&\n\t\t\t\t\ttype === oldVNode.type\n\t\t\t\t) {\n\t\t\t\t\treturn x;\n\t\t\t\t}\n\t\t\t\tx--;\n\t\t\t}\n\n\t\t\tif (y < oldChildren.length) {\n\t\t\t\toldVNode = oldChildren[y];\n\t\t\t\tif (\n\t\t\t\t\toldVNode &&\n\t\t\t\t\t(oldVNode._flags & MATCHED) === 0 &&\n\t\t\t\t\tkey == oldVNode.key &&\n\t\t\t\t\ttype === oldVNode.type\n\t\t\t\t) {\n\t\t\t\t\treturn y;\n\t\t\t\t}\n\t\t\t\ty++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn -1;\n}\n", "import {\n\tEMPTY_OBJ,\n\tMODE_HYDRATE,\n\tMODE_SUSPENDED,\n\tRESET_MODE\n} from '../constants';\nimport { BaseComponent, getDomSibling } from '../component';\nimport { Fragment } from '../create-element';\nimport { diffChildren } from './children';\nimport { setProperty } from './props';\nimport { assign, isArray, removeNode, slice } from '../util';\nimport options from '../options';\n\n/**\n * Diff two virtual nodes and apply proper changes to the DOM\n * @param {PreactElement} parentDom The parent of the DOM element\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object. Modified by\n * getChildContext\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {PreactElement} oldDom The current attached DOM element any new dom\n * elements should be placed around. Likely `null` on first render (except when\n * hydrating). Can be a sibling DOM element when diffing Fragments that have\n * siblings. In most cases, it starts out as `oldChildren[0]._dom`.\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n */\nexport function diff(\n\tparentDom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\toldDom,\n\tisHydrating,\n\trefQueue\n) {\n\t/** @type {any} */\n\tlet tmp,\n\t\tnewType = newVNode.type;\n\n\t// When passing through createElement it assigns the object\n\t// constructor as undefined. This to prevent JSON-injection.\n\tif (newVNode.constructor !== undefined) return null;\n\n\t// If the previous diff bailed out, resume creating/hydrating.\n\tif (oldVNode._flags & MODE_SUSPENDED) {\n\t\tisHydrating = !!(oldVNode._flags & MODE_HYDRATE);\n\t\toldDom = newVNode._dom = oldVNode._dom;\n\t\texcessDomChildren = [oldDom];\n\t}\n\n\tif ((tmp = options._diff)) tmp(newVNode);\n\n\touter: if (typeof newType == 'function') {\n\t\ttry {\n\t\t\tlet c, isNew, oldProps, oldState, snapshot, clearProcessingException;\n\t\t\tlet newProps = newVNode.props;\n\t\t\tconst isClassComponent =\n\t\t\t\t'prototype' in newType && newType.prototype.render;\n\n\t\t\t// Necessary for createContext api. Setting this property will pass\n\t\t\t// the context value as `this.context` just for this component.\n\t\t\ttmp = newType.contextType;\n\t\t\tlet provider = tmp && globalContext[tmp._id];\n\t\t\tlet componentContext = tmp\n\t\t\t\t? provider\n\t\t\t\t\t? provider.props.value\n\t\t\t\t\t: tmp._defaultValue\n\t\t\t\t: globalContext;\n\n\t\t\t// Get component and set it to `c`\n\t\t\tif (oldVNode._component) {\n\t\t\t\tc = newVNode._component = oldVNode._component;\n\t\t\t\tclearProcessingException = c._processingException = c._pendingError;\n\t\t\t} else {\n\t\t\t\t// Instantiate the new component\n\t\t\t\tif (isClassComponent) {\n\t\t\t\t\t// @ts-expect-error The check above verifies that newType is suppose to be constructed\n\t\t\t\t\tnewVNode._component = c = new newType(newProps, componentContext); // eslint-disable-line new-cap\n\t\t\t\t} else {\n\t\t\t\t\t// @ts-expect-error Trust me, Component implements the interface we want\n\t\t\t\t\tnewVNode._component = c = new BaseComponent(\n\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t);\n\t\t\t\t\tc.constructor = newType;\n\t\t\t\t\tc.render = doRender;\n\t\t\t\t}\n\t\t\t\tif (provider) provider.sub(c);\n\n\t\t\t\tc.props = newProps;\n\t\t\t\tif (!c.state) c.state = {};\n\t\t\t\tc.context = componentContext;\n\t\t\t\tc._globalContext = globalContext;\n\t\t\t\tisNew = c._dirty = true;\n\t\t\t\tc._renderCallbacks = [];\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t}\n\n\t\t\t// Invoke getDerivedStateFromProps\n\t\t\tif (isClassComponent && c._nextState == null) {\n\t\t\t\tc._nextState = c.state;\n\t\t\t}\n\n\t\t\tif (isClassComponent && newType.getDerivedStateFromProps != null) {\n\t\t\t\tif (c._nextState == c.state) {\n\t\t\t\t\tc._nextState = assign({}, c._nextState);\n\t\t\t\t}\n\n\t\t\t\tassign(\n\t\t\t\t\tc._nextState,\n\t\t\t\t\tnewType.getDerivedStateFromProps(newProps, c._nextState)\n\t\t\t\t);\n\t\t\t}\n\n\t\t\toldProps = c.props;\n\t\t\toldState = c.state;\n\t\t\tc._vnode = newVNode;\n\n\t\t\t// Invoke pre-render lifecycle methods\n\t\t\tif (isNew) {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == null &&\n\t\t\t\t\tc.componentWillMount != null\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillMount();\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidMount != null) {\n\t\t\t\t\tc._renderCallbacks.push(c.componentDidMount);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (\n\t\t\t\t\tisClassComponent &&\n\t\t\t\t\tnewType.getDerivedStateFromProps == null &&\n\t\t\t\t\tnewProps !== oldProps &&\n\t\t\t\t\tc.componentWillReceiveProps != null\n\t\t\t\t) {\n\t\t\t\t\tc.componentWillReceiveProps(newProps, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (\n\t\t\t\t\t!c._force &&\n\t\t\t\t\t((c.shouldComponentUpdate != null &&\n\t\t\t\t\t\tc.shouldComponentUpdate(\n\t\t\t\t\t\t\tnewProps,\n\t\t\t\t\t\t\tc._nextState,\n\t\t\t\t\t\t\tcomponentContext\n\t\t\t\t\t\t) === false) ||\n\t\t\t\t\t\tnewVNode._original === oldVNode._original)\n\t\t\t\t) {\n\t\t\t\t\t// More info about this here: https://gist.github.com/JoviDeCroock/bec5f2ce93544d2e6070ef8e0036e4e8\n\t\t\t\t\tif (newVNode._original !== oldVNode._original) {\n\t\t\t\t\t\t// When we are dealing with a bail because of sCU we have to update\n\t\t\t\t\t\t// the props, state and dirty-state.\n\t\t\t\t\t\t// when we are dealing with strict-equality we don't as the child could still\n\t\t\t\t\t\t// be dirtied see #3883\n\t\t\t\t\t\tc.props = newProps;\n\t\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t\t\tc._dirty = false;\n\t\t\t\t\t}\n\n\t\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t\t\tnewVNode._children.forEach(vnode => {\n\t\t\t\t\t\tif (vnode) vnode._parent = newVNode;\n\t\t\t\t\t});\n\n\t\t\t\t\tfor (let i = 0; i < c._stateCallbacks.length; i++) {\n\t\t\t\t\t\tc._renderCallbacks.push(c._stateCallbacks[i]);\n\t\t\t\t\t}\n\t\t\t\t\tc._stateCallbacks = [];\n\n\t\t\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\t\t\tcommitQueue.push(c);\n\t\t\t\t\t}\n\n\t\t\t\t\tbreak outer;\n\t\t\t\t}\n\n\t\t\t\tif (c.componentWillUpdate != null) {\n\t\t\t\t\tc.componentWillUpdate(newProps, c._nextState, componentContext);\n\t\t\t\t}\n\n\t\t\t\tif (isClassComponent && c.componentDidUpdate != null) {\n\t\t\t\t\tc._renderCallbacks.push(() => {\n\t\t\t\t\t\tc.componentDidUpdate(oldProps, oldState, snapshot);\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tc.context = componentContext;\n\t\t\tc.props = newProps;\n\t\t\tc._parentDom = parentDom;\n\t\t\tc._force = false;\n\n\t\t\tlet renderHook = options._render,\n\t\t\t\tcount = 0;\n\t\t\tif (isClassComponent) {\n\t\t\t\tc.state = c._nextState;\n\t\t\t\tc._dirty = false;\n\n\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\tfor (let i = 0; i < c._stateCallbacks.length; i++) {\n\t\t\t\t\tc._renderCallbacks.push(c._stateCallbacks[i]);\n\t\t\t\t}\n\t\t\t\tc._stateCallbacks = [];\n\t\t\t} else {\n\t\t\t\tdo {\n\t\t\t\t\tc._dirty = false;\n\t\t\t\t\tif (renderHook) renderHook(newVNode);\n\n\t\t\t\t\ttmp = c.render(c.props, c.state, c.context);\n\n\t\t\t\t\t// Handle setState called in render, see #2553\n\t\t\t\t\tc.state = c._nextState;\n\t\t\t\t} while (c._dirty && ++count < 25);\n\t\t\t}\n\n\t\t\t// Handle setState called in render, see #2553\n\t\t\tc.state = c._nextState;\n\n\t\t\tif (c.getChildContext != null) {\n\t\t\t\tglobalContext = assign(assign({}, globalContext), c.getChildContext());\n\t\t\t}\n\n\t\t\tif (isClassComponent && !isNew && c.getSnapshotBeforeUpdate != null) {\n\t\t\t\tsnapshot = c.getSnapshotBeforeUpdate(oldProps, oldState);\n\t\t\t}\n\n\t\t\tlet isTopLevelFragment =\n\t\t\t\ttmp != null && tmp.type === Fragment && tmp.key == null;\n\t\t\tlet renderResult = isTopLevelFragment ? tmp.props.children : tmp;\n\n\t\t\tdiffChildren(\n\t\t\t\tparentDom,\n\t\t\t\tisArray(renderResult) ? renderResult : [renderResult],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnamespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\toldDom,\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\tc.base = newVNode._dom;\n\n\t\t\t// We successfully rendered this VNode, unset any stored hydration/bailout state:\n\t\t\tnewVNode._flags &= RESET_MODE;\n\n\t\t\tif (c._renderCallbacks.length) {\n\t\t\t\tcommitQueue.push(c);\n\t\t\t}\n\n\t\t\tif (clearProcessingException) {\n\t\t\t\tc._pendingError = c._processingException = null;\n\t\t\t}\n\t\t} catch (e) {\n\t\t\tnewVNode._original = null;\n\t\t\t// if hydrating or creating initial tree, bailout preserves DOM:\n\t\t\tif (isHydrating || excessDomChildren != null) {\n\t\t\t\tnewVNode._flags |= isHydrating\n\t\t\t\t\t? MODE_HYDRATE | MODE_SUSPENDED\n\t\t\t\t\t: MODE_HYDRATE;\n\n\t\t\t\twhile (oldDom && oldDom.nodeType === 8 && oldDom.nextSibling) {\n\t\t\t\t\toldDom = oldDom.nextSibling;\n\t\t\t\t}\n\t\t\t\texcessDomChildren[excessDomChildren.indexOf(oldDom)] = null;\n\t\t\t\tnewVNode._dom = oldDom;\n\t\t\t} else {\n\t\t\t\tnewVNode._dom = oldVNode._dom;\n\t\t\t\tnewVNode._children = oldVNode._children;\n\t\t\t}\n\t\t\toptions._catchError(e, newVNode, oldVNode);\n\t\t}\n\t} else if (\n\t\texcessDomChildren == null &&\n\t\tnewVNode._original === oldVNode._original\n\t) {\n\t\tnewVNode._children = oldVNode._children;\n\t\tnewVNode._dom = oldVNode._dom;\n\t} else {\n\t\tnewVNode._dom = diffElementNodes(\n\t\t\toldVNode._dom,\n\t\t\tnewVNode,\n\t\t\toldVNode,\n\t\t\tglobalContext,\n\t\t\tnamespace,\n\t\t\texcessDomChildren,\n\t\t\tcommitQueue,\n\t\t\tisHydrating,\n\t\t\trefQueue\n\t\t);\n\t}\n\n\tif ((tmp = options.diffed)) tmp(newVNode);\n}\n\n/**\n * @param {Array} commitQueue List of components\n * which have callbacks to invoke in commitRoot\n * @param {VNode} root\n */\nexport function commitRoot(commitQueue, root, refQueue) {\n\troot._nextDom = undefined;\n\n\tfor (let i = 0; i < refQueue.length; i++) {\n\t\tapplyRef(refQueue[i], refQueue[++i], refQueue[++i]);\n\t}\n\n\tif (options._commit) options._commit(root, commitQueue);\n\n\tcommitQueue.some(c => {\n\t\ttry {\n\t\t\t// @ts-expect-error Reuse the commitQueue variable here so the type changes\n\t\t\tcommitQueue = c._renderCallbacks;\n\t\t\tc._renderCallbacks = [];\n\t\t\tcommitQueue.some(cb => {\n\t\t\t\t// @ts-expect-error See above comment on commitQueue\n\t\t\t\tcb.call(c);\n\t\t\t});\n\t\t} catch (e) {\n\t\t\toptions._catchError(e, c._vnode);\n\t\t}\n\t});\n}\n\n/**\n * Diff two virtual nodes representing DOM element\n * @param {PreactElement} dom The DOM element representing the virtual nodes\n * being diffed\n * @param {VNode} newVNode The new virtual node\n * @param {VNode} oldVNode The old virtual node\n * @param {object} globalContext The current context object\n * @param {string} namespace Current namespace of the DOM node (HTML, SVG, or MathML)\n * @param {Array} excessDomChildren\n * @param {Array} commitQueue List of components which have callbacks\n * to invoke in commitRoot\n * @param {boolean} isHydrating Whether or not we are in hydration\n * @param {any[]} refQueue an array of elements needed to invoke refs\n * @returns {PreactElement}\n */\nfunction diffElementNodes(\n\tdom,\n\tnewVNode,\n\toldVNode,\n\tglobalContext,\n\tnamespace,\n\texcessDomChildren,\n\tcommitQueue,\n\tisHydrating,\n\trefQueue\n) {\n\tlet oldProps = oldVNode.props;\n\tlet newProps = newVNode.props;\n\tlet nodeType = /** @type {string} */ (newVNode.type);\n\t/** @type {any} */\n\tlet i;\n\t/** @type {{ __html?: string }} */\n\tlet newHtml;\n\t/** @type {{ __html?: string }} */\n\tlet oldHtml;\n\t/** @type {ComponentChildren} */\n\tlet newChildren;\n\tlet value;\n\tlet inputValue;\n\tlet checked;\n\n\t// Tracks entering and exiting namespaces when descending through the tree.\n\tif (nodeType === 'svg') namespace = 'http://www.w3.org/2000/svg';\n\telse if (nodeType === 'math')\n\t\tnamespace = 'http://www.w3.org/1998/Math/MathML';\n\telse if (!namespace) namespace = 'http://www.w3.org/1999/xhtml';\n\n\tif (excessDomChildren != null) {\n\t\tfor (i = 0; i < excessDomChildren.length; i++) {\n\t\t\tvalue = excessDomChildren[i];\n\n\t\t\t// if newVNode matches an element in excessDomChildren or the `dom`\n\t\t\t// argument matches an element in excessDomChildren, remove it from\n\t\t\t// excessDomChildren so it isn't later removed in diffChildren\n\t\t\tif (\n\t\t\t\tvalue &&\n\t\t\t\t'setAttribute' in value === !!nodeType &&\n\t\t\t\t(nodeType ? value.localName === nodeType : value.nodeType === 3)\n\t\t\t) {\n\t\t\t\tdom = value;\n\t\t\t\texcessDomChildren[i] = null;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (dom == null) {\n\t\tif (nodeType === null) {\n\t\t\treturn document.createTextNode(newProps);\n\t\t}\n\n\t\tdom = document.createElementNS(\n\t\t\tnamespace,\n\t\t\tnodeType,\n\t\t\tnewProps.is && newProps\n\t\t);\n\n\t\t// we created a new parent, so none of the previously attached children can be reused:\n\t\texcessDomChildren = null;\n\t\t// we are creating a new node, so we can assume this is a new subtree (in\n\t\t// case we are hydrating), this deopts the hydrate\n\t\tisHydrating = false;\n\t}\n\n\tif (nodeType === null) {\n\t\t// During hydration, we still have to split merged text from SSR'd HTML.\n\t\tif (oldProps !== newProps && (!isHydrating || dom.data !== newProps)) {\n\t\t\tdom.data = newProps;\n\t\t}\n\t} else {\n\t\t// If excessDomChildren was not null, repopulate it with the current element's children:\n\t\texcessDomChildren = excessDomChildren && slice.call(dom.childNodes);\n\n\t\toldProps = oldVNode.props || EMPTY_OBJ;\n\n\t\t// If we are in a situation where we are not hydrating but are using\n\t\t// existing DOM (e.g. replaceNode) we should read the existing DOM\n\t\t// attributes to diff them\n\t\tif (!isHydrating && excessDomChildren != null) {\n\t\t\toldProps = {};\n\t\t\tfor (i = 0; i < dom.attributes.length; i++) {\n\t\t\t\tvalue = dom.attributes[i];\n\t\t\t\toldProps[value.name] = value.value;\n\t\t\t}\n\t\t}\n\n\t\tfor (i in oldProps) {\n\t\t\tvalue = oldProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\toldHtml = value;\n\t\t\t} else if (i !== 'key' && !(i in newProps)) {\n\t\t\t\tif (\n\t\t\t\t\t(i == 'value' && 'defaultValue' in newProps) ||\n\t\t\t\t\t(i == 'checked' && 'defaultChecked' in newProps)\n\t\t\t\t) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tsetProperty(dom, i, null, value, namespace);\n\t\t\t}\n\t\t}\n\n\t\t// During hydration, props are not diffed at all (including dangerouslySetInnerHTML)\n\t\t// @TODO we should warn in debug mode when props don't match here.\n\t\tfor (i in newProps) {\n\t\t\tvalue = newProps[i];\n\t\t\tif (i == 'children') {\n\t\t\t\tnewChildren = value;\n\t\t\t} else if (i == 'dangerouslySetInnerHTML') {\n\t\t\t\tnewHtml = value;\n\t\t\t} else if (i == 'value') {\n\t\t\t\tinputValue = value;\n\t\t\t} else if (i == 'checked') {\n\t\t\t\tchecked = value;\n\t\t\t} else if (\n\t\t\t\ti !== 'key' &&\n\t\t\t\t(!isHydrating || typeof value == 'function') &&\n\t\t\t\toldProps[i] !== value\n\t\t\t) {\n\t\t\t\tsetProperty(dom, i, value, oldProps[i], namespace);\n\t\t\t}\n\t\t}\n\n\t\t// If the new vnode didn't have dangerouslySetInnerHTML, diff its children\n\t\tif (newHtml) {\n\t\t\t// Avoid re-applying the same '__html' if it did not changed between re-render\n\t\t\tif (\n\t\t\t\t!isHydrating &&\n\t\t\t\t(!oldHtml ||\n\t\t\t\t\t(newHtml.__html !== oldHtml.__html &&\n\t\t\t\t\t\tnewHtml.__html !== dom.innerHTML))\n\t\t\t) {\n\t\t\t\tdom.innerHTML = newHtml.__html;\n\t\t\t}\n\n\t\t\tnewVNode._children = [];\n\t\t} else {\n\t\t\tif (oldHtml) dom.innerHTML = '';\n\n\t\t\tdiffChildren(\n\t\t\t\tdom,\n\t\t\t\tisArray(newChildren) ? newChildren : [newChildren],\n\t\t\t\tnewVNode,\n\t\t\t\toldVNode,\n\t\t\t\tglobalContext,\n\t\t\t\tnodeType === 'foreignObject'\n\t\t\t\t\t? 'http://www.w3.org/1999/xhtml'\n\t\t\t\t\t: namespace,\n\t\t\t\texcessDomChildren,\n\t\t\t\tcommitQueue,\n\t\t\t\texcessDomChildren\n\t\t\t\t\t? excessDomChildren[0]\n\t\t\t\t\t: oldVNode._children && getDomSibling(oldVNode, 0),\n\t\t\t\tisHydrating,\n\t\t\t\trefQueue\n\t\t\t);\n\n\t\t\t// Remove children that are not part of any vnode.\n\t\t\tif (excessDomChildren != null) {\n\t\t\t\tfor (i = excessDomChildren.length; i--; ) {\n\t\t\t\t\tif (excessDomChildren[i] != null) removeNode(excessDomChildren[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// As above, don't diff props during hydration\n\t\tif (!isHydrating) {\n\t\t\ti = 'value';\n\t\t\tif (\n\t\t\t\tinputValue !== undefined &&\n\t\t\t\t// #2756 For the -element the initial value is 0,\n\t\t\t\t// despite the attribute not being present. When the attribute\n\t\t\t\t// is missing the progress bar is treated as indeterminate.\n\t\t\t\t// To fix that we'll always update it when it is 0 for progress elements\n\t\t\t\t(inputValue !== dom[i] ||\n\t\t\t\t\t(nodeType === 'progress' && !inputValue) ||\n\t\t\t\t\t// This is only for IE 11 to fix