g(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b}\nfunction g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if(\"object\"===typeof performance&&\"function\"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()}}else{var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q}}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D=\"function\"===typeof setTimeout?setTimeout:null,E=\"function\"===typeof clearTimeout?clearTimeout:null,F=\"undefined\"!==typeof setImmediate?setImmediate:null;\n\"undefined\"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t)}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else{var b=h(t);null!==b&&K(H,b.startTime-a)}}\nfunction J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if(\"function\"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();\"function\"===typeof e?v.callback=e:v===h(r)&&k(r);G(b)}else k(r);v=h(r)}if(null!==v)var w=!0;else{var m=h(t);null!==m&&K(H,m.startTime-b);w=!1}return w}finally{v=null,y=c,z=!1}}var N=!1,O=null,L=-1,P=5,Q=-1;\nfunction M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a};\nexports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c}}};\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/scheduler.production.min.js');\n} else {\n module.exports = require('./cjs/scheduler.development.js');\n}\n","export enum PricingPeriod {\n MONTHLY = 'MONTHLY',\n ANNUAL = 'ANNUAL'\n}\n","import {\n PricingStrategy,\n PricingTier\n} from '@atlassiansox/asc-product-catalog';\n\nimport { PricingCalculation } from './pricing-calculation';\n\nexport type PricingBreakdown = ReadonlyArray;\n\nexport type PricingBreakdownItem = {\n readonly units: number;\n readonly unitPrice: number;\n readonly tier: PricingTier;\n};\n\nexport function reduceBreakdownToPricingCalculation(\n { total, currencyIsoCode, breakdown, pricingPlan }: PricingCalculation,\n { tier, units, unitPrice }: PricingBreakdownItem\n) {\n return {\n currencyIsoCode,\n breakdown,\n pricingPlan,\n total: updateTotal(total, tier.pricingStrategy, units, unitPrice)\n };\n}\n\nfunction updateTotal(\n total: number,\n pricingStrategy: PricingStrategy,\n units: number,\n unitPrice: number\n) {\n switch (pricingStrategy) {\n case PricingStrategy.FIXED_COST:\n return unitPrice;\n case PricingStrategy.MARGINAL_PER_UNIT:\n return total + units * unitPrice;\n case PricingStrategy.PER_UNIT:\n return units * unitPrice;\n }\n}\n","import { PricingTier } from '@atlassiansox/asc-product-catalog';\nimport { Predicate } from './predicate';\n\nexport function createPricingTierIsInUnitLimitsPredicate(\n units: number\n): Predicate {\n return ({ unitLimitLower, unitLimitUpper }) =>\n (unitLimitLower === null || units >= unitLimitLower) &&\n (unitLimitUpper === null || units <= unitLimitUpper);\n}\n\nexport function getUnitPrice(\n tier: PricingTier,\n currencyIsoCode: string\n): number {\n const locale = tier.prices.find(\n ({ currency }) => currency === currencyIsoCode\n );\n\n return locale ? locale.unitPrice : -1;\n}\n","import {\n PricingPlan as RawPricingPlan,\n PricingPlans as RawPricingPlans,\n PricingStrategy,\n PricingTierPrice\n} from '@atlassiansox/asc-product-catalog';\nimport { PricingPeriod } from '../models';\n\nexport type PricingTier = {\n readonly starter: boolean;\n readonly pricingStrategy: PricingStrategy;\n readonly unitDescription: string;\n readonly unitLimitLower: number;\n readonly unitLimitUpper: number | null;\n readonly prices: ReadonlyArray;\n};\n\nexport type PricingPlan = ReadonlyArray;\n\nexport type PricingPlans = {\n readonly [key in PricingPeriod]?: PricingPlan;\n};\n\nexport function sanitizePricingPlans({\n monthly,\n annual\n}: RawPricingPlans): PricingPlans {\n return {\n [PricingPeriod.MONTHLY]: sanitizePricingPlan(monthly),\n [PricingPeriod.ANNUAL]: sanitizePricingPlan(annual)\n };\n}\n\nconst MIN_UNIT_LIMIT = 1;\n\n// the first tier starts with a lower unit limit of 0, which for WAC needs to be 1\nconst correctFirstTierUnitLimitLower = (\n priceTiers: RawPricingPlan\n): PricingPlan => {\n const { unitLimitLower } = priceTiers[0];\n\n const correctedUnitLimitLower = Math.max(\n unitLimitLower || MIN_UNIT_LIMIT,\n MIN_UNIT_LIMIT\n );\n\n return [\n {\n ...priceTiers[0],\n unitLimitLower: correctedUnitLimitLower\n } as PricingTier\n ].concat(priceTiers.slice(1) as PricingTier[]);\n};\n\nexport function sanitizePricingPlan(\n pricingPlan?: RawPricingPlan\n): PricingPlan | undefined {\n if (pricingPlan) {\n return correctFirstTierUnitLimitLower(pricingPlan);\n } else {\n return undefined;\n }\n}\n\n// import { PriceTier } from '@atlassian/bxp-price-calculation';\n\n// const MAX_UNIT_LIMIT = 5000;\n\n// // pricing tiers out of HAMS have data that is invalid\n// // in various ways for displaying pricing on WAC\n\n// // these functions each make a transformation that makes valid\n// // the price tier data for our use case\n\n// // it doesn't make sense to have a unit limit below one on any tier\n// // for display on WAC, also the max tier limit shown should be 5000\n// const clampUnitLimits = (priceTiers: PriceTier[]): PriceTier[] =>\n// priceTiers.map(priceTier => {\n// const { unitLimitLower, unitLimitUpper } = priceTier;\n\n// const [clampedUnitLimitLower, clampedUnitLimitUpper] = [\n// unitLimitLower,\n// unitLimitUpper\n// ].map(unitLimit =>\n// Math.max(Math.min(unitLimit, MAX_UNIT_LIMIT), MIN_UNIT_LIMIT)\n// );\n\n// priceTier.unitLimitLower = clampedUnitLimitLower;\n// priceTier.unitLimitUpper = clampedUnitLimitUpper;\n\n// return priceTier;\n// });\n\n// // sometimes the first tier has a lower and upper unit limit of -987654321\n// // so drop this tier entirely\n// const dropInvalidFirstTier = (priceTiers: PriceTier[]): PriceTier[] => {\n// const { unitLimitLower, unitLimitUpper } = priceTiers[0];\n\n// return unitLimitLower === -987654321 &&\n// unitLimitLower === unitLimitUpper &&\n// priceTiers.length > 1\n// ? priceTiers.slice(1)\n// : priceTiers;\n// };\n\n// export default function(priceTiers: PriceTier[]): PriceTier[] {\n// return [\n// dropInvalidFirstTier,\n// clampUnitLimits,\n// correctFirstTierUnitLimitLower\n// ].reduce((tiers, tiersTransformFn) => tiersTransformFn(tiers), priceTiers);\n// }\n","import {\n CCPPricingPlanContent,\n CCPPricingPlanTier,\n PricingStrategy,\n PricingTier\n} from '@atlassiansox/asc-product-catalog';\nimport { PricingPlan, PricingPlans } from '.';\nimport { PricingPeriod } from '../models';\n\nconst HAMS_PRICING_STRATEGY_BY_CCP_PRICING_POLICY = {\n ['BLOCK']: PricingStrategy.FIXED_COST,\n ['MARGINAL_PER_UNIT']: PricingStrategy.MARGINAL_PER_UNIT,\n ['PER_UNIT']: PricingStrategy.PER_UNIT\n};\n\nconst convertCCPPricingStrategyToHAMS = (\n ccpPricingPolicy: string\n): PricingStrategy => {\n const hamsPricingStrategy =\n HAMS_PRICING_STRATEGY_BY_CCP_PRICING_POLICY[\n ccpPricingPolicy as 'BLOCK' | 'MARGINAL_PER_UNIT' | 'PER_UNIT'\n ];\n\n if (!hamsPricingStrategy) {\n throw new Error(\n `Could not find HAMS pricing strategy to match CCP pricing policy: \"${ccpPricingPolicy}\"`\n );\n }\n\n return hamsPricingStrategy;\n};\n\nconst convertCCPTiersToHAMS = (\n ccpTiers: CCPPricingPlanTier[],\n chargeElement: string,\n currency: string\n): PricingTier[] =>\n ccpTiers.map(ccpTier => ({\n starter: false,\n pricingStrategy: convertCCPPricingStrategyToHAMS(ccpTier.policy),\n unitDescription: chargeElement,\n unitLimitLower: ccpTier.floor,\n unitLimitUpper: ccpTier.ceiling,\n prices: [\n {\n currency,\n unitPrice: ccpTier.policy.includes('UNIT')\n ? ccpTier.unitAmount\n : ccpTier.flatAmount\n }\n ]\n }));\n\nconst convertCCPPricingPlansToHAMS = (\n pricingPlans: CCPPricingPlanContent[]\n): PricingPlans => {\n const [monthlyCCP, annualCCP] = ['MONTH', 'YEAR'].map(primaryCycle =>\n pricingPlans.find(\n pricingPlan => pricingPlan.primaryCycle_interval === primaryCycle\n )\n );\n\n const [monthly, annual] = [monthlyCCP, annualCCP].map(ccpPPContent => {\n if (!ccpPPContent) {\n return undefined;\n }\n\n const { tiers, chargeElement } = ccpPPContent.items[0];\n return convertCCPTiersToHAMS(tiers, chargeElement, ccpPPContent.currency);\n });\n\n return {\n [PricingPeriod.MONTHLY]: monthly as PricingPlan,\n [PricingPeriod.ANNUAL]: annual as PricingPlan\n };\n};\n\nexport { convertCCPPricingPlansToHAMS };\n","import { PricingPlan } from '@atlassiansox/asc-product-catalog';\nimport { PricingStrategy, PricingTier } from '@atlassiansox/asc-product-catalog';\n\nimport { PricingBreakdown, PricingBreakdownItem } from '../models';\nimport { Predicate } from './predicate';\nimport { getUnitPrice } from './pricing-tier';\n\nexport type PricingTierToPricingBreakdownItemTransform = (\n tier: PricingTier,\n index: number\n) => PricingBreakdownItem;\n\nexport function createMarginalPerUnitBreakdown(\n pricingPlan: PricingPlan,\n units: number,\n currencyIsoCode: string\n): PricingBreakdown {\n return pricingPlan\n .filter(createPricingTierIsMarginalPerUnitStrategy(units))\n .sort(comparePricingTierByUnitLimitLower)\n .map(\n createPricingTierToPricingBreakdownItemTransform(units, currencyIsoCode)\n );\n}\n\nexport function comparePricingTierByUnitLimitLower(\n { unitLimitLower: firstLimit }: PricingTier,\n { unitLimitLower: secondLimit }: PricingTier\n): number {\n if (firstLimit !== null && secondLimit !== null) {\n return firstLimit - secondLimit;\n } else if (firstLimit === null) {\n return 1;\n } else {\n return -1;\n }\n}\n\nexport function createPricingTierToPricingBreakdownItemTransform(\n units: number,\n currencyIsoCode: string\n): PricingTierToPricingBreakdownItemTransform {\n return (tier, index) => {\n const unitPrice = getUnitPrice(tier, currencyIsoCode);\n const ignoreUnitLimitLower = index === 0;\n \n if (ignoreUnitLimitLower) {\n return {\n units: Math.min(units, tier.unitLimitUpper || Infinity),\n unitPrice,\n tier: {\n ...tier,\n unitLimitLower: 1\n }\n };\n } else {\n const unitLimitLower = tier.unitLimitLower || 1;\n if (units < unitLimitLower) {\n return { units: 0, unitPrice, tier };\n } else {\n return {\n units:\n Math.min(units, tier.unitLimitUpper || Infinity) -\n unitLimitLower +\n 1,\n unitPrice,\n tier\n };\n }\n }\n };\n}\n\nfunction createPricingTierIsMarginalPerUnitStrategy(\n units: number\n): Predicate {\n return ({ pricingStrategy, unitLimitLower }) =>\n pricingStrategy === PricingStrategy.MARGINAL_PER_UNIT &&\n (unitLimitLower === null || units >= unitLimitLower);\n}\n","import {\n PricingStrategy,\n PricingTierPrice,\n ProductKey\n} from '@atlassiansox/asc-product-catalog';\nimport {\n PricingBreakdown,\n PricingCalculation,\n PricingPeriod,\n reduceBreakdownToPricingCalculation\n} from './models';\nimport { IProductPricingStore } from './product-pricing-store';\nimport {\n createPricingTierIsInUnitLimitsPredicate,\n getUnitPrice,\n PricingPlan\n} from './utils';\nimport { createMarginalPerUnitBreakdown } from './utils/marginal-per-unit';\n\nconst DEFAULT_CURRENCY = 'USD';\n\nexport type PricingCalculatorOptions = {\n readonly productPricingStore: IProductPricingStore;\n};\n\nexport class PricingCalculator {\n private readonly store: IProductPricingStore;\n\n constructor({ productPricingStore }: PricingCalculatorOptions) {\n this.store = productPricingStore;\n }\n\n async calculatePrice({\n productKey,\n units,\n period,\n currencyIsoCode\n }: GetPriceCalculationOptions): Promise {\n const pricingPlan = await this.getPricingPlan({ productKey, period });\n\n if (\n !pricingPlan[0].prices.some(\n ({ currency }) => currency === currencyIsoCode\n )\n ) {\n currencyIsoCode = DEFAULT_CURRENCY;\n }\n\n return await this.calculatePriceWithPricingPlan({\n units,\n currencyIsoCode,\n pricingPlan\n });\n }\n\n async calculatePriceWithPricingPlan({\n units,\n currencyIsoCode,\n pricingPlan\n }: GetPriceCalculationWithPricingPlanOptions): Promise {\n const breakdown = await this.getBreakdown({\n pricingPlan,\n units,\n currencyIsoCode\n });\n\n return breakdown.reduce(reduceBreakdownToPricingCalculation, {\n currencyIsoCode,\n breakdown,\n pricingPlan,\n total: 0\n });\n }\n\n private async getPricingPlan({\n productKey,\n period\n }: GetPricingPlanOptions): Promise {\n const {\n [PricingPeriod.MONTHLY]: monthly,\n [PricingPeriod.ANNUAL]: annual\n } = await this.store.getPricingPlans(productKey);\n\n // there are no \"annual free\" pricing plans but consumers of this package need to request\n // free pricing along with annual non-free pricing in one call so we need to return the\n // free monthly pricing plan always when the product key ends in '.free'\n const adjPeriod = productKey.endsWith('.free')\n ? PricingPeriod.MONTHLY\n : period;\n\n switch (adjPeriod) {\n case PricingPeriod.MONTHLY:\n if (monthly) {\n return monthly;\n } else {\n throw new Error(\n `Monthly pricing plan does not exist for product key: ${productKey}`\n );\n }\n case PricingPeriod.ANNUAL:\n if (annual) {\n return annual;\n } else {\n throw new Error(\n `Annual pricing plan does not exist for product key: ${productKey}`\n );\n }\n }\n }\n\n private async getBreakdown({\n pricingPlan,\n units,\n currencyIsoCode\n }: GetBreakdownOptions): Promise {\n const selectedTier = pricingPlan.find(\n createPricingTierIsInUnitLimitsPredicate(units)\n );\n if (selectedTier) {\n switch (selectedTier.pricingStrategy) {\n case PricingStrategy.MARGINAL_PER_UNIT:\n return createMarginalPerUnitBreakdown(\n pricingPlan,\n units,\n currencyIsoCode\n );\n default:\n return [\n {\n units,\n unitPrice: getUnitPrice(selectedTier, currencyIsoCode),\n tier: selectedTier\n }\n ];\n }\n } else {\n throw new Error(`Could not find pricing plan tier for ${units} units`);\n }\n }\n}\n\nexport type GetPriceCalculationOptions = {\n readonly productKey: ProductKey;\n readonly units: number;\n readonly period: PricingPeriod;\n readonly currencyIsoCode: string;\n};\n\nexport type GetPriceCalculationWithPricingPlanOptions = {\n readonly units: number;\n readonly currencyIsoCode: string;\n readonly pricingPlan: PricingPlan;\n};\n\nexport type GetBreakdownOptions = {\n readonly pricingPlan: PricingPlan;\n readonly units: number;\n readonly currencyIsoCode: string;\n};\n\nexport type GetPricingPlanOptions = {\n readonly productKey: ProductKey;\n readonly period: PricingPeriod;\n};\n\nexport { PricingStrategy, PricingTierPrice, ProductKey };\n","import {\n ICCPProductCatalogClient,\n IProductCatalogClient,\n OfferingSKU,\n OfferingSKUMap,\n ProductKey,\n ProductKeyMap\n} from '@atlassiansox/asc-product-catalog';\nimport { AddonProduct } from './models';\nimport {\n convertCCPPricingPlansToHAMS,\n PricingPlans,\n sanitizePricingPlans\n} from './utils';\n\nexport type ProductPricingStoreOptions = {\n readonly productCatalogClient: IProductCatalogClient;\n readonly ccpProductCatalogClient: ICCPProductCatalogClient;\n};\n\nexport interface IProductPricingStore {\n getPricingPlans(productKey: ProductKey): Promise;\n getProducts(\n productKeys: ReadonlyArray\n ): Promise>;\n searchAddons(\n parentProductKey: string,\n query: string,\n limit: number\n ): Promise;\n getOfferings(\n offeringSKUs: ReadonlyArray\n ): Promise>;\n}\n\nexport class ProductPricingStore implements IProductPricingStore {\n private readonly productCatalogClient: IProductCatalogClient;\n private readonly ccpProductCatalogClient: ICCPProductCatalogClient;\n private readonly cache: Map>;\n\n constructor({\n productCatalogClient,\n ccpProductCatalogClient\n }: ProductPricingStoreOptions) {\n this.productCatalogClient = productCatalogClient;\n this.ccpProductCatalogClient = ccpProductCatalogClient;\n this.cache = new Map();\n }\n\n public async getPricingPlans(productKey: ProductKey): Promise {\n const pricingPlans = (await this.getProducts([productKey]))[productKey];\n if (pricingPlans) {\n return pricingPlans;\n } else {\n throw new Error(\n `Could not find pricing plans for product key: ${productKey}`\n );\n }\n }\n\n public async getProducts(\n productKeys: ReadonlyArray\n ): Promise> {\n const uncachedProductKeys = productKeys.filter(this.isProductKeyUncached);\n\n if (uncachedProductKeys.length > 0) {\n this.fetchProducts(uncachedProductKeys);\n return this.getProducts(productKeys);\n } else {\n return this.getCachedProducts(productKeys);\n }\n }\n\n public async getOfferings(\n offeringSKUs: ReadonlyArray\n ): Promise> {\n const uncachedOfferingSKUs = offeringSKUs.filter(\n this.isOfferingSKUUncached\n );\n\n if (uncachedOfferingSKUs.length > 0) {\n this.fetchOfferings(uncachedOfferingSKUs);\n return this.getOfferings(offeringSKUs);\n } else {\n return this.getCachedOfferings(offeringSKUs);\n }\n }\n\n public async searchAddons(\n parentProductKey: string,\n query: string,\n limit = 100\n ): Promise {\n const addons = await this.productCatalogClient.searchAddons({\n parentProductKey,\n query,\n limit\n });\n\n return addons.map(addon => ({\n ...addon,\n pricing: sanitizePricingPlans(addon.pricing)\n }));\n }\n\n private fetchProducts(productKeys: ReadonlyArray): void {\n const pricingPromise = this.productCatalogClient.getPricing({\n productKeys\n });\n productKeys.forEach(productKey => {\n this.cache.set(\n productKey,\n new Promise(async resolve => {\n const pricing = await pricingPromise;\n const pricingPlans = pricing[productKey];\n if (pricingPlans) {\n resolve(sanitizePricingPlans(pricingPlans));\n } else {\n resolve(null);\n }\n })\n );\n });\n }\n\n private fetchOfferings(offeringSKUs: ReadonlyArray): void {\n const pricingPromise = this.ccpProductCatalogClient.getOfferingsBySKU({\n offeringSKUs\n });\n\n offeringSKUs.forEach(offeringSKU => {\n this.cache.set(\n offeringSKU,\n new Promise(\n async (resolve: (value: PricingPlans | null) => void, reject) => {\n const pricing = await pricingPromise;\n const offering = pricing[offeringSKU];\n\n let ccpPricingPlans;\n if (offering && offering.fields.defaultPricingPlans) {\n ccpPricingPlans = offering.fields.defaultPricingPlans.map(\n ccpPPContent => ccpPPContent.fields\n );\n }\n\n if (ccpPricingPlans && ccpPricingPlans.length > 0) {\n try {\n resolve(convertCCPPricingPlansToHAMS(ccpPricingPlans));\n } catch (e) {\n reject(e);\n }\n } else {\n resolve(null);\n }\n }\n )\n );\n });\n }\n\n private readonly isProductKeyUncached = (productKey: ProductKey): boolean =>\n !this.cache.has(productKey);\n\n private readonly isOfferingSKUUncached = (\n offeringSKU: OfferingSKU\n ): boolean => !this.cache.has(offeringSKU);\n\n private readonly getCachedProducts = async (\n productKeys: ReadonlyArray\n ): Promise> => {\n const products = await Promise.all(\n productKeys.map(async productKey => {\n const pricingPlans = await this.cache.get(productKey);\n return { productKey, pricingPlans };\n })\n );\n\n return products\n .filter(({ pricingPlans }) => !!pricingPlans)\n .reduce((result, { productKey, pricingPlans }) => {\n return { ...result, [productKey]: pricingPlans };\n }, {});\n };\n\n private readonly getCachedOfferings = async (\n offeringSKUs: ReadonlyArray\n ): Promise> => {\n const offerings = await Promise.all(\n offeringSKUs.map(async offeringSKU => {\n const pricingPlans = await this.cache.get(offeringSKU);\n return { offeringSKU, pricingPlans };\n })\n );\n\n return offerings\n .filter(({ pricingPlans }) => !!pricingPlans)\n .reduce((result, { offeringSKU, pricingPlans }) => {\n return { ...result, [offeringSKU]: pricingPlans };\n }, {});\n };\n}\n","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nimport React from 'react';\nimport { NAVIGATION_CHANNEL, OPERATIONAL_EVENT_TYPE, withAnalyticsEvents } from '../utils/analytics';\nimport { errorToReason } from '../utils/error-to-reason';\nimport { retryOnException } from '../utils/retry-operation';\nimport { withExperienceTracker } from '../utils/experience-tracker';\nconst DATA_PROVIDER_SUBJECT = 'atlassianSwitcherDataProvider';\nexport let Status = /*#__PURE__*/function (Status) {\n Status[\"LOADING\"] = \"loading\";\n Status[\"COMPLETE\"] = \"complete\";\n Status[\"ERROR\"] = \"error\";\n return Status;\n}({});\nexport const createResultComplete = data => ({\n status: Status.COMPLETE,\n data\n});\nexport const isComplete = result => result.status === Status.COMPLETE;\nexport const isError = result => result.status === Status.ERROR;\nexport const isLoading = result => result.status === Status.LOADING;\nexport const hasLoaded = result => result.status !== Status.LOADING;\nexport default function (name, experienceMark, mapPropsToPromise, mapPropsToInitialValue, retryConfig, shouldUpdate) {\n const getInitialState = props => {\n if (mapPropsToInitialValue) {\n const initialValue = mapPropsToInitialValue(props);\n if (initialValue !== undefined) {\n return {\n status: Status.COMPLETE,\n data: initialValue\n };\n }\n }\n return {\n status: Status.LOADING,\n data: null\n };\n };\n class DataProvider extends React.Component {\n constructor(...args) {\n super(...args);\n _defineProperty(this, \"acceptResults\", true);\n _defineProperty(this, \"state\", getInitialState(this.props.params));\n _defineProperty(this, \"fireOperationalEvent\", payload => {\n if (this.props.createAnalyticsEvent) {\n this.props.createAnalyticsEvent({\n eventType: OPERATIONAL_EVENT_TYPE,\n actionSubject: DATA_PROVIDER_SUBJECT,\n ...payload,\n attributes: {\n ...payload.attributes,\n outdated: !this.acceptResults\n }\n }).fire(NAVIGATION_CHANNEL);\n }\n });\n }\n componentWillUnmount() {\n /**\n * Promise resolved after component is unmounted to be ignored\n */\n this.acceptResults = false;\n }\n componentDidMount() {\n this.props.experienceTracker.markStart(experienceMark);\n this.fetchData();\n }\n componentDidUpdate(prevProps) {\n if (shouldUpdate !== null && shouldUpdate !== void 0 && shouldUpdate(prevProps.params, this.props.params)) {\n this.fetchData();\n }\n }\n fetchData() {\n retryOnException(() => mapPropsToPromise(this.props.params), {\n intervalsMS: (retryConfig === null || retryConfig === void 0 ? void 0 : retryConfig.intervalsMS) || [],\n shouldRetryOnException: retryConfig === null || retryConfig === void 0 ? void 0 : retryConfig.shouldRetryOnException,\n onRetry: (previousException, retryCount) => {\n this.onRetry(previousException, retryCount);\n }\n }).then(result => {\n this.onResult(result);\n }).catch(error => {\n this.onError(error);\n });\n }\n onResult(value) {\n if (this.acceptResults) {\n this.setState({\n data: value,\n status: Status.COMPLETE\n });\n }\n this.props.experienceTracker.markEnd(experienceMark);\n this.fireOperationalEvent({\n action: 'receivedResult',\n actionSubjectId: name,\n attributes: {\n provider: name\n }\n });\n }\n onRetry(error, retryCount) {\n this.fireOperationalEvent({\n action: 'retried',\n actionSubjectId: name,\n attributes: {\n provider: name,\n reason: retryConfig !== null && retryConfig !== void 0 && retryConfig.customErrorToReason ? retryConfig.customErrorToReason(error) : errorToReason(error),\n retryCount\n }\n });\n }\n onError(error) {\n /**\n * Do not transition from \"complete\" state to \"error\"\n */\n if (this.acceptResults && !isComplete(this.state)) {\n this.setState({\n error,\n status: Status.ERROR,\n data: null\n });\n }\n this.fireOperationalEvent({\n action: 'failed',\n actionSubjectId: name,\n attributes: {\n provider: name,\n reason: errorToReason(error)\n }\n });\n }\n render() {\n return this.props.children(this.state);\n }\n }\n\n // In prefetch, we start with empty args {}, but when getting data from the cache in the data provider, extra args are injected by HOC withAnalyticsEvents and withExperienceTracker\n // This results in a cache miss due to a key mismatch.\n // The workaround here is to use a wrapper (OuterComponent) that passes the original props as a separate prop(params) to the underlying component(InnerComponent).\n // For more info: https://product-fabric.atlassian.net/browse/CXP-2697\n _defineProperty(DataProvider, \"displayName\", `DataProvider(${name})`);\n const InnerComponent = withAnalyticsEvents()(withExperienceTracker(DataProvider));\n const OuterComponent = ({\n children,\n ...params\n }) => {\n return /*#__PURE__*/React.createElement(InnerComponent, {\n params: params\n }, children);\n };\n return OuterComponent;\n}","import asDataProvider from './as-data-provider';\nimport { fetchJson } from '../utils/fetch';\nimport { withCached } from '../utils/with-cached';\n\n/**\n * Some items might be using the type `ExportedDataProvider` instead due to errors with\n * the generated documentation\n */\n\n/**\n * `WithCached` within `DataProvider` breaks the documentation with error:\n * `Error: Missing converter for: TSMappedType` due to usage of Proxy function\n * so we are exporting a simpler type here just for the docs. There has been reported\n * on their repo already: https://github.com/atlassian/extract-react-types/issues/75\n */\n\nexport const createProvider = (name, experienceMark, url) => {\n const fetchMethod = withCached(param => fetchJson(url));\n return {\n fetchMethod,\n ProviderComponent: asDataProvider(name, experienceMark, fetchMethod, fetchMethod.cached,\n // fetch will only throw on a network exception,\n // so we can safely retry on all exceptions\n {\n shouldRetryOnException: () => true,\n intervalsMS: [50, 200, 1000]\n })\n };\n};\nexport const createProviderWithCustomFetchData = (name, experienceMark, fetchData, retryConfig) => {\n const fetchMethod = withCached(param => fetchData(param));\n return {\n fetchMethod,\n ProviderComponent: asDataProvider(name, experienceMark, fetchMethod, fetchMethod.cached, retryConfig)\n };\n};","const INFINITY = '+Inf';\nexport const ImageLoadTrackerBuckets = [4000, 2000, 1000, 500, 100, 50];\nexport const RenderTrackerBuckets = [1000, 900, 800, 700, 600, 500];\n\n// Group load times in to buckets for metric cardinality\nexport const getMetricBucket = (metricValue, buckets) => {\n return metricValue >= 0 ? buckets.reduce((lowestBucket, currentBucket) => {\n return metricValue <= currentBucket ? currentBucket.toString() : lowestBucket.toString();\n }, INFINITY) : null;\n};","import _extends from \"@babel/runtime/helpers/extends\";\nimport React from 'react';\nimport { NavigationAnalyticsContext } from '@atlaskit/analytics-namespaced-context';\nimport { createAndFireEvent, withAnalyticsEvents, useAnalyticsEvents } from '@atlaskit/analytics-next';\nimport { UI_EVENT_TYPE, OPERATIONAL_EVENT_TYPE } from '@atlaskit/analytics-gas-types';\nimport { hasLoaded, Status } from '../../providers/as-data-provider';\nimport { UserSiteDataError } from '../errors/user-site-data-error';\nimport { getMetricBucket, RenderTrackerBuckets, ImageLoadTrackerBuckets } from '../get-metric-bucket';\nimport { performanceNow } from '../performance-now';\nexport const NAVIGATION_CHANNEL = 'navigation';\nexport const SWITCHER_SUBJECT = 'atlassianSwitcher';\nexport const SWITCHER_ITEM_SUBJECT = 'atlassianSwitcherItem';\nexport const SWITCHER_ITEM_LOZENGES_SUBJECT = 'atlassianSwitcherItemLozenges';\nexport const SWITCHER_CHILD_ITEM_SUBJECT = 'atlassianSwitcherChildItem';\nexport const SWITCHER_ITEM_EXPAND_SUBJECT = 'atlassianSwitcherItemExpand';\nexport const SWITCHER_COMPONENT = 'atlassianSwitcher';\nexport const SWITCHER_SOURCE = 'atlassianSwitcher';\nexport const TRIGGER_COMPONENT = 'atlassianSwitcherPrefetch';\nexport const TRIGGER_SUBJECT = 'atlassianSwitcherPrefetch';\nexport const SWITCHER_PARTIAL_RESULTS = 'atlassianSwitcherPartialResultError';\nexport const SWITCHER_ORG_ITEM = 'atlassianSwitcherOrgItem';\nexport const SWITCHER_FOOTER_LEAVE_FEEDBACK = 'atlassianSwitcherFooterLeaveFeedback';\nexport const SWITCHER_CURRENT_ORG = 'atlassianSwitcherCurrentOrg';\nexport const SWITCHER_ORG_LIST = 'atlassianSwitcherOrganisationsList';\nexport const SWITCHER_JOINABLE_SITES = 'atlassianSwitcherJoinableSites';\nexport const SWITCHER_AVAILABLE_PRODUCTS = 'atlassianSwitcherAvailableProducts';\nconst SWITCHER_DISCOVER_SECTION = 'atlassianSwitcherDiscoverMore';\nconst SWITCHER_RECENT_CONTAINERS = 'atlassianSwitcherRecentContainers';\nconst SWITCHER_CUSTOM_LINKS = 'atlassianSwitcherCustomLinks';\nconst SWITCHER_REMOTE_ICON = 'atlassianSwitcherRemoteIcon';\nconst RENDERED_ACTION = 'rendered';\nconst NOT_RENDERED_ACTION = 'not_rendered';\nconst VIEWED_ACTION = 'viewed';\nconst LOADED_ACTION = 'loaded';\nconst NOT_LOADED_ACTION = 'not_loaded';\nexport const createAndFireNavigationEvent = createAndFireEvent(NAVIGATION_CHANNEL);\nexport const analyticsAttributes = attributes => ({\n attributes\n});\nexport const withAnalyticsContextData = function (mapPropsToContext) {\n return function (WrappedComponent) {\n return props => /*#__PURE__*/React.createElement(NavigationAnalyticsContext, {\n data: mapPropsToContext(props)\n }, /*#__PURE__*/React.createElement(WrappedComponent, props));\n };\n};\nconst isValidDuration = duration => {\n return duration !== null && duration !== undefined && duration >= 0;\n};\nexport const RenderTracker = withAnalyticsEvents({\n onRender: (createAnalyticsEvent, props) => {\n var _props$data;\n const duration = (_props$data = props.data) === null || _props$data === void 0 ? void 0 : _props$data.duration;\n return createAnalyticsEvent({\n eventType: OPERATIONAL_EVENT_TYPE,\n action: RENDERED_ACTION,\n actionSubject: props.subject,\n attributes: {\n ...props.data,\n ...(isValidDuration(duration) && {\n bucket: getMetricBucket(duration, RenderTrackerBuckets)\n })\n }\n }).fire(NAVIGATION_CHANNEL);\n }\n})(class extends React.Component {\n componentDidMount() {\n this.props.onRender();\n }\n render() {\n return null;\n }\n});\nexport const NotRenderedTracker = withAnalyticsEvents({\n onRender: (createAnalyticsEvent, props) => {\n return createAnalyticsEvent({\n eventType: OPERATIONAL_EVENT_TYPE,\n action: NOT_RENDERED_ACTION,\n actionSubject: props.subject,\n attributes: props.data\n }).fire(NAVIGATION_CHANNEL);\n }\n})(class extends React.Component {\n componentDidMount() {\n this.props.onRender();\n }\n render() {\n return null;\n }\n});\nexport const ViewedTracker = withAnalyticsEvents({\n onRender: (createAnalyticsEvent, props) => {\n return createAnalyticsEvent({\n eventType: UI_EVENT_TYPE,\n action: VIEWED_ACTION,\n actionSubject: props.subject,\n attributes: props.data\n }).fire(NAVIGATION_CHANNEL);\n }\n})(class extends React.Component {\n componentDidMount() {\n this.props.onRender();\n }\n render() {\n return null;\n }\n});\nexport const ImageLoadedTracker = props => {\n const {\n onLoad,\n onError,\n ...imgProps\n } = props;\n const {\n createAnalyticsEvent\n } = useAnalyticsEvents();\n const imageMountedAt = React.useRef(performanceNow());\n const analyticsHandler = React.useCallback((actionType, event, action) => {\n const duration = performanceNow() - imageMountedAt.current;\n createAnalyticsEvent({\n action: actionType,\n actionSubject: SWITCHER_REMOTE_ICON,\n attributes: {\n ...(isValidDuration(duration) && {\n bucket: getMetricBucket(duration, ImageLoadTrackerBuckets),\n duration\n }),\n src: imgProps.src\n },\n eventType: OPERATIONAL_EVENT_TYPE\n }).fire(NAVIGATION_CHANNEL);\n if (action) {\n action(event);\n }\n }, [createAnalyticsEvent, imageMountedAt, imgProps.src]);\n const onErrorAnalyticsHandler = React.useCallback(errorEvent => {\n analyticsHandler(NOT_LOADED_ACTION, errorEvent, onError);\n }, [analyticsHandler, onError]);\n const onLoadAnalyticsHandler = React.useCallback(loadEvent => {\n analyticsHandler(LOADED_ACTION, loadEvent, onLoad);\n }, [analyticsHandler, onLoad]);\n return /*#__PURE__*/React.createElement(\"img\", _extends({}, imgProps, {\n onError: onErrorAnalyticsHandler,\n onLoad: onLoadAnalyticsHandler\n }));\n};\nconst renderTrackerWithReason = ({\n subject,\n notRenderedReason,\n emptyRenderExpected,\n data\n}) => {\n if (notRenderedReason) {\n return /*#__PURE__*/React.createElement(NotRenderedTracker, {\n subject: subject,\n data: {\n ...data,\n notRenderedReason\n }\n });\n }\n return /*#__PURE__*/React.createElement(RenderTracker, {\n subject: subject,\n data: {\n ...data,\n emptyRender: emptyRenderExpected\n }\n });\n};\nconst renderTracker = ({\n subject,\n providerFailed,\n emptyRenderExpected,\n linksRendered,\n data\n}) => {\n if (providerFailed || linksRendered.length === 0 && !emptyRenderExpected) {\n return /*#__PURE__*/React.createElement(NotRenderedTracker, {\n subject: subject,\n data: {\n ...data,\n providerFailed\n }\n });\n }\n return /*#__PURE__*/React.createElement(RenderTracker, {\n subject: subject,\n data: {\n ...data,\n emptyRender: emptyRenderExpected\n }\n });\n};\nexport const getJoinableSitesRenderTracker = (providerResult, joinableSiteLinks, data) => {\n if (!hasLoaded(providerResult)) {\n return null;\n }\n if (providerResult.data && !providerResult.data.sites) {\n return null;\n }\n\n // The render is considered failed when either the provider failed, or the provider returned a non-empty result but nothing was rendered\n const emptyRenderExpected = Boolean(providerResult.data && providerResult.data.sites && providerResult.data.sites.length === 0);\n return renderTracker({\n subject: SWITCHER_JOINABLE_SITES,\n providerFailed: providerResult.data === null,\n emptyRenderExpected,\n linksRendered: joinableSiteLinks,\n data\n });\n};\nexport const getDiscoverSectionRenderTracker = (xflowProviderResult, provisionedProductsProviderResult, joinableSitesProviderResult, productRecommendationsProviderResult, suggestedProductLinks, data) => {\n const hasProviderNotReturnedExpectedData = provider => provider.data === null || provider.status === Status.ERROR;\n const collectResults = provider => ({\n failed: hasProviderNotReturnedExpectedData(provider),\n loaded: hasLoaded(provider)\n });\n const emptyRenderExpected = suggestedProductLinks.length === 0;\n const results = {\n xflow: collectResults(xflowProviderResult),\n provisionedProducts: collectResults(provisionedProductsProviderResult),\n joinableSites: collectResults(joinableSitesProviderResult),\n productRecommendations: collectResults(productRecommendationsProviderResult)\n };\n const providersLoaded = results.joinableSites.loaded && results.provisionedProducts.loaded && results.xflow.loaded && results.productRecommendations.loaded;\n if (!providersLoaded) {\n return null;\n }\n const didProviderFail = results.joinableSites.failed || results.provisionedProducts.failed || results.xflow.failed || results.productRecommendations.failed;\n /**\n * Stop tracking the SLO the moment one of the providers fail.\n */\n if (didProviderFail) {\n return renderTracker({\n subject: SWITCHER_DISCOVER_SECTION,\n providerFailed: true,\n emptyRenderExpected,\n linksRendered: suggestedProductLinks,\n data: {\n ...data,\n providerResults: {\n joinableSites: joinableSitesProviderResult.status,\n joinableSitesFailed: results.joinableSites.failed,\n provisionedProducts: provisionedProductsProviderResult.status,\n provisionedProductsFailed: results.provisionedProducts.failed,\n xflow: xflowProviderResult.status,\n xflowFailed: results.xflow.failed,\n productRecommendations: productRecommendationsProviderResult.status,\n productRecommendationsFailed: results.productRecommendations.failed\n }\n }\n });\n }\n return renderTracker({\n subject: SWITCHER_DISCOVER_SECTION,\n providerFailed: false,\n emptyRenderExpected,\n linksRendered: suggestedProductLinks,\n data\n });\n};\nexport const getRecentContainersRenderTracker = (isEnabled, cgRecentContainersProviderResult, userSiteDataProviderResult, recentLinks, data) => {\n if (!isEnabled) {\n return null;\n }\n const providerFailed = cgRecentContainersProviderResult.data === null || userSiteDataProviderResult.data === null;\n const emptyRenderExpected = Boolean(cgRecentContainersProviderResult.data && cgRecentContainersProviderResult.data.collaborationGraphEntities && cgRecentContainersProviderResult.data.collaborationGraphEntities.length === 0);\n return renderTracker({\n subject: SWITCHER_RECENT_CONTAINERS,\n providerFailed,\n emptyRenderExpected,\n linksRendered: recentLinks,\n data\n });\n};\nexport const getCustomLinksRenderTracker = (customLinksProviderResult, userSiteDataProviderResult, customLinks, data) => {\n // The render is only considered failed when one of the providers failed, and empty render is a valid case\n if (!customLinksProviderResult) {\n return;\n }\n const emptyRenderExpected = customLinks.length === 0;\n function getNotRenderedReason() {\n if ((customLinksProviderResult === null || customLinksProviderResult === void 0 ? void 0 : customLinksProviderResult.status) === Status.ERROR) {\n return 'custom_links_api_error';\n }\n const error = userSiteDataProviderResult.error;\n if (!error) {\n return null;\n }\n if (error instanceof UserSiteDataError) {\n return error.reason;\n } else {\n return 'usd_unknown';\n }\n }\n const notRenderedReason = getNotRenderedReason();\n return renderTrackerWithReason({\n subject: SWITCHER_CUSTOM_LINKS,\n notRenderedReason,\n emptyRenderExpected,\n data\n });\n};\n\n/**\n *\n * ***IMPORTANT*** DO NOT send PD / PII or any sensitive data.\n * This function defines analytic event attributes.\n *\n * @param groupIndex\n * @param id\n * @param type\n * @param productType\n * @param extraAttributes\n */\nexport const getItemAnalyticsContext = (groupIndex, id, type, productType, extraAttributes) => ({\n ...analyticsAttributes({\n groupIndex,\n itemId: id,\n itemType: type,\n productType,\n ...extraAttributes\n })\n});\nexport { withAnalyticsEvents, NavigationAnalyticsContext, OPERATIONAL_EVENT_TYPE, UI_EVENT_TYPE };","export default (channel => payload => createAnalyticsEvent => {\n const consumerEvent = createAnalyticsEvent(payload);\n const clonedEvent = consumerEvent.clone();\n if (clonedEvent) {\n clonedEvent.fire(channel);\n }\n return consumerEvent;\n});","export function errorToReason(error) {\n const {\n name = 'Unknown',\n status = undefined\n } = error || {};\n return {\n name,\n status\n };\n}","import _defineProperty from \"@babel/runtime/helpers/defineProperty\";\nexport const FETCH_ERROR_NAME = 'FetchError';\nexport class FetchError extends Error {\n constructor(message, status) {\n super(message);\n _defineProperty(this, \"name\", FETCH_ERROR_NAME);\n this.status = status;\n }\n static isFetchError(value) {\n if (process.env.NODE_ENV === 'testing') {\n // jest messes up globals badly, see https://github.com/facebook/jest/issues/2549\n // once that issue is fixed, the usages of this function can be inlined to `error instanceof BadStatusError`\n return (value === null || value === void 0 ? void 0 : value.name) === FETCH_ERROR_NAME;\n }\n return value instanceof FetchError;\n }\n}","import { errorToReason } from '../error-to-reason';\nexport let SwitcherLoadErrorReason = /*#__PURE__*/function (SwitcherLoadErrorReason) {\n SwitcherLoadErrorReason[\"AVAILABLE_PRODUCTS\"] = \"availableProducts\";\n SwitcherLoadErrorReason[\"PRODUCT_CONFIGURATION\"] = \"productConfiguration\";\n return SwitcherLoadErrorReason;\n}({});\nexport class SwitcherLoadError extends Error {\n constructor(errorReason, resultError) {\n super();\n this.errorReason = errorReason;\n this.resultError = resultError;\n }\n reason() {\n const potentialResultError = this.resultError;\n return {\n ...errorToReason(potentialResultError.error ? potentialResultError.error : this.resultError),\n source: this.errorReason\n };\n }\n}","export let UserSiteDataErrorReason = /*#__PURE__*/function (UserSiteDataErrorReason) {\n UserSiteDataErrorReason[\"APS_NO_SITE_MATCH\"] = \"aps_no_site_match\";\n UserSiteDataErrorReason[\"APS_EMPTY_RESULT\"] = \"aps_empty_result\";\n UserSiteDataErrorReason[\"APS_PARTIAL_EMPTY_RESULT\"] = \"aps_partial_response_empty_result\";\n return UserSiteDataErrorReason;\n}({});\nexport class UserSiteDataError extends Error {\n constructor(reason, message) {\n super(message);\n this.name = 'UserSiteDataError';\n this.reason = reason;\n }\n}","import { ExperienceTypes, ExperiencePerformanceTypes } from '@atlassian/ufo';\nimport { invertRecordOfArrays } from '../invert-record-of-arrays';\nexport let Experience = /*#__PURE__*/function (Experience) {\n Experience[\"RENDER_CUSTOM_LINKS_SECTION\"] = \"render-custom-links-section\";\n Experience[\"RENDER_DISCOVER_SECTION\"] = \"render-discover-section\";\n Experience[\"RENDER_JOIN_SECTION\"] = \"render-join-section\";\n Experience[\"RENDER_RECENT_SECTION\"] = \"render-recent-section\";\n Experience[\"RENDER_SWITCH_TO_SECTION\"] = \"render-switch-to-section\";\n Experience[\"RENDER_SWITCHER_EMPTY_STATE\"] = \"render-switcher-empty-state\";\n return Experience;\n}({});\nexport const EXPERIENCE_CONFIGS = {\n [Experience.RENDER_CUSTOM_LINKS_SECTION]: {\n type: ExperienceTypes.Load,\n performanceType: ExperiencePerformanceTypes.PageSegmentLoad\n },\n [Experience.RENDER_DISCOVER_SECTION]: {\n type: ExperienceTypes.Load,\n performanceType: ExperiencePerformanceTypes.PageSegmentLoad\n },\n [Experience.RENDER_JOIN_SECTION]: {\n type: ExperienceTypes.Load,\n performanceType: ExperiencePerformanceTypes.PageSegmentLoad\n },\n [Experience.RENDER_RECENT_SECTION]: {\n type: ExperienceTypes.Load,\n performanceType: ExperiencePerformanceTypes.PageSegmentLoad\n },\n [Experience.RENDER_SWITCH_TO_SECTION]: {\n type: ExperienceTypes.Load,\n performanceType: ExperiencePerformanceTypes.PageSegmentLoad\n },\n [Experience.RENDER_SWITCHER_EMPTY_STATE]: {\n type: ExperienceTypes.Load,\n performanceType: ExperiencePerformanceTypes.PageSegmentLoad\n }\n};\nexport let ExperienceMark = /*#__PURE__*/function (ExperienceMark) {\n ExperienceMark[\"API_APP_SWITCHER_BFF_AVAILABLE_PRODUCTS\"] = \"api-app-switcher-bff-available-products\";\n ExperienceMark[\"API_AVAILABLE_PRODUCTS\"] = \"api-available-products\";\n ExperienceMark[\"API_COLLABORATION_GRAPH_RECENT_CONTAINERS\"] = \"api-collaboration-graph-recent-containers\";\n ExperienceMark[\"API_CONFLUENCE_CUSTOM_LINKS\"] = \"api-confluence-custom-links\";\n ExperienceMark[\"API_FLIGHT_DECK\"] = \"api-flight-deck\";\n ExperienceMark[\"API_JIRA_CUSTOM_LINKS\"] = \"api-jira-custom-links\";\n ExperienceMark[\"API_JOINABLE_SITES\"] = \"api-joinable-sites\";\n ExperienceMark[\"API_PERMISSIONS\"] = \"api-permissions\";\n ExperienceMark[\"API_PRODUCT_CONFIGURATION\"] = \"api-product-configuration\";\n ExperienceMark[\"API_PRODUCT_RECOMMENDATIONS\"] = \"api-product-recommendations\";\n ExperienceMark[\"API_XFLOW_SETTINGS\"] = \"api-xflow-settings\";\n ExperienceMark[\"SWITCHER_INITIAL_MOUNT\"] = \"switcher-initial-mount\";\n ExperienceMark[\"SWITCHER_SKELETON_MOUNT\"] = \"switcher-skeleton-mount\";\n ExperienceMark[\"TEST_MARK\"] = \"test-mark\";\n return ExperienceMark;\n}({});\nconst allNonTestExperienceMarks = Object.values(ExperienceMark).filter(mark => mark !== ExperienceMark.TEST_MARK);\nexport const EXPERIENCES_TO_MARKS = {\n [Experience.RENDER_CUSTOM_LINKS_SECTION]: allNonTestExperienceMarks,\n [Experience.RENDER_DISCOVER_SECTION]: allNonTestExperienceMarks,\n [Experience.RENDER_JOIN_SECTION]: allNonTestExperienceMarks,\n [Experience.RENDER_RECENT_SECTION]: allNonTestExperienceMarks,\n [Experience.RENDER_SWITCH_TO_SECTION]: allNonTestExperienceMarks,\n [Experience.RENDER_SWITCHER_EMPTY_STATE]: allNonTestExperienceMarks\n};\nexport const MARKS_TO_EXPERIENCES = invertRecordOfArrays(EXPERIENCES_TO_MARKS);\nexport let ExperienceMarkPhase = /*#__PURE__*/function (ExperienceMarkPhase) {\n ExperienceMarkPhase[\"START\"] = \"start\";\n ExperienceMarkPhase[\"END\"] = \"end\";\n return ExperienceMarkPhase;\n}({});\nexport let AbortReason = /*#__PURE__*/function (AbortReason) {\n AbortReason[\"COMPONENT_UNMOUNTED\"] = \"component-unmounted\";\n AbortReason[\"WINDOW_UNLOADING\"] = \"window-unloading\";\n return AbortReason;\n}({});\nexport const SWITCHER_RENDER_START_PERFORMANCE_MARK = 'atlassianSwitcher.render.start';","export function invertRecordOfArrays(record) {\n const invertedRecord = {};\n Object.entries(record).forEach(([key, values]) => {\n values.forEach(value => {\n if (!invertedRecord[value]) {\n invertedRecord[value] = [];\n }\n invertedRecord[value].push(key);\n });\n });\n return invertedRecord;\n}","import _extends from \"@babel/runtime/helpers/extends\";\nimport React, { createContext, useContext } from 'react';\nconst noop = () => {};\nexport const SwitcherExperienceTrackerContext = /*#__PURE__*/createContext({\n start: noop,\n success: noop,\n failure: noop,\n failureAll: noop,\n abort: noop,\n abortAll: noop,\n markStart: noop,\n markEnd: noop\n});\nexport const useExperienceTracker = () => useContext(SwitcherExperienceTrackerContext);\nexport const withExperienceTracker = Component => {\n const WithExperienceTracker = props => {\n const experienceTracker = useExperienceTracker();\n return /*#__PURE__*/React.createElement(Component, _extends({}, props, {\n experienceTracker: experienceTracker\n }));\n };\n WithExperienceTracker.displayName = `WithExperienceTracker(${Component.displayName})`;\n return WithExperienceTracker;\n};","/* eslint-disable no-console */\nimport { useExperienceTracker } from './context';\nimport { useLayoutEffect } from 'react';\nimport { useOnceImmediately } from '../hooks';\nexport function useExperienceStart(experienceName, customStartTime) {\n const experienceTracker = useExperienceTracker();\n useOnceImmediately(() => experienceTracker.start(experienceName, customStartTime));\n}\nexport function useExperienceSuccess(experience, attributes) {\n const experienceTracker = useExperienceTracker();\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useLayoutEffect(() => experienceTracker.success(experience, attributes), []);\n}\nexport function useExperienceRenderAndMountMark(mark) {\n const experienceTracker = useExperienceTracker();\n useOnceImmediately(() => experienceTracker.markStart(mark));\n // eslint-disable-next-line react-hooks/exhaustive-deps\n useLayoutEffect(() => experienceTracker.markEnd(mark), []);\n}","import { useRef } from 'react';\nexport function useSingleton(builder) {\n const ref = useRef();\n if (!ref.current) {\n ref.current = builder();\n }\n return ref.current;\n}\n\n/**\n * Utility hook which allows us to execute callbacks immediately on component mount construction.\n * @see https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/\n *\n * We need this as `useEffect`/`useLayoutEffect` executes on a bottom-up/child-first order,\n * which will execute side effectful code in an order we might not want.\n * @example\n * // sideEffect1()\n * // sideEffect2()\n * \n */\nexport function useOnceImmediately(callback) {\n const wasCalledRef = useRef(false);\n const result = useRef();\n if (!wasCalledRef.current) {\n wasCalledRef.current = true;\n result.current = callback();\n }\n return result.current;\n}","import { defineMessages } from 'react-intl-next';\nconst messages = defineMessages({\n emptyStateExploreProductsTitle: {\n id: 'fabric.atlassianSwitcher.emptyState.exploreProducts.title',\n defaultMessage: 'Get started with cloud',\n description: 'The title text for the empty state explore products content, which prompts users to try new products.'\n },\n emptyStateExploreProductsBody: {\n id: 'fabric.atlassianSwitcher.emptyState.exploreProducts.body',\n defaultMessage: 'Try a product to start collaborating with your team.',\n description: 'The body text for the empty state explore products content, which prompts users to try new products.'\n },\n emptyStateExploreProductsLink: {\n id: 'fabric.atlassianSwitcher.emptyState.exploreProducts.link',\n defaultMessage: 'Explore products',\n description: 'The text for the empty state explore products link, which prompts users to try new products.'\n },\n atlassianHome: {\n id: 'fabric.atlassianSwitcher.home',\n defaultMessage: 'Atlassian Home',\n description: 'The text of a link redirecting the user to the Home site'\n },\n atlassianStart: {\n id: 'fabric.atlassianSwitcher.start',\n defaultMessage: 'Atlassian Start',\n description: 'The text of a link redirecting the user to the Start site'\n },\n recent: {\n id: 'fabric.atlassianSwitcher.recent',\n defaultMessage: 'Recent',\n description: \"In a context in which users are able to view recent projects or spaces they've viewed, this text is the title of the section displaying all the recent projects or spaces.\"\n },\n more: {\n id: 'fabric.atlassianSwitcher.more',\n defaultMessage: 'More',\n description: 'In a context in which users are able to view predefined custom links, this text is the title of the section displaying all existing custom links.'\n },\n try: {\n id: 'fabric.atlassianSwitcher.try',\n defaultMessage: 'Try',\n description: 'This text appears as a way to encourage the user to try a new Atlassian product.'\n },\n manageList: {\n id: 'fabric.atlassianSwitcher.manageList',\n defaultMessage: 'Manage list',\n description: 'This text is for the action for a user to manage the values present in an editable list of links.'\n },\n jiraProject: {\n id: 'fabric.atlassianSwitcher.jiraProject',\n defaultMessage: 'Jira project',\n description: 'In a context in which several items are listed , this text describes that the specific type of a given item is a Jira project'\n },\n confluenceSpace: {\n id: 'fabric.atlassianSwitcher.confluenceSpace',\n defaultMessage: 'Confluence space',\n description: 'In a context in which several items are listed , this text describes that the specific type of a given item is a Confluence space'\n },\n administration: {\n id: 'fabric.atlassianSwitcher.administration',\n defaultMessage: 'Administration',\n description: 'The text of a link redirecting the user to the site administration'\n },\n moreAtlassianProductsLink: {\n id: 'fabric.atlassianSwitcher.moreAtlassianProducts',\n defaultMessage: 'More Atlassian products',\n description: 'The text of a link redirecting the user to Discover More Atlassian products'\n },\n slackIntegrationLink: {\n id: 'fabric.atlassianSwitcher.slackIntegrationLink',\n defaultMessage: 'Slack',\n description: 'The text of a link which opens the Slack Authentication popup'\n },\n slackIntegrationLinkDescription: {\n id: 'fabric.atlassianSwitcher.slackIntegrationLinkDescription',\n defaultMessage: 'Integrate Slack with your Atlassian products',\n description: 'The description of a link which opens the Slack Authentication popup'\n },\n browseApps: {\n id: 'fabric.atlassianSwitcher.browseApps',\n defaultMessage: 'Browse Marketplace apps',\n description: 'The text of a link redirecting the user to Discover Embedded Marketplace within in the product (Marketplace is a brand name. Please dont translate it)'\n },\n errorEmptyPartialResults: {\n id: 'fabric.atlassianSwitcher.errorEmptyPartialResults',\n defaultMessage: \"We can't display your products right now.\",\n description: 'Heading of the error message when available products returns a partial result and no sites'\n },\n errorHeading: {\n id: 'fabric.atlassianSwitcher.errorHeading',\n defaultMessage: 'Something’s gone wrong',\n description: 'Heading of the error screen which is shown when an unknown error happens in the Atlassian Switcher. Usually due to failed network requests.'\n },\n errorText: {\n id: 'fabric.atlassianSwitcher.errorText',\n defaultMessage: 'We keep track of these errors, but feel free to contact us if refreshing doesn’t fix things',\n description: 'Text that is displayed when an unknown error happens in the Atlassian Switcher.'\n },\n errorImageAltText: {\n id: 'fabric.atlassianSwitcher.errorImageAltText',\n defaultMessage: 'A broken robot and a number of people busy fixing it.',\n description: 'Text displayed as alt text when an error occurs in the Atlassian Switcher'\n },\n errorTextNetwork: {\n id: 'fabric.atlassianSwitcher.errorTextNetwork',\n defaultMessage: 'We couldn’t load this list. Please reload the page and try again.',\n description: 'Text that is displayed when we detect a network issue.'\n },\n errorHeadingLoggedOut: {\n id: 'fabric.atlassianSwitcher.errorHeadingLoggedOut',\n defaultMessage: 'Your Atlassian account is logged out',\n description: 'Heading of the error screen which is shown when an unknown error happens in the Atlassian Switcher. Usually due to failed network requests.'\n },\n errorTextLoggedOut: {\n id: 'fabric.atlassianSwitcher.errorTextLoggedOut',\n defaultMessage: 'Log in again to use the Atlassian\\u00A0switcher.',\n description: 'Text that is displayed when we detect user is logged out.'\n },\n errorHeadingUnverified: {\n id: 'fabric.atlassianSwitcher.errorHeadingUnverified',\n defaultMessage: 'Your account is unverified',\n description: 'Heading that is displayed when we detect user account is unverified.'\n },\n errorPartialResults: {\n id: 'fabric.atlassianSwitcher.errorPartialResults',\n defaultMessage: \"We can't display some of your products right now.\",\n description: 'Heading of the error message when available products returns a partial result and 1 or more sites'\n },\n errorPartialResultsRefresh: {\n id: 'fabric.atlassianSwitcher.errorPartialResultsRefresh',\n defaultMessage: 'Refresh the page, or try again later.',\n description: 'Subtitle of the error message when available products returns a partial result'\n },\n errorTextUnverified: {\n id: 'fabric.atlassianSwitcher.errorTextUnverified',\n defaultMessage: 'Please confirm your email address to view a list of available products.',\n description: 'Text that is displayed when we detect user account is unverified.'\n },\n login: {\n id: 'fabric.atlassianSwitcher.login',\n defaultMessage: 'Log in',\n description: 'Text in log in button.'\n },\n discover: {\n id: 'fabric.atlassianSwitcher.discover',\n defaultMessage: 'Discover',\n description: 'The header of \"Discover\" section'\n },\n productDescriptionConfluence: {\n id: 'fabric.atlassianSwitcher.product.description.confluence',\n defaultMessage: 'Document collaboration',\n description: 'Text displayed under the Confluence product recommendation.'\n },\n productDescriptionJiraServiceManagement: {\n id: 'fabric.atlassianSwitcher.product.description.jsm',\n defaultMessage: 'Collaborative IT service management',\n description: 'Text displayed under the Jira Service Management product recommendation.'\n },\n productDescriptionJiraSoftware: {\n id: 'fabric.atlassianSwitcher.product.description.jsw',\n defaultMessage: 'Project and issue tracking',\n description: 'Text displayed under the Jira Software product recommendation.'\n },\n productDescriptionOpsgenie: {\n id: 'fabric.atlassianSwitcher.product.description.opsgenie',\n defaultMessage: 'Modern incident management',\n description: 'Text displayed under the Opsgenie product recommendation.'\n },\n productDescriptionCompass: {\n id: 'fabric.atlassianSwitcher.product.description.compass',\n defaultMessage: 'Component manager',\n description: 'Text displayed under the Compass product recommendation.'\n },\n join: {\n id: 'fabric.atlassianSwitcher.join',\n defaultMessage: 'Join',\n description: 'Section Header in Atlassian Switcher. To set the expectation of what items would be shown in following section. Shown when an user has at least one joinable site via Domain Enabled Sign up with common collaborators.'\n }\n});\nexport default messages;","export const performanceNow = typeof window !== 'undefined' && window.performance && window.performance.now.bind(performance) || Date.now;","export const wait = ms => new Promise(resolve => {\n setTimeout(resolve, ms);\n});\nexport const retryOnException = async (invokeOperation, config) => {\n let nextMSInterval = 0;\n let error = new Error('No calls made');\n const retries = config.intervalsMS.length;\n while (nextMSInterval !== undefined) {\n try {\n if (nextMSInterval > 0) {\n await wait(nextMSInterval);\n if (config.onRetry) {\n config.onRetry(error, retries - config.intervalsMS.length);\n }\n }\n return await invokeOperation();\n } catch (e) {\n error = e;\n if (config.shouldRetryOnException && !config.shouldRetryOnException(error)) {\n throw error;\n }\n nextMSInterval = config.intervalsMS.shift();\n }\n }\n throw error;\n};","export const RELEASE_RESOLVED_PROMISE_DELAY = 5000;\nconst isPromise = p => {\n return typeof p.then === 'function' && typeof p.catch === 'function';\n};\n/**\n * withCached wraps a function and keeps track of in-flight promises:\n *\n * 1. First call will result to normal invocation. After promise is resolved\n * it will be removed from the promise-cache and store value into result-cache.\n *\n * 2. Second and subsequent calls will:\n * a) return unresolved promise if any\n * b) do a normal invocation otherwise\n *\n * 3. Provides methods to get `cached` value and `reset` caches\n */\nexport const withCached = fn => {\n const resultCache = new Map();\n const promiseCache = new Map();\n function getCacheKey(...args) {\n return JSON.stringify(args);\n }\n const cached = (...args) => {\n const cacheKey = getCacheKey(...args);\n return resultCache.get(cacheKey);\n };\n const reset = () => {\n resultCache.clear();\n promiseCache.clear();\n };\n const execute = (...args) => {\n const cacheKey = getCacheKey(...args);\n const cachedPromise = promiseCache.get(cacheKey);\n if (cachedPromise !== undefined) {\n return cachedPromise;\n }\n const maybePromise = fn(...args);\n promiseCache.set(cacheKey, maybePromise);\n if (isPromise(maybePromise)) {\n maybePromise.then(result => {\n resultCache.set(cacheKey, result);\n setTimeout(() => promiseCache.delete(cacheKey), RELEASE_RESOLVED_PROMISE_DELAY);\n }).catch(() => {\n promiseCache.delete(cacheKey);\n });\n }\n return maybePromise;\n };\n return Object.assign(execute, fn, {\n cached,\n reset\n });\n};","import { createProviderWithCustomFetchData } from '../../common/providers/create-data-provider';\nimport { ExperienceMark } from '../../common/utils/experience-tracker';\nexport const fetchEmptyData = () => Promise.resolve({\n sites: undefined\n});\nexport const createJoinableSitesProvider = (fetchData = fetchEmptyData, retryConfig) => {\n return createProviderWithCustomFetchData('joinableSites', ExperienceMark.API_JOINABLE_SITES, fetchData, retryConfig);\n};","export let RecentContainerType = /*#__PURE__*/function (RecentContainerType) {\n RecentContainerType[\"JIRA_PROJECT\"] = \"jira-project\";\n RecentContainerType[\"CONFLUENCE_SPACE\"] = \"confluence-space\";\n return RecentContainerType;\n}({});\nexport let CollaborationGraphRecentContainerType = /*#__PURE__*/function (CollaborationGraphRecentContainerType) {\n CollaborationGraphRecentContainerType[\"JIRA_PROJECT\"] = \"jiraProject\";\n CollaborationGraphRecentContainerType[\"CONFLUENCE_SPACE\"] = \"confluenceSpace\";\n return CollaborationGraphRecentContainerType;\n}({});\nexport let Permissions = /*#__PURE__*/function (Permissions) {\n Permissions[\"MANAGE\"] = \"manage\";\n Permissions[\"CAN_INVITE_USERS\"] = \"invite-users\";\n return Permissions;\n}({});\nexport let Product = /*#__PURE__*/function (Product) {\n Product[\"BITBUCKET\"] = \"bitbucket\";\n Product[\"CONFLUENCE\"] = \"confluence\";\n Product[\"HOME\"] = \"home\";\n Product[\"JIRA\"] = \"jira\";\n Product[\"SITE_ADMIN\"] = \"site-admin\";\n Product[\"TRELLO\"] = \"trello\";\n Product[\"START\"] = \"start\";\n return Product;\n}({});\nexport let Feature = /*#__PURE__*/function (Feature) {\n Feature[\"enableRecentContainers\"] = \"enableRecentContainers\";\n Feature[\"xflow\"] = \"xflow\";\n Feature[\"isProductStoreInTrelloJSWFirstEnabled\"] = \"isProductStoreInTrelloJSWFirstEnabled\";\n Feature[\"isProductStoreInTrelloConfluenceFirstEnabled\"] = \"isProductStoreInTrelloConfluenceFirstEnabled\";\n Feature[\"isSlackDiscoveryEnabled\"] = \"isSlackDiscoveryEnabled\";\n Feature[\"isUFOEnabled\"] = \"isUFOEnabled\";\n Feature[\"isHighlightJwmInSwitcherExtendedAudienceEnabled\"] = \"isHighlightJwmInSwitcherExtendedAudienceEnabled\";\n return Feature;\n}({});\n\n// Coincides with the product types in the Available Products Service\n\nexport let AnalyticsItemType = /*#__PURE__*/function (AnalyticsItemType) {\n AnalyticsItemType[\"PRODUCT\"] = \"product\";\n AnalyticsItemType[\"ADMIN\"] = \"admin\";\n AnalyticsItemType[\"TRY\"] = \"try\";\n AnalyticsItemType[\"JOIN\"] = \"join\";\n AnalyticsItemType[\"CUSTOM_LINK\"] = \"customLink\";\n AnalyticsItemType[\"DISCOVER_FIXED_LINKS\"] = \"discover-fixed-links\";\n AnalyticsItemType[\"RECENT\"] = \"recent\";\n AnalyticsItemType[\"EMPTY_STATE_EXPLORE_PRODUCTS\"] = \"empty-state-explore-products\";\n return AnalyticsItemType;\n}({});\nexport let ProductKey = /*#__PURE__*/function (ProductKey) {\n ProductKey[\"CONFLUENCE\"] = \"confluence.ondemand\";\n ProductKey[\"JIRA_CORE\"] = \"jira-core.ondemand\";\n ProductKey[\"JIRA_SOFTWARE\"] = \"jira-software.ondemand\";\n ProductKey[\"JIRA_SERVICE_DESK\"] = \"jira-servicedesk.ondemand\";\n ProductKey[\"BITBUCKET\"] = \"bitbucket\";\n ProductKey[\"OPSGENIE\"] = \"opsgenie\";\n ProductKey[\"STATUSPAGE\"] = \"statuspage\";\n ProductKey[\"TRELLO\"] = \"trello\";\n ProductKey[\"COMPASS\"] = \"compass\";\n ProductKey[\"TEAM_CENTRAL\"] = \"townsquare\";\n return ProductKey;\n}({});\n\n// A map of feature flags used by the XFlow recommendations engine.\n\nexport let DiscoverLinkItemKeys = /*#__PURE__*/function (DiscoverLinkItemKeys) {\n DiscoverLinkItemKeys[\"DISCOVER_MORE\"] = \"discover-more\";\n DiscoverLinkItemKeys[\"SLACK_INTEGRATION\"] = \"slack-integration\";\n return DiscoverLinkItemKeys;\n}({});\n\n//","import { Product } from '../../types';\nexport let Environment = /*#__PURE__*/function (Environment) {\n Environment[\"Staging\"] = \"stg\";\n Environment[\"Production\"] = \"prod\";\n return Environment;\n}({});\n\n/**\n * Resolves product environment type,\n * Falls back to Environment.Staging\n *\n * !!! Trello only, other products to be added\n *\n * @param origin\n */\nexport const getEnvName = (origin = ((_window, _window$location) => (_window = window) === null || _window === void 0 ? void 0 : (_window$location = _window.location) === null || _window$location === void 0 ? void 0 : _window$location.origin)()) => ['https://trello.com'].includes(origin) ? Environment.Production : Environment.Staging;\nconst getProduct = product => {\n if (product) {\n const lowerJira = Product.JIRA.toLowerCase();\n const lowerProduct = product.toLowerCase();\n if (lowerProduct.includes(lowerJira)) {\n return lowerJira;\n }\n return lowerProduct;\n }\n};\nexport const getLoginUrl = (productType, env = getEnvName(), continueUrl = String(window.location), loginHint) => {\n const baseUrl = env === Environment.Production ? 'https://id.atlassian.com/login' : 'https://id.stg.internal.atlassian.com/login';\n const product = getProduct(productType);\n return `${baseUrl}?continue=${encodeURIComponent(continueUrl)}${product ? `&application=${encodeURIComponent(product)}` : ''}\n ${loginHint ? `&login_hint=${encodeURIComponent(loginHint)}` : ''}`;\n};","import React from 'react';\nimport Button from '@atlaskit/button/custom-theme-button';\n\n// This is a workaround because React.memo does not play well with styled-components\n// KIRBY-3030 TODO determine whether this workaround is still necessary after migration away from styled-components\nexport default function StyledComponentsButton(props) {\n return /*#__PURE__*/React.createElement(Button, props);\n}","import _extends from \"@babel/runtime/helpers/extends\";\nimport _defineProperty from \"@babel/runtime/helpers/defineProperty\";\n/** @jsx jsx */\n/** @jsxFrag */\n\nimport React, { Fragment, useState, useEffect } from 'react';\nimport { injectIntl } from 'react-intl-next';\nimport { css, jsx } from '@emotion/react';\nimport TRELLO_ERROR_SRC from '../../assets/trello-error';\nimport UNVERIFIED_ERROR_SRC from '../../assets/unverified-error';\nimport { NAVIGATION_CHANNEL, OPERATIONAL_EVENT_TYPE, UI_EVENT_TYPE, withAnalyticsEvents } from '../../common/utils/analytics';\nimport { getLoginUrl } from '../../common/utils/environment';\nimport { errorToReason } from '../../common/utils/error-to-reason';\nimport messages from '../../common/utils/messages';\nimport { Product } from '../../types';\nimport { FormattedMessage } from 'react-intl-next';\nimport StyledComponentsButton from '../primitives/styled-components-button';\nimport { SwitcherLoadError } from '../../common/utils/errors/switcher-load-error';\nimport { FETCH_ERROR_NAME } from '../../common/utils/errors/fetch-error';\nconst TRIGGER_SUBJECT = 'errorBoundary';\nconst ACTION_SUBJECT = 'rendered';\n// This image is also used as the generic error message in Notifications\n\nconst robotsImgStyles = css({\n height: 200\n});\nconst trelloErrorImgStyles = css({\n width: 140,\n height: 88\n});\nconst unverifiedUserImageStyles = css({\n height: 150\n});\nconst errorContentStyles = css({\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n flexDirection: 'column'\n});\nconst errorHeadingStyles = css({\n maxWidth: 240,\n marginTop: \"var(--ds-space-400, 32px)\"\n});\nconst errorMessageStyles = css({\n maxWidth: 240,\n marginTop: \"var(--ds-space-300, 24px)\"\n});\nconst loginButtonStyles = css({\n marginTop: \"var(--ds-space-300, 24px)\"\n});\nconst errorBoundaryBoxStyles = css({\n display: 'flex',\n justifyContent: 'center',\n flexDirection: 'column',\n textAlign: 'center'\n});\nconst errorBoundaryBoxDrawerStyles = css({\n // eslint-disable-next-line @atlaskit/design-system/use-tokens-space\n paddingTop: 128,\n paddingRight: \"var(--ds-space-800, 64px)\"\n});\nconst errorBoundaryBoxNonDrawerStyles = css({\n margin: `${\"var(--ds-space-600, 48px)\"} 0`\n});\nconst loginButtonNonDrawerStyles = css({\n justifyContent: 'center',\n alignSelf: 'stretch'\n});\nconst ErrorMessage = props => jsx(\"p\", {\n css: errorMessageStyles\n}, props.children);\nclass ErrorBoundary extends React.Component {\n constructor(...args) {\n super(...args);\n _defineProperty(this, \"state\", {\n hasError: false\n });\n _defineProperty(this, \"fireOperationalEvent\", payload => {\n if (this.props.createAnalyticsEvent) {\n this.props.createAnalyticsEvent({\n eventType: OPERATIONAL_EVENT_TYPE,\n actionSubject: this.props.triggerSubject || TRIGGER_SUBJECT,\n ...payload\n }).fire(NAVIGATION_CHANNEL);\n }\n });\n _defineProperty(this, \"handleLogin\", (_, analyticsEvent) => {\n analyticsEvent.update({\n eventType: UI_EVENT_TYPE,\n actionSubjectId: 'login'\n }).fire(NAVIGATION_CHANNEL);\n if (this.props.product !== Product.TRELLO) {\n window.location.reload();\n }\n });\n }\n componentDidCatch(error) {\n var _this$props$onErrorCa, _this$props;\n const reason = error instanceof SwitcherLoadError ? error.reason() : errorToReason(error);\n this.setState({\n hasError: true,\n reason\n }, () => {\n this.fireOperationalEvent({\n action: ACTION_SUBJECT,\n attributes: {\n ...reason,\n ...this.props.extraAnalyticProps\n }\n });\n });\n (_this$props$onErrorCa = (_this$props = this.props).onErrorCallback) === null || _this$props$onErrorCa === void 0 ? void 0 : _this$props$onErrorCa.call(_this$props, error);\n }\n renderErrorBody(appearance) {\n const {\n reason\n } = this.state;\n if (!reason) {\n return;\n }\n if (reason.name === FETCH_ERROR_NAME) {\n const isTrello = this.props.product === Product.TRELLO;\n if (reason.status === 401) {\n // Not authorised http error\n return jsx(Fragment, null, jsx(ErrorMessage, null, jsx(FormattedMessage, messages.errorTextLoggedOut)), isTrello ? jsx(StyledComponentsButton, {\n css: [loginButtonStyles, appearance !== 'drawer' && loginButtonNonDrawerStyles],\n appearance: \"link\",\n href: getLoginUrl(Product.TRELLO),\n onClick: this.handleLogin\n }, jsx(FormattedMessage, messages.login)) : jsx(StyledComponentsButton, {\n css: [loginButtonStyles, appearance !== 'drawer' && loginButtonNonDrawerStyles],\n onClick: this.handleLogin\n }, jsx(FormattedMessage, messages.login)));\n }\n if (reason.status === 403) {\n return jsx(ErrorMessage, null, jsx(FormattedMessage, messages.errorTextUnverified));\n }\n return jsx(ErrorMessage, null, jsx(FormattedMessage, messages.errorTextNetwork));\n }\n\n // Default error message\n return jsx(ErrorMessage, null, jsx(FormattedMessage, messages.errorText));\n }\n renderErrorHeading() {\n const {\n reason\n } = this.state;\n if (!reason) {\n return;\n }\n if (reason.name === FETCH_ERROR_NAME && reason.status === 401) {\n return jsx(FormattedMessage, messages.errorHeadingLoggedOut);\n }\n if (reason.name === FETCH_ERROR_NAME && reason.status === 403) {\n return jsx(FormattedMessage, messages.errorHeadingUnverified);\n }\n return jsx(FormattedMessage, messages.errorHeading);\n }\n renderErrorImage() {\n const {\n intl,\n product\n } = this.props;\n const {\n reason\n } = this.state;\n if (product === Product.TRELLO) {\n return jsx(\"img\", {\n css: trelloErrorImgStyles,\n src: TRELLO_ERROR_SRC,\n alt: intl.formatMessage(messages.errorImageAltText)\n });\n }\n if (reason.status === 403) {\n return jsx(\"img\", {\n css: unverifiedUserImageStyles,\n src: UNVERIFIED_ERROR_SRC,\n alt: intl.formatMessage(messages.errorImageAltText)\n });\n }\n return jsx(RobotImage, {\n css: robotsImgStyles,\n alt: intl.formatMessage(messages.errorImageAltText)\n });\n }\n render() {\n const {\n appearance,\n hideFallbackUI\n } = this.props;\n const {\n hasError\n } = this.state;\n if (hasError && hideFallbackUI) {\n return jsx(React.Fragment, null);\n }\n if (hasError) {\n return jsx(\"div\", {\n css: [errorBoundaryBoxStyles, appearance === 'drawer' ? errorBoundaryBoxDrawerStyles : errorBoundaryBoxNonDrawerStyles],\n \"data-testid\": \"error-boundary\"\n }, jsx(\"div\", {\n css: errorContentStyles\n }, this.renderErrorImage(), jsx(\"h3\", {\n css: errorHeadingStyles\n }, this.renderErrorHeading()), this.renderErrorBody(appearance)));\n }\n return this.props.children;\n }\n}\nconst RobotImage = props => {\n const [imgSrc, setImgSrc] = useState();\n useEffect(() => {\n import( /* webpackChunkName: \"@ak-switcher-chunk-robot-error-img\" */'../../assets/robot-error').then(src => setImgSrc(src.default));\n }, []);\n return jsx(\"img\", _extends({}, props, {\n src: imgSrc\n }));\n};\nexport default withAnalyticsEvents()(injectIntl(ErrorBoundary));","export default 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTQwIiBoZWlnaHQ9Ijg4IiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj48ZGVmcz48cGF0aCBpZD0iYSIgZD0iTS4xNjUuMDgzaDIwLjAzOHYyMS4xNTFILjE2NXoiLz48cGF0aCBpZD0iYyIgZD0iTTAgLjNoOC42NjV2Ny4zMjZIMHoiLz48cGF0aCBpZD0iZSIgZD0iTTAgLjMxMmgzOS4zM3Y0OS4yNTlIMHoiLz48cGF0aCBkPSJNLjE0NSAyOS4zMjdjMCAyLjE2NSAyLjY4MyAyLjM5OCA0LjM3NSA0LjAzNyAxLjY0OS0yLjIyNSAxMi4wOTMtMS40NiAxOC4wNS0xLjQ2IDUuNzk4IDAgNy44MiAxLjMxIDEwLjk0Ny0yLjgxdi0xNi4yOUMzMy41MTcgOC45NzUgMzUuMDEyLjQ1IDE2LjgyLjQ1IDEuNTc3LjQ1MS4xNDUgNi41NDkuMTQ1IDEyLjgwNHYxNi41MjN6IiBpZD0iZyIvPjwvZGVmcz48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGQ9Ik0xMzkuMzE5IDgzLjY0NmMwIDEuNTIyLTEwLjE3MyAyLjc1Ny0yMi43MjIgMi43NTctMTIuNTQ5IDAtMjIuNzIxLTEuMjM1LTIyLjcyMS0yLjc1N3MxMC4xNzItMi43NTYgMjIuNzIxLTIuNzU2IDIyLjcyMiAxLjIzNCAyMi43MjIgMi43NTZNOC43NDQgNzkuMzMzYy0yLjQ2My0uMTIyLTUuMDE3IDEuMTcxLTUuMTAzIDIuODkxLS4wODUgMS43MiAyLjMzNiAxLjkwNSA0Ljk2IDIuMDM1IDIuNjI2LjEzIDMwLjA1IDEuMjc3IDMwLjA1IDEuMjc3IDMuNjg0LjQgOS40Mi42ODYgMTguMzE3IDEuMTI4IDIwLjUyMSAxLjAyIDI4LjE3NiAxLjQgMjguMzc1LTIuNjEzLjE4Ny0zLjc4My0xNC4xODktNC43MjktMjcuOTc4LTUuNDE0LTEzLjc4OC0uNjg2LTI1LjY5NCAxLjYxMS0yNS42OTYgMS43MzVMOC43NDQgNzkuMzMzeiIgZmlsbD0iI0VGQjNBQiIvPjxwYXRoIGQ9Ik03NC41MyAxNC44NXM4LjQxMi0yLjU2IDEyLjkwNS0yLjkxN2M1LjQ5NC0uNDM2IDYuODQ2LjI5NSA1LjQ0MiAyLjIyNi0xLjQwNCAxLjkzLTcuODggMTEuNDYtNy44OCAxMS40NlM4MC4yNiAxNS4yODMgNzQuNTMxIDE0Ljg1IiBmaWxsPSIjRUM1MDMzIi8+PHBhdGggZD0iTTg0LjYxNCAxOS45MDFjLS41MS0uNzA2LTEuODI4LTIuMDYyLTEuODI4LTIuMDYyczYuODY1LTQuMTIyIDguMTk1LTQuNThjMS4zMy0uNDU3IDEuMjk2LjU4Mi43MyAxLjI1LS41NjguNjY2LTUuNzM3IDguMzAxLTUuNzM3IDguMzAxcy0uNDUtMS42NDktMS4zNi0yLjkwOSIgZmlsbD0iI0U3QTI5RiIvPjxwYXRoIGQ9Ik04Ny41OCAxNy40NDRhMi41OTUgMi41OTUgMCAwIDAtLjg2NC0uMDY3Yy4xMS0uMTc4LjM3NC0uNjI1LjMxMy0uNy0uMDc3LS4wOTQtLjMwNS0uMDExLS41NTMuMTI1LS4yNDguMTM2LTIuMTYyIDEuMTcyLTIuMTYyIDEuMTcyIDEuMjgzLjk4MyAxLjM3OSAyLjMyNCAxLjc1OCAyLjEyOC4zOC0uMTk2LjAxNy0xLjAzOS4wMTctMS4wMzkuMzI5LjI0Mi44MzQuMzYgMS4wMDguMDk4LjE3NC0uMjYxLS4zMTktLjU1Ny0uMzE5LS41NTdzLjcyNi40MTYuODMxLjA4N2MuMTA2LS4zMy0uNjYtLjc1OC0uNjYtLjc1OCAxLjE0NC0uMDk0LjgyMi0uNDM0LjYzLS40ODkiIGZpbGw9IiNFRkRGREUiLz48cGF0aCBkPSJNNTcuNjA4IDE3Ljc1NnMtNy45NDQgNi41MzktMTEuMTM5IDIxLjc5Yy0xLjA2NSAyLjU5NC0yMS4wOTYgMy43NzUtMjEuMzYgMjguODgtLjA3NyA3LjM2MyA2LjkwOCAxNC4yODQgMTkuNjg3IDE0LjI4NGgzNS41NDhjLTEuMDE1LTUuOTA0LTQuMjYtNi41MDctNS45ODQtNi41MDctMS4yNTEgMC0zLjc4My0xNC4wNzUtNS4wNC0yNS4xMDItLjQ3Ni00LjE3NCA1LjAxMy03LjcwNCA1LjA0MS0xMC4wNzcuMTAxLTguNjQyLTE2Ljc1My0yMy4yNjgtMTYuNzUzLTIzLjI2OCIgZmlsbD0iI0VDNTAzMyIvPjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKDU0LjE1OSAuNDU0KSI+PG1hc2sgaWQ9ImIiIGZpbGw9IiNmZmYiPjx1c2UgeGxpbms6aHJlZj0iI2EiLz48L21hc2s+PHBhdGggZD0iTS4xNjUgMjEuMjM0cy42NS02LjUyMiA1LjU5NS0xNC40NzljNC45NDQtNy45NTcgNS45NjQtNy40MzUgNy43MzEtNS4zNDggMS43NjcgMi4wODcgNS41NCAxMC42OTYgNi43MTIgMTMuMzA1IDAgMC0xMS4wNTktMS4xMDQtMjAuMDM4IDYuNTIyIiBmaWxsPSIjRUM1MDMzIiBtYXNrPSJ1cmwoI2IpIi8+PC9nPjxwYXRoIGQ9Ik03MC4wODQgODIuNzFMNjEuODUgNjQuNTY1cy0uNzc3IDIuMDI4LTExLjEyMiAyLjQ2VjgyLjcxaDE5LjM1NXoiIGZpbGw9IiNDQzM3MjciLz48cGF0aCBkPSJNNTYuODE1IDYyLjU3N3M2LjU0Mi4xNTMgNi41NDIgNS44NzJjMCA2Ljc4Ny03LjIyNyA3LjcwMy03LjIyNyA3LjcwM3MuNzYxLjA3NiAzLjU3Ni4wNzZjMi44MTQgMCAzLjcwMyAxLjIyIDMuNzAzIDYuNDgySDQ0LjExMlY2NS45NjdjMC00LjE3IDEyLjcwMy0zLjM5IDEyLjcwMy0zLjM5IiBmaWxsPSIjRUM1MDMzIi8+PHBhdGggZD0iTTY5LjI4MiA1MS4xMDdzLTE1Ljk2Mi05Ljg2My0xNS41LTE1LjIzNWMuNTUyLTYuMzk1IDMuODI2LTE4LjExNiAzLjgyNi0xOC4xMTZsMTQuNTY4IDI3LjA3OHMtMi4wOTIuODY3LTIuODk0IDYuMjczIiBmaWxsPSIjQ0MzNzI3Ii8+PHBhdGggZD0iTTUwLjM0OCAzNC43NDJzMTMuOTM3IDkuNzcyIDI0LjEwNSAxMC4zNjFjNi43NjIuMzkyIDkuMTkzLTIuOTMyIDEyLjk0Ni01LjA2LS4wMi04Ljk0LS44NDYtMTQuMDE3LTEuMDQtMTYuMzY1LS4xOTYtMi4zNDgtNC4zNDItMTIuNTU1LTE2LjE5LTEwLjczLTExLjg1IDEuODI3LTE1LjYzNyA0LjgwOC0xOS44MiAyMS43OTQiIGZpbGw9IiNFQzUwMzMiLz48cGF0aCBkPSJNNjEuMDIgMTQuNjI4Yy0uMTMzLjYwMiAxLjU3NS0yLjMyNiAxMC4yNDYtMS44OTcgMCAwLTMuNzAxLTguMTExLTQuMzEtOS40MzMtLjYwOC0xLjMyMi0xLjQyLTEuNjI3LTIuNjEzIDEuMDE3LS45ODUgMi4xOC0yLjA3MyA0LjYxNC0zLjMyNCAxMC4zMTMiIGZpbGw9IiNFN0EyOUYiLz48cGF0aCBkPSJNNjkuNjQ2IDExLjc2N3MtMS4xOTctNC43MzUtNC4yMy01LjIwOGMwIDAtLjcxNC0uMTEyIDEuMjAzIDEuNjU1IDAgMC0xLjUwMy0uNjc1LTEuODc4LS4xNDctLjM3NS41MjkgMS4wNjIgMS4xNTYgMS4wNjIgMS4xNTZzLS45OTUtLjQxMi0xLjE5Mi4xNDVjLS4xOTcuNTU2LjU0NiAxLjE4NSAxLjI3OCAxLjQxIDAgMC0xLjY3MS4zOTktMS41NCAxLjE5LjEzMy43OSA0Ljc3LS41NzYgNS4yOTctLjIwMSIgZmlsbD0iI0VGREZERSIvPjxwYXRoIGQ9Ik04My4yMzQgNDAuMTA5Yy0uNDE5IDMuNDkzLTMuNTgzIDUuOTg1LTcuMDY4IDUuNTY2LTMuNDg1LS40Mi01Ljk3LTMuNTkyLTUuNTUxLTcuMDg2LjQxOC0zLjQ5MyAzLjU4Mi01Ljk4NSA3LjA2Ny01LjU2NiAzLjQ4NC40MiA1Ljk3IDMuNTkyIDUuNTUyIDcuMDg2IiBmaWxsPSIjRkVGRUZFIi8+PHBhdGggZD0iTTcyLjE3NiAyOS4yNTNhMy4yNTkgMy4yNTkgMCAwIDEtMy4yNTUgMy4yNjMgMy4yNTkgMy4yNTkgMCAwIDEtMy4yNTUtMy4yNjMgMy4yNTkgMy4yNTkgMCAwIDEgMy4yNTUtMy4yNjMgMy4yNTkgMy4yNTkgMCAwIDEgMy4yNTUgMy4yNjMiIGZpbGw9IiM0NjRGMjIiLz48cGF0aCBkPSJNNzAuOTIyIDMwLjc4OWExLjM5NiAxLjM5NiAwIDEgMS0yLjY0Ni0uOSAxLjM5NiAxLjM5NiAwIDAgMSAxLjc3MS0uODc2IDEuNDAyIDEuNDAyIDAgMCAxIC44NzUgMS43NzYiIGZpbGw9IiMyMTFDMUIiLz48cGF0aCBkPSJNNjkuNDcxIDI5LjI5NGEuNzczLjc3MyAwIDEgMS0xLjU0Ni4wMDIuNzczLjc3MyAwIDAgMSAxLjU0Ni0uMDAyIiBmaWxsPSIjRkVGRUZFIi8+PHBhdGggZD0iTTc4Ljk2IDM2LjAzNnMtMS4yOS0uMjY1LTIuMDg0LjAwM2MtLjc5NC4yNy0uODYyLjUxNi0uNjEgMS4yODQuMjUzLjc2OCAxLjQxIDIuMDU2IDEuODgzIDIuMTU4LjQ3NC4xMDIgMS44ODctLjM2NSAyLjc1LTEuNzUzLjgxOC0xLjMxMy0xLjkzOS0xLjY5Mi0xLjkzOS0xLjY5MiIgZmlsbD0iI0Y0OTk5RiIvPjxwYXRoIGQ9Ik04My44NjMgMjQuMjQ1cy0zLjIuNjYyLTUuMjUtLjMxMiAxLjgyOS0yLjM1NyAxLjgyOS0yLjM1N2wzLjQyMSAyLjY2OXoiIGZpbGw9IiNFQzUwMzMiLz48cGF0aCBkPSJNODEuNDMxIDMwLjgyYTIuMjc2IDIuMjc2IDAgMCAwIDIuMjc0IDIuMjc5YzEuMjU1IDAgMi4yMDctMS4wMiAyLjIwNy0yLjI4IDAtMS4yNTgtLjk1Mi0yLjI3OS0yLjIwNy0yLjI3OWEyLjI3NiAyLjI3NiAwIDAgMC0yLjI3NCAyLjI4IiBmaWxsPSIjNDY0RjIyIi8+PHBhdGggZD0iTTgyLjg1NiAzMS4wNmEuOTguOTggMCAwIDAgLjI3OCAxLjM1NS45NzQuOTc0IDAgMCAwIDEuMzUyLS4yNzguOTguOTggMCAwIDAtLjI3OC0xLjM1NS45NzQuOTc0IDAgMCAwLTEuMzUyLjI3OCIgZmlsbD0iIzIxMUMxQiIvPjxwYXRoIGQ9Ik04My4yNSAzMS4xNmEuNTQuNTQgMCAxIDAtLjAwMi0xLjA3OS41NC41NCAwIDAgMCAuMDAyIDEuMDgiIGZpbGw9IiNGRUZFRkUiLz48cGF0aCBkPSJNNzUuOTEgNDIuMTAxczEuNzEtMS41MzQgNC4yMDktMS4wNjIiIHN0cm9rZT0iIzAxMDIwMiIgc3Ryb2tlLXdpZHRoPSIxLjAzOSIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIi8+PHBhdGggZD0iTTM3LjEyOCA3NC4zNzJzLTMuOTU1IDEuNjU1LTEzLjg5NCAyLjMzNGMtOS45NC42NzgtMTQuNzA2LS42MzEtMTguNTYtLjM2Qy44MiA3Ni42Mi4wMDggNzkuNDE0LjIxIDgwLjU3NmMuMjAzIDEuMTYgMi4wMjkgMi4zODEgNi44OTcgMi4zODFoMjYuNTIxYzUuMDcxIDAgMTAuNDgzLS4yNDYgMTAuNDgzLS4yNDZsLTYuOTg0LTguMzM4eiIgZmlsbD0iI0VDNTAzMyIvPjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAgNzUuOCkiPjxtYXNrIGlkPSJkIiBmaWxsPSIjZmZmIj48dXNlIHhsaW5rOmhyZWY9IiNjIi8+PC9tYXNrPjxwYXRoIGQ9Ik0uMTIzIDQuNjg4Qy41OCA2LjIxMyAxLjU2NCA4LjUgNy45NTYgNy4yOGMwIDAgMS41OTUtMS41MjUgMC0zLjQzMi0xLjU5NS0xLjkwNi0uNjgtMy4zNy0uNjgtMy4zNy0yLjU2Ni0uMy00LjU5LS4xNzEtNS4xLjAxNUMuNTA0IDEuMTA0LS4zMzMgMy4xNjMuMTIzIDQuNjg4IiBmaWxsPSIjRkZGIiBtYXNrPSJ1cmwoI2QpIi8+PC9nPjxnIHRyYW5zZm9ybT0idHJhbnNsYXRlKDkwLjY2MSAzNC4yMzEpIj48bWFzayBpZD0iZiIgZmlsbD0iI2ZmZiI+PHVzZSB4bGluazpocmVmPSIjZSIvPjwvbWFzaz48cGF0aCBkPSJNMzIuNDA4IDExLjAxNnMtMS4xMTMtMS41OTEtMS4xMTMtMy4xODNjMC0xLjU5IDEuMTEzLS40OSAxLjExMy0zLjMwNCAwLTIuODE1LTIuMjctMy4yMTgtNC43MTctMy41NjQtNS45NjQtLjg0Mi0xMS4zMS0uODk4LTE2LjQwOCAwLTIuNDM0LjQzLTQuMzM4Ljc0OS00LjMzOCAzLjU2NHMxLjExMyAxLjcxMyAxLjExMyAzLjMwNGMwIDEuNTkyLTEuMTEzIDMuMTgzLTEuMTEzIDMuMTgzQy0uNzggMTcuMTg1LjAyNCAxOS41ODMuMDI0IDIzLjAxdjE2LjUyM2MwIDYuNzMyIDguNzc1IDEwLjAzNyAxMi4xMTMgMTAuMDM3aDE1LjA4YzMuMzM3IDAgMTIuMTEyLTMuMzA1IDEyLjExMi0xMC4wMzdWMjMuMDExYzAtMy40MjggMC02LjU2LTYuOTIxLTExLjk5NSIgZmlsbD0iI0UzRUZGNCIgbWFzaz0idXJsKCNmKSIvPjwvZz48dXNlIGZpbGw9IiM5NUQ3RTQiIHhsaW5rOmhyZWY9IiNnIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSg5My41MDcgNDQuOTkpIi8+PHBhdGggZD0iTTEyMC4xOTcgMzcuNDU4YzAgLjgxNC00LjQyIDEuNDc1LTkuODcgMS40NzUtNS40NTIgMC05Ljg3Mi0uNjYtOS44NzItMS40NzUgMC0uODE0IDQuNDItMS40NzQgOS44NzEtMS40NzQgNS40NTIgMCA5Ljg3MS42NiA5Ljg3MSAxLjQ3NCIgZmlsbD0iIzgzOEM5MSIvPjxwYXRoIGQ9Ik0xMjEuNzgyIDQ1LjA4NWE3LjQ2IDcuNDYgMCAwIDEgMi4yOTcuOTg0Yy0uMzItLjI2OC0yLjEyMy0yLjQxMS0yLjEyMy00LjAwMiAwLS42OTEuMjEtLjg3NS40NDctMS4wOTFhMTA3LjcyIDEwNy43MiAwIDAgMS0yLjIwNiAxLjM0NGMtMS4yNTguNzM0LTEuMTk2IDIuMTA0IDEuNTg1IDIuNzY1bS0yMi44NDggMGE3LjQ2IDcuNDYgMCAwIDAtMi4yOTcuOTg0Yy4zMi0uMjY4IDIuMTIyLTIuNDExIDIuMTIyLTQuMDAyIDAtLjY5MS0uMjEtLjg3NS0uNDQ3LTEuMDkxLjc2Ni40NzYgMS42MjkgMS4wMDYgMi4yMDcgMS4zNDQgMS4yNTguNzM0IDEuMTk2IDIuMTA0LTEuNTg1IDIuNzY1IiBmaWxsPSIjQkNEOEU5Ii8+PHBhdGggZD0iTTEyNy4wMjQgNzQuMDgzcy4wOTQgMy4xOC0yLjk0NSA0LjQwM2MtMy4wMzkgMS4yMjQtNy4xOC0uNDktOC42IDAtMS40MjIuNDktMi43ODIgMS4yMjQtNC41MTIgMS4xMDEtMS43My0uMTIyLTUuNzM0LTEuMTctNy4xMDctLjg1Ni0zLjgxNy44Ny02LjA0Ni0uNTI4LTYuMDQ2LS41MjhzMi41MjMtMy4wMjIgNC41NjMtMy42MzRjMi4wMzktLjYxMiAzLjI3LS4wMjYgNC42NjMtLjgwOSAxLjM5My0uNzgyIDUuODQzLTIuNjE4IDcuOTQ0LTIuMjUgMi4xMDEuMzY2IDYuMjMuNjExIDYuNzYuNDg5LjUzMi0uMTIzIDQuMDk1LS45MSA1LjI4IDIuMDg0IiBmaWxsPSIjQkRFQ0YzIi8+PHBhdGggZD0iTTEyMC4wMDUgNDkuODExYzAgLjc0NC00LjMzMy42ODUtOS42NzkuNjg1cy05LjY4LjA1OS05LjY4LS42ODVjMC0uNzQzIDQuMzM0LTIuMDA3IDkuNjgtMi4wMDdzOS42OCAxLjI2NCA5LjY4IDIuMDA3IiBmaWxsPSIjNjdDQURDIi8+PHBhdGggZD0iTTExOC40MzQgNzQuNDFzLS40MjgtLjU4Mi0uNDM4LTEuMjkzYy0uMDEtLjcxMi0uMDA2LS45ODQgMS4xOTctMi4xNDggMS4yMDEtMS4xNjQgMS4yMDQtMi42OTIgMS4yMDQtMi42OTJzLjYzNCAyLjM0MS4wNSAzLjU1OGMtLjU4MyAxLjIxOC43OTUgMy40OTguNjg1IDMuNDc1LS4xMS0uMDIzLTIuMDMyLjExNS0yLjY5OC0uOW0tMTQuNDY2LjUxOXMtLjI1NS0uMzQ3LS4yNjEtLjc3MmMtLjAwNi0uNDI1LS4wMDMtLjU4Ny43MTQtMS4yODIuNzE3LS42OTQuNzE5LTEuNjA2LjcxOS0xLjYwNnMuMzc4IDEuMzk3LjAzIDIuMTIzYy0uMzQ5LjcyNy40NzQgMi4wODcuNDA4IDIuMDc0LS4wNjYtLjAxNC0xLjIxMi4wNjgtMS42MS0uNTM3IiBmaWxsPSIjM0Y2RjIxIi8+PHBhdGggZD0iTTEwMi4yMzkgNzQuODI3cy0uNDA2LS40MTItLjQxNi0uOTE3Yy0uMDEtLjUwNS0uMDA1LS42OTggMS4xMzUtMS41MjMgMS4xNDEtLjgyNiAxLjE0NC0xLjkxIDEuMTQ0LTEuOTFzLjYwMiAxLjY2LjA0NyAyLjUyNGMtLjU1NC44NjQuNzU0IDIuNDgxLjY1IDIuNDY1LS4xMDQtLjAxNy0xLjkyOC4wOC0yLjU2LS42MzkiIGZpbGw9IiM2MUJENEYiLz48cGF0aCBkPSJNMTE2LjkxMyA3NS4zNDlzLTIuMDEyLTIuMzQ3LS41NDQtMy44NDJjMS40NjgtMS40OTMgMS43OTQtMS45NzMgMS4xOTYtMy4xNDctLjU5OC0xLjE3NC45MjQtMi4wOC45MjQtMi4wOHMtLjI3MiAxLjI4LjM4IDIuMjRjLjY1My45Ni43NjIgMi41MDggMCAzLjU3NC0uNzYgMS4wNjcuOTggMy41NzUuOTggMy41NzVzLTIuMjg0LjI5My0yLjkzNi0uMzJsMTQuNzE4IDEuNjg4IiBmaWxsPSIjNjNCQzUwIi8+PHBhdGggZD0iTTExOC4xMzUgNTcuNzQ2Yy42MTctMi4zNDEgMi4zMzQtMy40MzcgNS4xNS0zLjI4Ni0xLjEyMyAxLjU5LTEuODYgMy4yLTIuMjA4IDQuODI5bDIuMjA5IDUuMDc4Yy0yLjQwMy4zNzItNC4xMi0uNjM5LTUuMTUxLTMuMDMyLTIuNTQ2IDEuMjQ3LTUuNzI1IDQuMTQ3LTExLjQxIDMuNTktMy43OTEtLjM3Mi02LjY5LTIuMjUtOC42OTktNS42MzYgMi4yNDktMy40MSA1LjM1LTUuMTE2IDkuMzAzLTUuMTE2IDMuOTU0IDAgNy41NTUgMS4xOSAxMC44MDYgMy41NzN6IiBzdHJva2U9IiNFNEY3RkEiIHN0cm9rZS13aWR0aD0iMi42NCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtZGFzaGFycmF5PSIyLjY0MDAwMDE2MjEyNDYzNiwzLjk2MDAwMDI0MzE4Njk1NCIvPjwvZz48L3N2Zz4K';","export default `data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB2aWV3Qm94PSIwIDAgMTYzLjI4IDIxOCI+PGRlZnM+PHN0eWxlPi5jbHMtMXtmaWxsOnVybCgjbGluZWFyLWdyYWRpZW50KTt9LmNscy0ye2ZpbGw6IzI1Mzg1ODt9LmNscy0ze2ZpbGw6I2ZmYzQwMDt9LmNscy00e2ZpbGw6I2ZmYWIwMDt9LmNscy01LC5jbHMtNntmaWxsOm5vbmU7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLW1pdGVybGltaXQ6MTA7c3Ryb2tlLXdpZHRoOjJweDt9LmNscy01e3N0cm9rZTojMzQ0NTYzO30uY2xzLTZ7c3Ryb2tlOiM1ZTZjODQ7fTwvc3R5bGU+PGxpbmVhckdyYWRpZW50IGlkPSJsaW5lYXItZ3JhZGllbnQiIHgxPSIxMzMuODYiIHkxPSIxMzYuNDMiIHgyPSItMi43OSIgeTI9IjIwMC4xNSIgZ3JhZGllbnRVbml0cz0idXNlclNwYWNlT25Vc2UiPjxzdG9wIG9mZnNldD0iMCIgc3RvcC1jb2xvcj0iI2ZmZDc0MCIvPjxzdG9wIG9mZnNldD0iMSIgc3RvcC1jb2xvcj0iI2ZmYWIwMCIvPjwvbGluZWFyR3JhZGllbnQ+PGNsaXBQYXRoIGlkPSJjbGlwLXBhdGgiPjxwYXRoIGlkPSJfUG9seWdvbl8iIGRhdGEtbmFtZT0iJmx0O1BvbHlnb24mZ3Q7IiBjbGFzcz0iY2xzLTEiIGQ9Ik05NC43OCw4MC4xNmw2Ni40NCwxMTUuMDhBMTUuMTcsMTUuMTcsMCwwLDEsMTQ4LjA4LDIxOEgxNS4yQTE1LjE3LDE1LjE3LDAsMCwxLDIuMDYsMTk1LjI0TDY4LjUsODAuMTZBMTUuMTcsMTUuMTcsMCwwLDEsOTQuNzgsODAuMTZaIi8+PC9jbGlwUGF0aD48L2RlZnM+PHRpdGxlPkVycm9yPC90aXRsZT48ZyBpZD0iTGF5ZXJfMiIgZGF0YS1uYW1lPSJMYXllciAyIj48ZyBpZD0iU29mdHdhcmUiPjxwYXRoIGlkPSJfUG9seWdvbl8yIiBkYXRhLW5hbWU9IiZsdDtQb2x5Z29uJmd0OyIgY2xhc3M9ImNscy0xIiBkPSJNOTQuNzgsODAuMTZsNjYuNDQsMTE1LjA4QTE1LjE3LDE1LjE3LDAsMCwxLDE0OC4wOCwyMThIMTUuMkExNS4xNywxNS4xNywwLDAsMSwyLjA2LDE5NS4yNEw2OC41LDgwLjE2QTE1LjE3LDE1LjE3LDAsMCwxLDk0Ljc4LDgwLjE2WiIvPjxwYXRoIGNsYXNzPSJjbHMtMiIgZD0iTTg3LjIyLDE2My43MWwyLjg4LTQ0LjM1YTkuMTgsOS4xOCwwLDAsMC05LjE2LTkuNzhoMGE5LjE4LDkuMTgsMCwwLDAtOS4xNiw5Ljc4bDIuODgsNDQuMzVhNi4zLDYuMywwLDAsMCw2LjI4LDUuODloMEE2LjMsNi4zLDAsMCwwLDg3LjIyLDE2My43MVoiLz48cGF0aCBjbGFzcz0iY2xzLTIiIGQ9Ik03MS4zOCwxODcuMjVhOS41Myw5LjUzLDAsMCwwLDEwLjM5LDkuNTgsOS42OCw5LjY4LDAsMCwwLS45LTE5LjMyQTkuNjQsOS42NCwwLDAsMCw3MS4zOCwxODcuMjVaIi8+PHBhdGggY2xhc3M9ImNscy0zIiBkPSJNOTEuNywyNy4xNyw4NC4yOS40NUEuNjEuNjEsMCwwLDAsODMuMS41TDc4LjQ0LDI1LjZsLTUuOC0xLjA4YS42MS42MSwwLDAsMC0uNy43Nkw3OS4zNSw1MkEuNjEuNjEsMCwwLDAsODAuNTQsNTJsNC42Ni0yNS4xTDkxLDI3LjkzQS42MS42MSwwLDAsMCw5MS43LDI3LjE3WiIvPjxwYXRoIGNsYXNzPSJjbHMtNCIgZD0iTTY1LjEyLDQxLjgxLDU0LjI0LDMzLjI2YS4yNy4yNywwLDAsMC0uNDEuMzNMNTkuMzYsNDUsNTYuNyw0Ni4zMWEuMjcuMjcsMCwwLDAsMCwuNDVsMTAuODcsOC41NWEuMjcuMjcsMCwwLDAsLjQxLS4zM0w2Mi40MSw0My41NWwyLjY2LTEuMjlBLjI3LjI3LDAsMCwwLDY1LjEyLDQxLjgxWiIvPjxwYXRoIGNsYXNzPSJjbHMtNSIgZD0iTTExNS4xNSwzNi42Yy0xLjE3LDEuNTktMTEtNS42LTEyLjE2LTRzOC42Niw4Ljc5LDcuNSwxMC4zOS0xMS01LjYtMTIuMTctNCw4LjY2LDguNzksNy40OSwxMC4zOS0xMS01LjYtMTIuMTctNCw4LjY2LDguNzksNy40OSwxMC4zOSIvPjxwYXRoIGNsYXNzPSJjbHMtNiIgZD0iTTExOS45Miw2NC4xOWMtMS40NiwxLjMzLTcuMDUtNC43OC04LjUxLTMuNDRzNC4xMyw3LjQ1LDIuNjcsOC43OC03LjA1LTQuNzgtOC41MS0zLjQ0Yy0uNjguNjIuMTYsMi4yNywxLjExLDQiLz48cGF0aCBjbGFzcz0iY2xzLTYiIGQ9Ik00NC44LDY0YzEuODIuNzcsNS02Ljg3LDYuODYtNi4xcy0xLjM5LDguNC40Myw5LjE3LDUtNi44Nyw2Ljg2LTYuMWMuODUuMzYuNjEsMi4xOS4yOSw0LjEzIi8+PC9nPjwvZz48L3N2Zz4=`;","import Loadable from 'react-loadable';\nimport React from 'react';\nimport { Skeleton } from '../primitives';\nexport const loadAtlassianSwitcher = () => import( /* webpackChunkName: \"@ak-switcher-chunk-atlassian-switcher\" */'./atlassian-switcher').then(module => module.default);\nexport const loadJiraSwitcher = () => import( /* webpackChunkName: \"@ak-switcher-chunk-jira-switcher\" */'./jira-switcher').then(module => module.default);\nexport const loadConfluenceSwitcher = () => import( /* webpackChunkName: \"@ak-switcher-chunk-confluence-switcher\" */'./confluence-switcher').then(module => module.default);\nexport const loadGenericSwitcher = () => import( /* webpackChunkName: \"@ak-switcher-chunk-generic-switcher\" */'./generic-switcher').then(module => module.default);\nexport const loadTrelloSwitcher = () => import( /* webpackChunkName: \"@ak-switcher-chunk-trello-switcher\" */'./trello-switcher').then(module => module.default);\nexport const AtlassianSwitcherLoader = Loadable({\n loader: loadAtlassianSwitcher,\n loading: () => /*#__PURE__*/React.createElement(Skeleton, null)\n});\nexport const JiraSwitcherLoader = Loadable({\n loader: loadJiraSwitcher,\n loading: () => /*#__PURE__*/React.createElement(Skeleton, null)\n});\nexport const ConfluenceSwitcherLoader = Loadable({\n loader: loadConfluenceSwitcher,\n loading: () => /*#__PURE__*/React.createElement(Skeleton, null)\n});\nexport const GenericSwitcherLoader = Loadable({\n loader: loadGenericSwitcher,\n loading: () => /*#__PURE__*/React.createElement(Skeleton, null)\n});\nexport const TrelloSwitcherLoader = Loadable({\n loader: loadTrelloSwitcher,\n loading: () => /*#__PURE__*/React.createElement(Skeleton, null)\n});","/** @jsx jsx */\nimport React from 'react';\nimport { css, keyframes, jsx } from '@emotion/react';\nconst fadeIn = keyframes({\n to: {\n opacity: 1\n }\n});\nconst fadeInStyles = css({\n animation: `${fadeIn} 500ms ease forwards`,\n opacity: 0,\n margin: 0,\n padding: 0\n});\nexport const FadeIn = ({\n children,\n className,\n tag: Tag = 'div'\n}) => jsx(Tag, {\n css: fadeInStyles,\n className: className\n}, children);","import _extends from \"@babel/runtime/helpers/extends\";\n/** @jsx jsx */\n/** @jsxFrag */\nimport React from 'react';\nimport { LinkItem } from '@atlaskit/menu';\nimport { RenderTracker, SWITCHER_ITEM_LOZENGES_SUBJECT } from '../../common/utils/analytics';\nimport { FadeIn } from './fade-in';\nimport { css, jsx } from '@emotion/react';\nimport Lozenge from '@atlaskit/lozenge';\nimport { FormattedMessage } from 'react-intl-next';\nimport messages from './messages';\nimport ErrorBoundary from '../components/error-boundary';\nexport let LozengeType = /*#__PURE__*/function (LozengeType) {\n LozengeType[\"New\"] = \"new\";\n return LozengeType;\n}({});\nconst lozengeData = {\n [LozengeType.New]: {\n label: messages.newLozenge,\n componentProps: {\n appearance: 'new'\n }\n }\n};\nconst fadeInStyles = css({\n width: '100%'\n});\nconst childrenStyles = css({\n lineHeight: '14px',\n minHeight: '16px',\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap'\n});\nconst itemDescriptionStyles = css({\n color: \"var(--ds-text-subtlest, #626F86)\",\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n lineHeight: \"var(--ds-space-150, 12px)\",\n fontWeight: \"var(--ds-font-weight-regular, 400)\"\n});\nconst SwitcherItem = ({\n icon,\n description,\n elemAfter,\n shouldAllowMultiline,\n onClick,\n children,\n lozenges,\n product,\n createAnalyticsEvent,\n tag,\n href,\n ...rest\n}) => {\n const itemDescription = React.useMemo(() => {\n if ( /*#__PURE__*/React.isValidElement(description) || typeof description === 'string') {\n return jsx(\"div\", {\n css: itemDescriptionStyles\n }, description);\n }\n return undefined;\n }, [description]);\n const renderLozenges = React.useMemo(() => {\n if (!(lozenges !== null && lozenges !== void 0 && lozenges.length)) {\n return null;\n }\n return jsx(ErrorBoundary, {\n product: product,\n triggerSubject: \"switcherItemLozengeErrorBoundary\",\n hideFallbackUI: true\n }, jsx(React.Fragment, null, lozenges.map((lozenge, index) => {\n const {\n componentProps,\n label\n } = lozengeData[lozenge];\n return jsx(\"span\", {\n key: index,\n style: {\n marginLeft: \"var(--ds-space-100, 8px)\"\n }\n }, jsx(Lozenge, _extends({}, componentProps, {\n \"data-testid\": \"switcher-item-lozenge\"\n }), jsx(FormattedMessage, label)));\n }), jsx(RenderTracker, {\n subject: SWITCHER_ITEM_LOZENGES_SUBJECT,\n data: {\n product,\n lozenges,\n children,\n description\n }\n })));\n }, [lozenges, product, children, description]);\n return jsx(FadeIn, {\n css: fadeInStyles,\n tag: tag\n }, jsx(LinkItem, _extends({\n testId: \"switcher-base-item\",\n description: itemDescription,\n iconBefore: icon,\n iconAfter: elemAfter,\n target: \"_blank\",\n href: href !== null && href !== void 0 ? href : '#',\n onClick: event => {\n // To prevent the page from reloading when using a fallback '#' in href, make sure to use preventDefault.\n if (!href) {\n event.preventDefault();\n }\n if (onClick) {\n onClick(event);\n }\n }\n }, rest), jsx(\"span\", {\n css: childrenStyles\n }, children, renderLozenges)));\n};\nexport default SwitcherItem;","import { defineMessages } from 'react-intl-next';\nconst messages = defineMessages({\n newLozenge: {\n id: 'fabric.atlassianSwitcher.newLozenge',\n defaultMessage: 'New',\n description: 'The lozenge text for a lozenge indicating a new switcher item'\n },\n sites: {\n id: 'fabric.atlassianSwitcher.sites',\n defaultMessage: '{productName} {numSites, plural, one {site} other {sites}}',\n description: 'The text of a toggle showing or hiding more site options'\n }\n});\nexport default messages;","import _extends from \"@babel/runtime/helpers/extends\";\nimport React from 'react';\nimport Button from '@atlaskit/button';\nimport ShortcutIcon from '@atlaskit/icon/glyph/shortcut';\nimport { withAnalyticsEvents } from '@atlaskit/analytics-next';\nimport { UI_EVENT_TYPE } from '@atlaskit/analytics-gas-types';\nimport { createAndFireNavigationEvent, SWITCHER_ITEM_SUBJECT } from '../../common/utils/analytics';\nimport { FormattedMessage } from 'react-intl-next';\nconst ItemLink = ({\n label,\n href,\n testId,\n onClick,\n ariaLabel\n}) => {\n const buttonProps = {\n appearance: 'link',\n href,\n className: 'section-link',\n target: '_blank',\n rel: 'noopener noreferrer',\n iconAfter: /*#__PURE__*/React.createElement(ShortcutIcon, {\n size: \"small\",\n label: \"\"\n }),\n onClick: onClick ? (e, a) => onClick(e, a) : undefined,\n testId\n };\n if (ariaLabel) {\n return /*#__PURE__*/React.createElement(FormattedMessage, ariaLabel, placeholder => /*#__PURE__*/React.createElement(Button, _extends({}, buttonProps, {\n \"aria-label\": String(placeholder)\n }), label));\n }\n return /*#__PURE__*/React.createElement(Button, buttonProps, label);\n};\nexport default withAnalyticsEvents({\n onClick: createAndFireNavigationEvent({\n eventType: UI_EVENT_TYPE,\n action: 'clicked',\n actionSubject: SWITCHER_ITEM_SUBJECT\n })\n})(ItemLink);","/** @jsx jsx */\nimport React from 'react';\nimport { fontFallback } from '@atlaskit/theme/typography';\nimport ShortcutIcon from '@atlaskit/icon/glyph/shortcut';\nimport { css, jsx } from '@emotion/react';\nimport { analyticsAttributes, getItemAnalyticsContext, NavigationAnalyticsContext, withAnalyticsContextData } from '../../common/utils/analytics';\nimport { FadeIn } from './fade-in';\nimport ItemLink from './item-link';\nimport { AnalyticsItemType } from '../../types';\nconst sectionContainerStyles = css({\n padding: `${\"var(--ds-space-075, 6px)\"} 0`\n});\nconst secondarySectionTitleBaseStyles = css({\n // eslint-disable-next-line @atlaskit/design-system/no-nested-styles\n '&&': {\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n textTransform: 'uppercase',\n whiteSpace: 'nowrap',\n marginTop: `${\"var(--ds-space-200, 16px)\"}`,\n marginLeft: `${\"var(--ds-space-100, 8px)\"}`\n }\n});\nconst secondarySectionTitleStandaloneStyles = css({\n marginBottom: \"var(--ds-space-050, 4px)\"\n});\nconst secondarySectionTitleDrawerStyles = css({\n marginBottom: \"var(--ds-space-100, 8px)\"\n});\nconst sectionTitleStyles = css({\n color: \"var(--ds-text-subtle, #44546F)\",\n font: `var(--ds-font-body-small, ${fontFallback.body.small})`,\n fontWeight: \"var(--ds-font-weight-bold, 700)\"\n});\nconst sectionChildrenWrapperStyles = css({\n listStyleType: 'none',\n padding: 0,\n margin: 0\n});\nexport const SectionContainerTitle = ({\n appearance,\n title\n}) => jsx(\"h2\", {\n css: [secondarySectionTitleBaseStyles, appearance === 'standalone' ? secondarySectionTitleStandaloneStyles : secondarySectionTitleDrawerStyles, sectionTitleStyles]\n}, title);\nconst SectionContainerComponent = ({\n title,\n titleLink,\n children,\n appearance,\n actionSubject,\n sectionId\n}) => {\n return React.Children.toArray(children).some(Boolean) ? jsx(\"section\", {\n css: sectionContainerStyles,\n \"data-testid\": `${sectionId}__section`\n }, jsx(FadeIn, null, title && jsx(SectionContainerTitle, {\n appearance: appearance,\n title: title\n }), titleLink && jsx(TitleLink, {\n titleLink: titleLink,\n actionSubject: actionSubject\n })), jsx(\"ul\", {\n css: sectionChildrenWrapperStyles\n }, children)) : null;\n};\nconst TitleLink = ({\n titleLink,\n actionSubject\n}) => jsx(NavigationAnalyticsContext, {\n key: titleLink.key,\n data: getItemAnalyticsContext(0, titleLink.key, AnalyticsItemType.PRODUCT, titleLink.productType)\n}, jsx(ItemLink, {\n href: titleLink.href,\n iconAfter: jsx(ShortcutIcon, {\n size: \"small\",\n label: \"\"\n }),\n label: titleLink.label,\n testId: \"section-title__link\",\n actionSubject: actionSubject,\n ariaLabel: titleLink.ariaLabel\n}));\nexport const SectionContainer = withAnalyticsContextData(props => analyticsAttributes({\n group: props.sectionId,\n groupItemsCount: React.Children.count(props.children)\n}))(SectionContainerComponent);","/** @jsx jsx */\nimport { css, jsx } from '@emotion/react';\nimport * as colors from '@atlaskit/theme/colors';\nimport { SectionContainer } from './section-container';\nimport SwitcherItem from './item';\nimport { useExperienceRenderAndMountMark, ExperienceMark } from '../../common/utils/experience-tracker';\nconst iconSkeletonStyles = css({\n display: 'inline-block',\n width: 32,\n height: 32,\n backgroundColor: `var(--ds-skeleton, ${colors.N20})`,\n borderRadius: \"var(--ds-border-radius-200, 8px)\"\n});\nconst lineSkeletonStyles = css({\n display: 'inline-block',\n width: 98,\n height: 10,\n backgroundColor: `var(--ds-skeleton, ${colors.N20})`,\n borderRadius: \"var(--ds-border-radius, 3px)\"\n});\n\n// TODO: add loading text for screen reader\n// https://product-fabric.atlassian.net/browse/CXP-2998\nconst iconSkeleton = jsx(\"div\", {\n css: iconSkeletonStyles\n});\nconst lineSkeleton = jsx(\"div\", {\n css: lineSkeletonStyles\n});\nexport default (() => {\n useExperienceRenderAndMountMark(ExperienceMark.SWITCHER_SKELETON_MOUNT);\n return jsx(SectionContainer, {\n sectionId: \"skeleton\",\n title: lineSkeleton\n }, jsx(SwitcherItem, {\n tag: \"li\",\n icon: iconSkeleton,\n isDisabled: true\n }, lineSkeleton), jsx(SwitcherItem, {\n tag: \"li\",\n icon: iconSkeleton,\n isDisabled: true\n }, lineSkeleton), jsx(SwitcherItem, {\n tag: \"li\",\n icon: iconSkeleton,\n isDisabled: true\n }, lineSkeleton));\n});","export let ExperienceTypes = /*#__PURE__*/function (ExperienceTypes) {\n ExperienceTypes[\"Load\"] = \"load\";\n ExperienceTypes[\"Experience\"] = \"experience\";\n ExperienceTypes[\"Operation\"] = \"operation\";\n return ExperienceTypes;\n}({});\nexport let ExperiencePerformanceTypes = /*#__PURE__*/function (ExperiencePerformanceTypes) {\n ExperiencePerformanceTypes[\"PageLoad\"] = \"page-load\";\n ExperiencePerformanceTypes[\"PageSegmentLoad\"] = \"page-segment-load\";\n ExperiencePerformanceTypes[\"InlineResult\"] = \"inline-result\";\n ExperiencePerformanceTypes[\"Custom\"] = \"custom\";\n return ExperiencePerformanceTypes;\n}({});","export type UnsucessfulFetchErrorOptions = {\n readonly message?: string;\n readonly response: Response;\n};\n\nexport class UnsucessfulFetchError extends Error {\n public readonly response: Response;\n\n public constructor({ message, response }: UnsucessfulFetchErrorOptions) {\n super(message ?? response.statusText);\n this.name = UnsucessfulFetchError.name;\n this.response = response;\n }\n\n public get url(): string {\n return this.response.url;\n }\n\n public get status(): number {\n return this.response.status;\n }\n}\n\nexport function isUnsucessfulFetchError(\n value: unknown\n): value is UnsucessfulFetchError {\n return (value as UnsucessfulFetchError).name === UnsucessfulFetchError.name;\n}\n","import { serialize } from 'cookie';\n\nimport { Cookie } from '../models';\n\nexport function serializeCookie({ name, value }: Cookie): string {\n return serialize(name, value);\n}\n\nexport function mapCookieToHeaders(cookie?: Cookie): HeadersInit {\n if (cookie) {\n return { cookie: serializeCookie(cookie) };\n } else {\n return {};\n }\n}\n","import { isUndefined } from '@atlassiansox/bxp-shared-utils';\n\nexport type Headers = {\n readonly [name: string]: string;\n};\n\nexport function createHeaders(headers: {\n readonly [name: string]: string | number | boolean | undefined;\n}): Headers {\n return Object.keys(headers).reduce((result, name) => {\n const value = headers[name];\n if (!isUndefined(value)) {\n return {\n ...result,\n [name]: value.toString()\n };\n } else {\n return result;\n }\n }, {});\n}\n","import { UnsucessfulFetchError } from '../errors';\n\nexport async function mapResponseToText(response: Response): Promise {\n if (response.ok) {\n return await response.text();\n } else {\n throw new UnsucessfulFetchError({\n message: await mapResponseToMessage(response),\n response\n });\n }\n}\n\nexport async function mapResponseToJson(\n response: Response\n): Promise {\n if (response.ok) {\n return await response.json();\n } else {\n throw new UnsucessfulFetchError({\n message: await mapResponseToMessage(response),\n response\n });\n }\n}\n\nasync function mapResponseToMessage(response: Response): Promise {\n const { statusText } = response;\n const message = await response.text();\n if (message.length > 0) {\n return `${statusText} ${message}`;\n } else {\n return statusText;\n }\n}\n","import { isUndefined } from '@atlassiansox/bxp-shared-utils';\n\nexport type CreateUrlOptions = {\n readonly baseUrl?: string;\n readonly path?: string;\n readonly query?: Query;\n};\n\nexport type Query = Readonly<\n Record\n>;\n\nexport function createUrl({\n baseUrl = '',\n path = '',\n query\n}: CreateUrlOptions = {}): string {\n const queryString = mapQueryToQueryString(query);\n if (queryString) {\n return `${baseUrl}${path}?${queryString}`;\n } else {\n return `${baseUrl}${path}`;\n }\n}\n\nfunction mapQueryToQueryString(query: Query = {}): string | null {\n const queryString = Object.keys(query)\n .reduce((pairs, name) => {\n const value = query[name];\n if (isUndefined(value)) {\n return pairs;\n } else if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n return [\n ...pairs,\n `${encodeURIComponent(name)}=${encodeURIComponent(value)}`\n ];\n } else {\n return [\n ...pairs,\n value.map((item) => mapQueryToQueryString({ [name]: item })).join('&')\n ];\n }\n }, [])\n .join('&');\n\n if (queryString.length > 0) {\n return queryString;\n } else {\n return null;\n }\n}\n","import { Cookie } from '@atlassiansox/asc-core';\nimport { Asap, UserProfile } from './models';\nimport { PRODUCT_KEY_MAP } from './constants';\nimport { XOR } from './utils';\n\ntype ProductActivation = {\n readonly productKey: string;\n readonly edition?: string;\n};\n\nexport type GetUserPermissionsIsPermittedRequest = {\n readonly permissionId: GetUserPermissionsIsPermittedRequestPermissionId;\n readonly resourceId: string;\n readonly dontRequirePrincipalInSite?: boolean;\n readonly webPlatform?: string;\n};\n\nexport type GetUserPermissionsIsPermittedResponse = {\n readonly permitted: boolean;\n};\n\nexport enum AuthenticationMethodsType {\n PASSWORD = 'password',\n GOOGLE = 'google',\n SAML = 'saml',\n MICROSOFT = 'microsoft',\n APPLE = 'apple',\n SLACK = 'slack'\n}\n\ntype Method = {\n readonly type: AuthenticationMethodsType;\n readonly redirect_to?: string;\n};\n\nexport type CheckAuthenticationMethodsAvailableResponse = {\n readonly methods: Method[];\n readonly userExists: boolean;\n readonly passwordEnabled: boolean;\n readonly samlRequired: boolean;\n};\n\nexport type PostCloudSignUpRequest = {\n payload: FormPayloadType | FormPayloadActivateProducts;\n webPlatform?: string;\n};\n\ntype ProductPayloadObject = {\n readonly accountName?: string | null;\n readonly edition?: string | null;\n readonly product?: string | null;\n readonly productKey?: string | null;\n};\n\ntype FormPayloadActivateProducts = {\n activateProducts?: boolean;\n products: ProductPayloadObject[];\n cloudId?: string;\n cloudName: string | null;\n advancedSettings?: {\n [key: string]: number | boolean | string | Record;\n };\n signupContext?: string;\n};\n\ntype ConsentsObject = {\n key: string;\n displayedText: unknown;\n granted: boolean;\n};\n\nexport type Consent = {\n readonly site: string | null;\n readonly locale: string | null;\n readonly formUrl: string | null;\n readonly consents: ConsentsObject[];\n};\n\ntype FormPayloadType = {\n adminUsername: string;\n gRecaptchaResponse?: string;\n cloudName: string | null;\n email: string | null;\n timezone: string | null;\n firstName: string | null;\n lastName: string | null;\n adminPassword?: string | null;\n signupContext?: string;\n dataRegion?: string;\n consent: Consent;\n} & FormPayloadActivateProducts;\n\nexport type CheckAuthenticationMethodsAvailableRequest = {\n readonly email: string;\n readonly application?: string;\n readonly webPlatform?: string;\n readonly successRedirect: string;\n};\n\nexport enum GetUserPermissionsIsPermittedRequestPermissionId {\n ADD_PRODUCTS = 'add-products',\n INVITE_USERS = 'invite-users',\n MANAGE = 'manage',\n WRITE = 'write',\n /**\n * @deprecated ADD_PRODUCT is a legacy permissionId, use ADD_PRODUCTS instead.\n */\n ADD_PRODUCT = 'addProduct'\n}\n\nexport type RenameCloudRequest = {\n readonly webPlatform?: string;\n readonly cloudId: string;\n readonly cloudName: string;\n};\n\nexport type RenameCloudResponse = {\n readonly progressUri: string;\n};\n\nexport type CheckCloudNameAvailabilityRequest = {\n readonly cloudName: string;\n readonly webPlatform?: string;\n};\n\nexport type CheckCloudNameAvailabilityResponse = {\n readonly availability: CloudNameAvailability;\n};\n\nexport type GetUserCloudSitesRequest = {\n readonly product: string;\n readonly editions: string[];\n readonly adminAccess: boolean;\n readonly billingFrequency: string[];\n readonly licenseLevels: string[];\n};\n\nexport type GetUserCloudSitesResponse = {\n readonly name: string;\n readonly sites: ReadonlyArray;\n};\n\ntype CloudSitesInfo = {\n readonly siteName: string;\n readonly edition: string;\n readonly license: string;\n readonly product: string;\n readonly siteId: string;\n readonly adminAccess: boolean;\n};\n\nexport type CloudNameAvailability =\n | 'AVAILABLE'\n | 'TAKEN'\n | 'ERROR'\n | 'INVALID'\n | 'NOT_AVAILABLE_FOR_TRANSFER';\n\nexport type SitesType = {\n readonly adminAccess: boolean;\n readonly cloudId: string;\n readonly products: string[];\n readonly url: string;\n readonly displayName: string;\n readonly edition?: string | null;\n readonly orgId?: string | null;\n readonly productsAndEditions: ProductsAndEditionsObjectType[];\n};\n\nexport type CloudSessionTokenCookieType = {\n readonly cloudSessionTokenCookie?: Cookie;\n};\n\nexport type AvailableProductsResponse = {\n sites: SitesType[];\n isNewUser: boolean;\n};\n\nexport type AvailableProductsLegacyResponse = SitesType[];\n\nexport type AvailableProductsOptions = {\n readonly includeInvalidSites?: boolean;\n readonly includeInvalidBitbucketSite?: boolean;\n readonly removeNonAdminSites?: boolean;\n} & CloudSessionTokenCookieType;\n\nexport type ProductType = {\n productKey?: string;\n edition?: string;\n};\n\nexport type UserSignupRequest = {\n email: string;\n locale: string;\n redirectTo: string;\n displayName: string;\n gRecaptchaResponse?: string;\n webPlatform?: string;\n products?: ProductType[];\n};\n\nexport type UserSignupResponse = {\n id: string;\n otpRedirect?: string;\n};\n\ntype ActivateProductResponseItems = {\n itemId: string;\n orderItemId: string;\n};\n\nexport type Platform = 'ccp' | 'hams' | 'routing';\n\nexport type CcpProduct = {\n readonly offeringId: string;\n readonly pricingPlanId: string;\n readonly productKey: string;\n readonly edition: string;\n readonly chargeElement: string;\n readonly pricingType?: string;\n};\n\nexport type ActivateProductRequest = {\n email: string;\n ccpProducts: CcpProduct[];\n siteName?: string;\n timezone: string;\n useCcpPlatform: boolean;\n platform: Platform;\n displayName?: string;\n consent?: Consent;\n signupContext?: string;\n advancedSettings?: {\n [key: string]: number | boolean | string | Record;\n };\n gRecaptchaResponse?: string;\n testingPurposes?: boolean;\n isNewUser?: boolean;\n migrationId?: string;\n webPlatform?: string;\n orgId?: string;\n workspaceId?: string;\n};\n\nexport type ActivateProductUpstreamResponse = XOR<\n ActivateProductCcpUpstreamResponse,\n ActivateProductCofsResponse\n>;\n\nexport type ActivateProductCcpUpstreamResponse = {\n statusUrl: string;\n orderId: string;\n slug: string;\n items: ActivateProductResponseItems[];\n transactionAccountId: string;\n invoiceGroupId: string;\n metadata: {\n provisionRequestId: string;\n };\n cloudId: string;\n service: string;\n};\n\nexport type ActivateProductResponse = XOR<\n ActivateProductCcpResponse,\n ActivateProductCofsResponse\n>;\n\nexport type ActivateProductCcpResponse = {\n orderId: string;\n slug: string;\n transactionAccountId: string;\n invoiceGroupId: string;\n metadata: {\n provisionRequestId: string;\n };\n items: ActivateProductResponseItems[];\n cloudId: string;\n service: string;\n};\n\nexport type ActivateProductCofsResponse = {\n cloudId: string;\n progressUri: string;\n service: string;\n};\nexport type CofsActivateProductExistingRequest = {\n cloudId: string;\n products: ProductActivation[];\n timezone: string;\n signupContext?: string;\n webPlatform?: string;\n advancedSettings?: {\n [key: string]: number | boolean | string | Record;\n };\n gRecaptchaResponse?: string;\n};\nexport interface ProductActivationStatusRequest {\n provisioningRequestId: string;\n webPlatform?: string;\n}\n\nexport interface ProductActivationStatusResponse {\n provisionRequestId: string;\n resourcePackages: ResourcePackage[];\n}\n\nexport interface GetLicenceInformationRequest {\n cloudId: string;\n webPlatform?: string;\n}\nexport type GetLicenseInformationResponse = {\n readonly firstActivationDate: number;\n readonly hostname: string;\n readonly products: {\n [key: string]: GetLicenseInformationProduct;\n };\n};\n\nexport type GetLicenseInformationProduct = {\n readonly ccpEntitlementId?: string;\n readonly ccpTransactionAccountId: string;\n readonly edition: string;\n readonly isSuspended?: boolean;\n readonly state: string;\n readonly relatesFromEntitlements?: GetLicenseInformationRelatedEntitlement[];\n};\n\nexport type GetLicenseInformationRelatedEntitlement = {\n readonly relationshipType: string;\n readonly entitlementId: string;\n readonly relationshipId: string;\n};\n\nexport interface ProductActivateRequest {\n readonly transactionAccountId: string;\n readonly entitlementId: string;\n readonly offerings: OfferingsType[];\n readonly cloudId: string;\n readonly siteName?: string;\n readonly webPlatform?: string;\n readonly advancedSettings?: advancedSettingsType;\n}\n\n// For cross flow /product/activate endpoint\nexport type advancedSettingsType = {\n readonly signupContext?: string;\n};\n\nexport interface COFSProductActivateRequest {\n readonly edition: string;\n readonly productKey: string;\n readonly cloudId: string;\n readonly webPlatform?: string;\n}\n\nexport type OfferingsType = {\n readonly offeringId: string;\n readonly pricingPlanId: string;\n readonly chargeElement: string;\n};\n\nexport type ProductActivateResponse = {\n readonly orderId: string;\n readonly progressUri: string;\n readonly cloudId: string;\n};\nexport type COFSProductActivateResponse = {\n readonly progressUri: string;\n readonly cloudId: string;\n};\n\nexport interface ResourcePackage {\n entitlementId: string;\n action: {\n type: RecourcePackageActionTypes;\n status: ProductActivationStatus;\n errorDetails?: ResourceActivationError[];\n };\n resourceAris: string[];\n}\n\nexport type RecourcePackageActionTypes = 'ACTIVATE';\n\nexport type ProductActivationStatus =\n | 'IN_PROGRESS'\n | 'SUCCESS'\n | 'PROVISIONING_FAILURE';\n\nexport interface ResourceActivationError {\n source: string;\n message: string;\n}\n\n/**\n * Identity Client section\n */\nexport type AsapAuth = {\n readonly asap: Asap;\n};\n\nexport function isAsapAuth(auth: AsapAuth) {\n return !!auth.asap;\n}\n\nexport type MeResponse = {\n readonly account_id: string;\n readonly name: string;\n readonly email: string;\n readonly picture: string;\n readonly locale: string;\n readonly zoneinfo: string;\n};\n\nexport type MeOptions = CloudSessionTokenCookieType;\n\nexport function mapMeResponseToUserProfile({\n account_id,\n ...others\n}: MeResponse): UserProfile {\n return {\n accountId: account_id,\n ...others\n };\n}\n\nexport type BitbucketWorkspaceOptions = {\n readonly nextUrl?: string;\n readonly urlQuery?: string;\n} & CloudSessionTokenCookieType;\n\nexport type BitbucketWorkspacesResponse = {\n readonly page: number;\n readonly pagelen: number;\n readonly size: number;\n readonly next?: string;\n readonly previous?: string;\n readonly values: [\n {\n // owner: has admin access, collaborator: has write access\n readonly permission: 'owner' | 'member' | 'collaborator';\n readonly user?: WorkspaceUserType;\n readonly workspace?: WorkspaceType;\n readonly last_accessed?: string | null;\n readonly type?: string;\n readonly links?: Record;\n readonly added_on?: string | null;\n }\n ];\n};\n\nexport type WorkspaceUserType = {\n readonly display_name: string;\n readonly account_id: string;\n readonly links: Record;\n readonly nickname: string;\n readonly type: string;\n readonly uuid: string;\n};\n\nexport type WorkspaceType = {\n readonly name: string;\n readonly type: string;\n readonly uuid: string;\n readonly links: Record;\n readonly slug: string;\n};\n\nexport type AvailableProductsType = {\n readonly adminAccess: boolean;\n readonly cloudId: string;\n readonly displayName: string;\n readonly url: string;\n readonly availableProducts: [\n {\n readonly activityCount: number;\n readonly productType: keyof typeof PRODUCT_KEY_MAP;\n readonly url?: string;\n }\n ];\n readonly avatar?: string;\n};\n\n/**\n * /user/:id/manage/profile\n */\n\nexport type PatchUserProfileRequestBody = {\n readonly name?: string;\n readonly nickname: string;\n};\n\nexport type PatchUserProfileRequest = {\n readonly cloudSessionTokenCookie: Cookie;\n readonly body: PatchUserProfileRequestBody;\n readonly userId: string;\n};\n\nexport type PermissionsPermittedRequestAsap = {\n readonly auth: AsapAuth;\n};\nexport type PermissionsPermittedRequestParams = {\n readonly dontRequirePrincipalInSite: boolean;\n readonly permissionId: string;\n readonly principalId: string;\n readonly resourceId: string;\n};\nexport type GetCcpHamsStatus = {\n readonly cloudId: string;\n readonly offeringKeys: string;\n};\nexport type GetCcpHamsResponse = {\n readonly service: string;\n};\n\nexport type GetAvailableSitesRequest = {\n readonly orderId: string;\n readonly transactionAccount: string;\n readonly webPlatform?: string;\n};\ntype ProductsAndEditionsObjectType = {\n readonly productEdition: string;\n readonly productKey: string;\n};\nexport type Site = {\n readonly siteName: string;\n readonly cloudId: string;\n readonly products: string[];\n readonly displayName: string;\n readonly url: string;\n readonly edition: string;\n readonly productsAndEditions: ProductsAndEditionsObjectType[];\n readonly entitlements: {\n ccpEntitlementId: string;\n billingSourceSystem: string;\n productKey: string;\n }[];\n readonly adminAccess: boolean;\n};\n\nexport type SiteFlags = {\n readonly useLockedInSite: boolean;\n};\n\nexport type GetAvailableSitesResponse = {\n readonly sites: Site[];\n readonly flags: SiteFlags;\n};\n\nexport type PermissionsPermittedRequest = PermissionsPermittedRequestAsap &\n PermissionsPermittedRequestParams;\n\nexport type PermissionsPermittedResponse = string;\n\n/**\n * getProductHubInfo section\n * TODO: find a single source for these models (these were just copied over from bxp-express)\n */\n\nexport enum Editions {\n FREE = 'free',\n STANDARD = 'standard',\n PREMIUM = 'premium'\n}\n\nexport enum ProductKeys {\n CONFLUENCE = 'confluence.ondemand',\n JIRA_CORE = 'jira-core.ondemand',\n JIRA_SERVICE_DESK = 'jira-servicedesk.ondemand',\n JIRA_SOFTWARE = 'jira-software.ondemand',\n JIRA_PRODUCT_DISCOVERY = 'jira-product-discovery',\n TRELLO = 'trello',\n OPSGENIE = 'opsgenie',\n BITBUCKET = 'bitbucket.ondemand',\n BITBUCKET_COFS = 'com.atlassian.bitbucket',\n STATUSPAGE = 'statuspage',\n TEAM_CENTRAL = 'townsquare',\n AVOCADO = 'avocado',\n COMPASS = 'compass',\n ANALYTICS = 'atlassian-analytics-free',\n WHITEBOARD = 'atlassian-whiteboard'\n}\n\nexport interface RelatesFromEntitlements {\n entitlementId: string;\n relationshipId: string;\n relationshipType: string;\n}\n\nexport interface Product {\n applicationUrl: string;\n edition: Editions;\n isSuspended: boolean;\n state: 'ACTIVE' | 'DEACTIVATED' | string;\n adminAccess?: boolean;\n billingPeriod?: 'MONTHLY' | 'ANNUAL';\n ccpTransactionAccountId?: string;\n ccpEntitlementId?: string;\n relatesFromEntitlements?: RelatesFromEntitlements[];\n trialEndDate?: string;\n lastActiveTimestamp: string | null;\n}\n\nexport interface ProductHub {\n cloudId: string;\n hostname: string;\n firstActivationDate: number;\n products?: Partial<{\n [key in ProductKeys]: Product;\n }>;\n adminAccess: boolean;\n}\n\nexport type GetProductHubInfoResponse = {\n readonly sites: ProductHub[];\n};\n\nexport interface ActivateDirectBuyProductRequest {\n timezone: string;\n region: string;\n orderId: string;\n transactionAccountId: string;\n webPlatform?: string;\n site: XOR<\n ActivateDirectBuyProductForExistingSiteRequest,\n ActivateDirectBuyProductForNewSiteRequest\n >;\n}\n\nexport interface ActivateDirectBuyProductForExistingSiteRequest {\n cloudId: string;\n}\n\nexport interface ActivateDirectBuyProductForNewSiteRequest {\n name: string;\n}\n\nexport interface ActivateDirectBuyProductResponse {\n provisionRequestId: string;\n}\n\nexport interface GetCloudProductInfoRequest {\n cloudId: string;\n webPlatform?: string;\n}\n\nexport type CloudProductInfo = Record;\n\nexport type GetProductEditionRequest = {\n readonly cloudId: string;\n readonly productKey: string;\n};\n\nexport type GetProductEditionResponse = {\n readonly edition: string;\n};\n\nexport type getConsentConfigResponse = {\n readonly locale: string;\n readonly localeRequiresMarketingCommunicationOptIn: boolean;\n readonly hasUserMadeChoiceOnMarketingCommunicationOptIn: boolean;\n readonly usersChoiceOnMarketingCommunicationOptIn: boolean;\n};\n\nexport type postConsentConfigResponse = {\n readonly locale: string;\n readonly localeRequiresMarketingCommunicationOptIn: boolean;\n readonly hasUserMadeChoiceOnMarketingCommunicationOptIn: boolean;\n readonly usersChoiceOnMarketingCommunicationOptIn: boolean;\n};\n\nexport type PostExpandFreeValidationRequest = {\n readonly cloudId: string;\n readonly productKeys: string[];\n};\n\nexport type PostExpandFreeValidationResponse = {\n readonly isInBreachOfFree: boolean;\n};\n\nexport type GetActivationAuthorizationRequest = {\n readonly productKeys: string[];\n readonly productEdition: string;\n readonly cloudId?: string;\n readonly webPlatform?: string;\n readonly siteName: string;\n};\n\nexport type GetActivationAuthorizationResponse = {\n readonly redirectUrl: string;\n readonly authorized: boolean;\n};\n\nexport type GetFeatureFlagRequest = string;\n\nexport type GetFeatureFlagResponse = {\n readonly result: unknown;\n};\n\nexport type GetFeatureFlagSyncRequest = string;\n\nexport type GetFeatureFlagSyncResponse = {\n readonly result: unknown;\n};\n\nexport type GetRecommendedSiteNameRequest = {\n readonly email: string;\n readonly webPlatform?: string;\n} & CloudSessionTokenCookieType;\n\nexport type GetRecommendedSiteNameResponse = {\n readonly recommendedName: string;\n};\n\nexport type GetAccountOrgsRequest = {\n readonly includeVortexMode?: boolean;\n readonly webPlatform?: string;\n};\n\nexport type GetAccountOrgsResponse = {\n readonly id: string;\n readonly name: string;\n readonly isAdmin: boolean;\n readonly vortexMode?: string;\n}[];\n\nexport type CreateOrgRequest = {\n readonly orgDisplayName: string;\n readonly webPlatform?: string;\n};\n\nexport type CreateOrgResponse = {\n readonly orgId: string;\n readonly progressUri: string;\n};\n\nexport type BitbucketValidateWorkspaceSlugRequest = {\n readonly workspaceSlug: string;\n};\n\nexport type BitbucketValidateWorkspaceSlugResponse = {\n readonly new_ari: string;\n};\n","export const ASAP_AUDIENCE = 'identity-platform';\n\nexport const PRODUCT_KEY_MAP = {\n CONFLUENCE: 'confluence.ondemand',\n JIRA_CORE: 'jira-core.ondemand',\n JIRA_BUSINESS: 'jira-core.ondemand',\n JIRA_SOFTWARE: 'jira-software.ondemand',\n JIRA_SERVICE_DESK: 'jira-servicedesk.ondemand',\n BITBUCKET: 'com.atlassian.bitbucket',\n OPSGENIE: 'opsgenie',\n STATUSPAGE: 'statuspage',\n TRELLO: 'trello'\n};\n","import Cookies from 'js-cookie';\n\nexport function getAtlCohortIdFromCookie() {\n let atlCohortId;\n try {\n const cookie = JSON.parse(Cookies.get('atlCohort') || '');\n atlCohortId = cookie['bucketAll'].index;\n } catch (e) {\n atlCohortId = '';\n console.warn('Cannot parse atlCohort cookie', e);\n }\n return atlCohortId;\n}\n","import { SitesType } from '../stargate-client.types';\n\n/**\n * Filter out internal/invalid sites\n */\n\ntype IsValidSiteType = {\n readonly site: SitesType;\n readonly includeInvalidBitbucketSite?: boolean;\n};\n\nexport const isValidSite = ({\n site,\n includeInvalidBitbucketSite\n}: IsValidSiteType): boolean => {\n const ignoreSiteNames = [\n 'servicedog',\n 'ecosystem',\n 'atlassiantraining',\n 'Atlassian Stride',\n 'volunteerhub',\n 'atlassiantraining',\n 'hello-staging',\n 'ecosystem',\n 'riskmanagement',\n 'hello-staging3',\n 'hello-staging6',\n 'hello-staging9',\n 'jdog',\n 'sre-ehlo',\n 'trello',\n 'Trello'\n ];\n\n if (!includeInvalidBitbucketSite) {\n ignoreSiteNames.push('bitbucket', 'Bitbucket');\n }\n\n if (ignoreSiteNames.includes(site.displayName)) {\n return false;\n }\n\n if (site.cloudId.startsWith('DUMMY')) {\n return false;\n }\n\n return true;\n};\n","import axios from 'axios';\nimport _ from 'lodash';\nimport {\n mapCookieToHeaders,\n mapResponseToJson,\n mapResponseToText,\n serializeCookie,\n UnsucessfulFetchError\n} from '@atlassiansox/asc-core';\nimport { fetch } from 'cross-fetch';\nimport Cookies from 'js-cookie';\n\nimport {\n ActivateProductUpstreamResponse,\n ActivateProductResponse,\n ActivateProductRequest,\n AvailableProductsOptions,\n AvailableProductsResponse,\n AvailableProductsType,\n BitbucketWorkspaceOptions,\n BitbucketWorkspacesResponse,\n CheckAuthenticationMethodsAvailableResponse,\n CheckAuthenticationMethodsAvailableRequest,\n CheckCloudNameAvailabilityRequest,\n CheckCloudNameAvailabilityResponse,\n GetUserCloudSitesRequest,\n GetUserCloudSitesResponse,\n GetLicenseInformationResponse,\n GetLicenceInformationRequest,\n GetUserPermissionsIsPermittedRequest,\n GetUserPermissionsIsPermittedResponse,\n MeOptions,\n mapMeResponseToUserProfile,\n PostCloudSignUpRequest,\n ProductActivationStatusRequest,\n ProductActivationStatusResponse,\n PatchUserProfileRequest,\n RenameCloudRequest,\n RenameCloudResponse,\n SitesType,\n UserSignupRequest,\n UserSignupResponse,\n ProductActivateRequest,\n ProductActivateResponse,\n COFSProductActivateRequest,\n COFSProductActivateResponse,\n GetProductHubInfoResponse,\n GetCcpHamsStatus,\n GetCcpHamsResponse,\n GetAvailableSitesRequest,\n GetAvailableSitesResponse,\n ActivateDirectBuyProductRequest,\n ActivateDirectBuyProductResponse,\n GetCloudProductInfoRequest,\n CloudProductInfo,\n GetProductEditionRequest,\n GetProductEditionResponse,\n GetActivationAuthorizationRequest,\n GetActivationAuthorizationResponse,\n GetFeatureFlagRequest,\n GetFeatureFlagResponse,\n AvailableProductsLegacyResponse,\n getConsentConfigResponse,\n postConsentConfigResponse,\n GetFeatureFlagSyncRequest,\n GetFeatureFlagSyncResponse,\n PostExpandFreeValidationResponse,\n PostExpandFreeValidationRequest,\n GetRecommendedSiteNameResponse,\n GetRecommendedSiteNameRequest,\n GetAccountOrgsResponse,\n GetAccountOrgsRequest,\n CreateOrgRequest,\n CreateOrgResponse,\n CofsActivateProductExistingRequest,\n ActivateProductCofsResponse,\n BitbucketValidateWorkspaceSlugRequest,\n BitbucketValidateWorkspaceSlugResponse\n} from './stargate-client.types';\nimport { PRODUCT_KEY_MAP } from './constants';\nimport { UserProfile } from './models';\nimport { getAtlCohortIdFromCookie, isValidSite } from './utils';\n\nexport interface IStargateClient {\n activateProduct(\n request: ActivateProductRequest\n ): Promise;\n availableProducts(\n options: AvailableProductsOptions\n ): Promise;\n availableProductsLegacy(\n options: AvailableProductsOptions\n ): Promise;\n bitbucketWorkspaces(\n options: BitbucketWorkspaceOptions\n ): Promise;\n checkCloudNameAvailability(\n request: CheckCloudNameAvailabilityRequest\n ): Promise;\n checkAuthenticationMethodsAvailable(\n request: CheckAuthenticationMethodsAvailableRequest\n ): Promise;\n getLicenceInformationStatus(\n request: GetLicenceInformationRequest\n ): Promise;\n getSignupServerXsrfToken(): Promise;\n getProductActivationStatus(\n requires: ProductActivationStatusRequest\n ): Promise;\n getUserCloudSites(\n request: GetUserCloudSitesRequest\n ): Promise;\n getUserPermissionsIsPermitted(\n request: GetUserPermissionsIsPermittedRequest\n ): Promise;\n getCurrentAuthenticatedUser(): Promise;\n getProductHubInfo(): Promise;\n me(options: MeOptions): Promise;\n patchUserProfile(request: PatchUserProfileRequest): Promise;\n postCloudSignUp(payload: PostCloudSignUpRequest): Promise;\n postProductActivate(\n request: ProductActivateRequest\n ): Promise;\n postCOFSProductActivate(\n request: COFSProductActivateRequest\n ): Promise;\n renameCloud(request: RenameCloudRequest): Promise;\n userSignup(request: UserSignupRequest): Promise;\n getCcpHamsStatus(request: GetCcpHamsStatus): Promise;\n getAvailableSites(\n request: GetAvailableSitesRequest\n ): Promise;\n activateDirectBuyProduct(\n request: ActivateDirectBuyProductRequest\n ): Promise;\n getCloudProductInfo(\n request: GetCloudProductInfoRequest\n ): Promise;\n getProductEdition(\n request: GetProductEditionRequest\n ): Promise;\n getActivationAuthorization(\n request: GetActivationAuthorizationRequest\n ): Promise;\n getFeatureFlag(\n request: GetFeatureFlagRequest\n ): Promise;\n postExpandFreeValidation(\n request: PostExpandFreeValidationRequest\n ): Promise;\n getFeatureFlagSync(\n request: GetFeatureFlagSyncRequest\n ): Promise;\n postConsentConfig(): Promise;\n getConsentConfig(): Promise;\n getRecommendedSiteName(\n request: GetRecommendedSiteNameRequest\n ): Promise;\n getAccountOrgs(\n request: GetAccountOrgsRequest\n ): Promise;\n cofsCreateOrg(request: CreateOrgRequest): Promise;\n cofsActivateProductExisting(\n request: CofsActivateProductExistingRequest\n ): Promise;\n bitbucketValidateWorkspaceSlug(\n request: BitbucketValidateWorkspaceSlugRequest\n ): Promise;\n}\n\nexport const DEFAULT_STARGATE_BASE_URL =\n 'https://wac.stg.internal.atlassian.com/gateway/api';\nexport const DEFAULT_IDENTITY_BASE_URL = 'https://id.staging.atl-paas.net';\n\nexport type StargateClientOptions = {\n readonly baseUrl: string;\n readonly disableRequestDeduplication?: boolean;\n};\n\nconst openRequestCache = new Map>();\n\n/**\n * @see https://bitbucket.org/atlassian/stargate/src/master/src/main/resources/application.yml\n */\nexport class StargateClient implements IStargateClient {\n public readonly baseUrl: string;\n public readonly disableRequestDeduplication?: boolean;\n\n public constructor({\n baseUrl,\n disableRequestDeduplication\n }: StargateClientOptions) {\n this.baseUrl = baseUrl;\n this.disableRequestDeduplication = disableRequestDeduplication;\n }\n\n /**\n * Deduplicate fetch requests made while there is an open request with the same cacheKey\n * @param cacheKey\n * @param input\n * @param init\n * @private\n */\n private async dedupeFetch(\n cacheKey: string,\n input: RequestInfo,\n init?: RequestInit\n ): Promise {\n if (this.disableRequestDeduplication) {\n return fetch(input, init);\n }\n\n // Check for an open request\n const cachedResult = openRequestCache.get(cacheKey);\n if (cachedResult) {\n return cachedResult.then((res) => res.clone());\n }\n\n // Create a new request based on the input\n const request = fetch(input, init);\n openRequestCache.set(cacheKey, request);\n\n // Return the request and clear it from cache when it completes\n return request.finally(() => {\n openRequestCache.delete(cacheKey);\n });\n }\n\n /**\n * Get the xsrf token required to make calls to the signup server\n *\n * @see https://bxp-signup-server.staging.atl-paas.net/swagger/#/Authentication/get_auth_xsrf\n */\n public async getSignupServerXsrfToken(webPlatform?: string): Promise {\n return mapResponseToText(\n await fetch(`${this.baseUrl}/bxp/signup/auth/xsrf`, {\n method: 'GET',\n credentials: 'include',\n headers: {\n 'accept': 'text/plain',\n 'web-platform': webPlatform || 'no-platform'\n }\n })\n );\n }\n\n /**\n * Get the authentication methods available to a given user.\n *\n * @see https://bxp-signup-server.us-west-2.prod.atl-paas.net/swagger/#/Identity/post_authentication_methods_available\n */\n public async checkAuthenticationMethodsAvailable({\n email,\n application = 'wac',\n successRedirect,\n webPlatform\n }: CheckAuthenticationMethodsAvailableRequest): Promise {\n const xsrfToken = await this.getSignupServerXsrfToken();\n const atlCohortId = getAtlCohortIdFromCookie();\n\n return mapResponseToJson(\n await fetch(\n `${this.baseUrl}/bxp/signup/authentication/methods-available`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'xsrf-token': xsrfToken,\n 'X-Atl-Cohort-Id': atlCohortId,\n 'web-platform': webPlatform || 'no-platform'\n },\n credentials: 'include',\n body: JSON.stringify({\n email,\n application,\n continue: successRedirect\n })\n }\n )\n );\n }\n\n /**\n * Get whether a user has a permission for a particular resource.\n *\n * @see https://id-public-api-facade.prod.atl-paas.net/swagger.json\n */\n public async getUserPermissionsIsPermitted({\n permissionId,\n resourceId,\n dontRequirePrincipalInSite,\n webPlatform\n }: GetUserPermissionsIsPermittedRequest): Promise {\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/permissions/permitted`, {\n credentials: 'include',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'web-platform': webPlatform || 'no-platform'\n },\n body: JSON.stringify({\n permissionId,\n resourceId,\n dontRequirePrincipalInSite\n })\n })\n );\n }\n\n /**\n * Returns details about the current authenticated user.\n * This is expected to be consistent with Atlassian account.\n *\n * @see https://id-public-api-facade.prod.atl-paas.net/swagger.json\n */\n public async getCurrentAuthenticatedUser(): Promise {\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/me`, {\n credentials: 'include'\n })\n );\n }\n\n /**\n * Gets trial information for Atlassian products. Currently only supports\n * JSW.\n *\n * @returns\n */\n public async getProductHubInfo(): Promise {\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/producthub/info`, {\n credentials: 'include'\n })\n );\n }\n\n public async postCloudSignUp({\n payload,\n webPlatform\n }: PostCloudSignUpRequest): Promise {\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/cloud/signup`, {\n method: 'POST',\n headers: {\n 'web-platform': webPlatform || 'no-platform',\n 'Content-Type': 'application/json',\n 'atl-cookies': JSON.stringify({\n _ga: Cookies.get('_ga') || '',\n seg_xid: localStorage.getItem('seg_xid') || '',\n __atl_path: Cookies.get('__atl_path') || '',\n ajs_anonymous_id: Cookies.get('ajs_anonymous_id') || ''\n })\n },\n body: JSON.stringify(payload),\n credentials: 'include'\n })\n );\n }\n\n /**\n * Rename a Cloud\n * @see https://cofs.dev.public.atl-paas.net/api.html#external__cloudId__rename_put\n */\n public async renameCloud({\n cloudId,\n cloudName,\n webPlatform\n }: RenameCloudRequest): Promise {\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/cofs/${cloudId}/rename`, {\n method: 'put',\n body: JSON.stringify({\n cloudName\n }),\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'web-platform': webPlatform || 'no-platform'\n },\n credentials: 'include'\n })\n );\n }\n\n /**\n * @see https://cloud-name-availability.prod.atl-paas.net/swagger-ui/index.html#/name-availability-stargate-controller/checkAvailabilityUsingPOST\n */\n public async checkCloudNameAvailability({\n cloudName,\n webPlatform\n }: CheckCloudNameAvailabilityRequest): Promise {\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/hostname/cloud/availability/check`, {\n method: 'post',\n body: JSON.stringify({\n cloudName\n }),\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'web-platform': webPlatform || 'no-platform'\n },\n credentials: 'include'\n })\n );\n }\n\n public async getUserCloudSites({\n product,\n editions,\n adminAccess,\n licenseLevels,\n billingFrequency\n }: GetUserCloudSitesRequest): Promise {\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/cloud/users/cloudsites`, {\n method: 'post',\n body: JSON.stringify({\n product,\n editions,\n adminAccess,\n licenseLevels,\n billingFrequency\n }),\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json'\n },\n credentials: 'include'\n })\n );\n }\n\n /**\n * Get the new ais/available-products\n */\n public async availableProducts({\n includeInvalidSites,\n includeInvalidBitbucketSite,\n removeNonAdminSites\n }: AvailableProductsOptions): Promise {\n const reqUrl = `${this.baseUrl}/ais/available-products`;\n const response = await this.dedupeFetch(reqUrl, reqUrl, {\n method: 'GET',\n credentials: 'include'\n });\n if (response.ok) {\n const result = await response.json();\n let sites = (result && result.sites) || [];\n\n if (removeNonAdminSites) {\n sites = sites.filter((site: SitesType) => site.adminAccess);\n }\n\n if (!includeInvalidSites) {\n sites = sites.filter((site: SitesType) =>\n isValidSite({\n site,\n includeInvalidBitbucketSite\n })\n );\n }\n\n return Promise.resolve({\n sites,\n isNewUser: !!(result && result.isNewUser)\n });\n } else {\n throw new UnsucessfulFetchError({\n response\n });\n }\n }\n\n public async userSignup(\n request: UserSignupRequest\n ): Promise {\n const xsrfToken = await this.getSignupServerXsrfToken();\n const atlCohortId = getAtlCohortIdFromCookie();\n\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/bxp/signup/identity/user-signup`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'xsrf-token': xsrfToken,\n 'X-Atl-Cohort-Id': atlCohortId,\n 'web-platform': request.webPlatform || 'no-platform'\n },\n credentials: 'include',\n body: JSON.stringify({ ...request })\n })\n );\n }\n\n public async activateProduct(\n request: ActivateProductRequest\n ): Promise {\n const xsrfToken = await this.getSignupServerXsrfToken();\n const atlCohortId = getAtlCohortIdFromCookie();\n\n const upstreamResponse =\n await mapResponseToJson(\n await fetch(`${this.baseUrl}/bxp/signup/activate-product`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'xsrf-token': xsrfToken,\n 'X-Atl-Cohort-Id': atlCohortId,\n 'web-platform': request.webPlatform || 'no-platform'\n },\n credentials: 'include',\n body: JSON.stringify(request)\n })\n );\n\n return upstreamResponse;\n }\n\n public async getProductActivationStatus(\n request: ProductActivationStatusRequest\n ): Promise {\n const xsrfToken = await this.getSignupServerXsrfToken();\n\n return mapResponseToJson(\n await fetch(\n `${this.baseUrl}/bxp/signup/activate/status/${request.provisioningRequestId}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n 'xsrf-token': xsrfToken,\n 'web-platform': request.webPlatform || 'no-platform'\n },\n credentials: 'include'\n }\n )\n );\n }\n\n public async getLicenceInformationStatus(\n request: GetLicenceInformationRequest\n ): Promise {\n const xsrfToken = await this.getSignupServerXsrfToken();\n\n return mapResponseToJson(\n await fetch(\n `${this.baseUrl}/bxp/signup/cloud/${request.cloudId}/license-information`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n 'xsrf-token': xsrfToken,\n 'web-platform': request.webPlatform || 'no-platform'\n },\n credentials: 'include'\n }\n )\n );\n }\n // for attaching a product to an existing site, xflow worked on the endpoint\n public async postProductActivate(\n request: ProductActivateRequest\n ): Promise {\n const xsrfToken = await this.getSignupServerXsrfToken();\n\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/bxp/signup/product/activate`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'xsrf-token': xsrfToken,\n 'web-platform': request.webPlatform || 'no-platform'\n },\n credentials: 'include',\n body: JSON.stringify(request)\n })\n );\n }\n // for attaching a product to an existing site using COFS, xflow worked on the endpoint\n public async postCOFSProductActivate(\n request: COFSProductActivateRequest\n ): Promise {\n const xsrfToken = await this.getSignupServerXsrfToken();\n const { cloudId } = request;\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/xflow/${cloudId}/activate`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'xsrf-token': xsrfToken,\n 'web-platform': request.webPlatform || 'no-platform'\n },\n credentials: 'include',\n body: JSON.stringify(request)\n })\n );\n }\n /**\n * Indentity calls\n */\n public async me({\n cloudSessionTokenCookie\n }: MeOptions): Promise {\n const url = `${this.baseUrl}/me`;\n const response = await this.dedupeFetch(\n `${url}-${cloudSessionTokenCookie}`,\n url,\n {\n headers: mapCookieToHeaders(cloudSessionTokenCookie),\n credentials: 'include'\n }\n );\n if (response.ok) {\n return mapMeResponseToUserProfile(await response.json());\n } else {\n throw new UnsucessfulFetchError({\n response\n });\n }\n }\n\n /**\n * Get a list of Bitbucket workspaces\n * @param nextUrl - override the request URL for pagination\n * bitbucket/user/permissions/workspaces?sort=workspace.slug\n */\n public async bitbucketWorkspaces({\n nextUrl,\n cloudSessionTokenCookie,\n urlQuery\n }: BitbucketWorkspaceOptions): Promise {\n let reqUrl = `${this.baseUrl}/bitbucket/user/permissions/workspaces`;\n if (nextUrl) {\n reqUrl = nextUrl;\n }\n if (urlQuery) {\n reqUrl = `${reqUrl}?${urlQuery}`;\n }\n\n const response = await fetch(reqUrl, {\n headers: mapCookieToHeaders(cloudSessionTokenCookie),\n credentials: 'include'\n });\n\n if (response.ok) {\n return Promise.resolve(await response.json());\n } else {\n throw new UnsucessfulFetchError({\n response\n });\n }\n }\n\n /**\n * The legacy get availableProducts call from IdentityClient\n */\n public async availableProductsLegacy({\n cloudSessionTokenCookie,\n includeInvalidSites,\n includeInvalidBitbucketSite\n }: AvailableProductsOptions): Promise {\n const reqUrl = `${this.baseUrl}/available-products/api/available-products`;\n const response = await fetch(reqUrl, {\n headers: mapCookieToHeaders(cloudSessionTokenCookie),\n credentials: 'include'\n });\n\n if (response.ok) {\n const result = await response.json();\n let sites = (result && result.sites) || [];\n\n sites = _.remove(\n _.map(sites, (site: AvailableProductsType) => {\n const products = _.map(site.availableProducts, (product) => {\n return PRODUCT_KEY_MAP[product.productType];\n }).filter((product) => product !== undefined);\n\n if (!_.isEmpty(products)) {\n return {\n adminAccess: site.adminAccess,\n cloudId: site.cloudId,\n displayName: site.displayName,\n url: site.url,\n products\n };\n } else {\n return null;\n }\n }),\n (site) => site !== undefined && site !== null\n );\n\n if (!includeInvalidSites) {\n sites = sites.filter((site: SitesType) =>\n isValidSite({\n site,\n includeInvalidBitbucketSite\n })\n );\n }\n\n return Promise.resolve(sites);\n } else {\n throw new UnsucessfulFetchError({\n response\n });\n }\n }\n\n public async patchUserProfile(\n request: PatchUserProfileRequest\n ): Promise {\n const { body, userId, cloudSessionTokenCookie } = request;\n\n const options = {\n headers: {\n 'content-type': 'application/json',\n 'Cookie': serializeCookie(cloudSessionTokenCookie)\n }\n };\n return new Promise((resolve, reject) => {\n axios\n .patch(`${this.baseUrl}/users/${userId}/manage/profile`, body, options)\n .then((response) => {\n resolve(response.data);\n })\n .catch((err) => {\n reject(err.toString());\n });\n });\n }\n\n public async getCcpHamsStatus(\n request: GetCcpHamsStatus\n ): Promise {\n const { cloudId, offeringKeys } = request;\n\n return mapResponseToJson(\n await fetch(\n `${this.baseUrl}/bag/rollout/service?cloudId=${cloudId}&offeringKeys=${offeringKeys}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json'\n },\n credentials: 'include'\n }\n )\n );\n }\n\n public async getAvailableSites(\n request: GetAvailableSitesRequest\n ): Promise {\n const { orderId, transactionAccount } = request;\n\n return mapResponseToJson(\n await fetch(\n `${this.baseUrl}/bxp/signup/v1/order/${orderId}/available-sites`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Transaction-Account': transactionAccount,\n 'web-platform': request.webPlatform || 'no-platform'\n },\n credentials: 'include'\n }\n )\n );\n }\n\n public async activateDirectBuyProduct(\n request: ActivateDirectBuyProductRequest\n ): Promise {\n const xsrfToken = await this.getSignupServerXsrfToken();\n\n return mapResponseToJson(\n await fetch(\n `${this.baseUrl}/bxp/signup/v1/order/${request.orderId}/activation`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'xsrf-token': xsrfToken,\n 'X-Transaction-Account': request.transactionAccountId,\n 'web-platform': request.webPlatform || 'no-platform'\n },\n credentials: 'include',\n body: JSON.stringify({\n timezone: request.timezone,\n region: request.region,\n site: request.site\n })\n }\n )\n );\n }\n\n public async getCloudProductInfo(\n request: GetCloudProductInfoRequest\n ): Promise {\n return mapResponseToJson(\n await fetch(\n `${this.baseUrl}/bxp/signup/v1/cloud/${request.cloudId}/product-information`,\n {\n headers: {\n 'web-platform': request.webPlatform || 'no-platform'\n },\n credentials: 'include'\n }\n )\n );\n }\n\n public async getProductEdition(\n request: GetProductEditionRequest\n ): Promise {\n const { cloudId, productKey } = request;\n\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/cloud/edition/${cloudId}/${productKey}`, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json'\n },\n credentials: 'include'\n })\n );\n }\n\n public async getConsentConfig(): Promise {\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/preferencesV2/consent-config`, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json'\n },\n credentials: 'include'\n })\n );\n }\n\n public async postConsentConfig(): Promise {\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/preferencesV2/consent-config`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n credentials: 'include'\n })\n );\n }\n\n public async postExpandFreeValidation(\n request: PostExpandFreeValidationRequest\n ): Promise {\n const { cloudId, productKeys } = request;\n\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/cloud/expand-free-validation`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n credentials: 'include',\n body: JSON.stringify({\n cloudId,\n productKeys\n })\n })\n );\n }\n\n public async getActivationAuthorization(\n request: GetActivationAuthorizationRequest\n ): Promise {\n const { productKeys, productEdition, cloudId, siteName } = request;\n const atlCohortId = getAtlCohortIdFromCookie();\n\n return mapResponseToJson(\n await fetch(\n `${\n this.baseUrl\n }/bxp/signup/activation-authorization?${new URLSearchParams({\n productKeys: productKeys.join(','),\n productEdition: productEdition,\n cloudId: cloudId ?? '',\n siteName\n })}`,\n {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Atl-Cohort-Id': atlCohortId,\n 'web-platform': request.webPlatform || 'no-platform'\n },\n credentials: 'include'\n }\n )\n );\n }\n\n public async getFeatureFlag(\n request: GetFeatureFlagRequest,\n webPlatform?: string\n ): Promise {\n const flag = request;\n\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/bxp/signup/feature-flag/${flag}`, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n 'web-platform': webPlatform || 'no-platform'\n },\n credentials: 'include'\n })\n );\n }\n\n public async getFeatureFlagSync(\n request: GetFeatureFlagSyncRequest,\n webPlatform?: string\n ): Promise {\n const flag = request;\n const atlCohortId = getAtlCohortIdFromCookie();\n\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/bxp/signup/feature-flag/sync/${flag}`, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n 'X-Atl-Cohort-Id': atlCohortId,\n 'web-platform': webPlatform || 'no-platform'\n },\n credentials: 'include'\n })\n );\n }\n\n public async getRecommendedSiteName(\n request: GetRecommendedSiteNameRequest\n ): Promise {\n const xsrfToken = await this.getSignupServerXsrfToken();\n const atlCohortId = getAtlCohortIdFromCookie();\n const headers = mapCookieToHeaders(request.cloudSessionTokenCookie);\n Object.assign(headers, {\n 'Content-Type': 'application/json',\n 'xsrf-token': xsrfToken,\n 'X-Atl-Cohort-Id': atlCohortId,\n 'web-platform': request.webPlatform || 'no-platform'\n });\n\n const response = await mapResponseToJson(\n await fetch(`${this.baseUrl}/bxp/signup/site/recommended-name`, {\n method: 'POST',\n headers,\n credentials: 'include',\n body: JSON.stringify(request)\n })\n );\n\n return response;\n }\n\n public async getAccountOrgs({\n includeVortexMode,\n webPlatform\n }: GetAccountOrgsRequest): Promise {\n const params = includeVortexMode === true ? `?includeVortexMode=true` : '';\n\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/bxp/signup/account/orgs${params}`, {\n method: 'GET',\n headers: {\n 'Content-Type': 'application/json',\n 'web-platform': webPlatform || 'no-platform'\n },\n credentials: 'include'\n })\n );\n }\n\n public async cofsCreateOrg(\n request: CreateOrgRequest\n ): Promise {\n const xsrfToken = await this.getSignupServerXsrfToken();\n const atlCohortId = getAtlCohortIdFromCookie();\n\n return mapResponseToJson(\n await fetch(`${this.baseUrl}/bxp/signup/cofs-create-organization`, {\n method: 'POST',\n headers: {\n 'Accept': 'application/json',\n 'Content-Type': 'application/json',\n 'xsrf-token': xsrfToken,\n 'X-Atl-Cohort-Id': atlCohortId,\n 'web-platform': request.webPlatform || 'no-platform'\n },\n credentials: 'include',\n body: JSON.stringify(request)\n })\n );\n }\n\n public async cofsActivateProductExisting(\n request: CofsActivateProductExistingRequest\n ): Promise {\n const xsrfToken = await this.getSignupServerXsrfToken();\n const atlCohortId = getAtlCohortIdFromCookie();\n\n const upstreamResponse =\n await mapResponseToJson(\n await fetch(\n `${this.baseUrl}/bxp/signup/cofs-activate-product-existing`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'xsrf-token': xsrfToken,\n 'X-Atl-Cohort-Id': atlCohortId,\n 'web-platform': request.webPlatform || 'no-platform'\n },\n credentials: 'include',\n body: JSON.stringify(request)\n }\n )\n );\n\n return upstreamResponse;\n }\n\n public async bitbucketValidateWorkspaceSlug({\n workspaceSlug\n }: BitbucketValidateWorkspaceSlugRequest): Promise {\n return mapResponseToJson(\n await fetch(\n `${this.baseUrl}/bitbucket/api/internal/workspace/slug/validate`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n credentials: 'include',\n body: JSON.stringify({\n workspace_slug: workspaceSlug\n })\n }\n )\n );\n }\n}\n","var util;\n(function (util) {\n util.assertEqual = (val) => val;\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array\n .map((val) => (typeof val === \"string\" ? `'${val}'` : val))\n .join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nvar objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nconst ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nconst getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then &&\n typeof data.then === \"function\" &&\n data.catch &&\n typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n\nconst ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nconst quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nclass ZodError extends Error {\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n get errors() {\n return this.issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly equal to `\n : issue.inclusive\n ? `greater than or equal to `\n : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `less than or equal to`\n : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact\n ? `exactly`\n : issue.inclusive\n ? `smaller than or equal to`\n : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\n\nlet overrideErrorMap = errorMap;\nfunction setErrorMap(map) {\n overrideErrorMap = map;\n}\nfunction getErrorMap() {\n return overrideErrorMap;\n}\n\nconst makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message || errorMessage,\n };\n};\nconst EMPTY_PATH = [];\nfunction addIssueToContext(ctx, issueData) {\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nclass ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n syncPairs.push({\n key: await pair.key,\n value: await pair.value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (typeof value.value !== \"undefined\" || pair.alwaysSet) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nconst INVALID = Object.freeze({\n status: \"aborted\",\n});\nconst DIRTY = (value) => ({ status: \"dirty\", value });\nconst OK = (value) => ({ status: \"valid\", value });\nconst isAborted = (x) => x.status === \"aborted\";\nconst isDirty = (x) => x.status === \"dirty\";\nconst isValid = (x) => x.status === \"valid\";\nconst isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n\nvar errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message === null || message === void 0 ? void 0 : message.message;\n})(errorUtil || (errorUtil = {}));\n\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (this._key instanceof Array) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n if (typeof ctx.data === \"undefined\") {\n return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };\n }\n return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nclass ZodType {\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n }\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n var _a;\n const ctx = {\n common: {\n issues: [],\n async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false,\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap,\n async: true,\n },\n path: (params === null || params === void 0 ? void 0 : params.path) || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult)\n ? maybeAsyncResult\n : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\"\n ? refinementData(val, ctx)\n : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this, this._def);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[a-z][a-z0-9]*$/;\nconst ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/;\nconst uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\nconst emailRegex = /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst emojiRegex = /^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$/u;\nconst ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;\nconst ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\n// Adapted from https://stackoverflow.com/a/3143231\nconst datetimeRegex = (args) => {\n if (args.precision) {\n if (args.offset) {\n return new RegExp(`^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}\\\\.\\\\d{${args.precision}}(([+-]\\\\d{2}(:?\\\\d{2})?)|Z)$`);\n }\n else {\n return new RegExp(`^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}\\\\.\\\\d{${args.precision}}Z$`);\n }\n }\n else if (args.precision === 0) {\n if (args.offset) {\n return new RegExp(`^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}(([+-]\\\\d{2}(:?\\\\d{2})?)|Z)$`);\n }\n else {\n return new RegExp(`^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}Z$`);\n }\n }\n else {\n if (args.offset) {\n return new RegExp(`^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}(\\\\.\\\\d+)?(([+-]\\\\d{2}(:?\\\\d{2})?)|Z)$`);\n }\n else {\n return new RegExp(`^\\\\d{4}-\\\\d{2}-\\\\d{2}T\\\\d{2}:\\\\d{2}:\\\\d{2}(\\\\.\\\\d+)?Z$`);\n }\n }\n};\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nclass ZodString extends ZodType {\n constructor() {\n super(...arguments);\n this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n /**\n * @deprecated Use z.string().min(1) instead.\n * @see {@link ZodString.min}\n */\n this.nonempty = (message) => this.min(1, errorUtil.errToObj(message));\n this.trim = () => new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n this.toLowerCase = () => new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n this.toUpperCase = () => new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n }\n //\n );\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch (_a) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n var _a;\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === \"undefined\" ? null : options === null || options === void 0 ? void 0 : options.precision,\n offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options === null || options === void 0 ? void 0 : options.position,\n ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n var _a;\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / Math.pow(10, decCount);\n}\nclass ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" ||\n (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null, min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" ||\n ch.kind === \"int\" ||\n ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = BigInt(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive\n ? input.data < check.value\n : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive\n ? input.data > check.value\n : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n var _a;\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false,\n ...processCreateParams(params),\n });\n};\nclass ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n ...processCreateParams(params),\n });\n};\nclass ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nclass ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nclass ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nclass ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nclass ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nclass ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nclass ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nclass ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nclass ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nclass ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n return (this._cached = { shape, keys });\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever &&\n this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") ;\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n syncPairs.push({\n key,\n value: await pair.value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n var _a, _b, _c, _d;\n const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: (_d = errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // (def: Def) =>\n // (\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge(\n // merging: Incoming\n // ): //ZodObject = (merging) => {\n // ZodObject<\n // extendShape>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n util.objectKeys(mask).forEach((key) => {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n util.objectKeys(this.shape).forEach((key) => {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n });\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nclass ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return Object.keys(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else {\n return null;\n }\n};\nclass ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util\n .objectKeys(a)\n .filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date &&\n bType === ZodParsedType.date &&\n +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nclass ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\nclass ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nclass ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nclass ZodMap extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nclass ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nclass ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap,\n ctx.schemaErrorMap,\n getErrorMap(),\n errorMap,\n ].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n return OK(async (...args) => {\n const error = new ZodError([]);\n const parsedArgs = await this._def.args\n .parseAsync(args, params)\n .catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await fn(...parsedArgs);\n const parsedReturns = await this._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n return OK((...args) => {\n const parsedArgs = this._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = fn(...parsedArgs.data);\n const parsedReturns = this._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args\n ? args\n : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nclass ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nclass ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nclass ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (this._def.values.indexOf(input.data) === -1) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values) {\n return ZodEnum.create(values);\n }\n exclude(values) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));\n }\n}\nZodEnum.create = createZodEnum;\nclass ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string &&\n ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (nativeEnumValues.indexOf(input.data) === -1) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nclass ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise &&\n ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise\n ? ctx.data\n : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nclass ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data);\n if (ctx.common.async) {\n return Promise.resolve(processed).then((processed) => {\n return this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n });\n }\n else {\n return this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc\n // effect: RefinementEffect\n ) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return base;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema\n ._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx })\n .then((base) => {\n if (!isValid(base))\n return base;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ status: status.value, value: result }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nclass ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nclass ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nclass ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\"\n ? params.default\n : () => params.default,\n ...processCreateParams(params),\n });\n};\nclass ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nclass ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nconst BRAND = Symbol(\"zod_brand\");\nclass ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nclass ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nconst custom = (check, params = {}, \n/*\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) => {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n var _a, _b;\n if (!check(data)) {\n const p = typeof params === \"function\"\n ? params(data)\n : typeof params === \"string\"\n ? { message: params }\n : params;\n const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n ctx.addIssue({ code: \"custom\", ...p2, fatal: _fatal });\n }\n });\n return ZodAny.create();\n};\nconst late = {\n object: ZodObject.lazycreate,\n};\nvar ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\nconst instanceOfType = (\n// const instanceOfType = any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nconst coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nconst NEVER = INVALID;\n\nvar z = /*#__PURE__*/Object.freeze({\n __proto__: null,\n defaultErrorMap: errorMap,\n setErrorMap: setErrorMap,\n getErrorMap: getErrorMap,\n makeIssue: makeIssue,\n EMPTY_PATH: EMPTY_PATH,\n addIssueToContext: addIssueToContext,\n ParseStatus: ParseStatus,\n INVALID: INVALID,\n DIRTY: DIRTY,\n OK: OK,\n isAborted: isAborted,\n isDirty: isDirty,\n isValid: isValid,\n isAsync: isAsync,\n get util () { return util; },\n get objectUtil () { return objectUtil; },\n ZodParsedType: ZodParsedType,\n getParsedType: getParsedType,\n ZodType: ZodType,\n ZodString: ZodString,\n ZodNumber: ZodNumber,\n ZodBigInt: ZodBigInt,\n ZodBoolean: ZodBoolean,\n ZodDate: ZodDate,\n ZodSymbol: ZodSymbol,\n ZodUndefined: ZodUndefined,\n ZodNull: ZodNull,\n ZodAny: ZodAny,\n ZodUnknown: ZodUnknown,\n ZodNever: ZodNever,\n ZodVoid: ZodVoid,\n ZodArray: ZodArray,\n ZodObject: ZodObject,\n ZodUnion: ZodUnion,\n ZodDiscriminatedUnion: ZodDiscriminatedUnion,\n ZodIntersection: ZodIntersection,\n ZodTuple: ZodTuple,\n ZodRecord: ZodRecord,\n ZodMap: ZodMap,\n ZodSet: ZodSet,\n ZodFunction: ZodFunction,\n ZodLazy: ZodLazy,\n ZodLiteral: ZodLiteral,\n ZodEnum: ZodEnum,\n ZodNativeEnum: ZodNativeEnum,\n ZodPromise: ZodPromise,\n ZodEffects: ZodEffects,\n ZodTransformer: ZodEffects,\n ZodOptional: ZodOptional,\n ZodNullable: ZodNullable,\n ZodDefault: ZodDefault,\n ZodCatch: ZodCatch,\n ZodNaN: ZodNaN,\n BRAND: BRAND,\n ZodBranded: ZodBranded,\n ZodPipeline: ZodPipeline,\n custom: custom,\n Schema: ZodType,\n ZodSchema: ZodType,\n late: late,\n get ZodFirstPartyTypeKind () { return ZodFirstPartyTypeKind; },\n coerce: coerce,\n any: anyType,\n array: arrayType,\n bigint: bigIntType,\n boolean: booleanType,\n date: dateType,\n discriminatedUnion: discriminatedUnionType,\n effect: effectsType,\n 'enum': enumType,\n 'function': functionType,\n 'instanceof': instanceOfType,\n intersection: intersectionType,\n lazy: lazyType,\n literal: literalType,\n map: mapType,\n nan: nanType,\n nativeEnum: nativeEnumType,\n never: neverType,\n 'null': nullType,\n nullable: nullableType,\n number: numberType,\n object: objectType,\n oboolean: oboolean,\n onumber: onumber,\n optional: optionalType,\n ostring: ostring,\n pipeline: pipelineType,\n preprocess: preprocessType,\n promise: promiseType,\n record: recordType,\n set: setType,\n strictObject: strictObjectType,\n string: stringType,\n symbol: symbolType,\n transformer: effectsType,\n tuple: tupleType,\n 'undefined': undefinedType,\n union: unionType,\n unknown: unknownType,\n 'void': voidType,\n NEVER: NEVER,\n ZodIssueCode: ZodIssueCode,\n quotelessJson: quotelessJson,\n ZodError: ZodError\n});\n\nexport { BRAND, DIRTY, EMPTY_PATH, INVALID, NEVER, OK, ParseStatus, ZodType as Schema, ZodAny, ZodArray, ZodBigInt, ZodBoolean, ZodBranded, ZodCatch, ZodDate, ZodDefault, ZodDiscriminatedUnion, ZodEffects, ZodEnum, ZodError, ZodFirstPartyTypeKind, ZodFunction, ZodIntersection, ZodIssueCode, ZodLazy, ZodLiteral, ZodMap, ZodNaN, ZodNativeEnum, ZodNever, ZodNull, ZodNullable, ZodNumber, ZodObject, ZodOptional, ZodParsedType, ZodPipeline, ZodPromise, ZodRecord, ZodType as ZodSchema, ZodSet, ZodString, ZodSymbol, ZodEffects as ZodTransformer, ZodTuple, ZodType, ZodUndefined, ZodUnion, ZodUnknown, ZodVoid, addIssueToContext, anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, coerce, custom, dateType as date, z as default, errorMap as defaultErrorMap, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, getErrorMap, getParsedType, instanceOfType as instanceof, intersectionType as intersection, isAborted, isAsync, isDirty, isValid, late, lazyType as lazy, literalType as literal, makeIssue, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, objectUtil, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, quotelessJson, recordType as record, setType as set, setErrorMap, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, util, voidType as void, z };\n","import { Schema, z } from 'zod';\n\nexport enum AppearanceType {\n Toggle = 'TOGGLE',\n Dropdown = 'DROPDOWN'\n}\n\nexport type Appearance = {\n type: 'TOGGLE' | 'DROPDOWN';\n helpText: string;\n};\n\nexport const AppearanceSchema: Schema = z.object({\n type: z.nativeEnum(AppearanceType),\n helpText: z.string()\n});\n","import { z } from 'zod';\n\n/**\n * Media type of the asset resource. Includes images, attachments, presentations, spreadsheets, pdfdocuments, archives, and videos.\n * @typedef ContentType\n */\n\nexport const ContentTypeSchema = z.enum([\n 'image/gif',\n 'image/jpeg',\n 'image/png',\n 'application/json',\n 'application/pdf',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'application/vnd.oasis.opendocument.presentation',\n 'application/vnd.oasis.opendocument.spreadsheet',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'application/gzip',\n 'application/x-tar',\n 'application/x-7z-compressed',\n 'application/zip',\n 'video/mp4',\n 'video/mpeg'\n]);\n\nexport type ContentType = z.infer;\n","import { Schema, z } from 'zod';\n\nexport type Channel = 'web' | 'mobile' | 'desktop';\n\nexport const ChannelSchema: Schema = z.union([\n z.literal('web'),\n z.literal('mobile'),\n z.literal('desktop')\n]);\n","import { Schema, z } from 'zod';\n\n/**\n * Activation status of a definition.\n */\nexport type DefinitionStatusType = 'active' | 'inactive';\n\n/**\n * Activation status of this zone definition.\n */\n\nexport enum DefinitionStatus {\n Active = 'active',\n Inactive = 'inactive'\n}\n\nexport const DefinitionStatusSchema: Schema =\n z.nativeEnum(DefinitionStatus);\n","import { Schema, z } from 'zod';\nimport { Appearance, AppearanceSchema } from '../commons';\n\n/**\n * Common properties of module definition configs\n * @typedef BaseFieldDefinition\n * @property - name : name of the field\n * @property - label : a human readable name used in the management tool as a label for the field.\n * @property - description : used in the management tool to provide guidance to editors.\n * @property - appearance : used in the management tool to alter the editing experience.\n * @property - validations : an optional object for defining rules about how a module definition can be instantiated.\n */\nexport type BaseFieldDefinition = {\n name: string;\n label: string;\n description?: string;\n appearance?: Appearance;\n validations?: {\n isRequired?: boolean;\n };\n};\n\nexport const BaseFieldDefinitionSchema: Schema = z.object({\n name: z.string(),\n label: z.string(),\n description: z.string().optional(),\n appearance: AppearanceSchema.optional(),\n validations: z\n .object({\n isRequired: z.boolean().optional()\n })\n .optional()\n});\n","import { Schema, z } from 'zod';\nimport { BaseFieldDefinition, BaseFieldDefinitionSchema } from './base';\n\nimport { ContentType, ContentTypeSchema } from '../commons';\n\nexport namespace AssetFieldDefinition {\n export const TYPE = 'assetReference';\n}\n\n/**\n * Field definition of type asset\n * @typedef AssetFieldDefinition\n * @property - type : type of the field.\n * @property - i18n : an optional translatable properties of the field.\n * @property - validations : an optional object for defining rules about how a module definition can be instantiated. (contentTypeRestrictions - allowed content types.)\n */\nexport type AssetFieldDefinition = BaseFieldDefinition & {\n type: typeof AssetFieldDefinition.TYPE;\n i18n?: boolean;\n validations?: {\n contentTypeRestrictions?: ReadonlyArray;\n };\n};\n\nexport const AssetFieldDefinitionSchema: Schema =\n BaseFieldDefinitionSchema.and(\n z.object({\n type: z.literal(AssetFieldDefinition.TYPE),\n i18n: z.boolean().optional(),\n validations: z\n .object({\n contentTypeRestrictions: z.array(ContentTypeSchema).optional()\n })\n .optional()\n })\n );\n","import { Schema, z } from 'zod';\nimport { BaseFieldDefinition, BaseFieldDefinitionSchema } from './base';\n\nexport namespace DateFieldDefinition {\n export const TYPE = 'date';\n}\n\n/**\n * Field definition of type date\n * @typedef DateFieldDefinition\n * @property - type : type of the field.\n * @property - defaultValue : default value if value isn't set.\n * @property - validations : an optional object for defining rules about how a module definition can be instantiated.\n */\nexport type DateFieldDefinition = BaseFieldDefinition & {\n type: typeof DateFieldDefinition.TYPE;\n defaultValue?: string;\n validations?: {\n min?: string;\n max?: string;\n };\n};\n\nexport const DateFieldDefinitionSchema: Schema =\n BaseFieldDefinitionSchema.and(\n z.object({\n type: z.literal(DateFieldDefinition.TYPE),\n defaultValue: z.string().optional(),\n validations: z\n .object({\n min: z.string().optional(),\n max: z.string().optional()\n })\n .optional()\n })\n );\n","import { Schema, z } from 'zod';\nimport { BaseFieldDefinition, BaseFieldDefinitionSchema } from './base';\n\nexport namespace StringFieldDefinition {\n export const TYPE = 'string';\n}\n\n/**\n * Field definition of type string\n * @typedef StringFieldDefinition\n * @property - type : type of the field.\n * @property - defaultValue : default value if value isn't set.\n * @property - i18n : translatable properties of the field.\n * @property - validations : an optional object for defining rules about how a module definition can be instantiated.\n */\nexport type StringFieldDefinition = BaseFieldDefinition & {\n type: typeof StringFieldDefinition.TYPE;\n defaultValue?: string;\n i18n?: boolean;\n validations?: {\n minLength?: number;\n maxLength?: number;\n pattern?: string;\n };\n};\n\nexport const StringFieldDefinitionSchema = BaseFieldDefinitionSchema.and(\n z.object({\n type: z.literal(StringFieldDefinition.TYPE),\n defaultValue: z.string().optional(),\n i18n: z.boolean().optional(),\n validations: z\n .object({\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n pattern: z.string().optional()\n })\n .optional()\n })\n);\n\nexport namespace BooleanFieldDefinition {\n export const TYPE = 'boolean';\n}\n\n/**\n * Field definition of type boolean\n * @typedef BooleanFieldDefinition\n * @property - type : type of the field.\n * @property - defaultValue : default value if value isn't set.\n */\nexport type BooleanFieldDefinition = BaseFieldDefinition & {\n type: typeof BooleanFieldDefinition.TYPE;\n defaultValue?: boolean;\n};\n\nexport const BooleanFieldDefinitionSchema: Schema =\n BaseFieldDefinitionSchema.and(\n z.object({\n type: z.literal(BooleanFieldDefinition.TYPE),\n defaultValue: z.boolean().optional()\n })\n );\n\nexport namespace NumberFieldDefinition {\n export const TYPE = 'number';\n}\n\n/**\n * Field definition of type number\n * @typedef NumberFieldDefinition\n * @property - type : type of the field.\n * @property - defaultValue : default value if value isn't set.\n * @property - validations : an optional object for defining rules about how a module definition can be instantiated.\n */\nexport type NumberFieldDefinition = BaseFieldDefinition & {\n type: typeof NumberFieldDefinition.TYPE;\n defaultValue?: number;\n validations?: {\n isInteger?: boolean;\n min?: number;\n max?: number;\n };\n};\n\nexport const NumberFieldDefinitionSchema: Schema =\n BaseFieldDefinitionSchema.and(\n z.object({\n type: z.literal(NumberFieldDefinition.TYPE),\n defaultValue: z.number().optional(),\n validations: z\n .object({\n isInteger: z.boolean().optional(),\n min: z.number().optional(),\n max: z.number().optional()\n })\n .optional()\n })\n );\n\n/**\n * Primitive type Field definition (string, number, boolean)\n * @typedef PrimitiveFieldDefinition\n */\nexport type PrimitiveFieldDefinition =\n | StringFieldDefinition\n | BooleanFieldDefinition\n | NumberFieldDefinition;\n\nexport const PrimitiveFieldDefinitionSchema = StringFieldDefinitionSchema.or(\n BooleanFieldDefinitionSchema\n).or(NumberFieldDefinitionSchema);\n","import { Schema, z } from 'zod';\nimport { BaseFieldDefinition, BaseFieldDefinitionSchema } from './base';\n\nexport namespace RichTextFieldDefinition {\n export const TYPE = 'richText';\n}\n\n/**\n * Field definition of type richtext\n * @typedef RichTextFieldDefinition\n * @property - type : type of the field.\n * @property - i18n : translatable properties of the field.\n */\nexport type RichTextFieldDefinition = BaseFieldDefinition & {\n type: typeof RichTextFieldDefinition.TYPE;\n i18n?: boolean;\n};\n\nexport const RichTextFieldDefinitionSchema: Schema =\n BaseFieldDefinitionSchema.and(\n z.object({\n type: z.literal(RichTextFieldDefinition.TYPE),\n i18n: z.boolean().optional()\n })\n );\n","import { Schema, z } from 'zod';\nimport { BaseFieldDefinition, BaseFieldDefinitionSchema } from './base';\n\nexport namespace EnumFieldDefinition {\n export const TYPE = 'enum';\n}\n/***\n * Field definition of type enum\n * @typedef EnumFieldDefinition\n * @property - type: type of field\n * @property - options : properties of the field\n */\nexport type EnumFieldDefinition = BaseFieldDefinition & {\n type: typeof EnumFieldDefinition.TYPE;\n validations: {\n cases: ReadonlyArray;\n };\n};\n\nexport const EnumFieldDefinitionSchema: Schema =\n BaseFieldDefinitionSchema.and(\n z.object({\n type: z.literal(EnumFieldDefinition.TYPE),\n validations: z.object({\n cases: z.array(z.string())\n })\n })\n );\n","import { Schema, z } from 'zod';\nimport { BaseFieldDefinition, BaseFieldDefinitionSchema } from './base';\nimport { FieldDefinition, FieldDefinitionSchema } from './composite';\n\nexport namespace ObjectFieldDefinition {\n export const TYPE = 'object';\n}\n\n/**\n * Field definition of type object\n * @typedef ObjectFieldDefinition\n * @property - type : type of the field.\n * @property - fieldDefinitions : array of field definitions.\n */\n\nexport type ObjectFieldDefinition = BaseFieldDefinition & {\n type: typeof ObjectFieldDefinition.TYPE;\n fieldDefinitions: ReadonlyArray;\n};\n\nexport const ObjectFieldDefinitionSchema: Schema =\n BaseFieldDefinitionSchema.and(\n z.object({\n type: z.literal(ObjectFieldDefinition.TYPE),\n fieldDefinitions: z.array(z.lazy(() => FieldDefinitionSchema))\n })\n );\n","import { Schema, z } from 'zod';\nimport { BaseFieldDefinition, BaseFieldDefinitionSchema } from './base';\nimport { FieldDefinition, FieldDefinitionSchema } from './composite';\n\nexport namespace ArrayFieldDefinition {\n export const TYPE = 'array';\n}\n\n/**\n * Field definition of type array\n * @typedef ArrayFieldDefinition\n * @property - type : type of the field.\n * @property - fieldDefinition : type of the elements within the array.\n * @property - validations : an optional object for defining rules about how a module definition can be instantiated.\n */\n\nexport type ArrayFieldDefinition = BaseFieldDefinition & {\n type: typeof ArrayFieldDefinition.TYPE;\n fieldDefinition: FieldDefinition;\n validations?: {\n minItems?: number;\n maxItems?: number;\n hasUniqueItems?: boolean;\n };\n};\n\nexport const ArrayFieldDefinitionSchema: Schema =\n BaseFieldDefinitionSchema.and(\n z.object({\n type: z.literal(ArrayFieldDefinition.TYPE),\n fieldDefinition: z.lazy(() => FieldDefinitionSchema),\n validations: z\n .object({\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n hasUniqueItems: z.boolean().optional()\n })\n .optional()\n })\n );\n","import { Schema } from 'zod';\nimport {\n PrimitiveFieldDefinition,\n PrimitiveFieldDefinitionSchema\n} from './primitive';\nimport { DateFieldDefinition, DateFieldDefinitionSchema } from './date';\nimport {\n RichTextFieldDefinition,\n RichTextFieldDefinitionSchema\n} from './richtext';\nimport { AssetFieldDefinition, AssetFieldDefinitionSchema } from './asset';\nimport { EnumFieldDefinition, EnumFieldDefinitionSchema } from './enum';\n\nimport { ObjectFieldDefinitionSchema, ObjectFieldDefinition } from './object';\nimport { ArrayFieldDefinition, ArrayFieldDefinitionSchema } from './array';\n\n/**\n * All the field definition types.\n * @typedef FieldDefinition\n */\nexport type FieldDefinition =\n | PrimitiveFieldDefinition\n | DateFieldDefinition\n | RichTextFieldDefinition\n | AssetFieldDefinition\n | ObjectFieldDefinition\n | ArrayFieldDefinition\n | EnumFieldDefinition;\n\nexport const FieldDefinitionSchema: Schema =\n PrimitiveFieldDefinitionSchema.or(AssetFieldDefinitionSchema)\n .or(DateFieldDefinitionSchema)\n .or(RichTextFieldDefinitionSchema)\n .or(ArrayFieldDefinitionSchema)\n .or(ObjectFieldDefinitionSchema)\n .or(EnumFieldDefinitionSchema);\n","import { Schema, z } from 'zod';\nimport { DefinitionStatusType, DefinitionStatusSchema } from './schema';\n\nexport type ModuleRestriction = {\n readonly name: string;\n readonly version: string;\n};\n\nexport type ZoneValidation = {\n readonly isInheritable?: boolean;\n readonly moduleRestrictions?: ReadonlyArray;\n};\n\nexport const ZoneValidationSchema: Schema = z.object({\n isInheritable: z.boolean().optional(),\n moduleRestrictions: z\n .array(\n z.object({\n name: z.string(),\n version: z.string()\n })\n )\n .optional()\n});\n\n/**\n * Zones are different sections of a surface.\n * @property - label - a human readable name.\n * @property - description - a human readable description.\n * @property - status - represents whether new surface definitions are allowed to use this zone definition.\n * @property - validations - an optional object for defining rules about how a zones behave both during Surface instantiation and in Module selection.\n */\n\nexport type ZoneDefinition = {\n readonly name: string;\n readonly label: string;\n readonly description: string;\n readonly status: DefinitionStatusType;\n readonly validations?: ZoneValidation;\n};\nexport const ZoneDefinitionSchema: Schema = z.object({\n name: z.string(),\n label: z.string(),\n description: z.string(),\n status: DefinitionStatusSchema,\n validations: ZoneValidationSchema.optional()\n});\n","import { z, Schema } from 'zod';\nimport {\n Channel,\n ChannelSchema,\n DefinitionStatusType,\n DefinitionStatusSchema,\n FieldDefinition,\n FieldDefinitionSchema\n} from './schema';\nimport { ZoneDefinition, ZoneDefinitionSchema } from './zone-definition';\n\n/**\n * Structure of a module definition.\n * @typedef ModuleDefinition\n * @property - label - A human readable name of the web module created from this module definition.\n * @property - description - A human readable description.\n * @property - status - 'active' / 'inactive' state of the web module.\n * @property - channels - An array indicating where module instances of this type are allowed to appear.\n * @property - fieldDefinitions - An array of field definitions that define the type of data that can be placed on a module configuration.\n * @property - zoneDefinitions - An optional array of zone definitions that can be used to subdivide the module for the purposes of placing children modules within the module configuration.\n * @property - validations - An optional object for defining rules about how a module configuration can be instantiated.\n */\nexport type ModuleDefinition = {\n readonly label: string;\n readonly description: string;\n readonly status: DefinitionStatusType;\n readonly channels: ReadonlyArray;\n readonly fieldDefinitions: ReadonlyArray;\n readonly zonesDefinitions?: ReadonlyArray;\n readonly validations?: {\n surfaceRestrictions?: ReadonlyArray<{\n readonly name?: string;\n readonly version?: string;\n }>;\n };\n};\n\nexport const ModuleDefinitionSchema: Schema = z.object({\n label: z.string(),\n description: z.string(),\n status: DefinitionStatusSchema,\n channels: z.array(ChannelSchema),\n fieldDefinitions: z.array(FieldDefinitionSchema),\n zonesDefinitions: z.array(ZoneDefinitionSchema).optional(),\n validations: z\n .object({\n surfaceRestrictions: z\n .array(\n z.object({\n name: z.string().optional(),\n version: z.string().optional()\n })\n )\n .optional()\n })\n .optional()\n});\n\n/**\n * Indexable version type of a module defintion.\n * @typedef ModuleDefinitionVersion\n * @property - version - Format in whole number.\n */\nexport type ModuleDefinitionVersion = {\n readonly [version: string]: ModuleDefinition;\n};\n\nexport const ModuleDefinitionVersionSchema: Schema =\n z.record(z.string(), ModuleDefinitionSchema);\n\n/**\n * Structure of a web module definition.\n * @typedef WebModuleDefinition\n * @property - name - The type of module instance that will be created from this definition.\n * @property - schema - A semantic version.\n * @property - type - Defines a web module definition type.\n * @property - versions - Supports module definition versioning.\n */\nexport type WebModuleDefinition = {\n readonly name: string;\n readonly schema: string;\n readonly type: 'module';\n readonly versions: ModuleDefinitionVersion;\n};\n\nexport const WebModuleDefinitionSchema: Schema = z.object({\n name: z.string(),\n schema: z.string(),\n type: z.literal('module'),\n versions: ModuleDefinitionVersionSchema\n});\n\n/**\n * Create a versioned module from a module definition json.\n * @param definition Module definition json, conforming with ModuleDefinition type.\n * @returns - Module definition object.\n * @example\n * ```ts\n * import { createModuleDefinitionVersion } from \"@atlassiansox/bxp-definition-sdk\";\n *\n * export const ExampleWebModule = createModuleDefinitionVersion({\n * {\n * label: 'signup-wac',\n * description: 'Test module description',\n * status: 'active',\n * channels: ['web', 'mobile'],\n * fieldDefinitions: [\n * {\n * type: \"string\",\n * name: \"title\",\n * validations: {\n * isRequired: true,\n * }\n * },\n * {\n * type: \"boolean\",\n * name: \"isProduction\",\n * validations: {\n * isRequired: true,\n * }\n * }\n * ]\n * }\n * });\n * ```\n */\n\nexport function createModuleDefinitionVersion(\n moduleDefinition: M\n): M {\n return ModuleDefinitionSchema.parse(moduleDefinition) as M;\n}\n","import { Schema, z } from 'zod';\n\n/**\n * Represents an italic styling\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/marks/em\n *\n * @typedef EmMark\n * @property - type : type of node\n */\nexport type EmMark = {\n readonly type: 'em';\n};\n\nexport const EmMarkSchema: Schema = z.object({\n type: z.literal('em')\n});\n/**\n * Represents a bold styling\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/marks/strong\n *\n * @typedef StrongMark\n * @property - type : type of node\n */\nexport type StrongMark = {\n readonly type: 'strong';\n};\n\nexport const StrongMarkSchema: Schema = z.object({\n type: z.literal('strong')\n});\n/**\n * Represents an underline styling\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/marks/underline\n *\n * @typedef UnderlineMark\n * @property - type : type of node\n */\nexport type UnderlineMark = {\n readonly type: 'underline';\n};\n\nexport const UnderlineMarkSchema: Schema = z.object({\n type: z.literal('underline')\n});\n\n/**\n * Represents additional styling for links\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/marks/link/#attributes\n *\n * @typedef LinkMarkAttributes\n * @property - href : URI\n * @property - title\n * @property - id\n * @property - collection\n * @property - occurrenceKey\n */\nexport type LinkMarkAttributes = {\n readonly href: string;\n readonly title?: string;\n readonly id?: string;\n readonly collection?: string;\n readonly occurrenceKey?: string;\n};\n\nexport const LinkMarkAttributesSchema: Schema = z.object({\n href: z.string(),\n title: z.string().optional(),\n id: z.string().optional(),\n collection: z.string().optional(),\n occurrenceKey: z.string().optional()\n});\n\n/**\n * Represents a hyperlink\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/marks/link\n *\n * @typedef LinkMark\n * @property - type : type of node\n * @property - attrs : additional styling for the link\n */\nexport type LinkMark = {\n readonly type: 'link';\n readonly attrs: LinkMarkAttributes;\n};\n\nexport const LinkMarkSchema: Schema = z.object({\n type: z.literal('link'),\n attrs: LinkMarkAttributesSchema\n});\n\n/**\n * Represents additional styling for string values\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/structure/#marks\n *\n * @typedef Mark\n */\nexport type Mark = EmMark | LinkMark | StrongMark | UnderlineMark;\n\nexport const MarkSchema = z.union([\n EmMarkSchema,\n LinkMarkSchema,\n StrongMarkSchema,\n UnderlineMarkSchema\n]);\n\n/**\n * Represents a text\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/nodes/text\n *\n * @typedef Text\n * @property - type : type of node\n * @property - text : text value\n * @property - marks : array of additional styling, @typedef Mark , for the text\n */\nexport type Text = {\n readonly type: 'text';\n readonly text: string;\n readonly marks?: readonly Mark[];\n};\n\nexport const TextSchema: Schema = z.object({\n type: z.literal('text'),\n text: z.string(),\n marks: z.array(MarkSchema).optional()\n});\n\n/**\n * Represents a new line in a text string\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/nodes/hardBreak\n *\n * @typedef HardBreak\n * @property - type : type of node\n */\nexport type HardBreak = {\n readonly type: 'hardBreak';\n};\n\nexport const HardBreakSchema: Schema = z.object({\n type: z.literal('hardBreak')\n});\n\n/**\n * Inline Node consists of nodes that can be used within a TopLevelNode\n * eg : Paragraph -> Text\n * Only the supported top level nodes are listed below.\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/structure/#inline-nodes\n *\n * @typedef InlineNode\n */\nexport type InlineNode = HardBreak | Text;\n\nexport const InlineNodeSchema = z.union([HardBreakSchema, TextSchema]);\n\n/**\n * Represents unordered list\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/nodes/bulletList\n *\n * @typedef BulletList\n * @property - type : type of node\n * @property - content : array containing ListItem nodes\n */\nexport type BulletList = {\n readonly type: 'bulletList';\n readonly content: readonly ListItem[];\n};\n\nexport const BulletListSchema: Schema = z.object({\n type: z.literal('bulletList'),\n content: z.array(z.lazy(() => ListItemSchema))\n});\n\n/**\n * Represents heading attributes\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/nodes/heading/#attributes\n *\n * @typedef HeadingAttributes\n * @property - level : represents depth of heading\n */\n\nexport const HeadingAttributesSchema = z.object({\n level: z.union([\n z.literal(1),\n z.literal(2),\n z.literal(3),\n z.literal(4),\n z.literal(5),\n z.literal(6)\n ])\n});\nexport type HeadingAttributes = z.infer;\n\n/**\n * Represents heading\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/nodes/heading\n *\n * @typedef Heading\n * @property - type : type of node\n * @property - content : array containing @typedef InlineNode\n */\nexport type Heading = {\n readonly type: 'heading';\n readonly attrs: HeadingAttributes;\n readonly content?: readonly InlineNode[];\n};\n\nexport const HeadingSchema: Schema = z.object({\n type: z.literal('heading'),\n attrs: HeadingAttributesSchema,\n content: z.array(InlineNodeSchema).optional()\n});\n\n/**\n * Represents attributes for an ordered list\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/nodes/orderedList/#attributes\n *\n * @typedef OrderedListAttributes\n * @property - order : number of the first item in the list. When not specified, the list starts from 1.\n * eg : order of 3 would mean the list starts at number three.\n */\nexport type OrderedListAttributes = {\n readonly order?: number;\n};\n\nexport const OrderedListAttributesSchema: Schema =\n z.object({\n order: z.number().optional()\n });\n\n/**\n * Represents an ordered list\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/nodes/orderedList\n *\n * @typedef OrderedList\n * @property - type : type of node\n * @property - content : array containing ListItem nodes\n * @property - attrs : attributes for an ordered list\n */\nexport type OrderedList = {\n readonly type: 'orderedList';\n readonly content: readonly ListItem[];\n readonly attrs?: OrderedListAttributes;\n};\n\nexport const OrderedListSchema: Schema = z.object({\n type: z.literal('orderedList'),\n content: z.array(z.lazy(() => ListItemSchema)),\n attrs: z.optional(OrderedListAttributesSchema)\n});\n\n/**\n * Represents a paragraph\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/nodes/paragraph\n *\n * @typedef Paragraph\n * @property - type : type of node\n * @property - content : array containing @typedef InlineNode\n */\nexport type Paragraph = {\n readonly type: 'paragraph';\n readonly content?: readonly InlineNode[];\n};\n\nexport const ParagraphSchema = z.object({\n type: z.literal('paragraph'),\n content: z.array(InlineNodeSchema).optional()\n});\n\n/**\n * Represents child list item of BulletList and OrderedList\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/nodes/listItem\n *\n * @typedef ListItem\n * @property - type : type of node\n * @property - content : array containing sub BulletList, sub OrderedList, or Paragraph nodes\n */\nexport type ListItem = {\n readonly type: 'listItem';\n readonly content: readonly (BulletList | OrderedList | Paragraph)[];\n};\n\nexport const ListItemSchema: Schema = z.object({\n type: z.literal('listItem'),\n content: z.array(\n z.union([BulletListSchema, OrderedListSchema, ParagraphSchema])\n )\n});\n\n/**\n * Represents a divider\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/nodes/rule\n *\n * @typedef Rule\n * @property - type : type of node\n */\nexport type Rule = {\n readonly type: 'rule';\n};\n\nexport const RuleSchema: Schema = z.object({\n type: z.literal('rule')\n});\n\n/**\n * Top Level Node consists of nodes that can be used at the root content level\n * Only the supported top level nodes are listed below\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/structure/#top-level-block-nodes\n *\n * @typedef TopLevelNode\n */\nexport type TopLevelNode =\n | BulletList\n | Heading\n | OrderedList\n | Paragraph\n | Rule;\n\nexport const TopLevelNodeSchema: Schema = z.union([\n BulletListSchema,\n HeadingSchema,\n OrderedListSchema,\n ParagraphSchema,\n RuleSchema\n]);\n\n/**\n * Atlassian Document Format (ADF) - Format for representing rich text\n * https://developer.atlassian.com/cloud/jira/platform/apis/document/structure/#atlassian-document-format\n *\n * @typedef ADF\n * @property - version : version of ADF used\n * @property - type : type of node\n * @property - content : array containing @typedef TopLevelNode\n */\nexport type ADF = {\n version: 1;\n type: 'doc';\n content: readonly TopLevelNode[];\n};\n\nexport const ADFSchema: Schema = z.object({\n version: z.literal(1),\n type: z.literal('doc'),\n content: z.array(TopLevelNodeSchema)\n});\n","import { z, Schema } from 'zod';\nimport {\n Channel,\n ChannelSchema,\n DefinitionStatusType,\n DefinitionStatusSchema,\n FieldDefinition,\n FieldDefinitionSchema\n} from './schema';\nimport { ZoneDefinition, ZoneDefinitionSchema } from './zone-definition';\n\n/**\n * Structure of a surface definition.\n * @typedef SurfaceDefinition\n * @property - label - A human readable name of the surface created from this surface definition.\n * @property - description - A human readable description.\n * @property - status - 'active' / 'inactive' state of the surface.\n * @property - channels - An array indicating where surface instances of this type are allowed to appear.\n * @property - fieldDefinitions - An array of field definitions that define the type of data that can be placed on a surface configuration.\n * @property - zoneDefinitions - An optional array of zone definitions that can be used to subdivide the surface for the purposes of placing children modules within the surface configuration.\n */\nexport type SurfaceDefinition = {\n readonly label: string;\n readonly description: string;\n readonly status: DefinitionStatusType;\n readonly channels: ReadonlyArray;\n readonly fieldDefinitions: ReadonlyArray;\n readonly zonesDefinitions?: ReadonlyArray;\n};\n\nexport const SurfaceDefinitionSchema: Schema = z.object({\n label: z.string(),\n description: z.string(),\n status: DefinitionStatusSchema,\n channels: z.array(ChannelSchema),\n fieldDefinitions: z.array(FieldDefinitionSchema),\n zonesDefinitions: z.array(ZoneDefinitionSchema).optional()\n});\n\n/**\n * Indexable version type of a surface defintion.\n * @typedef SurfaceDefinitionVersion\n * @property - version - Format in whole number.\n */\nexport type SurfaceDefinitionVersion = {\n readonly [version: string]: SurfaceDefinition;\n};\n\nexport const SurfaceDefinitionVersionSchema: Schema =\n z.record(z.string(), SurfaceDefinitionSchema);\n\n/**\n * Structure of a web surface definition.\n * @typedef WebSurfaceDefinition\n * @property - name - The type of surface instance that will be created from this definition.\n * @property - schema - A semantic version.\n * @property - type - Defines a web surface definition type.\n * @property - versions - Supports surface definition versioning.\n */\nexport type WebSurfaceDefinition = {\n readonly name: string;\n readonly schema: string;\n readonly type: 'surface';\n readonly versions: SurfaceDefinitionVersion;\n};\n\nexport const WebSurfaceDefinitionSchema: Schema =\n z.object({\n name: z.string(),\n schema: z.string(),\n type: z.literal('surface'),\n versions: SurfaceDefinitionVersionSchema\n });\n\n/**\n * Create a versioned surface from a surface definition json.\n * @param definition Surface definition json, conforming with SurfaceDefinition type.\n * @returns - Surface definition object.\n * @example\n * ```ts\n * import { createSurfaceDefinitionVersion } from '@atlassiansox/bxp-definition-sdk';\n *\n * export const ExampleSurface = createSurfaceDefinitionVersion({\n * {\n * label:'Example Surface Definition',\n * description:'Example Surface Definition',\n * status:'active',\n * channels:'web',\n * fieldDefinitions:[\n * {\n * name:'title',\n * type:'string',\n * label:'Title'\n * },\n * {\n * name:'description',\n * type:'string',\n * label:'Description'\n * }\n * ],\n * zonesDefinitions:[\n * {\n * name:'main',\n * label:'Main Zone',\n * description:'A zone where an example module can be added.',\n * status:'active',\n * validations:{\n * moduleRestrictions:[ {\n * name: 'SomeModule',\n * version: '1'\n * } ]\n * }\n * }\n * ]\n * }\n * });\n * ```\n */\n\nexport function createSurfaceDefinitionVersion<\n const M extends SurfaceDefinition\n>(surfaceDefinition: M): M {\n return SurfaceDefinitionSchema.parse(surfaceDefinition) as M;\n}\n","import { Schema, z } from 'zod';\nimport { ContentType, ContentTypeSchema } from './schema/commons';\n\n/**\n * Asset type with details regarding the asset location.\n * @typedef Asset\n * @property - contentType : One of the Content type\n * @property - description : Description of the asset field\n * @property - details : Additional details for the asset\n * @property - fileName : Name of the file including the extension\n * @property - title : Title of the file\n * @property - url : Location of the asset. i.e. http link, directory path\n */\nexport type Asset = {\n contentType: ContentType;\n description: string;\n details: {\n image?: {\n height: number;\n width: number;\n };\n size?: number;\n };\n fileName: string;\n title: string;\n url: string;\n};\n\nexport const AssetSchema: Schema = z.object({\n contentType: ContentTypeSchema,\n description: z.string(),\n details: z.object({\n image: z\n .object({\n height: z.number(),\n width: z.number()\n })\n .optional(),\n size: z.number().optional()\n }),\n fileName: z.string(),\n title: z.string(),\n url: z.string()\n});\n","import {\n WebModuleDefinition,\n WebModuleDefinitionSchema,\n WebSurfaceDefinition,\n WebSurfaceDefinitionSchema\n} from '.';\n\nexport type Definition = WebModuleDefinition | WebSurfaceDefinition;\n\nexport function createDefinition(definition: D): D {\n const type = definition.type;\n switch (type) {\n case 'module': {\n return WebModuleDefinitionSchema.parse(definition) as D;\n }\n case 'surface': {\n return WebSurfaceDefinitionSchema.parse(definition) as D;\n }\n }\n}\n","import { mapResponseToJson, mapResponseToText } from '@atlassiansox/asc-core';\nimport { fetch } from 'cross-fetch';\n\nimport {\n CloudExpandFreeValidationRequest,\n CloudExpandFreeValidationResponse,\n CloudSignUpRequest,\n CloudSignUpResponse,\n FreeBreachRequest,\n FreeBreachResponse,\n ProductEditionByCloudIdRequest,\n ProductEditionByCloudIdResponse,\n MarketplaceAppInstallRequest,\n MarketplaceAppInstallResponse\n} from './bxp-express-client.types';\n\nexport type BXPExpressClientOptions = {\n readonly baseUrl?: string;\n};\n\nexport interface IBXPExpressClient {\n getXsrfToken(): Promise;\n cloudSignupAnonymous(\n request: CloudSignUpRequest\n ): Promise;\n cloudExpandFreeValidation(\n request: CloudExpandFreeValidationRequest\n ): Promise