@lockerverse/sdk 0.2.185 → 0.2.190-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"checkout.js","names":[],"sources":["../src/checkout-environment.ts","../src/checkout-schemas.ts","../src/checkout-input-schemas.ts","../src/custom-amount.ts","../src/checkout-selection.ts","../src/snapshots.ts","../src/checkout-client.ts","../src/checkout-estimate.ts"],"sourcesContent":["import { resolveResourceEnvironment } from \"./environment.ts\";\nimport type { CreateLockerverseWidgetOptions } from \"./types.ts\";\n\nexport function resolveWidgetEnvironment(\n options: CreateLockerverseWidgetOptions\n) {\n const runtime = resolveResourceEnvironment(options, \"widgetSlug\");\n return {\n ...runtime,\n widgetSlug: runtime.resourceSlug,\n widgetSlugValue: runtime.resourceSlugValue,\n };\n}\n","import {\n array,\n boolean,\n check,\n finite,\n type InferOutput,\n literal,\n looseObject,\n maxValue,\n minValue,\n nullable,\n number,\n object,\n optional,\n parser,\n picklist,\n pipe,\n regex,\n safeParse,\n string,\n transform,\n unknown,\n variant,\n} from \"valibot\";\n\nimport {\n vPaymentWidgetPaymentResultResponseDto,\n vPaymentWidgetQuoteResponseDto,\n vPublicPaymentWidgetResponseDto,\n} from \"./generated/public-api/valibot.gen.ts\";\nimport {\n customFieldsSchema,\n nonEmptyStringSchema,\n optionalNullableStringSchema,\n safeIntegerSchema,\n} from \"./schema-helpers.ts\";\n\nconst paymentOptionSchema = picklist([\n \"one-time\",\n \"monthly\",\n \"annually\",\n \"every-six-months\",\n]);\nconst fulfillmentTypeSchema = picklist([\"none\", \"event_admission\"]);\nconst nullableNonNegativeIntegerSchema = nullable(safeIntegerSchema(0));\nconst availabilityStatusSchema = picklist([\"available\", \"sold_out\"]);\nconst availabilitySchema = optional(\n object({\n listings: array(\n object({\n listingId: nonEmptyStringSchema,\n maxPurchasableQuantity: nullableNonNegativeIntegerSchema,\n remainingQuantity: nullableNonNegativeIntegerSchema,\n status: availabilityStatusSchema,\n })\n ),\n sharedLimits: array(\n object({\n id: nonEmptyStringSchema,\n listingIds: array(nonEmptyStringSchema),\n remainingQuantity: safeIntegerSchema(0),\n status: availabilityStatusSchema,\n })\n ),\n }),\n { listings: [], sharedLimits: [] }\n);\nconst publishableKeySchema = pipe(\n string(),\n regex(/^pk_(?:test|live)_\\S+$/, \"Invalid publishable key.\")\n);\n\nconst productBaseEntries = {\n description: optionalNullableStringSchema,\n fulfillmentType: fulfillmentTypeSchema,\n id: nonEmptyStringSchema,\n inventoryQuantity: nullableNonNegativeIntegerSchema,\n maxQuantity: nullableNonNegativeIntegerSchema,\n minimumAmountCents: nullableNonNegativeIntegerSchema,\n minQuantity: nullableNonNegativeIntegerSchema,\n name: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n};\n\nconst eventSchema = object({\n description: nullable(string()),\n endAt: nonEmptyStringSchema,\n id: nonEmptyStringSchema,\n location: nullable(string()),\n name: nonEmptyStringSchema,\n startAt: nonEmptyStringSchema,\n status: picklist([\"draft\", \"active\", \"finished\", \"cancelled\"]),\n});\n\nconst publicProductSchema = variant(\"pricingMode\", [\n object({\n ...productBaseEntries,\n amountCents: safeIntegerSchema(0),\n pricingMode: literal(\"fixed\"),\n }),\n object({\n ...productBaseEntries,\n amountCents: nullableNonNegativeIntegerSchema,\n pricingMode: literal(\"custom\"),\n }),\n]);\n\nconst productListingSchema = object({\n acceptsDiscounts: optional(boolean(), false),\n id: nonEmptyStringSchema,\n maxQuantityPerOrder: optional(nullableNonNegativeIntegerSchema, null),\n product: publicProductSchema,\n productId: nonEmptyStringSchema,\n slug: nonEmptyStringSchema,\n});\n\nconst widgetFieldsSchema = optional(\n object({\n memberId: optional(boolean(), false),\n merchSize: optional(boolean(), false),\n phone: optional(boolean(), false),\n promoCode: optional(boolean(), false),\n serviceFee: optional(boolean(), false),\n shipping: optional(boolean(), false),\n tipping: optional(boolean(), false),\n }),\n {}\n);\n\nconst requiredShippingSchema = optional(\n object({\n additionalUnitAmountCents: optional(\n pipe(safeIntegerSchema(0), maxValue(2_147_483_647))\n ),\n productId: nonEmptyStringSchema,\n triggerProductIds: array(nonEmptyStringSchema),\n })\n);\n\nexport const publicWidgetSchema = pipe(\n object({\n availability: availabilitySchema,\n community: optional(\n object({\n color: string(),\n memberIdLabel: optional(nullable(string())),\n name: nonEmptyStringSchema,\n thumbnail: nullable(string()),\n widgetAchEnabled: optional(boolean()),\n })\n ),\n config: optional(\n object({\n customFields: customFieldsSchema,\n fields: widgetFieldsSchema,\n requiredShipping: requiredShippingSchema,\n })\n ),\n description: optionalNullableStringSchema,\n event: nullable(eventSchema),\n id: optional(string(), \"\"),\n name: optional(string(), \"Lockerverse widget\"),\n payment: object({\n connectedAccountId: optional(nullable(nonEmptyStringSchema), null),\n currency: literal(\"usd\"),\n publishableKey: publishableKeySchema,\n }),\n pricingPolicy: optional(\n object({\n currency: optional(literal(\"usd\"), \"usd\"),\n serviceFeeRateBasisPoints: optional(safeIntegerSchema(0), 0),\n })\n ),\n products: optional(array(productListingSchema), []),\n showCommunityBranding: optional(boolean(), true),\n title: optionalNullableStringSchema,\n }),\n transform((widget) => ({\n ...widget,\n config: {\n customFields: widget.config?.customFields ?? [],\n fields: {\n memberId: widget.config?.fields?.memberId ?? false,\n merchSize: widget.config?.fields?.merchSize ?? false,\n phone: widget.config?.fields?.phone ?? false,\n promoCode: widget.config?.fields?.promoCode ?? false,\n serviceFee: widget.config?.fields?.serviceFee ?? false,\n shipping: widget.config?.fields?.shipping ?? false,\n tipping: widget.config?.fields?.tipping ?? false,\n },\n requiredShipping: widget.config?.requiredShipping,\n },\n pricingPolicy: widget.pricingPolicy ?? {\n currency: \"usd\" as const,\n serviceFeeRateBasisPoints: 0,\n },\n }))\n);\n\nconst catalogProductSchema = object({\n acceptsDiscounts: boolean(),\n amountCents: nullable(safeIntegerSchema(0)),\n description: nullable(string()),\n fulfillmentType: fulfillmentTypeSchema,\n id: nonEmptyStringSchema,\n inventoryQuantity: nullableNonNegativeIntegerSchema,\n listingId: nonEmptyStringSchema,\n maximumQuantity: nullableNonNegativeIntegerSchema,\n minimumAmountCents: nullableNonNegativeIntegerSchema,\n minimumQuantity: nullableNonNegativeIntegerSchema,\n name: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n pricingMode: picklist([\"fixed\", \"custom\"]),\n slug: nonEmptyStringSchema,\n});\n\nconst catalogSchema = object({\n availability: availabilitySchema,\n community: nullable(\n object({\n accentColor: string(),\n imageUrl: nullable(string()),\n memberIdLabel: optional(nullable(string())),\n name: nonEmptyStringSchema,\n widgetAchEnabled: optional(boolean()),\n })\n ),\n event: nullable(eventSchema),\n payment: object({\n connectedAccountId: optional(nullable(nonEmptyStringSchema), null),\n currency: literal(\"usd\"),\n publishableKey: publishableKeySchema,\n }),\n pricingPolicy: object({\n currency: literal(\"usd\"),\n serviceFeeRateBasisPoints: safeIntegerSchema(0),\n }),\n products: array(catalogProductSchema),\n widget: object({\n customFields: customFieldsSchema,\n description: nullable(string()),\n fields: widgetFieldsSchema,\n id: string(),\n name: nonEmptyStringSchema,\n requiredShipping: requiredShippingSchema,\n showCommunityBranding: boolean(),\n title: nullable(string()),\n }),\n});\n\nconst appliedDiscountSchema = nullable(\n object({\n amountOffCents: optional(safeIntegerSchema(0)),\n message: optional(string()),\n percentageOff: optional(\n pipe(number(), finite(), minValue(0), maxValue(100))\n ),\n source: picklist([\"email_list\", \"promo_code\"]),\n })\n);\n\nconst checkoutLineItemSchema = object({\n acceptsDiscounts: boolean(),\n eventId: nullable(nonEmptyStringSchema),\n fulfillmentType: fulfillmentTypeSchema,\n listingId: nonEmptyStringSchema,\n listingSlug: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n pricingMode: picklist([\"fixed\", \"custom\"]),\n productId: nonEmptyStringSchema,\n productName: nonEmptyStringSchema,\n quantity: safeIntegerSchema(1),\n subtotalCents: safeIntegerSchema(0),\n unitAmountCents: safeIntegerSchema(0),\n});\n\nexport const checkoutQuoteSchema = pipe(\n vPaymentWidgetQuoteResponseDto,\n object({\n amountCents: safeIntegerSchema(0),\n appliedDiscount: appliedDiscountSchema,\n connectedAccountId: nullable(nonEmptyStringSchema),\n discountableSubtotalCents: safeIntegerSchema(0),\n discountCents: safeIntegerSchema(0),\n lineItems: array(checkoutLineItemSchema),\n paymentOption: paymentOptionSchema,\n serviceFeeCents: safeIntegerSchema(0),\n subtotalCents: safeIntegerSchema(0),\n tipCents: safeIntegerSchema(0),\n totalCents: safeIntegerSchema(0),\n }),\n check(({ lineItems, paymentOption }) => {\n if (\n lineItems.length === 0 ||\n lineItems.some((item) => item.paymentOption !== paymentOption)\n ) {\n return false;\n }\n return (\n paymentOption === \"one-time\" ||\n (lineItems.length === 1 &&\n lineItems[0]?.pricingMode === \"fixed\" &&\n lineItems[0].quantity === 1)\n );\n }, \"Invalid checkout cadence composition.\")\n);\n\nexport const paymentResultSchema = pipe(\n object({\n ...vPaymentWidgetPaymentResultResponseDto.entries,\n retryUrl: optional(pipe(nonEmptyStringSchema, regex(/^https:\\/\\//))),\n }),\n check((payment) => {\n if (!(payment.checkoutId.trim() && payment.paymentReference.trim())) {\n return false;\n }\n if (payment.checkoutStatus === \"action_required\") {\n return (\n payment.paymentRequired &&\n ((payment.requiresAction && Boolean(payment.clientSecret?.trim())) ||\n (!payment.requiresAction &&\n payment.clientSecret === null &&\n Boolean(payment.retryUrl)))\n );\n }\n return !payment.requiresAction && payment.clientSecret === null;\n }, \"Invalid payment result state.\")\n);\n\nexport type PublicCheckoutQuote = InferOutput<typeof checkoutQuoteSchema>;\nexport type PublicProductListing = InferOutput<typeof productListingSchema>;\nexport type PublicWidget = InferOutput<typeof publicWidgetSchema>;\n\nexport const parseCheckoutQuote = parser(checkoutQuoteSchema);\nexport const parseCatalog = parser(catalogSchema);\nexport const parsePaymentResult = parser(paymentResultSchema);\nconst parsePublicWidgetContract = parser(vPublicPaymentWidgetResponseDto);\nconst parseSdkPublicWidget = parser(publicWidgetSchema);\n\nexport function parsePublicWidget<Input>(input: Input) {\n parsePublicWidgetContract(input);\n return parseSdkPublicWidget(input);\n}\n\nexport function parsePublicWidgetLoad<Input>(input: Input) {\n const response = safeParse(\n looseObject({ quote: optional(unknown()) }),\n input\n );\n const widget = parsePublicWidget(input);\n const quote = response.success ? response.output.quote : undefined;\n return quote === undefined\n ? { widget }\n : { quote: parseCheckoutQuote(quote), widget };\n}\n","import {\n array,\n boolean,\n type InferOutput,\n literal,\n looseObject,\n minLength,\n nullable,\n object,\n optional,\n parser,\n picklist,\n pipe,\n record,\n strictObject,\n string,\n transform,\n union,\n unknown,\n} from \"valibot\";\n\nimport { parseCheckoutQuote } from \"./checkout-schemas.ts\";\nimport {\n customFieldAnswerSchema,\n nonEmptyStringSchema,\n safeIntegerSchema,\n} from \"./schema-helpers.ts\";\n\nconst checkoutPricingEntries = {\n email: optional(string()),\n includeServiceFee: optional(boolean()),\n promoCode: optional(string()),\n tipCents: optional(safeIntegerSchema(0)),\n};\n\nconst checkoutPricingInputSchema = strictObject(checkoutPricingEntries);\n\nexport const parseCheckoutPricingInput = parser(\n optional(checkoutPricingInputSchema, {})\n);\n\nconst paymentSubmissionSchema = strictObject({\n confirmationToken: optional(nonEmptyStringSchema),\n customFieldAnswers: optional(array(customFieldAnswerSchema)),\n email: string(),\n memberId: optional(string()),\n merchSize: optional(picklist([\"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\", \"XXXL\"])),\n metadata: optional(record(string(), string())),\n paymentMethodConfiguration: optional(literal(\"explicit\")),\n phone: optional(string()),\n shipping: optional(\n strictObject({\n address: strictObject({\n city: string(),\n country: string(),\n line1: string(),\n line2: optional(string()),\n postal_code: string(),\n state: string(),\n }),\n name: string(),\n })\n ),\n});\n\nconst checkoutItemSchema = union([\n strictObject({\n amountCents: safeIntegerSchema(1),\n productId: nonEmptyStringSchema,\n }),\n strictObject({\n productId: nonEmptyStringSchema,\n quantity: safeIntegerSchema(1),\n }),\n strictObject({\n productId: nonEmptyStringSchema,\n }),\n]);\n\nconst checkoutSelectionItemSchema = union([\n strictObject({\n amountCents: safeIntegerSchema(1),\n productSlug: nonEmptyStringSchema,\n }),\n strictObject({\n productSlug: nonEmptyStringSchema,\n quantity: safeIntegerSchema(1),\n }),\n strictObject({\n productSlug: nonEmptyStringSchema,\n }),\n]);\n\nconst checkoutItemsSchema = pipe(array(checkoutItemSchema), minLength(1));\nconst checkoutSelectionItemsSchema = pipe(\n array(checkoutSelectionItemSchema),\n minLength(1)\n);\n\nconst loadCheckoutInputSchema = object({\n selection: checkoutSelectionItemsSchema,\n});\n\nconst calculateTotalInputSchema = looseObject({\n catalog: optional(unknown()),\n email: optional(unknown()),\n includeServiceFee: optional(unknown()),\n items: optional(checkoutItemsSchema),\n promoCode: optional(unknown()),\n selection: optional(checkoutSelectionItemsSchema),\n tipCents: optional(unknown()),\n});\n\nconst preparedCheckoutInputSchema = pipe(\n looseObject({\n authoritative: literal(true),\n items: checkoutItemsSchema,\n payment: object({\n connectedAccountId: nullable(nonEmptyStringSchema),\n currency: literal(\"usd\"),\n publishableKey: pipe(string(), minLength(1)),\n }),\n paymentReference: pipe(string(), minLength(1)),\n pricing: checkoutPricingInputSchema,\n }),\n transform((checkout) => {\n const { items, payment, paymentReference, pricing, ...quoteInput } =\n checkout;\n const parsedQuote = parseCheckoutQuote({\n ...quoteInput,\n connectedAccountId: payment.connectedAccountId,\n });\n const { connectedAccountId, ...quote } = parsedQuote;\n return {\n items,\n pricing,\n quote: {\n ...quote,\n authoritative: true as const,\n payment: {\n connectedAccountId,\n currency: \"usd\" as const,\n publishableKey: payment.publishableKey,\n },\n paymentOption: parsedQuote.paymentOption,\n paymentReference,\n },\n };\n })\n);\n\nconst submitPaymentInputSchema = looseObject({\n checkout: preparedCheckoutInputSchema,\n submission: paymentSubmissionSchema,\n});\n\nconst paymentReferenceInputSchema = nonEmptyStringSchema;\nconst parseCatalogInputFields = parser(looseObject({}));\n\nexport type ParsedPreparedCheckoutInput = InferOutput<\n typeof preparedCheckoutInputSchema\n>;\nexport type ParsedLoadCheckoutInput = InferOutput<\n typeof loadCheckoutInputSchema\n>;\nexport type ParsedPaymentReferenceInput = InferOutput<\n typeof paymentReferenceInputSchema\n>;\nexport type ParsedSubmitPaymentInput = InferOutput<\n typeof submitPaymentInputSchema\n>;\n\nconst parseCalculateTotalInputFields = parser(calculateTotalInputSchema);\n\nexport function parseCalculateTotalInput<Input>(input: Input) {\n const { catalog, items, selection, ...pricingInput } =\n parseCalculateTotalInputFields(input);\n let parsedCatalog: ReturnType<typeof parseCatalogInputFields>;\n try {\n parsedCatalog = parseCatalogInputFields(catalog);\n } catch (error) {\n throw new TypeError(\"A catalog is required to calculate a checkout.\", {\n cause: error,\n });\n }\n try {\n return {\n catalog: parsedCatalog,\n items,\n pricing: parseCheckoutPricingInput(pricingInput),\n selection,\n };\n } catch (error) {\n throw new TypeError(\"Checkout pricing input is invalid.\", { cause: error });\n }\n}\n\nexport type ParsedCalculateTotalInput = ReturnType<\n typeof parseCalculateTotalInput\n>;\nexport type ParsedCheckoutPricingInput = InferOutput<\n typeof checkoutPricingInputSchema\n>;\n\nexport const parseLoadCheckoutInput = parser(loadCheckoutInputSchema);\nexport const parsePaymentReferenceInput = parser(paymentReferenceInputSchema);\nexport const parsePreparedCheckoutInput = parser(preparedCheckoutInputSchema);\nexport const parseSubmitPaymentInput = parser(submitPaymentInputSchema);\n\nexport const parseCheckoutSelectionItems = parser(checkoutSelectionItemsSchema);\n","import type { LockerverseProduct } from \"./types.ts\";\n\nconst minimumCustomAmountCents = 100;\n\nexport function getLockerverseMinimumCustomAmountCents(\n product: Pick<LockerverseProduct, \"minimumAmountCents\">\n) {\n return Math.max(minimumCustomAmountCents, product.minimumAmountCents ?? 0);\n}\n","import { parseCheckoutSelectionItems } from \"./checkout-input-schemas.ts\";\nimport { getLockerverseMinimumCustomAmountCents } from \"./custom-amount.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCheckoutItem,\n LockerverseCheckoutLineItem,\n LockerverseCheckoutSelectionItem,\n LockerverseProduct,\n} from \"./types.ts\";\nimport { LockerverseSdkError } from \"./types.ts\";\n\ntype ResolvedSelectionItem = {\n checkoutItem: LockerverseCheckoutItem;\n quantity: number;\n unitAmountCents: number;\n};\n\nexport function assertCheckoutItemsAreAvailable(\n catalog: LockerverseCatalog,\n items: LockerverseCheckoutItem[]\n) {\n const listingIdByProductId = new Map(\n catalog.products.map(({ id, listingId }) => [id, listingId])\n );\n const requestedByListingId = items.reduce((requested, item) => {\n const listingId = listingIdByProductId.get(item.productId);\n if (listingId) {\n requested.set(\n listingId,\n (requested.get(listingId) ?? 0) +\n (\"quantity\" in item ? (item.quantity ?? 1) : 1)\n );\n }\n return requested;\n }, new Map<string, number>());\n const listingIsSoldOut = catalog.availability.listings.some(\n ({ listingId, maxPurchasableQuantity, status }) =>\n requestedByListingId.has(listingId) &&\n (status === \"sold_out\" ||\n (maxPurchasableQuantity !== null &&\n (requestedByListingId.get(listingId) ?? 0) > maxPurchasableQuantity))\n );\n const sharedLimitIsSoldOut = catalog.availability.sharedLimits.some(\n ({ listingIds, remainingQuantity, status }) => {\n const requestedQuantity = listingIds.reduce(\n (total, listingId) =>\n total + (requestedByListingId.get(listingId) ?? 0),\n 0\n );\n return (\n requestedQuantity > 0 &&\n (status === \"sold_out\" || requestedQuantity > remainingQuantity)\n );\n }\n );\n if (listingIsSoldOut || sharedLimitIsSoldOut) {\n throw new LockerverseSdkError({\n code: \"total_calculation_failed\",\n message: \"This option is sold out.\",\n operation: \"calculate_total\",\n reportable: false,\n serverCode: \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\",\n });\n }\n}\n\nfunction resolveAmountItem(\n product: LockerverseProduct,\n amountCents: number\n): ResolvedSelectionItem {\n if (\n product.pricingMode !== \"custom\" ||\n product.paymentOption !== \"one-time\" ||\n amountCents < getLockerverseMinimumCustomAmountCents(product)\n ) {\n throw new TypeError(\"Selected Product amount is invalid.\");\n }\n return {\n checkoutItem: { amountCents, productId: product.id },\n quantity: 1,\n unitAmountCents: amountCents,\n };\n}\n\nfunction resolveFixedItem(\n product: LockerverseProduct,\n quantity: number\n): ResolvedSelectionItem {\n if (product.pricingMode !== \"fixed\" || product.amountCents === null) {\n throw new TypeError(\"Selected Product quantity is invalid.\");\n }\n if (product.paymentOption !== \"one-time\" && quantity !== 1) {\n throw new TypeError(\"Selected recurring Product is invalid.\");\n }\n if (\n (product.minimumQuantity !== null && quantity < product.minimumQuantity) ||\n (product.maximumQuantity !== null && quantity > product.maximumQuantity) ||\n (product.inventoryQuantity !== null && quantity > product.inventoryQuantity)\n ) {\n throw new TypeError(\"Selected Product quantity is invalid.\");\n }\n return {\n checkoutItem:\n product.paymentOption === \"one-time\"\n ? { productId: product.id, quantity }\n : { productId: product.id },\n quantity,\n unitAmountCents: product.amountCents,\n };\n}\n\nfunction resolveSelectionItem(\n catalog: LockerverseCatalog,\n product: LockerverseProduct,\n selection: LockerverseCheckoutSelectionItem\n) {\n const selectedQuantity = \"quantity\" in selection ? selection.quantity : 1;\n const resolved =\n \"amountCents\" in selection\n ? resolveAmountItem(product, selection.amountCents)\n : resolveFixedItem(product, selectedQuantity);\n const { checkoutItem, quantity, unitAmountCents } = resolved;\n\n return {\n checkoutItem,\n lineItem: {\n acceptsDiscounts: product.acceptsDiscounts,\n eventId:\n product.fulfillmentType === \"event_admission\" && catalog.event\n ? catalog.event.id\n : null,\n fulfillmentType: product.fulfillmentType,\n listingId: product.listingId,\n listingSlug: product.slug,\n paymentOption: product.paymentOption,\n pricingMode: product.pricingMode,\n productId: product.id,\n productName: product.name,\n quantity,\n subtotalCents: unitAmountCents * quantity,\n unitAmountCents,\n } satisfies LockerverseCheckoutLineItem,\n };\n}\n\nexport function resolveCheckoutSelection(\n catalog: LockerverseCatalog,\n input: LockerverseCheckoutSelectionItem[]\n) {\n let selection = parseCheckoutSelectionItems(input);\n const shipping = catalog.widget.requiredShipping;\n if (shipping) {\n const shippingProduct = catalog.products.find(\n ({ id }) => id === shipping.productId\n );\n const needsShipping = selection.some((item) =>\n catalog.products.some(\n (product) =>\n product.slug === item.productSlug &&\n shipping.triggerProductIds.includes(product.id)\n )\n );\n selection = selection.filter(\n (item) => item.productSlug !== shippingProduct?.slug\n );\n if (needsShipping) {\n if (!shippingProduct) {\n throw new TypeError(\"Required shipping Product is unavailable.\");\n }\n selection.push({ productSlug: shippingProduct.slug, quantity: 1 });\n }\n }\n const selectedProducts = new Set<string>();\n const resolved = selection.map((item) => {\n const product = catalog.products.find(\n (candidate) => candidate.slug === item.productSlug\n );\n if (!product) {\n throw new TypeError(\"Selected Product is unavailable.\");\n }\n if (selectedProducts.has(product.id)) {\n throw new TypeError(\"Each Product can appear only once per checkout.\");\n }\n selectedProducts.add(product.id);\n return resolveSelectionItem(catalog, product, item);\n });\n if (shipping?.additionalUnitAmountCents) {\n const triggerQuantity = resolved.reduce(\n (total, { lineItem }) =>\n total +\n (shipping.triggerProductIds.includes(lineItem.productId)\n ? lineItem.quantity\n : 0),\n 0\n );\n const shippingLine = resolved.find(\n ({ lineItem }) => lineItem.productId === shipping.productId\n )?.lineItem;\n if (shippingLine) {\n const amountCents =\n shippingLine.unitAmountCents +\n Math.max(0, triggerQuantity - 1) * shipping.additionalUnitAmountCents;\n if (!Number.isSafeInteger(amountCents) || amountCents > 2_147_483_647) {\n throw new TypeError(\"Required shipping amount is invalid.\");\n }\n shippingLine.unitAmountCents = amountCents;\n shippingLine.subtotalCents = amountCents;\n }\n }\n const paymentOption = resolved[0]?.lineItem.paymentOption;\n if (!paymentOption) {\n throw new TypeError(\"Select at least one Product.\");\n }\n if (\n resolved.length > 1 &&\n (paymentOption !== \"one-time\" ||\n resolved.some(({ lineItem }) => lineItem.paymentOption !== paymentOption))\n ) {\n throw new TypeError(\"Recurring Products must be purchased separately.\");\n }\n const items = resolved.map(({ checkoutItem }) => checkoutItem);\n assertCheckoutItemsAreAvailable(catalog, items);\n return {\n items,\n lineItems: resolved.map(({ lineItem }) => lineItem),\n paymentOption,\n };\n}\n","import type { PublicProductListing, PublicWidget } from \"./checkout-schemas.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCommunityBranding,\n LockerversePaymentResult,\n LockerversePreparedCheckout,\n LockerverseProduct,\n} from \"./types.ts\";\n\nfunction mapProduct(listing: PublicProductListing): LockerverseProduct {\n const { product } = listing;\n\n return {\n acceptsDiscounts: listing.acceptsDiscounts ?? false,\n amountCents: product.amountCents,\n description: product.description ?? null,\n fulfillmentType: product.fulfillmentType,\n id: product.id,\n inventoryQuantity: product.inventoryQuantity,\n listingId: listing.id,\n maximumQuantity: listing.maxQuantityPerOrder,\n minimumAmountCents: product.minimumAmountCents,\n minimumQuantity: product.minQuantity,\n name: product.name,\n paymentOption: product.paymentOption,\n pricingMode: product.pricingMode,\n slug: listing.slug,\n };\n}\n\nfunction mapCommunity(\n community: PublicWidget[\"community\"]\n): LockerverseCommunityBranding | null {\n if (!community) {\n return null;\n }\n const branding: LockerverseCommunityBranding = {\n accentColor: community.color,\n imageUrl: community.thumbnail || null,\n name: community.name,\n };\n if (community.widgetAchEnabled !== undefined) {\n branding.widgetAchEnabled = community.widgetAchEnabled;\n }\n if (community.memberIdLabel !== undefined) {\n branding.memberIdLabel = community.memberIdLabel;\n }\n return branding;\n}\n\nexport function createCatalog(widget: PublicWidget): LockerverseCatalog {\n const fields = widget.config?.fields ?? {};\n\n return {\n availability: widget.availability,\n community: mapCommunity(widget.community),\n event: widget.event\n ? {\n description: widget.event.description,\n endAt: widget.event.endAt,\n id: widget.event.id,\n location: widget.event.location,\n name: widget.event.name,\n startAt: widget.event.startAt,\n status: widget.event.status,\n }\n : null,\n payment: {\n connectedAccountId: widget.payment.connectedAccountId,\n currency: widget.payment.currency,\n publishableKey: widget.payment.publishableKey,\n },\n pricingPolicy: {\n currency: \"usd\",\n serviceFeeRateBasisPoints:\n widget.pricingPolicy?.serviceFeeRateBasisPoints ?? 0,\n },\n products: (widget.products ?? []).map(mapProduct),\n widget: {\n customFields: widget.config?.customFields ?? [],\n description: widget.description ?? null,\n fields: {\n memberId: fields.memberId ?? false,\n merchSize: fields.merchSize ?? false,\n phone: fields.phone ?? false,\n promoCode: fields.promoCode ?? false,\n serviceFee: fields.serviceFee ?? false,\n shipping: fields.shipping ?? false,\n tipping: fields.tipping ?? false,\n },\n id: widget.id ?? \"\",\n name: widget.name ?? \"Lockerverse widget\",\n requiredShipping: widget.config?.requiredShipping,\n showCommunityBranding: widget.showCommunityBranding ?? true,\n title: widget.title ?? null,\n },\n };\n}\n\nexport function cloneCatalog(catalog: LockerverseCatalog): LockerverseCatalog {\n return cloneSnapshot(catalog);\n}\n\nexport function clonePreparedCheckout(\n checkout: LockerversePreparedCheckout\n): LockerversePreparedCheckout {\n return cloneSnapshot(checkout);\n}\n\nexport function clonePaymentResult(\n paymentResult: LockerversePaymentResult\n): LockerversePaymentResult {\n return cloneSnapshot(paymentResult);\n}\n\nfunction cloneSnapshot<T>(value: T): T {\n return deepFreeze(structuredClone(value));\n}\n","import { object, picklist, safeParse } from \"valibot\";\nimport { resolveWidgetEnvironment } from \"./checkout-environment.ts\";\nimport {\n type ParsedCalculateTotalInput,\n type ParsedCheckoutPricingInput,\n parseCalculateTotalInput,\n parseLoadCheckoutInput,\n parsePaymentReferenceInput,\n parseSubmitPaymentInput,\n} from \"./checkout-input-schemas.ts\";\nimport {\n parseCatalog,\n parseCheckoutQuote,\n parsePaymentResult,\n parsePublicWidgetLoad,\n} from \"./checkout-schemas.ts\";\nimport {\n assertCheckoutItemsAreAvailable,\n resolveCheckoutSelection,\n} from \"./checkout-selection.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport { createSdkErrorReporter } from \"./error-reporting.ts\";\nimport {\n cloneCatalog,\n clonePaymentResult,\n clonePreparedCheckout,\n createCatalog,\n} from \"./snapshots.ts\";\nimport { createTransport } from \"./transport.ts\";\nimport {\n type CreateLockerverseWidgetOptions,\n type LockerverseCalculateTotalInput,\n type LockerverseCatalog,\n type LockerverseCheckoutClient,\n type LockerverseCheckoutItem,\n type LockerverseCheckoutPricingInput,\n type LockerverseCheckoutSelectionItem,\n type LockerverseLoadCheckoutInput,\n type LockerverseLoadedCheckout,\n type LockerversePreparedCheckout,\n LockerverseSdkError,\n type LockerverseSdkOperation,\n type LockerverseSdkServerCode,\n type LockerverseSubmitPaymentInput,\n} from \"./types.ts\";\n\ntype OperationErrorContext = {\n code:\n | \"payment_status_failed\"\n | \"payment_submit_failed\"\n | \"total_calculation_failed\"\n | \"widget_load_failed\";\n message: string;\n operation:\n | \"calculate_total\"\n | \"get_payment_status\"\n | \"load_widget\"\n | \"submit_payment\";\n};\n\nconst MAX_SELECTED_WIDGET_URL_LENGTH = 4000;\nconst paymentServerErrorSchema = object({\n code: picklist([\n \"PAYMENT_WIDGET_PHONE_INVALID\",\n \"PAYMENT_WIDGET_PHONE_REQUIRED\",\n \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\",\n ]),\n});\n\nasync function readPaymentServerCode(\n response: Response\n): Promise<LockerverseSdkServerCode | undefined> {\n if (response.status !== 400 && response.status !== 409) {\n return;\n }\n try {\n const result = safeParse(paymentServerErrorSchema, await response.json());\n return result.success ? result.output.code : undefined;\n } catch {\n // Non-JSON error bodies do not contain a safe server code.\n }\n}\n\nfunction resolveCalculateTotalItems({\n catalog,\n items,\n selection,\n}: ParsedCalculateTotalInput) {\n if (items !== undefined && selection !== undefined) {\n throw new TypeError(\"Use items or selection, not both.\");\n }\n const selectionCatalog = cloneCatalog(parseCatalog(catalog));\n const checkoutItems =\n selection === undefined\n ? requireCheckoutItems(items)\n : resolveCheckoutSelection(selectionCatalog, selection).items;\n assertCheckoutItemsAreAvailable(selectionCatalog, checkoutItems);\n return {\n catalog: selectionCatalog,\n items: checkoutItems,\n };\n}\n\nfunction requireCheckoutItems(\n items: ParsedCalculateTotalInput[\"items\"]\n): LockerverseCheckoutItem[] {\n if (items === undefined) {\n throw new TypeError(\"Checkout selection is invalid.\");\n }\n return items;\n}\n\nexport function createLockerverseCheckoutClient(\n options: CreateLockerverseWidgetOptions\n): LockerverseCheckoutClient {\n const {\n apiBaseUrl,\n communitySlug,\n communitySlugValue,\n environment,\n fetchImplementation,\n onError,\n requestTimeoutMs,\n sentryDsn,\n widgetSlug,\n widgetSlugValue,\n } = resolveWidgetEnvironment(options);\n const reportError = createSdkErrorReporter({\n communitySlug: communitySlugValue,\n environment,\n getContext: () => ({ widgetSlug: widgetSlugValue }),\n onError,\n resourceContextName: \"lockerverse_widget\",\n sentryDsn,\n });\n const { requestJson } = createTransport(\n fetchImplementation,\n reportError,\n requestTimeoutMs\n );\n const checkoutBaseUrl = `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}/checkout`;\n const widgetUrl = `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}`;\n\n function invalidInput(\n message: string,\n operation: LockerverseSdkOperation,\n code: \"invalid_selection\" | \"payment_submit_failed\" = \"invalid_selection\"\n ): never {\n throw reportError(\n new LockerverseSdkError({\n code,\n message,\n operation,\n reportable: false,\n })\n );\n }\n\n function normalizeOperationError<ErrorValue>(\n error: ErrorValue,\n context: OperationErrorContext\n ) {\n return error instanceof LockerverseSdkError\n ? error\n : new LockerverseSdkError({ ...context, reportable: true });\n }\n\n function failOperation<ErrorValue>(\n error: ErrorValue,\n context: OperationErrorContext,\n recoveryMayBeRequired = false\n ): never {\n const normalized = normalizeOperationError(error, context);\n const recoveryRecommended =\n recoveryMayBeRequired &&\n (normalized.status === undefined || normalized.status >= 500);\n if (!recoveryRecommended) {\n throw reportError(normalized);\n }\n const recoveryError =\n normalized.status === undefined\n ? new LockerverseSdkError({\n code: normalized.code,\n message: normalized.message,\n operation: normalized.operation,\n recoveryRecommended: true,\n reportable: normalized.reportable,\n })\n : new LockerverseSdkError({\n code: normalized.code,\n message: normalized.message,\n operation: normalized.operation,\n recoveryRecommended: true,\n reportable: normalized.reportable,\n status: normalized.status,\n });\n throw reportError(recoveryError);\n }\n\n function normalizePricingInput(input: ParsedCheckoutPricingInput) {\n const email = input.email?.trim().toLowerCase();\n const promoCode = input.promoCode?.trim();\n const pricing: LockerverseCheckoutPricingInput = {};\n if (email) {\n pricing.email = email;\n }\n if (input.includeServiceFee !== undefined) {\n pricing.includeServiceFee = input.includeServiceFee;\n }\n if (promoCode) {\n pricing.promoCode = promoCode;\n }\n if (input.tipCents !== undefined) {\n pricing.tipCents = input.tipCents;\n }\n return pricing;\n }\n\n function normalizeLoadSelection(input: LockerverseLoadCheckoutInput) {\n try {\n return parseLoadCheckoutInput(input).selection;\n } catch {\n invalidInput(\"Checkout selection is invalid.\", \"load_widget\");\n }\n }\n\n function createPreparedCheckout(\n quote: ReturnType<typeof parseCheckoutQuote>,\n items: LockerverseCheckoutItem[],\n pricing: LockerverseCheckoutPricingInput,\n payment: LockerverseCatalog[\"payment\"]\n ): LockerversePreparedCheckout {\n const { connectedAccountId, ...checkoutQuote } = quote;\n return clonePreparedCheckout(\n deepFreeze({\n ...checkoutQuote,\n authoritative: true as const,\n items,\n payment: {\n connectedAccountId,\n currency: \"usd\" as const,\n publishableKey: payment.publishableKey,\n },\n paymentOption: quote.paymentOption,\n paymentReference: globalThis.crypto.randomUUID(),\n pricing,\n })\n );\n }\n\n function resolveSelectedCheckoutItems(\n catalog: LockerverseCatalog,\n selection: LockerverseCheckoutSelectionItem[],\n operation: LockerverseSdkOperation\n ) {\n try {\n return resolveCheckoutSelection(catalog, selection).items;\n } catch (error) {\n if (error instanceof TypeError) {\n invalidInput(error.message, operation);\n }\n throw error;\n }\n }\n\n function createSelectedCheckout(\n catalog: LockerverseCatalog,\n selection: LockerverseCheckoutSelectionItem[],\n quote: ReturnType<typeof parseCheckoutQuote> | undefined,\n context: OperationErrorContext\n ) {\n if (!quote) {\n throw new LockerverseSdkError({\n ...context,\n message: \"Lockerverse did not return the requested initial quote.\",\n reportable: true,\n });\n }\n const checkoutItems = resolveSelectedCheckoutItems(\n catalog,\n selection,\n context.operation\n );\n return deepFreeze({\n catalog: cloneCatalog(catalog),\n checkout: createPreparedCheckout(\n quote,\n checkoutItems,\n { includeServiceFee: catalog.widget.fields.serviceFee },\n catalog.payment\n ),\n });\n }\n\n function requestWidgetResource(): Promise<LockerverseCatalog>;\n function requestWidgetResource(\n selection: LockerverseCheckoutSelectionItem[]\n ): Promise<LockerverseLoadedCheckout>;\n async function requestWidgetResource(\n selection?: LockerverseCheckoutSelectionItem[]\n ): Promise<LockerverseCatalog | LockerverseLoadedCheckout> {\n const context = {\n code: \"widget_load_failed\" as const,\n message: \"Lockerverse returned an invalid widget catalog.\",\n operation: \"load_widget\" as const,\n };\n const requestUrl = selection\n ? `${widgetUrl}?selection=${encodeURIComponent(JSON.stringify(selection))}`\n : widgetUrl;\n const response = await requestJson(\n requestUrl,\n selection ? { cache: \"no-store\" } : undefined,\n parsePublicWidgetLoad,\n {\n ...context,\n message:\n \"Unable to load Lockerverse widget because the request failed.\",\n report: false,\n },\n { ...context, report: false },\n readPaymentServerCode\n );\n if (!response.ok) {\n const serverCode = response.errorValue;\n if (serverCode === \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\") {\n throw new LockerverseSdkError({\n ...context,\n message: \"This option is sold out.\",\n reportable: false,\n serverCode,\n status: response.response.status,\n });\n }\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to load Lockerverse widget (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n const catalog = deepFreeze(createCatalog(response.value.widget));\n if (!selection) {\n return cloneCatalog(catalog);\n }\n return createSelectedCheckout(\n catalog,\n selection,\n response.value.quote,\n context\n );\n }\n\n async function loadLargeSelection(\n selection: LockerverseCheckoutSelectionItem[],\n context: OperationErrorContext\n ): Promise<LockerverseLoadedCheckout> {\n const loaded = await requestWidgetResource();\n const pricing = {\n includeServiceFee: loaded.widget.fields.serviceFee,\n };\n const items = resolveSelectedCheckoutItems(\n loaded,\n selection,\n context.operation\n );\n return deepFreeze({\n catalog: loaded,\n checkout: await requestCheckoutQuote(\n items,\n pricing,\n loaded.payment,\n context\n ),\n });\n }\n\n async function loadWidget(\n selection?: LockerverseCheckoutSelectionItem[]\n ): Promise<LockerverseCatalog | LockerverseLoadedCheckout> {\n const context = {\n code: \"widget_load_failed\" as const,\n message: \"Lockerverse returned an invalid widget catalog.\",\n operation: \"load_widget\" as const,\n };\n try {\n if (\n selection &&\n `${widgetUrl}?selection=${encodeURIComponent(JSON.stringify(selection))}`\n .length > MAX_SELECTED_WIDGET_URL_LENGTH\n ) {\n return await loadLargeSelection(selection, context);\n }\n return selection\n ? await requestWidgetResource(selection)\n : await requestWidgetResource();\n } catch (error) {\n failOperation(error, context);\n }\n }\n\n function load(): Promise<LockerverseCatalog>;\n function load(\n input: LockerverseLoadCheckoutInput\n ): Promise<LockerverseLoadedCheckout>;\n function load(input?: LockerverseLoadCheckoutInput) {\n return input === undefined\n ? loadWidget()\n : loadWidget(normalizeLoadSelection(input));\n }\n\n async function requestCheckoutQuote(\n items: LockerverseCheckoutItem[],\n pricing: LockerverseCheckoutPricingInput,\n payment: LockerverseCatalog[\"payment\"],\n context: OperationErrorContext\n ) {\n const response = await requestJson(\n `${checkoutBaseUrl}/quote`,\n {\n body: JSON.stringify({ ...pricing, items }),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n },\n parseCheckoutQuote,\n {\n ...context,\n message:\n \"Unable to calculate the Lockerverse checkout total because the request failed.\",\n report: false,\n },\n { ...context, report: false },\n readPaymentServerCode\n );\n if (!response.ok) {\n const serverCode = response.errorValue;\n if (serverCode === \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\") {\n throw new LockerverseSdkError({\n ...context,\n message: \"This option is sold out.\",\n reportable: false,\n serverCode,\n status: response.response.status,\n });\n }\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to calculate the Lockerverse checkout total (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n return createPreparedCheckout(response.value, items, pricing, payment);\n }\n\n async function calculateTotal(input: LockerverseCalculateTotalInput) {\n const { catalog, items, pricing } = normalizeCalculateTotalInput(input);\n const context = {\n code: \"total_calculation_failed\" as const,\n message: \"Lockerverse returned an invalid checkout total.\",\n operation: \"calculate_total\" as const,\n };\n try {\n return await requestCheckoutQuote(\n items,\n pricing,\n catalog.payment,\n context\n );\n } catch (error) {\n failOperation(error, context);\n }\n }\n\n function normalizeCalculateTotalInput(input: LockerverseCalculateTotalInput) {\n try {\n const parsed = parseCalculateTotalInput(input);\n const resolved = resolveCalculateTotalItems(parsed);\n const pricing = normalizePricingInput(parsed.pricing);\n return {\n catalog: resolved.catalog,\n items: resolved.items,\n pricing:\n pricing.includeServiceFee === undefined\n ? {\n ...pricing,\n includeServiceFee: resolved.catalog.widget.fields.serviceFee,\n }\n : pricing,\n };\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n throw error;\n }\n invalidInput(\n error instanceof TypeError\n ? error.message\n : \"Checkout selection is invalid.\",\n \"calculate_total\"\n );\n }\n }\n\n function normalizeSubmitPaymentInput(input: LockerverseSubmitPaymentInput) {\n try {\n const parsed = parseSubmitPaymentInput(input);\n const {\n items,\n pricing: pricingInput,\n quote: quoteInput,\n } = parsed.checkout;\n const pricing = normalizePricingInput(pricingInput);\n const quote = deepFreeze(quoteInput);\n const { submission } = parsed;\n if (quote.totalCents > 0 && !submission.confirmationToken) {\n invalidInput(\n \"Stripe confirmation is required for a paid checkout.\",\n \"submit_payment\",\n \"payment_submit_failed\"\n );\n }\n const email = submission.email.trim().toLowerCase();\n if (!email || email !== pricing.email) {\n invalidInput(\n \"Payment email must match the current checkout quote.\",\n \"submit_payment\"\n );\n }\n return {\n items,\n pricing,\n quote,\n submission: { ...submission, email },\n };\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n throw error;\n }\n invalidInput(\n \"Lockerverse payment submission is invalid.\",\n \"submit_payment\",\n \"payment_submit_failed\"\n );\n }\n }\n\n return {\n calculateTotal,\n async getPaymentStatus(paymentReference) {\n let normalizedReference: string;\n try {\n normalizedReference =\n parsePaymentReferenceInput(paymentReference).trim();\n } catch {\n invalidInput(\n \"Provide a payment reference to recover its status.\",\n \"get_payment_status\"\n );\n }\n const context = {\n code: \"payment_status_failed\" as const,\n message: \"Lockerverse returned an invalid payment status.\",\n operation: \"get_payment_status\" as const,\n };\n try {\n const response = await requestJson(\n `${checkoutBaseUrl}/${encodeURIComponent(normalizedReference)}/status`,\n undefined,\n parsePaymentResult,\n {\n ...context,\n message:\n \"Unable to recover the Lockerverse payment status because the request failed.\",\n report: false,\n },\n { ...context, report: false }\n );\n if (!response.ok) {\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to recover the Lockerverse payment status (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n if (response.value.paymentReference !== normalizedReference) {\n throw new LockerverseSdkError({ ...context, reportable: true });\n }\n return clonePaymentResult(response.value);\n } catch (error) {\n failOperation(error, context);\n }\n },\n load,\n async submitPayment(input) {\n const { items, pricing, quote, submission } =\n normalizeSubmitPaymentInput(input);\n const context = {\n code: \"payment_submit_failed\" as const,\n message: \"Lockerverse returned an invalid payment confirmation.\",\n operation: \"submit_payment\" as const,\n };\n try {\n const response = await requestJson(\n `${checkoutBaseUrl}/confirm`,\n {\n body: JSON.stringify({\n confirmationToken: submission.confirmationToken,\n customFieldAnswers: submission.customFieldAnswers,\n email: submission.email,\n expectedAmountCents: quote.amountCents,\n expectedAppliedDiscount: quote.appliedDiscount,\n expectedConnectedAccountId: quote.payment.connectedAccountId,\n expectedDiscountableSubtotalCents:\n quote.discountableSubtotalCents,\n expectedDiscountCents: quote.discountCents,\n expectedServiceFeeCents: quote.serviceFeeCents,\n expectedSubtotalCents: quote.subtotalCents,\n expectedTipCents: quote.tipCents,\n expectedTotalCents: quote.totalCents,\n ...pricing,\n items,\n memberId: submission.memberId,\n merchSize: submission.merchSize,\n metadata: submission.metadata,\n paymentMethodConfiguration: submission.paymentMethodConfiguration,\n paymentReference: quote.paymentReference,\n phone: submission.phone,\n quoteContractVersion: 1,\n shipping: submission.shipping,\n }),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n },\n parsePaymentResult,\n {\n ...context,\n message:\n \"Unable to submit the Lockerverse payment because the request failed.\",\n report: false,\n },\n { ...context, report: false },\n readPaymentServerCode\n );\n if (!response.ok) {\n const serverCode = response.errorValue;\n if (serverCode) {\n throw new LockerverseSdkError({\n ...context,\n message:\n serverCode === \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\"\n ? \"This option is sold out.\"\n : `Unable to submit the Lockerverse payment (${response.response.status}).`,\n reportable: false,\n serverCode,\n status: response.response.status,\n });\n }\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to submit the Lockerverse payment (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n if (response.value.paymentReference !== quote.paymentReference) {\n throw new LockerverseSdkError({ ...context, reportable: true });\n }\n return clonePaymentResult(response.value);\n } catch (error) {\n failOperation(error, context, true);\n }\n },\n };\n}\n","import { parseCheckoutPricingInput } from \"./checkout-input-schemas.ts\";\nimport { resolveCheckoutSelection } from \"./checkout-selection.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCheckoutEstimate,\n LockerverseEstimateCheckoutInput,\n} from \"./types.ts\";\n\nexport function estimateLockerverseCheckout(\n catalog: LockerverseCatalog,\n input: LockerverseEstimateCheckoutInput\n): LockerverseCheckoutEstimate {\n const { selection, ...pricingInput } = input;\n let pricing: ReturnType<typeof parseCheckoutPricingInput>;\n try {\n pricing = parseCheckoutPricingInput(pricingInput);\n } catch (error) {\n throw new TypeError(\"Checkout pricing is invalid.\", { cause: error });\n }\n const includeServiceFee =\n pricing.includeServiceFee ?? catalog.widget.fields.serviceFee;\n const { tipCents = 0 } = pricing;\n const { items, lineItems, paymentOption } = resolveCheckoutSelection(\n catalog,\n selection\n );\n const subtotalCents = lineItems.reduce(\n (total, lineItem) => total + lineItem.subtotalCents,\n 0\n );\n if (\n !Number.isSafeInteger(subtotalCents) ||\n subtotalCents <= 0 ||\n subtotalCents > 2_147_483_647\n ) {\n throw new TypeError(\"Checkout total is invalid.\");\n }\n const discountableSubtotalCents = lineItems.reduce(\n (total, lineItem) =>\n total + (lineItem.acceptsDiscounts ? lineItem.subtotalCents : 0),\n 0\n );\n const serviceFeeCents = includeServiceFee\n ? Math.round(\n (subtotalCents * catalog.pricingPolicy.serviceFeeRateBasisPoints) /\n 10_000\n )\n : 0;\n const amountCents = subtotalCents + serviceFeeCents;\n const totalCents = amountCents + tipCents;\n if (!Number.isSafeInteger(totalCents) || totalCents > 2_147_483_647) {\n throw new TypeError(\"Checkout total is invalid.\");\n }\n\n return deepFreeze({\n amountCents,\n appliedDiscount: null,\n authoritative: false,\n discountableSubtotalCents,\n discountCents: 0,\n items,\n lineItems,\n paymentOption,\n serviceFeeCents,\n subtotalCents,\n tipCents,\n totalCents,\n });\n}\n"],"mappings":"0iBAGA,SAAgB,GACd,EACA,CACA,IAAM,EAAU,EAA2B,EAAS,YAAY,EAChE,MAAO,CACL,GAAG,EACH,WAAY,EAAQ,aACpB,gBAAiB,EAAQ,iBAC3B,CACF,CCyBA,MAAM,EAAsB,EAAS,CACnC,WACA,UACA,WACA,kBACF,CAAC,EACK,EAAwB,EAAS,CAAC,OAAQ,iBAAiB,CAAC,EAC5D,EAAmC,EAAS,EAAkB,CAAC,CAAC,EAChE,GAA2B,EAAS,CAAC,YAAa,UAAU,CAAC,EAC7D,GAAqB,EACzB,EAAO,CACL,SAAU,EACR,EAAO,CACL,UAAW,EACX,uBAAwB,EACxB,kBAAmB,EACnB,OAAQ,EACV,CAAC,CACH,EACA,aAAc,EACZ,EAAO,CACL,GAAI,EACJ,WAAY,EAAM,CAAoB,EACtC,kBAAmB,EAAkB,CAAC,EACtC,OAAQ,EACV,CAAC,CACH,CACF,CAAC,EACD,CAAE,SAAU,CAAC,EAAG,aAAc,CAAC,CAAE,CACnC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Ac,CAAa,GACnC,GAAiB,GACjB,EAAgB,WAEhB,MAAU,UAAU,4BAA4B,EAElD,IAAM,EAA4B,EAAU,QACzC,EAAO,IACN,GAAS,EAAS,iBAAmB,EAAS,cAAgB,GAChE,CACF,EACM,EAAkB,EACpB,KAAK,MACF,EAAgB,EAAQ,cAAc,0BACrC,GACJ,EACA,EACE,EAAc,EAAgB,EAC9B,EAAa,EAAc,EACjC,GAAI,CAAC,OAAO,cAAc,CAAU,GAAK,EAAa,WACpD,MAAU,UAAU,4BAA4B,EAGlD,OAAO,EAAW,CAChB,cACA,gBAAiB,KACjB,cAAe,GACf,4BACA,cAAe,EACf,QACA,YACA,gBACA,kBACA,gBACA,WACA,YACF,CAAC,CACH"}
1
+ {"version":3,"file":"checkout.js","names":[],"sources":["../src/checkout-environment.ts","../src/checkout-schemas.ts","../src/checkout-input-schemas.ts","../src/custom-amount.ts","../src/checkout-selection.ts","../src/snapshots.ts","../src/checkout-client.ts","../src/checkout-estimate.ts"],"sourcesContent":["import { resolveResourceEnvironment } from \"./environment.ts\";\nimport type { CreateLockerverseWidgetOptions } from \"./types.ts\";\n\nexport function resolveWidgetEnvironment(\n options: CreateLockerverseWidgetOptions\n) {\n const runtime = resolveResourceEnvironment(options, \"widgetSlug\");\n return {\n ...runtime,\n widgetSlug: runtime.resourceSlug,\n widgetSlugValue: runtime.resourceSlugValue,\n };\n}\n","import {\n array,\n boolean,\n check,\n finite,\n type InferOutput,\n literal,\n looseObject,\n maxValue,\n minValue,\n nullable,\n number,\n object,\n optional,\n parser,\n picklist,\n pipe,\n regex,\n safeParse,\n string,\n transform,\n unknown,\n variant,\n} from \"valibot\";\n\nimport {\n vPaymentWidgetPaymentResultResponseDto,\n vPaymentWidgetQuoteResponseDto,\n vPublicPaymentWidgetResponseDto,\n} from \"./generated/public-api/valibot.gen.ts\";\nimport {\n customFieldsSchema,\n nonEmptyStringSchema,\n optionalNullableStringSchema,\n safeIntegerSchema,\n} from \"./schema-helpers.ts\";\n\nconst paymentOptionSchema = picklist([\n \"one-time\",\n \"monthly\",\n \"annually\",\n \"every-six-months\",\n]);\nconst fulfillmentTypeSchema = picklist([\"none\", \"event_admission\"]);\nconst nullableNonNegativeIntegerSchema = nullable(safeIntegerSchema(0));\nconst availabilityStatusSchema = picklist([\"available\", \"sold_out\"]);\nconst availabilitySchema = optional(\n object({\n listings: array(\n object({\n listingId: nonEmptyStringSchema,\n maxPurchasableQuantity: nullableNonNegativeIntegerSchema,\n remainingQuantity: nullableNonNegativeIntegerSchema,\n status: availabilityStatusSchema,\n })\n ),\n sharedLimits: array(\n object({\n id: nonEmptyStringSchema,\n listingIds: array(nonEmptyStringSchema),\n remainingQuantity: safeIntegerSchema(0),\n status: availabilityStatusSchema,\n })\n ),\n }),\n { listings: [], sharedLimits: [] }\n);\nconst publishableKeySchema = pipe(\n string(),\n regex(/^pk_(?:test|live)_\\S+$/, \"Invalid publishable key.\")\n);\n\nconst productBaseEntries = {\n description: optionalNullableStringSchema,\n fulfillmentType: fulfillmentTypeSchema,\n id: nonEmptyStringSchema,\n inventoryQuantity: nullableNonNegativeIntegerSchema,\n maxQuantity: nullableNonNegativeIntegerSchema,\n minimumAmountCents: nullableNonNegativeIntegerSchema,\n minQuantity: nullableNonNegativeIntegerSchema,\n name: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n};\n\nconst eventSchema = object({\n description: nullable(string()),\n endAt: nonEmptyStringSchema,\n id: nonEmptyStringSchema,\n location: nullable(string()),\n name: nonEmptyStringSchema,\n startAt: nonEmptyStringSchema,\n status: picklist([\"draft\", \"active\", \"finished\", \"cancelled\"]),\n});\n\nconst publicProductSchema = variant(\"pricingMode\", [\n object({\n ...productBaseEntries,\n amountCents: safeIntegerSchema(0),\n pricingMode: literal(\"fixed\"),\n }),\n object({\n ...productBaseEntries,\n amountCents: nullableNonNegativeIntegerSchema,\n pricingMode: literal(\"custom\"),\n }),\n]);\n\nconst productListingSchema = object({\n acceptsDiscounts: optional(boolean(), false),\n id: nonEmptyStringSchema,\n maxQuantityPerOrder: optional(nullableNonNegativeIntegerSchema, null),\n product: publicProductSchema,\n productId: nonEmptyStringSchema,\n slug: nonEmptyStringSchema,\n});\n\nconst widgetFieldsSchema = optional(\n object({\n memberId: optional(boolean(), false),\n merchSize: optional(boolean(), false),\n phone: optional(boolean(), false),\n promoCode: optional(boolean(), false),\n serviceFee: optional(boolean(), false),\n shipping: optional(boolean(), false),\n tipping: optional(boolean(), false),\n }),\n {}\n);\n\nconst requiredShippingSchema = optional(\n object({\n additionalUnitAmountCents: optional(\n pipe(safeIntegerSchema(0), maxValue(2_147_483_647))\n ),\n productId: nonEmptyStringSchema,\n triggerProductIds: array(nonEmptyStringSchema),\n })\n);\n\nexport const publicWidgetSchema = pipe(\n object({\n availability: availabilitySchema,\n community: optional(\n object({\n color: string(),\n memberIdLabel: optional(nullable(string())),\n name: nonEmptyStringSchema,\n thumbnail: nullable(string()),\n widgetAchEnabled: optional(boolean()),\n })\n ),\n config: optional(\n object({\n customFields: customFieldsSchema,\n fields: widgetFieldsSchema,\n requiredShipping: requiredShippingSchema,\n })\n ),\n description: optionalNullableStringSchema,\n event: nullable(eventSchema),\n id: optional(string(), \"\"),\n name: optional(string(), \"Lockerverse widget\"),\n payment: object({\n connectedAccountId: optional(nullable(nonEmptyStringSchema), null),\n currency: literal(\"usd\"),\n publishableKey: publishableKeySchema,\n }),\n pricingPolicy: optional(\n object({\n currency: optional(literal(\"usd\"), \"usd\"),\n serviceFeeRateBasisPoints: optional(safeIntegerSchema(0), 0),\n })\n ),\n products: optional(array(productListingSchema), []),\n showCommunityBranding: optional(boolean(), true),\n title: optionalNullableStringSchema,\n }),\n transform((widget) => ({\n ...widget,\n config: {\n customFields: widget.config?.customFields ?? [],\n fields: {\n memberId: widget.config?.fields?.memberId ?? false,\n merchSize: widget.config?.fields?.merchSize ?? false,\n phone: widget.config?.fields?.phone ?? false,\n promoCode: widget.config?.fields?.promoCode ?? false,\n serviceFee: widget.config?.fields?.serviceFee ?? false,\n shipping: widget.config?.fields?.shipping ?? false,\n tipping: widget.config?.fields?.tipping ?? false,\n },\n requiredShipping: widget.config?.requiredShipping,\n },\n pricingPolicy: widget.pricingPolicy ?? {\n currency: \"usd\" as const,\n serviceFeeRateBasisPoints: 0,\n },\n }))\n);\n\nconst catalogProductSchema = object({\n acceptsDiscounts: boolean(),\n amountCents: nullable(safeIntegerSchema(0)),\n description: nullable(string()),\n fulfillmentType: fulfillmentTypeSchema,\n id: nonEmptyStringSchema,\n inventoryQuantity: nullableNonNegativeIntegerSchema,\n listingId: nonEmptyStringSchema,\n maximumQuantity: nullableNonNegativeIntegerSchema,\n minimumAmountCents: nullableNonNegativeIntegerSchema,\n minimumQuantity: nullableNonNegativeIntegerSchema,\n name: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n pricingMode: picklist([\"fixed\", \"custom\"]),\n slug: nonEmptyStringSchema,\n});\n\nconst catalogSchema = object({\n availability: availabilitySchema,\n community: nullable(\n object({\n accentColor: string(),\n imageUrl: nullable(string()),\n memberIdLabel: optional(nullable(string())),\n name: nonEmptyStringSchema,\n widgetAchEnabled: optional(boolean()),\n })\n ),\n event: nullable(eventSchema),\n payment: object({\n connectedAccountId: optional(nullable(nonEmptyStringSchema), null),\n currency: literal(\"usd\"),\n publishableKey: publishableKeySchema,\n }),\n pricingPolicy: object({\n currency: literal(\"usd\"),\n serviceFeeRateBasisPoints: safeIntegerSchema(0),\n }),\n products: array(catalogProductSchema),\n widget: object({\n customFields: customFieldsSchema,\n description: nullable(string()),\n fields: widgetFieldsSchema,\n id: string(),\n name: nonEmptyStringSchema,\n requiredShipping: requiredShippingSchema,\n showCommunityBranding: boolean(),\n title: nullable(string()),\n }),\n});\n\nconst appliedDiscountSchema = nullable(\n object({\n amountOffCents: optional(safeIntegerSchema(0)),\n message: optional(string()),\n percentageOff: optional(\n pipe(number(), finite(), minValue(0), maxValue(100))\n ),\n source: picklist([\"email_list\", \"promo_code\"]),\n })\n);\n\nconst checkoutLineItemSchema = object({\n acceptsDiscounts: boolean(),\n eventId: nullable(nonEmptyStringSchema),\n fulfillmentType: fulfillmentTypeSchema,\n listingId: nonEmptyStringSchema,\n listingSlug: nonEmptyStringSchema,\n paymentOption: paymentOptionSchema,\n pricingMode: picklist([\"fixed\", \"custom\"]),\n productId: nonEmptyStringSchema,\n productName: nonEmptyStringSchema,\n quantity: safeIntegerSchema(1),\n subtotalCents: safeIntegerSchema(0),\n unitAmountCents: safeIntegerSchema(0),\n});\n\nexport const checkoutQuoteSchema = pipe(\n vPaymentWidgetQuoteResponseDto,\n object({\n amountCents: safeIntegerSchema(0),\n appliedDiscount: appliedDiscountSchema,\n connectedAccountId: nullable(nonEmptyStringSchema),\n discountableSubtotalCents: safeIntegerSchema(0),\n discountCents: safeIntegerSchema(0),\n lineItems: array(checkoutLineItemSchema),\n paymentOption: paymentOptionSchema,\n serviceFeeCents: safeIntegerSchema(0),\n subtotalCents: safeIntegerSchema(0),\n tipCents: safeIntegerSchema(0),\n totalCents: safeIntegerSchema(0),\n }),\n check(({ lineItems, paymentOption }) => {\n if (\n lineItems.length === 0 ||\n lineItems.some((item) => item.paymentOption !== paymentOption)\n ) {\n return false;\n }\n return (\n paymentOption === \"one-time\" ||\n (lineItems.length === 1 &&\n lineItems[0]?.pricingMode === \"fixed\" &&\n lineItems[0].quantity === 1)\n );\n }, \"Invalid checkout cadence composition.\")\n);\n\nexport const paymentResultSchema = pipe(\n object({\n ...vPaymentWidgetPaymentResultResponseDto.entries,\n retryUrl: optional(pipe(nonEmptyStringSchema, regex(/^https:\\/\\//))),\n }),\n check((payment) => {\n if (!(payment.checkoutId.trim() && payment.paymentReference.trim())) {\n return false;\n }\n if (payment.checkoutStatus === \"action_required\") {\n return (\n payment.paymentRequired &&\n ((payment.requiresAction && Boolean(payment.clientSecret?.trim())) ||\n (!payment.requiresAction &&\n payment.clientSecret === null &&\n Boolean(payment.retryUrl)))\n );\n }\n return !payment.requiresAction && payment.clientSecret === null;\n }, \"Invalid payment result state.\")\n);\n\nexport type PublicCheckoutQuote = InferOutput<typeof checkoutQuoteSchema>;\nexport type PublicProductListing = InferOutput<typeof productListingSchema>;\nexport type PublicWidget = InferOutput<typeof publicWidgetSchema>;\n\nexport const parseCheckoutQuote = parser(checkoutQuoteSchema);\nexport const parseCatalog = parser(catalogSchema);\nexport const parsePaymentResult = parser(paymentResultSchema);\nconst parsePublicWidgetContract = parser(vPublicPaymentWidgetResponseDto);\nconst parseSdkPublicWidget = parser(publicWidgetSchema);\n\nexport function parsePublicWidget<Input>(input: Input) {\n parsePublicWidgetContract(input);\n return parseSdkPublicWidget(input);\n}\n\nexport function parsePublicWidgetLoad<Input>(input: Input) {\n const response = safeParse(\n looseObject({ quote: optional(unknown()) }),\n input\n );\n const widget = parsePublicWidget(input);\n const quote = response.success ? response.output.quote : undefined;\n return quote === undefined\n ? { widget }\n : { quote: parseCheckoutQuote(quote), widget };\n}\n","import {\n array,\n boolean,\n type InferOutput,\n literal,\n looseObject,\n minLength,\n nullable,\n object,\n optional,\n parser,\n picklist,\n pipe,\n record,\n strictObject,\n string,\n transform,\n union,\n unknown,\n} from \"valibot\";\n\nimport { parseCheckoutQuote } from \"./checkout-schemas.ts\";\nimport {\n customFieldAnswerSchema,\n nonEmptyStringSchema,\n safeIntegerSchema,\n} from \"./schema-helpers.ts\";\n\nconst checkoutPricingEntries = {\n email: optional(string()),\n includeServiceFee: optional(boolean()),\n promoCode: optional(string()),\n tipCents: optional(safeIntegerSchema(0)),\n};\n\nconst checkoutPricingInputSchema = strictObject(checkoutPricingEntries);\n\nexport const parseCheckoutPricingInput = parser(\n optional(checkoutPricingInputSchema, {})\n);\n\nconst paymentSubmissionSchema = strictObject({\n confirmationToken: optional(nonEmptyStringSchema),\n customFieldAnswers: optional(array(customFieldAnswerSchema)),\n email: string(),\n memberId: optional(string()),\n merchSize: optional(picklist([\"XS\", \"S\", \"M\", \"L\", \"XL\", \"XXL\", \"XXXL\"])),\n metadata: optional(record(string(), string())),\n paymentMethodConfiguration: optional(literal(\"explicit\")),\n phone: optional(string()),\n shipping: optional(\n strictObject({\n address: strictObject({\n city: string(),\n country: string(),\n line1: string(),\n line2: optional(string()),\n postal_code: string(),\n state: string(),\n }),\n name: string(),\n })\n ),\n});\n\nconst checkoutItemSchema = union([\n strictObject({\n amountCents: safeIntegerSchema(1),\n productId: nonEmptyStringSchema,\n }),\n strictObject({\n productId: nonEmptyStringSchema,\n quantity: safeIntegerSchema(1),\n }),\n strictObject({\n productId: nonEmptyStringSchema,\n }),\n]);\n\nconst checkoutSelectionItemSchema = union([\n strictObject({\n amountCents: safeIntegerSchema(1),\n productSlug: nonEmptyStringSchema,\n }),\n strictObject({\n productSlug: nonEmptyStringSchema,\n quantity: safeIntegerSchema(1),\n }),\n strictObject({\n productSlug: nonEmptyStringSchema,\n }),\n]);\n\nconst checkoutItemsSchema = pipe(array(checkoutItemSchema), minLength(1));\nconst checkoutSelectionItemsSchema = pipe(\n array(checkoutSelectionItemSchema),\n minLength(1)\n);\n\nconst loadCheckoutInputSchema = object({\n selection: checkoutSelectionItemsSchema,\n});\n\nconst calculateTotalInputSchema = looseObject({\n catalog: optional(unknown()),\n email: optional(unknown()),\n includeServiceFee: optional(unknown()),\n items: optional(checkoutItemsSchema),\n promoCode: optional(unknown()),\n selection: optional(checkoutSelectionItemsSchema),\n tipCents: optional(unknown()),\n});\n\nconst preparedCheckoutInputSchema = pipe(\n looseObject({\n authoritative: literal(true),\n items: checkoutItemsSchema,\n payment: object({\n connectedAccountId: nullable(nonEmptyStringSchema),\n currency: literal(\"usd\"),\n publishableKey: pipe(string(), minLength(1)),\n }),\n paymentReference: pipe(string(), minLength(1)),\n pricing: checkoutPricingInputSchema,\n }),\n transform((checkout) => {\n const { items, payment, paymentReference, pricing, ...quoteInput } =\n checkout;\n const parsedQuote = parseCheckoutQuote({\n ...quoteInput,\n connectedAccountId: payment.connectedAccountId,\n });\n const { connectedAccountId, ...quote } = parsedQuote;\n return {\n items,\n pricing,\n quote: {\n ...quote,\n authoritative: true as const,\n payment: {\n connectedAccountId,\n currency: \"usd\" as const,\n publishableKey: payment.publishableKey,\n },\n paymentOption: parsedQuote.paymentOption,\n paymentReference,\n },\n };\n })\n);\n\nconst submitPaymentInputSchema = looseObject({\n checkout: preparedCheckoutInputSchema,\n submission: paymentSubmissionSchema,\n});\n\nconst paymentReferenceInputSchema = nonEmptyStringSchema;\nconst parseCatalogInputFields = parser(looseObject({}));\n\nexport type ParsedPreparedCheckoutInput = InferOutput<\n typeof preparedCheckoutInputSchema\n>;\nexport type ParsedLoadCheckoutInput = InferOutput<\n typeof loadCheckoutInputSchema\n>;\nexport type ParsedPaymentReferenceInput = InferOutput<\n typeof paymentReferenceInputSchema\n>;\nexport type ParsedSubmitPaymentInput = InferOutput<\n typeof submitPaymentInputSchema\n>;\n\nconst parseCalculateTotalInputFields = parser(calculateTotalInputSchema);\n\nexport function parseCalculateTotalInput<Input>(input: Input) {\n const { catalog, items, selection, ...pricingInput } =\n parseCalculateTotalInputFields(input);\n let parsedCatalog: ReturnType<typeof parseCatalogInputFields>;\n try {\n parsedCatalog = parseCatalogInputFields(catalog);\n } catch (error) {\n throw new TypeError(\"A catalog is required to calculate a checkout.\", {\n cause: error,\n });\n }\n try {\n return {\n catalog: parsedCatalog,\n items,\n pricing: parseCheckoutPricingInput(pricingInput),\n selection,\n };\n } catch (error) {\n throw new TypeError(\"Checkout pricing input is invalid.\", { cause: error });\n }\n}\n\nexport type ParsedCalculateTotalInput = ReturnType<\n typeof parseCalculateTotalInput\n>;\nexport type ParsedCheckoutPricingInput = InferOutput<\n typeof checkoutPricingInputSchema\n>;\n\nexport const parseLoadCheckoutInput = parser(loadCheckoutInputSchema);\nexport const parsePaymentReferenceInput = parser(paymentReferenceInputSchema);\nexport const parsePreparedCheckoutInput = parser(preparedCheckoutInputSchema);\nexport const parseSubmitPaymentInput = parser(submitPaymentInputSchema);\n\nexport const parseCheckoutSelectionItems = parser(checkoutSelectionItemsSchema);\n","import type { LockerverseProduct } from \"./types.ts\";\n\nconst minimumCustomAmountCents = 100;\n\nexport function getLockerverseMinimumCustomAmountCents(\n product: Pick<LockerverseProduct, \"minimumAmountCents\">\n) {\n return Math.max(minimumCustomAmountCents, product.minimumAmountCents ?? 0);\n}\n","import { parseCheckoutSelectionItems } from \"./checkout-input-schemas.ts\";\nimport { getLockerverseMinimumCustomAmountCents } from \"./custom-amount.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCheckoutItem,\n LockerverseCheckoutLineItem,\n LockerverseCheckoutSelectionItem,\n LockerverseProduct,\n} from \"./types.ts\";\nimport { LockerverseSdkError } from \"./types.ts\";\n\ntype ResolvedSelectionItem = {\n checkoutItem: LockerverseCheckoutItem;\n quantity: number;\n unitAmountCents: number;\n};\n\nexport function assertCheckoutItemsAreAvailable(\n catalog: LockerverseCatalog,\n items: LockerverseCheckoutItem[]\n) {\n const listingIdByProductId = new Map(\n catalog.products.map(({ id, listingId }) => [id, listingId])\n );\n const requestedByListingId = items.reduce((requested, item) => {\n const listingId = listingIdByProductId.get(item.productId);\n if (listingId) {\n requested.set(\n listingId,\n (requested.get(listingId) ?? 0) +\n (\"quantity\" in item ? (item.quantity ?? 1) : 1)\n );\n }\n return requested;\n }, new Map<string, number>());\n const listingIsSoldOut = catalog.availability.listings.some(\n ({ listingId, maxPurchasableQuantity, status }) =>\n requestedByListingId.has(listingId) &&\n (status === \"sold_out\" ||\n (maxPurchasableQuantity !== null &&\n (requestedByListingId.get(listingId) ?? 0) > maxPurchasableQuantity))\n );\n const sharedLimitIsSoldOut = catalog.availability.sharedLimits.some(\n ({ listingIds, remainingQuantity, status }) => {\n const requestedQuantity = listingIds.reduce(\n (total, listingId) =>\n total + (requestedByListingId.get(listingId) ?? 0),\n 0\n );\n return (\n requestedQuantity > 0 &&\n (status === \"sold_out\" || requestedQuantity > remainingQuantity)\n );\n }\n );\n if (listingIsSoldOut || sharedLimitIsSoldOut) {\n throw new LockerverseSdkError({\n code: \"total_calculation_failed\",\n message: \"This option is sold out.\",\n operation: \"calculate_total\",\n reportable: false,\n serverCode: \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\",\n });\n }\n}\n\nfunction resolveAmountItem(\n product: LockerverseProduct,\n amountCents: number\n): ResolvedSelectionItem {\n if (\n product.pricingMode !== \"custom\" ||\n product.paymentOption !== \"one-time\" ||\n amountCents < getLockerverseMinimumCustomAmountCents(product)\n ) {\n throw new TypeError(\"Selected Product amount is invalid.\");\n }\n return {\n checkoutItem: { amountCents, productId: product.id },\n quantity: 1,\n unitAmountCents: amountCents,\n };\n}\n\nfunction resolveFixedItem(\n product: LockerverseProduct,\n quantity: number\n): ResolvedSelectionItem {\n if (product.pricingMode !== \"fixed\" || product.amountCents === null) {\n throw new TypeError(\"Selected Product quantity is invalid.\");\n }\n if (product.paymentOption !== \"one-time\" && quantity !== 1) {\n throw new TypeError(\"Selected recurring Product is invalid.\");\n }\n if (\n (product.minimumQuantity !== null && quantity < product.minimumQuantity) ||\n (product.maximumQuantity !== null && quantity > product.maximumQuantity) ||\n (product.inventoryQuantity !== null && quantity > product.inventoryQuantity)\n ) {\n throw new TypeError(\"Selected Product quantity is invalid.\");\n }\n return {\n checkoutItem:\n product.paymentOption === \"one-time\"\n ? { productId: product.id, quantity }\n : { productId: product.id },\n quantity,\n unitAmountCents: product.amountCents,\n };\n}\n\nfunction resolveSelectionItem(\n catalog: LockerverseCatalog,\n product: LockerverseProduct,\n selection: LockerverseCheckoutSelectionItem\n) {\n const selectedQuantity = \"quantity\" in selection ? selection.quantity : 1;\n const resolved =\n \"amountCents\" in selection\n ? resolveAmountItem(product, selection.amountCents)\n : resolveFixedItem(product, selectedQuantity);\n const { checkoutItem, quantity, unitAmountCents } = resolved;\n\n return {\n checkoutItem,\n lineItem: {\n acceptsDiscounts: product.acceptsDiscounts,\n eventId:\n product.fulfillmentType === \"event_admission\" && catalog.event\n ? catalog.event.id\n : null,\n fulfillmentType: product.fulfillmentType,\n listingId: product.listingId,\n listingSlug: product.slug,\n paymentOption: product.paymentOption,\n pricingMode: product.pricingMode,\n productId: product.id,\n productName: product.name,\n quantity,\n subtotalCents: unitAmountCents * quantity,\n unitAmountCents,\n } satisfies LockerverseCheckoutLineItem,\n };\n}\n\nexport function resolveCheckoutSelection(\n catalog: LockerverseCatalog,\n input: LockerverseCheckoutSelectionItem[]\n) {\n let selection = parseCheckoutSelectionItems(input);\n const shipping = catalog.widget.requiredShipping;\n if (shipping) {\n const shippingProduct = catalog.products.find(\n ({ id }) => id === shipping.productId\n );\n const needsShipping = selection.some((item) =>\n catalog.products.some(\n (product) =>\n product.slug === item.productSlug &&\n shipping.triggerProductIds.includes(product.id)\n )\n );\n selection = selection.filter(\n (item) => item.productSlug !== shippingProduct?.slug\n );\n if (needsShipping) {\n if (!shippingProduct) {\n throw new TypeError(\"Required shipping Product is unavailable.\");\n }\n selection.push({ productSlug: shippingProduct.slug, quantity: 1 });\n }\n }\n const selectedProducts = new Set<string>();\n const resolved = selection.map((item) => {\n const product = catalog.products.find(\n (candidate) => candidate.slug === item.productSlug\n );\n if (!product) {\n throw new TypeError(\"Selected Product is unavailable.\");\n }\n if (selectedProducts.has(product.id)) {\n throw new TypeError(\"Each Product can appear only once per checkout.\");\n }\n selectedProducts.add(product.id);\n return resolveSelectionItem(catalog, product, item);\n });\n if (shipping?.additionalUnitAmountCents) {\n const triggerQuantity = resolved.reduce(\n (total, { lineItem }) =>\n total +\n (shipping.triggerProductIds.includes(lineItem.productId)\n ? lineItem.quantity\n : 0),\n 0\n );\n const shippingLine = resolved.find(\n ({ lineItem }) => lineItem.productId === shipping.productId\n )?.lineItem;\n if (shippingLine) {\n const amountCents =\n shippingLine.unitAmountCents +\n Math.max(0, triggerQuantity - 1) * shipping.additionalUnitAmountCents;\n if (!Number.isSafeInteger(amountCents) || amountCents > 2_147_483_647) {\n throw new TypeError(\"Required shipping amount is invalid.\");\n }\n shippingLine.unitAmountCents = amountCents;\n shippingLine.subtotalCents = amountCents;\n }\n }\n const paymentOption = resolved[0]?.lineItem.paymentOption;\n if (!paymentOption) {\n throw new TypeError(\"Select at least one Product.\");\n }\n if (\n resolved.length > 1 &&\n (paymentOption !== \"one-time\" ||\n resolved.some(({ lineItem }) => lineItem.paymentOption !== paymentOption))\n ) {\n throw new TypeError(\"Recurring Products must be purchased separately.\");\n }\n const items = resolved.map(({ checkoutItem }) => checkoutItem);\n assertCheckoutItemsAreAvailable(catalog, items);\n return {\n items,\n lineItems: resolved.map(({ lineItem }) => lineItem),\n paymentOption,\n };\n}\n","import type { PublicProductListing, PublicWidget } from \"./checkout-schemas.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCommunityBranding,\n LockerversePaymentResult,\n LockerversePreparedCheckout,\n LockerverseProduct,\n} from \"./types.ts\";\n\nfunction mapProduct(listing: PublicProductListing): LockerverseProduct {\n const { product } = listing;\n\n return {\n acceptsDiscounts: listing.acceptsDiscounts ?? false,\n amountCents: product.amountCents,\n description: product.description ?? null,\n fulfillmentType: product.fulfillmentType,\n id: product.id,\n inventoryQuantity: product.inventoryQuantity,\n listingId: listing.id,\n maximumQuantity: listing.maxQuantityPerOrder,\n minimumAmountCents: product.minimumAmountCents,\n minimumQuantity: product.minQuantity,\n name: product.name,\n paymentOption: product.paymentOption,\n pricingMode: product.pricingMode,\n slug: listing.slug,\n };\n}\n\nfunction mapCommunity(\n community: PublicWidget[\"community\"]\n): LockerverseCommunityBranding | null {\n if (!community) {\n return null;\n }\n const branding: LockerverseCommunityBranding = {\n accentColor: community.color,\n imageUrl: community.thumbnail || null,\n name: community.name,\n };\n if (community.widgetAchEnabled !== undefined) {\n branding.widgetAchEnabled = community.widgetAchEnabled;\n }\n if (community.memberIdLabel !== undefined) {\n branding.memberIdLabel = community.memberIdLabel;\n }\n return branding;\n}\n\nexport function createCatalog(widget: PublicWidget): LockerverseCatalog {\n const fields = widget.config?.fields ?? {};\n\n return {\n availability: widget.availability,\n community: mapCommunity(widget.community),\n event: widget.event\n ? {\n description: widget.event.description,\n endAt: widget.event.endAt,\n id: widget.event.id,\n location: widget.event.location,\n name: widget.event.name,\n startAt: widget.event.startAt,\n status: widget.event.status,\n }\n : null,\n payment: {\n connectedAccountId: widget.payment.connectedAccountId,\n currency: widget.payment.currency,\n publishableKey: widget.payment.publishableKey,\n },\n pricingPolicy: {\n currency: \"usd\",\n serviceFeeRateBasisPoints:\n widget.pricingPolicy?.serviceFeeRateBasisPoints ?? 0,\n },\n products: (widget.products ?? []).map(mapProduct),\n widget: {\n customFields: widget.config?.customFields ?? [],\n description: widget.description ?? null,\n fields: {\n memberId: fields.memberId ?? false,\n merchSize: fields.merchSize ?? false,\n phone: fields.phone ?? false,\n promoCode: fields.promoCode ?? false,\n serviceFee: fields.serviceFee ?? false,\n shipping: fields.shipping ?? false,\n tipping: fields.tipping ?? false,\n },\n id: widget.id ?? \"\",\n name: widget.name ?? \"Lockerverse widget\",\n requiredShipping: widget.config?.requiredShipping,\n showCommunityBranding: widget.showCommunityBranding ?? true,\n title: widget.title ?? null,\n },\n };\n}\n\nexport function cloneCatalog(catalog: LockerverseCatalog): LockerverseCatalog {\n return cloneSnapshot(catalog);\n}\n\nexport function clonePreparedCheckout(\n checkout: LockerversePreparedCheckout\n): LockerversePreparedCheckout {\n return cloneSnapshot(checkout);\n}\n\nexport function clonePaymentResult(\n paymentResult: LockerversePaymentResult\n): LockerversePaymentResult {\n return cloneSnapshot(paymentResult);\n}\n\nfunction cloneSnapshot<T>(value: T): T {\n return deepFreeze(structuredClone(value));\n}\n","import { object, picklist, safeParse } from \"valibot\";\nimport { resolveWidgetEnvironment } from \"./checkout-environment.ts\";\nimport {\n type ParsedCalculateTotalInput,\n type ParsedCheckoutPricingInput,\n parseCalculateTotalInput,\n parseLoadCheckoutInput,\n parsePaymentReferenceInput,\n parseSubmitPaymentInput,\n} from \"./checkout-input-schemas.ts\";\nimport {\n parseCatalog,\n parseCheckoutQuote,\n parsePaymentResult,\n parsePublicWidgetLoad,\n} from \"./checkout-schemas.ts\";\nimport {\n assertCheckoutItemsAreAvailable,\n resolveCheckoutSelection,\n} from \"./checkout-selection.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport { createSdkErrorReporter } from \"./error-reporting.ts\";\nimport {\n cloneCatalog,\n clonePaymentResult,\n clonePreparedCheckout,\n createCatalog,\n} from \"./snapshots.ts\";\nimport { createTransport } from \"./transport.ts\";\nimport {\n type CreateLockerverseWidgetOptions,\n type LockerverseCalculateTotalInput,\n type LockerverseCatalog,\n type LockerverseCheckoutClient,\n type LockerverseCheckoutItem,\n type LockerverseCheckoutPricingInput,\n type LockerverseCheckoutSelectionItem,\n type LockerverseLoadCheckoutInput,\n type LockerverseLoadedCheckout,\n type LockerversePreparedCheckout,\n LockerverseSdkError,\n type LockerverseSdkOperation,\n type LockerverseSdkServerCode,\n type LockerverseSubmitPaymentInput,\n} from \"./types.ts\";\n\ntype OperationErrorContext = {\n code:\n | \"payment_status_failed\"\n | \"payment_submit_failed\"\n | \"total_calculation_failed\"\n | \"widget_load_failed\";\n message: string;\n operation:\n | \"calculate_total\"\n | \"get_payment_status\"\n | \"load_widget\"\n | \"submit_payment\";\n};\n\nconst MAX_SELECTED_WIDGET_URL_LENGTH = 4000;\nconst paymentServerErrorSchema = object({\n code: picklist([\n \"PAYMENT_WIDGET_PHONE_INVALID\",\n \"PAYMENT_WIDGET_PHONE_REQUIRED\",\n \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\",\n ]),\n});\n\nasync function readPaymentServerCode(\n response: Response\n): Promise<LockerverseSdkServerCode | undefined> {\n if (response.status !== 400 && response.status !== 409) {\n return;\n }\n try {\n const result = safeParse(paymentServerErrorSchema, await response.json());\n return result.success ? result.output.code : undefined;\n } catch {\n // Non-JSON error bodies do not contain a safe server code.\n }\n}\n\nfunction resolveCalculateTotalItems({\n catalog,\n items,\n selection,\n}: ParsedCalculateTotalInput) {\n if (items !== undefined && selection !== undefined) {\n throw new TypeError(\"Use items or selection, not both.\");\n }\n const selectionCatalog = cloneCatalog(parseCatalog(catalog));\n const checkoutItems =\n selection === undefined\n ? requireCheckoutItems(items)\n : resolveCheckoutSelection(selectionCatalog, selection).items;\n assertCheckoutItemsAreAvailable(selectionCatalog, checkoutItems);\n return {\n catalog: selectionCatalog,\n items: checkoutItems,\n };\n}\n\nfunction requireCheckoutItems(\n items: ParsedCalculateTotalInput[\"items\"]\n): LockerverseCheckoutItem[] {\n if (items === undefined) {\n throw new TypeError(\"Checkout selection is invalid.\");\n }\n return items;\n}\n\nexport function createLockerverseCheckoutClient(\n options: CreateLockerverseWidgetOptions\n): LockerverseCheckoutClient {\n const {\n apiBaseUrl,\n communitySlug,\n communitySlugValue,\n environment,\n fetchImplementation,\n onError,\n requestTimeoutMs,\n sentryDsn,\n widgetSlug,\n widgetSlugValue,\n } = resolveWidgetEnvironment(options);\n const reportError = createSdkErrorReporter({\n communitySlug: communitySlugValue,\n environment,\n getContext: () => ({ widgetSlug: widgetSlugValue }),\n onError,\n resourceContextName: \"lockerverse_widget\",\n sentryDsn,\n });\n const { requestJson } = createTransport(\n fetchImplementation,\n reportError,\n requestTimeoutMs\n );\n const checkoutBaseUrl = `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}/checkout`;\n const widgetUrl = `${apiBaseUrl}/v2/community/${communitySlug}/payment-widgets/${widgetSlug}`;\n\n function invalidInput(\n message: string,\n operation: LockerverseSdkOperation,\n code: \"invalid_selection\" | \"payment_submit_failed\" = \"invalid_selection\"\n ): never {\n throw reportError(\n new LockerverseSdkError({\n code,\n message,\n operation,\n reportable: false,\n })\n );\n }\n\n function normalizeOperationError<ErrorValue>(\n error: ErrorValue,\n context: OperationErrorContext\n ) {\n return error instanceof LockerverseSdkError\n ? error\n : new LockerverseSdkError({ ...context, reportable: true });\n }\n\n function failOperation<ErrorValue>(\n error: ErrorValue,\n context: OperationErrorContext,\n recoveryMayBeRequired = false\n ): never {\n const normalized = normalizeOperationError(error, context);\n const recoveryRecommended =\n recoveryMayBeRequired &&\n (normalized.status === undefined || normalized.status >= 500);\n if (!recoveryRecommended) {\n throw reportError(normalized);\n }\n const recoveryError = new LockerverseSdkError({\n code: normalized.code,\n failureKind: normalized.failureKind,\n message: normalized.message,\n operation: normalized.operation,\n recoveryRecommended: true,\n reportable: normalized.reportable,\n status: normalized.status,\n });\n throw reportError(recoveryError);\n }\n\n function normalizePricingInput(input: ParsedCheckoutPricingInput) {\n const email = input.email?.trim().toLowerCase();\n const promoCode = input.promoCode?.trim();\n const pricing: LockerverseCheckoutPricingInput = {};\n if (email) {\n pricing.email = email;\n }\n if (input.includeServiceFee !== undefined) {\n pricing.includeServiceFee = input.includeServiceFee;\n }\n if (promoCode) {\n pricing.promoCode = promoCode;\n }\n if (input.tipCents !== undefined) {\n pricing.tipCents = input.tipCents;\n }\n return pricing;\n }\n\n function normalizeLoadSelection(input: LockerverseLoadCheckoutInput) {\n try {\n return parseLoadCheckoutInput(input).selection;\n } catch {\n invalidInput(\"Checkout selection is invalid.\", \"load_widget\");\n }\n }\n\n function createPreparedCheckout(\n quote: ReturnType<typeof parseCheckoutQuote>,\n items: LockerverseCheckoutItem[],\n pricing: LockerverseCheckoutPricingInput,\n payment: LockerverseCatalog[\"payment\"]\n ): LockerversePreparedCheckout {\n const { connectedAccountId, ...checkoutQuote } = quote;\n return clonePreparedCheckout(\n deepFreeze({\n ...checkoutQuote,\n authoritative: true as const,\n items,\n payment: {\n connectedAccountId,\n currency: \"usd\" as const,\n publishableKey: payment.publishableKey,\n },\n paymentOption: quote.paymentOption,\n paymentReference: globalThis.crypto.randomUUID(),\n pricing,\n })\n );\n }\n\n function resolveSelectedCheckoutItems(\n catalog: LockerverseCatalog,\n selection: LockerverseCheckoutSelectionItem[],\n operation: LockerverseSdkOperation\n ) {\n try {\n return resolveCheckoutSelection(catalog, selection).items;\n } catch (error) {\n if (error instanceof TypeError) {\n invalidInput(error.message, operation);\n }\n throw error;\n }\n }\n\n function createSelectedCheckout(\n catalog: LockerverseCatalog,\n selection: LockerverseCheckoutSelectionItem[],\n quote: ReturnType<typeof parseCheckoutQuote> | undefined,\n context: OperationErrorContext\n ) {\n if (!quote) {\n throw new LockerverseSdkError({\n ...context,\n message: \"Lockerverse did not return the requested initial quote.\",\n reportable: true,\n });\n }\n const checkoutItems = resolveSelectedCheckoutItems(\n catalog,\n selection,\n context.operation\n );\n return deepFreeze({\n catalog: cloneCatalog(catalog),\n checkout: createPreparedCheckout(\n quote,\n checkoutItems,\n { includeServiceFee: catalog.widget.fields.serviceFee },\n catalog.payment\n ),\n });\n }\n\n function requestWidgetResource(): Promise<LockerverseCatalog>;\n function requestWidgetResource(\n selection: LockerverseCheckoutSelectionItem[]\n ): Promise<LockerverseLoadedCheckout>;\n async function requestWidgetResource(\n selection?: LockerverseCheckoutSelectionItem[]\n ): Promise<LockerverseCatalog | LockerverseLoadedCheckout> {\n const context = {\n code: \"widget_load_failed\" as const,\n message: \"Lockerverse returned an invalid widget catalog.\",\n operation: \"load_widget\" as const,\n };\n const requestUrl = selection\n ? `${widgetUrl}?selection=${encodeURIComponent(JSON.stringify(selection))}`\n : widgetUrl;\n const request = () =>\n requestJson(\n requestUrl,\n selection ? { cache: \"no-store\" } : undefined,\n parsePublicWidgetLoad,\n {\n ...context,\n message:\n \"Unable to load Lockerverse widget because the request failed.\",\n report: false,\n },\n { ...context, report: false },\n readPaymentServerCode\n );\n async function requestWithRetry() {\n try {\n return await request();\n } catch (error) {\n if (\n !(error instanceof LockerverseSdkError) ||\n (error.failureKind !== \"network\" && error.failureKind !== \"timeout\")\n ) {\n throw error;\n }\n }\n // Retry only this public GET. A checkout POST can create an uncertain payment.\n return request();\n }\n const response = await requestWithRetry();\n if (!response.ok) {\n const serverCode = response.errorValue;\n if (serverCode === \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\") {\n throw new LockerverseSdkError({\n ...context,\n message: \"This option is sold out.\",\n reportable: false,\n serverCode,\n status: response.response.status,\n });\n }\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to load Lockerverse widget (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n const catalog = deepFreeze(createCatalog(response.value.widget));\n if (!selection) {\n return cloneCatalog(catalog);\n }\n return createSelectedCheckout(\n catalog,\n selection,\n response.value.quote,\n context\n );\n }\n\n async function loadLargeSelection(\n selection: LockerverseCheckoutSelectionItem[],\n context: OperationErrorContext\n ): Promise<LockerverseLoadedCheckout> {\n const loaded = await requestWidgetResource();\n const pricing = {\n includeServiceFee: loaded.widget.fields.serviceFee,\n };\n const items = resolveSelectedCheckoutItems(\n loaded,\n selection,\n context.operation\n );\n return deepFreeze({\n catalog: loaded,\n checkout: await requestCheckoutQuote(\n items,\n pricing,\n loaded.payment,\n context\n ),\n });\n }\n\n async function loadWidget(\n selection?: LockerverseCheckoutSelectionItem[]\n ): Promise<LockerverseCatalog | LockerverseLoadedCheckout> {\n const context = {\n code: \"widget_load_failed\" as const,\n message: \"Lockerverse returned an invalid widget catalog.\",\n operation: \"load_widget\" as const,\n };\n try {\n if (\n selection &&\n `${widgetUrl}?selection=${encodeURIComponent(JSON.stringify(selection))}`\n .length > MAX_SELECTED_WIDGET_URL_LENGTH\n ) {\n return await loadLargeSelection(selection, context);\n }\n return selection\n ? await requestWidgetResource(selection)\n : await requestWidgetResource();\n } catch (error) {\n failOperation(error, context);\n }\n }\n\n function load(): Promise<LockerverseCatalog>;\n function load(\n input: LockerverseLoadCheckoutInput\n ): Promise<LockerverseLoadedCheckout>;\n function load(input?: LockerverseLoadCheckoutInput) {\n return input === undefined\n ? loadWidget()\n : loadWidget(normalizeLoadSelection(input));\n }\n\n async function requestCheckoutQuote(\n items: LockerverseCheckoutItem[],\n pricing: LockerverseCheckoutPricingInput,\n payment: LockerverseCatalog[\"payment\"],\n context: OperationErrorContext\n ) {\n const response = await requestJson(\n `${checkoutBaseUrl}/quote`,\n {\n body: JSON.stringify({ ...pricing, items }),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n },\n parseCheckoutQuote,\n {\n ...context,\n message:\n \"Unable to calculate the Lockerverse checkout total because the request failed.\",\n report: false,\n },\n { ...context, report: false },\n readPaymentServerCode\n );\n if (!response.ok) {\n const serverCode = response.errorValue;\n if (serverCode === \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\") {\n throw new LockerverseSdkError({\n ...context,\n message: \"This option is sold out.\",\n reportable: false,\n serverCode,\n status: response.response.status,\n });\n }\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to calculate the Lockerverse checkout total (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n return createPreparedCheckout(response.value, items, pricing, payment);\n }\n\n async function calculateTotal(input: LockerverseCalculateTotalInput) {\n const { catalog, items, pricing } = normalizeCalculateTotalInput(input);\n const context = {\n code: \"total_calculation_failed\" as const,\n message: \"Lockerverse returned an invalid checkout total.\",\n operation: \"calculate_total\" as const,\n };\n try {\n return await requestCheckoutQuote(\n items,\n pricing,\n catalog.payment,\n context\n );\n } catch (error) {\n failOperation(error, context);\n }\n }\n\n function normalizeCalculateTotalInput(input: LockerverseCalculateTotalInput) {\n try {\n const parsed = parseCalculateTotalInput(input);\n const resolved = resolveCalculateTotalItems(parsed);\n const pricing = normalizePricingInput(parsed.pricing);\n return {\n catalog: resolved.catalog,\n items: resolved.items,\n pricing:\n pricing.includeServiceFee === undefined\n ? {\n ...pricing,\n includeServiceFee: resolved.catalog.widget.fields.serviceFee,\n }\n : pricing,\n };\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n throw error;\n }\n invalidInput(\n error instanceof TypeError\n ? error.message\n : \"Checkout selection is invalid.\",\n \"calculate_total\"\n );\n }\n }\n\n function normalizeSubmitPaymentInput(input: LockerverseSubmitPaymentInput) {\n try {\n const parsed = parseSubmitPaymentInput(input);\n const {\n items,\n pricing: pricingInput,\n quote: quoteInput,\n } = parsed.checkout;\n const pricing = normalizePricingInput(pricingInput);\n const quote = deepFreeze(quoteInput);\n const { submission } = parsed;\n if (quote.totalCents > 0 && !submission.confirmationToken) {\n invalidInput(\n \"Stripe confirmation is required for a paid checkout.\",\n \"submit_payment\",\n \"payment_submit_failed\"\n );\n }\n const email = submission.email.trim().toLowerCase();\n if (!email || email !== pricing.email) {\n invalidInput(\n \"Payment email must match the current checkout quote.\",\n \"submit_payment\"\n );\n }\n return {\n items,\n pricing,\n quote,\n submission: { ...submission, email },\n };\n } catch (error) {\n if (error instanceof LockerverseSdkError) {\n throw error;\n }\n invalidInput(\n \"Lockerverse payment submission is invalid.\",\n \"submit_payment\",\n \"payment_submit_failed\"\n );\n }\n }\n\n return {\n calculateTotal,\n async getPaymentStatus(paymentReference) {\n let normalizedReference: string;\n try {\n normalizedReference =\n parsePaymentReferenceInput(paymentReference).trim();\n } catch {\n invalidInput(\n \"Provide a payment reference to recover its status.\",\n \"get_payment_status\"\n );\n }\n const context = {\n code: \"payment_status_failed\" as const,\n message: \"Lockerverse returned an invalid payment status.\",\n operation: \"get_payment_status\" as const,\n };\n try {\n const response = await requestJson(\n `${checkoutBaseUrl}/${encodeURIComponent(normalizedReference)}/status`,\n undefined,\n parsePaymentResult,\n {\n ...context,\n message:\n \"Unable to recover the Lockerverse payment status because the request failed.\",\n report: false,\n },\n { ...context, report: false }\n );\n if (!response.ok) {\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to recover the Lockerverse payment status (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n if (response.value.paymentReference !== normalizedReference) {\n throw new LockerverseSdkError({ ...context, reportable: true });\n }\n return clonePaymentResult(response.value);\n } catch (error) {\n failOperation(error, context);\n }\n },\n load,\n async submitPayment(input) {\n const { items, pricing, quote, submission } =\n normalizeSubmitPaymentInput(input);\n const context = {\n code: \"payment_submit_failed\" as const,\n message: \"Lockerverse returned an invalid payment confirmation.\",\n operation: \"submit_payment\" as const,\n };\n try {\n const response = await requestJson(\n `${checkoutBaseUrl}/confirm`,\n {\n body: JSON.stringify({\n confirmationToken: submission.confirmationToken,\n customFieldAnswers: submission.customFieldAnswers,\n email: submission.email,\n expectedAmountCents: quote.amountCents,\n expectedAppliedDiscount: quote.appliedDiscount,\n expectedConnectedAccountId: quote.payment.connectedAccountId,\n expectedDiscountableSubtotalCents:\n quote.discountableSubtotalCents,\n expectedDiscountCents: quote.discountCents,\n expectedServiceFeeCents: quote.serviceFeeCents,\n expectedSubtotalCents: quote.subtotalCents,\n expectedTipCents: quote.tipCents,\n expectedTotalCents: quote.totalCents,\n ...pricing,\n items,\n memberId: submission.memberId,\n merchSize: submission.merchSize,\n metadata: submission.metadata,\n paymentMethodConfiguration: submission.paymentMethodConfiguration,\n paymentReference: quote.paymentReference,\n phone: submission.phone,\n quoteContractVersion: 1,\n shipping: submission.shipping,\n }),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n },\n parsePaymentResult,\n {\n ...context,\n message:\n \"Unable to submit the Lockerverse payment because the request failed.\",\n report: false,\n },\n { ...context, report: false },\n readPaymentServerCode\n );\n if (!response.ok) {\n const serverCode = response.errorValue;\n if (serverCode) {\n throw new LockerverseSdkError({\n ...context,\n message:\n serverCode === \"PAYMENT_WIDGET_SALES_LIMIT_REACHED\"\n ? \"This option is sold out.\"\n : `Unable to submit the Lockerverse payment (${response.response.status}).`,\n reportable: false,\n serverCode,\n status: response.response.status,\n });\n }\n throw new LockerverseSdkError({\n ...context,\n message: `Unable to submit the Lockerverse payment (${response.response.status}).`,\n reportable: response.response.status >= 500,\n status: response.response.status,\n });\n }\n if (response.value.paymentReference !== quote.paymentReference) {\n throw new LockerverseSdkError({ ...context, reportable: true });\n }\n return clonePaymentResult(response.value);\n } catch (error) {\n failOperation(error, context, true);\n }\n },\n };\n}\n","import { parseCheckoutPricingInput } from \"./checkout-input-schemas.ts\";\nimport { resolveCheckoutSelection } from \"./checkout-selection.ts\";\nimport { deepFreeze } from \"./deep-freeze.ts\";\nimport type {\n LockerverseCatalog,\n LockerverseCheckoutEstimate,\n LockerverseEstimateCheckoutInput,\n} from \"./types.ts\";\n\nexport function estimateLockerverseCheckout(\n catalog: LockerverseCatalog,\n input: LockerverseEstimateCheckoutInput\n): LockerverseCheckoutEstimate {\n const { selection, ...pricingInput } = input;\n let pricing: ReturnType<typeof parseCheckoutPricingInput>;\n try {\n pricing = parseCheckoutPricingInput(pricingInput);\n } catch (error) {\n throw new TypeError(\"Checkout pricing is invalid.\", { cause: error });\n }\n const includeServiceFee =\n pricing.includeServiceFee ?? catalog.widget.fields.serviceFee;\n const { tipCents = 0 } = pricing;\n const { items, lineItems, paymentOption } = resolveCheckoutSelection(\n catalog,\n selection\n );\n const subtotalCents = lineItems.reduce(\n (total, lineItem) => total + lineItem.subtotalCents,\n 0\n );\n if (\n !Number.isSafeInteger(subtotalCents) ||\n subtotalCents <= 0 ||\n subtotalCents > 2_147_483_647\n ) {\n throw new TypeError(\"Checkout total is invalid.\");\n }\n const discountableSubtotalCents = lineItems.reduce(\n (total, lineItem) =>\n total + (lineItem.acceptsDiscounts ? lineItem.subtotalCents : 0),\n 0\n );\n const serviceFeeCents = includeServiceFee\n ? Math.round(\n (subtotalCents * catalog.pricingPolicy.serviceFeeRateBasisPoints) /\n 10_000\n )\n : 0;\n const amountCents = subtotalCents + serviceFeeCents;\n const totalCents = amountCents + tipCents;\n if (!Number.isSafeInteger(totalCents) || totalCents > 2_147_483_647) {\n throw new TypeError(\"Checkout total is invalid.\");\n }\n\n return deepFreeze({\n amountCents,\n appliedDiscount: null,\n authoritative: false,\n discountableSubtotalCents,\n discountCents: 0,\n items,\n lineItems,\n paymentOption,\n serviceFeeCents,\n subtotalCents,\n tipCents,\n totalCents,\n });\n}\n"],"mappings":"0iBAGA,SAAgB,GACd,EACA,CACA,IAAM,EAAU,EAA2B,EAAS,YAAY,EAChE,MAAO,CACL,GAAG,EACH,WAAY,EAAQ,aACpB,gBAAiB,EAAQ,iBAC3B,CACF,CCyBA,MAAM,EAAsB,EAAS,CACnC,WACA,UACA,WACA,kBACF,CAAC,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AAC,EAEhE,OAAO,GAAmB,EAAS,KAAK,CAC1C,OAAS,EAAO,CACd,EAAc,EAAO,EAAS,EAAI,CACpC,CACF,CACF,CACF,CChqBA,SAAgB,GACd,EACA,EAC6B,CAC7B,GAAM,CAAE,YAAW,GAAG,GAAiB,EACnC,EACJ,GAAI,CACF,EAAU,EAA0B,CAAY,CAClD,OAAS,EAAO,CACd,MAAU,UAAU,+BAAgC,CAAE,MAAO,CAAM,CAAC,CACtE,CACA,IAAM,EACJ,EAAQ,mBAAqB,EAAQ,OAAO,OAAO,WAC/C,CAAE,WAAW,GAAM,EACnB,CAAE,QAAO,YAAW,iBAAkB,EAC1C,EACA,CACF,EACM,EAAgB,EAAU,QAC7B,EAAO,IAAa,EAAQ,EAAS,cACtC,CACF,EACA,GACE,CAAC,OAAO,cAAc,CAAa,GACnC,GAAiB,GACjB,EAAgB,WAEhB,MAAU,UAAU,4BAA4B,EAElD,IAAM,EAA4B,EAAU,QACzC,EAAO,IACN,GAAS,EAAS,iBAAmB,EAAS,cAAgB,GAChE,CACF,EACM,EAAkB,EACpB,KAAK,MACF,EAAgB,EAAQ,cAAc,0BACrC,GACJ,EACA,EACE,EAAc,EAAgB,EAC9B,EAAa,EAAc,EACjC,GAAI,CAAC,OAAO,cAAc,CAAU,GAAK,EAAa,WACpD,MAAU,UAAU,4BAA4B,EAGlD,OAAO,EAAW,CAChB,cACA,gBAAiB,KACjB,cAAe,GACf,4BACA,cAAe,EACf,QACA,YACA,gBACA,kBACA,gBACA,WACA,YACF,CAAC,CACH"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { B as LockerverseSdkErrorCode, C as LockerverseEnvironment, V as LockerverseSdkOperation, n as LOCKERVERSE_SDK_VERSION, z as LockerverseSdkError } from "./types.js";
1
+ import { B as LockerverseSdkErrorCode, C as LockerverseEnvironment, H as LockerverseSdkOperation, n as LOCKERVERSE_SDK_VERSION, z as LockerverseSdkError } from "./types.js";
2
2
  //#region src/generated/public-api/core/auth.gen.d.ts
3
3
  type AuthToken = string | undefined;
4
4
  interface Auth {
package/dist/telemetry.js CHANGED
@@ -4,5 +4,5 @@ ${JSON.stringify(t)}
4
4
  `),typeof n==`string`||n instanceof Uint8Array)i(n);else{let e;try{e=JSON.stringify(n)}catch{e=JSON.stringify(O(n))}i(e)}}return typeof r==`string`?r:sn(r)}function sn(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function cn(e){let t=typeof e.data==`string`?an(e.data):e.data;return[{type:`attachment`,length:t.length,filename:e.filename,content_type:e.contentType,attachment_type:e.attachmentType},t]}const ln={sessions:`session`,event:`error`,client_report:`internal`,user_report:`default`,profile_chunk:`profile`,replay_event:`replay`,replay_recording:`replay`,check_in:`monitor`,raw_security:`security`,log:`log_item`,trace_metric:`metric`};function un(e){return e in ln}function dn(e){return un(e)?ln[e]:e}function fn(e){if(!e?.sdk)return;let{name:t,version:n}=e.sdk;return{name:t,version:n}}function pn(e,t,n,r){let i=e.sdkProcessingMetadata?.dynamicSamplingContext;return{event_id:e.event_id,sent_at:new Date(D()).toISOString(),...t&&{sdk:t},...!!n&&r&&{dsn:z(r)},...i&&{trace:i}}}function mn(e,t){if(!t)return e;let n=e.sdk||{};return e.sdk={...n,name:n.name||t.name,version:n.version||t.version,integrations:[...e.sdk?.integrations||[],...t.integrations||[]],packages:[...e.sdk?.packages||[],...t.packages||[]],settings:e.sdk?.settings||t.settings?{...e.sdk?.settings,...t.settings}:void 0},e}function hn(e,t,n,r){let i=fn(n);return B({sent_at:new Date(D()).toISOString(),...i&&{sdk:i},...!!r&&t&&{dsn:z(t)}},[`aggregates`in e?[{type:`sessions`},e]:[{type:`session`},e.toJSON()]])}function gn(e,t,n,r){let i=fn(n),a=e.type&&e.type!==`replay_event`?e.type:`event`;mn(e,n?.sdk);let o=pn(e,i,r,t);return delete e.sdkProcessingMetadata,B(o,[[{type:a},e]])}function _n(e){return e.getOptions().traceLifecycle===`stream`}function vn(e,t){let{fingerprint:n,span:r,breadcrumbs:i,sdkProcessingMetadata:a}=t;xn(e,t),r&&wn(e,r),Tn(e,n),Sn(e,i),Cn(e,a)}function yn(e,t){let{extra:n,tags:r,attributes:i,user:a,contexts:o,level:s,sdkProcessingMetadata:c,breadcrumbs:l,fingerprint:u,eventProcessors:d,attachments:f,propagationContext:p,transactionName:m,span:h}=t;V(e,`extra`,n),V(e,`tags`,r),V(e,`attributes`,i),V(e,`user`,a),V(e,`contexts`,o),e.sdkProcessingMetadata=I(e.sdkProcessingMetadata,c,2),s&&(e.level=s),m&&(e.transactionName=m),h&&(e.span=h),l.length&&(e.breadcrumbs=[...e.breadcrumbs,...l]),u.length&&(e.fingerprint=[...e.fingerprint,...u]),d.length&&(e.eventProcessors=[...e.eventProcessors,...d]),f.length&&(e.attachments=[...e.attachments,...f]),e.propagationContext={...e.propagationContext,...p}}function V(e,t,n){e[t]=I(e[t],n,1)}function bn(e,t){let n=dt().getScopeData();return e&&yn(n,e.getScopeData()),t&&yn(n,t.getScopeData()),n}function xn(e,t){let{extra:n,tags:r,user:i,contexts:a,level:o,transactionName:s}=t;Object.keys(n).length&&(e.extra={...n,...e.extra}),Object.keys(r).length&&(e.tags={...r,...e.tags}),Object.keys(i).length&&(e.user={...i,...e.user}),Object.keys(a).length&&(e.contexts={...a,...e.contexts}),o&&(e.level=o),s&&e.type!==`transaction`&&(e.transaction=s)}function Sn(e,t){let n=[...e.breadcrumbs||[],...t];e.breadcrumbs=n.length?n:void 0}function Cn(e,t){e.sdkProcessingMetadata={...e.sdkProcessingMetadata,...t}}function wn(e,t){e.contexts={trace:kt(t),...e.contexts},e.sdkProcessingMetadata={dynamicSamplingContext:$t(t),...e.sdkProcessingMetadata};let n=Nt(Bt(t)).description;n&&!e.transaction&&e.type===`transaction`&&(e.transaction=n)}function Tn(e,t){e.fingerprint=e.fingerprint?Array.isArray(e.fingerprint)?e.fingerprint:[e.fingerprint]:[],t&&(e.fingerprint=e.fingerprint.concat(t)),e.fingerprint.length||delete e.fingerprint}function H(e){return new En(t=>{t(e)})}function U(e){return new En((t,n)=>{n(e)})}var En=class e{constructor(e){this._state=0,this._handlers=[],this._runExecutor(e)}then(t,n){return new e((e,r)=>{this._handlers.push([!1,n=>{if(!t)e(n);else try{e(t(n))}catch(e){r(e)}},t=>{if(!n)r(t);else try{e(n(t))}catch(e){r(e)}}]),this._executeHandlers()})}catch(e){return this.then(e=>e,e)}finally(t){return new e((e,n)=>{let r,i;return this.then(e=>{i=!1,r=e,t&&t()},e=>{i=!0,r=e,t&&t()}).then(()=>{if(i){n(r);return}e(r)})})}_executeHandlers(){if(this._state===0)return;let e=this._handlers.slice();this._handlers=[],e.forEach(e=>{e[0]||=(this._state===1&&e[1](this._value),this._state===2&&e[2](this._value),!0)})}_runExecutor(e){let t=(e,t)=>{if(this._state===0){if(C(t)){t.then(n,r);return}this._state=e,this._value=t,this._executeHandlers()}},n=e=>{t(1,e)},r=e=>{t(2,e)};try{e(n,r)}catch(e){r(e)}}};function Dn(e,t,n,r=0){try{let i=W(t,n,e,r);return C(i)?i:H(i)}catch(e){return U(e)}}function W(t,n,r,i){let a=r[i];if(!t||!a)return t;let o=a({...t},n);return e&&o===null&&g.log(`Event processor "${a.id||`?`}" dropped event`),C(o)?o.then(e=>W(e,n,r,i+1)):W(o,n,r,i+1)}let G,On,kn,K;function An(e){let n=t._sentryDebugIds,r=t._debugIds;if(!n&&!r)return{};let i=n?Object.keys(n):[],a=r?Object.keys(r):[];if(K&&i.length===On&&a.length===kn)return K;On=i.length,kn=a.length,K={},G||={};let o=(t,n)=>{for(let r of t){let t=n[r],i=G?.[r];if(i&&K&&t)K[i[0]]=t,G&&(G[r]=[i[0],t]);else if(t){let n=e(r);for(let e=n.length-1;e>=0;e--){let i=n[e]?.filename;if(i&&K&&G){K[i]=t,G[r]=[i,t];break}}}}};return n&&o(i,n),r&&o(a,r),K}function jn(e,t,n,r,i,a){let{normalizeDepth:o=3,normalizeMaxBreadth:s=1e3}=e,c={...t,event_id:t.event_id||n.event_id||M(),timestamp:t.timestamp||P()},l=n.integrations||e.integrations.map(e=>e.name);Mn(c,e),Fn(c,l),i&&i.emit(`applyFrameMetadata`,t),t.type===void 0&&Nn(c,e.stackParser);let u=Ln(r,n.captureContext);n.mechanism&&N(c,n.mechanism);let d=i?i.getEventProcessors():[],f=bn(a,u),p=[...n.attachments||[],...f.attachments];p.length&&(n.attachments=p),vn(c,f);let m=[...d,...f.eventProcessors];return(n.data&&n.data.__sentry__===!0?H(c):Dn(m,c,n)).then(e=>(e&&Pn(e),typeof o==`number`&&o>0?In(e,o,s):e))}function Mn(e,t){let{environment:n,release:r,dist:i,maxValueLength:a}=t;e.environment=e.environment||n||`production`,!e.release&&r&&(e.release=r),!e.dist&&i&&(e.dist=i);let o=e.request;o?.url&&a&&(o.url=A(o.url,a)),a&&e.exception?.values?.forEach(e=>{e.value&&=A(e.value,a)})}function Nn(e,t){let n=An(t);e.exception?.values?.forEach(e=>{e.stacktrace?.frames?.forEach(e=>{e.filename&&(e.debug_id=n[e.filename])})})}function Pn(e){let t={};if(e.exception?.values?.forEach(e=>{e.stacktrace?.frames?.forEach(e=>{e.debug_id&&(e.abs_path?t[e.abs_path]=e.debug_id:e.filename&&(t[e.filename]=e.debug_id),delete e.debug_id)})}),Object.keys(t).length===0)return;e.debug_meta=e.debug_meta||{},e.debug_meta.images=e.debug_meta.images||[];let n=e.debug_meta.images;Object.entries(t).forEach(([e,t])=>{n.push({type:`sourcemap`,code_file:e,debug_id:t})})}function Fn(e,t){t.length>0&&(e.sdk=e.sdk||{},e.sdk.integrations=[...e.sdk.integrations||[],...t])}function In(e,t,n){if(!e)return null;let r={...e,...e.breadcrumbs&&{breadcrumbs:e.breadcrumbs.map(e=>({...e,...e.data&&{data:O(e.data,t,n)}}))},...e.user&&{user:O(e.user,t,n)},...e.contexts&&{contexts:O(e.contexts,t,n)},...e.extra&&{extra:O(e.extra,t,n)}};return e.contexts?.trace&&r.contexts&&(r.contexts.trace=e.contexts.trace,e.contexts.trace.data&&(r.contexts.trace.data=O(e.contexts.trace.data,t,n))),e.spans&&(r.spans=e.spans.map(e=>({...e,...e.data&&{data:O(e.data,t,n)}}))),e.contexts?.flags&&r.contexts&&(r.contexts.flags=O(e.contexts.flags,3,n)),r}function Ln(e,t){if(!t)return e;let n=e?e.clone():new L;return n.update(t),n}function Rn(e){return typeof e==`object`&&typeof e.unref==`function`&&e.unref(),e}function zn(e){let t=e.protocol?`${e.protocol}:`:``,n=e.port?`:${e.port}`:``;return`${t}//${e.host}${n}${e.path?`/${e.path}`:``}/api/`}function Bn(e){return`${zn(e)}${e.projectId}/envelope/`}function Vn(e,t){let n={sentry_version:`7`};return e.publicKey&&(n.sentry_key=e.publicKey),t&&(n.sentry_client=`${t.name}/${t.version}`),new URLSearchParams(n).toString()}function Hn(e,t,n){return t||`${Bn(e)}?${Vn(e,n)}`}const Un=[];function Wn(e,t){let n={};return t.forEach(t=>{t?.beforeSetup&&t.beforeSetup(e)}),t.forEach(t=>{t&&Kn(e,t,n)}),n}function Gn(e,t){for(let n of t)n?.afterAllSetup&&n.afterAllSetup(e)}function Kn(t,n,r){if(r[n.name]){e&&g.log(`Integration skipped because it was already installed: ${n.name}`);return}if(r[n.name]=n,!Un.includes(n.name)&&typeof n.setupOnce==`function`&&(n.setupOnce(),Un.push(n.name)),n.setup&&typeof n.setup==`function`&&n.setup(t),typeof n.preprocessEvent==`function`){let e=n.preprocessEvent.bind(n);t.on(`preprocessEvent`,(n,r)=>e(n,r,t))}if(typeof n.processEvent==`function`){let e=n.processEvent.bind(n),r=Object.assign((n,r)=>e(n,r,t),{id:n.name});t.addEventProcessor(r)}[`processSpan`,`processSegmentSpan`].forEach(e=>{let r=n[e];typeof r==`function`&&t.on(e,e=>r.call(n,e,t))}),e&&g.log(`Integration installed: ${n.name}`)}function qn(){return typeof __SENTRY_BROWSER_BUNDLE__<`u`&&!!__SENTRY_BROWSER_BUNDLE__}function Jn(){
5
5
  /*! __SENTRY_SDK_SOURCE__ */
6
6
  return`npm`}function Yn(){return!qn()&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`}function Xn(){return typeof window<`u`&&(!Yn()||Zn())}function Zn(){return t.process?.type===`renderer`}function Qn(e,t){let n=t?`auto`:`never`;return[{type:`log`,item_count:e.length,content_type:`application/vnd.sentry.items.log+json`},{version:2,...Xn()&&{ingest_settings:{infer_ip:n,infer_user_agent:n}},items:e}]}function $n(e,t,n,r,i){let a={};return t?.sdk&&(a.sdk={name:t.sdk.name,version:t.sdk.version}),n&&r&&(a.dsn=z(r)),B(a,[Qn(e,i)])}function er(e,t){let n=t??tr(e)??[];if(n.length===0)return;let r=e.getOptions(),i=$n(n,r._metadata,r.tunnel,e.getDsn(),e.getDataCollectionOptions().userInfo);nr().set(e,[]),e.emit(`flushLogs`),e.sendEnvelope(i)}function tr(e){return nr().get(e)}function nr(){return a(`clientToLogBufferMap`,()=>new WeakMap)}function rr(e,t){let n=t?`auto`:`never`;return[{type:`trace_metric`,item_count:e.length,content_type:`application/vnd.sentry.items.trace-metric+json`},{version:2,...Xn()&&{ingest_settings:{infer_ip:n,infer_user_agent:n}},items:e}]}function ir(e,t,n,r,i){let a={};return t?.sdk&&(a.sdk={name:t.sdk.name,version:t.sdk.version}),n&&r&&(a.dsn=z(r)),B(a,[rr(e,i)])}function ar(e,t){let n=t??or(e)??[];if(n.length===0)return;let r=e.getOptions(),i=ir(n,r._metadata,r.tunnel,e.getDsn(),e.getDataCollectionOptions().userInfo);sr().set(e,[]),e.emit(`flushMetrics`),e.sendEnvelope(i)}function or(e){return sr().get(e)}function sr(){return a(`clientToMetricBufferMap`,()=>new WeakMap)}function cr(e){return Ft({trace_id:e.trace_id,span_id:e.span_id,parent_span_id:e.parent_span_id,name:e.description||``,start_timestamp:e.start_timestamp,end_timestamp:e.timestamp||e.start_timestamp,status:!e.status||e.status===`ok`||e.status===`cancelled`?`ok`:`error`,is_segment:!1,attributes:{...e.data},links:e.links})}function lr(e,t){if(e.type!==`transaction`||!e.spans?.length||!e.sdkProcessingMetadata?.hasGenAiSpans||t.getOptions().streamGenAiSpans===!1||_n(t))return;let n=[],r=[];for(let t of e.spans)t.op?.startsWith(`gen_ai.`)?n.push(cr(t)):r.push(t);if(n.length===0)return;e.spans=r;let i=t.getDataCollectionOptions().userInfo?`auto`:`never`;return[{type:`span`,item_count:n.length,content_type:`application/vnd.sentry.items.span.v2+json`},{version:2,...Xn()&&{ingest_settings:{infer_ip:i,infer_user_agent:i}},items:n}]}const ur=Symbol.for(`SentryBufferFullError`);function dr(e=100){let t=new Set;function n(){return t.size<e}function r(e){t.delete(e)}function i(e){if(!n())return U(ur);let i=e();return t.add(i),i.then(()=>r(i),()=>r(i)),i}function a(e){if(!t.size)return H(!0);let n=Promise.allSettled(Array.from(t)).then(()=>!0);if(!e)return n;let r=[n,new Promise(t=>Rn(setTimeout(()=>t(!1),e)))];return Promise.race(r)}return{get $(){return Array.from(t)},add:i,drain:a}}function fr(e,t=D()){let n=parseInt(`${e}`,10);if(!isNaN(n))return n*1e3;let r=Date.parse(`${e}`);return isNaN(r)?6e4:r-t}function pr(e,t){return e[t]||e.all||0}function mr(e,t,n=D()){return pr(e,t)>n}function hr(e,{statusCode:t,headers:n},r=D()){let i={...e},a=n?.[`x-sentry-rate-limits`],o=n?.[`retry-after`];if(a)for(let e of a.trim().split(`,`)){let[t,n,,,a]=e.split(`:`,5),o=parseInt(t,10),s=(isNaN(o)?60:o)*1e3;if(!n)i.all=r+s;else for(let e of n.split(`;`))e===`metric_bucket`?(!a||a.split(`;`).includes(`custom`))&&(i[e]=r+s):i[e]=r+s}else o?i.all=r+fr(o,r):t===429&&(i.all=r+6e4);return i}function gr(t,n,r=dr(t.bufferSize||64)){let i={},a=e=>r.drain(e);function o(a){let o=[];if(nn(a,(e,n)=>{let r=dn(n);mr(i,r)?t.recordDroppedEvent(`ratelimit_backoff`,r):o.push(e)}),o.length===0)return Promise.resolve({});let s=B(a[0],o),c=n=>{if(rn(s,[`client_report`])){e&&g.warn(`Dropping client report. Will not send outcomes (reason: ${n}).`);return}nn(s,(e,r)=>{t.recordDroppedEvent(n,dn(r))})};return r.add(()=>n({body:on(s)}).then(t=>t.statusCode===413?(e&&g.error(`Sentry responded with status code 413. Envelope was discarded due to exceeding size limits.`),c(`send_error`),t):(e&&t.statusCode!==void 0&&(t.statusCode<200||t.statusCode>=300)&&g.warn(`Sentry responded with status code ${t.statusCode} to sent event.`),i=hr(i,t),t),t=>{throw c(`network_error`),e&&g.error(`Encountered error running transport request:`,t),t})).then(e=>e,t=>{if(t===ur)return e&&g.error(`Skipped sending event because buffer is full.`),c(`queue_overflow`),Promise.resolve({});throw t})}return{send:o,flush:a}}function _r(e,t,n){let r=[{type:`client_report`},{timestamp:n||P(),discarded_events:e}];return B(t?{dsn:t}:{},[r])}function vr(e){let t=[];e.message&&t.push(e.message);try{let n=e.exception.values[e.exception.values.length-1];n?.value&&(t.push(n.value),n.type&&t.push(`${n.type}: ${n.value}`))}catch{}return t}function yr(e){let{trace_id:t,parent_span_id:n,span_id:r,status:i,origin:a,data:o,op:s}=e.contexts?.trace??{};return{data:o??{},description:e.transaction,op:s,parent_span_id:n,span_id:r??``,start_timestamp:e.start_timestamp??0,status:i,timestamp:e.timestamp,trace_id:t??``,origin:a,profile_id:o?.[`sentry.profile_id`],exclusive_time:o?.[`sentry.exclusive_time`],measurements:e.measurements,is_segment:!0}}function br(e){return{type:`transaction`,timestamp:e.timestamp,start_timestamp:e.start_timestamp,transaction:e.description,contexts:{trace:{trace_id:e.trace_id,span_id:e.span_id,parent_span_id:e.parent_span_id,op:e.op,status:e.status,origin:e.origin,data:{...e.data,...e.profile_id&&{"sentry.profile_id":e.profile_id},...e.exclusive_time&&{"sentry.exclusive_time":e.exclusive_time}}}},measurements:e.measurements}}const q=[`forwarded`,`-ip`,`remote-`,`via`,`-user`];function xr(e){return e===!0?{userInfo:!0,cookies:!0,httpHeaders:{request:!0,response:!0},httpBodies:[`incomingRequest`,`outgoingRequest`,`incomingResponse`,`outgoingResponse`],urlQueryParams:!0,graphQL:{document:!0,variables:!0},genAI:{inputs:!0,outputs:!0},databaseQueryData:!0,stackFrameVariables:!0,frameContextLines:7}:{userInfo:!1,cookies:{deny:q},httpHeaders:{request:{deny:q},response:{deny:q}},httpBodies:[],urlQueryParams:{deny:q},graphQL:{document:!0,variables:!0},genAI:{inputs:!1,outputs:!1},databaseQueryData:!1,stackFrameVariables:!0,frameContextLines:7}}const Sr={userInfo:!0,cookies:!0,httpHeaders:{request:!0,response:!0},httpBodies:[`incomingRequest`,`outgoingRequest`,`incomingResponse`,`outgoingResponse`],urlQueryParams:!0,graphQL:{document:!0,variables:!0},genAI:{inputs:!0,outputs:!0},databaseQueryData:!0,stackFrameVariables:!0,frameContextLines:5};function Cr(e){let t=e.dataCollection==null?xr(e.sendDefaultPii):Sr,n=e.dataCollection??{};return{userInfo:n.userInfo??t.userInfo,cookies:n.cookies??t.cookies,httpHeaders:{request:n.httpHeaders?.request??t.httpHeaders.request,response:n.httpHeaders?.response??t.httpHeaders.response},httpBodies:n.httpBodies??t.httpBodies,urlQueryParams:n.urlQueryParams??n.queryParams??t.urlQueryParams,graphQL:{document:n.graphQL?.document??t.graphQL.document,variables:n.graphQL?.variables??t.graphQL.variables},genAI:{inputs:n.genAI?.inputs??t.genAI.inputs,outputs:n.genAI?.outputs??t.genAI.outputs},databaseQueryData:n.databaseQueryData??t.databaseQueryData,stackFrameVariables:n.stackFrameVariables??t.stackFrameVariables,frameContextLines:n.frameContextLines??t.frameContextLines}}const wr=`Not capturing exception because it's already been captured.`,Tr=`Discarded session because of missing or non-string release`,Er=Symbol.for(`SentryInternalError`),Dr=Symbol.for(`SentryDoNotSendEventError`);function J(e){return{message:e,[Er]:!0}}function Or(e){return{message:e,[Dr]:!0}}function kr(e){return fe(e)&&Er in e}function Ar(e){return fe(e)&&Dr in e}function jr(e,t,n,r,i){let a=0,o,s=!1;e.on(n,()=>{a=0,clearTimeout(o),s=!1}),e.on(t,t=>{if(a+=r(t),a>=8e5)i(e);else if(!s){let t=e.getOptions()._flushInterval??5e3;t>0&&(s=!0,o=Rn(setTimeout(()=>{i(e)},t)))}}),e.on(`flush`,()=>{i(e)})}var Mr=class{constructor(t){if(this._options=t,this._integrations={},this._numProcessing=0,this._outcomes={},this._hooks={},this._eventProcessors=[],this._promiseBuffer=dr(t.transportOptions?.bufferSize??64),this._dataCollection=Cr(t),t.dsn?this._dsn=Et(t.dsn):e&&g.warn(`No DSN provided, client will not send events.`),this._dsn){let e=Hn(this._dsn,t.tunnel,t._metadata?t._metadata.sdk:void 0);this._transport=t.transport({tunnel:this._options.tunnel,recordDroppedEvent:this.recordDroppedEvent.bind(this),...t.transportOptions,url:e})}this._options.enableLogs=this._options.enableLogs??this._options._experiments?.enableLogs,this._options.enableLogs&&jr(this,`afterCaptureLog`,`flushLogs`,zr,er),(this._options.enableMetrics??this._options._experiments?.enableMetrics??!0)&&jr(this,`afterCaptureMetric`,`flushMetrics`,Rr,ar)}captureException(t,n,r){let i=M();if(Pe(t))return e&&g.log(wr),i;let a={event_id:i,...n};return this._process(()=>this.eventFromException(t,a).then(e=>this._captureEvent(e,a,r)).then(e=>e),`error`),a.event_id}captureMessage(e,t,n,r){let i={event_id:M(),...n},a=ue(e)?e:String(e),o=de(e),s=o?this.eventFromMessage(a,t,i):this.eventFromException(e,i);return this._process(()=>s.then(e=>this._captureEvent(e,i,r)),o?`unknown`:`error`),i.event_id}captureEvent(t,n,r){let i=M();if(n?.originalException&&Pe(n.originalException))return e&&g.log(wr),i;let a={event_id:i,...n},o=t.sdkProcessingMetadata||{},s=o.capturedSpanScope,c=o.capturedSpanIsolationScope,l=Nr(t.type);return this._process(()=>this._captureEvent(t,a,s||r,c),l),a.event_id}captureSession(e){this.sendSession(e),F(e,{init:!1})}getDsn(){return this._dsn}getOptions(){return this._options}getDataCollectionOptions(){return this._dataCollection}getSdkMetadata(){return this._options._metadata}getTransport(){return this._transport}async flush(e){let t=this._transport;if(this.emit(`flush`),!t)return!0;let n=await this._isClientDoneProcessing(e),r=await t.flush(e);return n&&r}async close(e){let t=await this.flush(e);return this.getOptions().enabled=!1,this.emit(`close`),t}getEventProcessors(){return this._eventProcessors}addEventProcessor(e){this._eventProcessors.push(e)}init(){(this._isEnabled()||this._options.integrations.some(({name:e})=>e.startsWith(`Spotlight`)))&&this._setupIntegrations()}getIntegrationByName(e){return this._integrations[e]}getIntegrationNames(){return Object.keys(this._integrations)}addIntegration(e){let t=this._integrations[e.name];!t&&e.beforeSetup&&e.beforeSetup(this),Kn(this,e,this._integrations),t||Gn(this,[e])}sendEvent(e,t={}){this.emit(`beforeSendEvent`,e,t);let n=lr(e,this),r=gn(e,this._dsn,this._options._metadata,this._options.tunnel);for(let e of t.attachments||[])r=tn(r,cn(e));n&&(r=tn(r,n)),this.sendEnvelope(r).then(t=>this.emit(`afterSendEvent`,e,t))}sendSession(t){let{release:n,environment:r=`production`}=this._options;if(`aggregates`in t){let i=t.attrs||{};if(!i.release&&!n){e&&g.warn(Tr);return}i.release=i.release||n,i.environment=i.environment||r,t.attrs=i}else{if(!t.release&&!n){e&&g.warn(Tr);return}t.release=t.release||n,t.environment=t.environment||r}this.emit(`beforeSendSession`,t);let i=hn(t,this._dsn,this._options._metadata,this._options.tunnel);this.sendEnvelope(i)}recordDroppedEvent(t,n,r=1){if(this._options.sendClientReports){let i=`${t}:${n}`;e&&g.log(`Recording outcome: "${i}"${r>1?` (${r} times)`:``}`),this._outcomes[i]=(this._outcomes[i]||0)+r}}on(e,t){let n=this._hooks[e]=this._hooks[e]||new Set,r=(...e)=>t(...e);return n.add(r),()=>{n.delete(r)}}emit(e,...t){let n=this._hooks[e];n&&n.forEach(e=>e(...t))}async sendEnvelope(t){if(this.emit(`beforeEnvelope`,t),this._isEnabled()&&this._transport)try{return await this._transport.send(t)}catch(t){return e&&g.error(`Error while sending envelope:`,t),{}}return e&&g.error(`Transport disabled`),{}}registerCleanup(e){}dispose(){}_setupIntegrations(){let{integrations:e}=this._options;this._integrations=Wn(this,e),Gn(this,e)}_updateSessionFromEvent(e,t){let n=t.level===`fatal`,r=!1,i=t.exception?.values;if(i){r=!0,n=!1;for(let e of i)if(e.mechanism?.handled===!1){n=!0;break}}let a=e.status===`ok`;(a&&e.errors===0||a&&n)&&(F(e,{...n&&{status:`crashed`},errors:e.errors||Number(r||n)}),this.captureSession(e))}async _isClientDoneProcessing(e){let t=0;for(;!e||t<e;){if(await new Promise(e=>setTimeout(e,1)),!this._numProcessing)return!0;t++}return!1}_isEnabled(){return this.getOptions().enabled!==!1&&this._transport!==void 0}_prepareEvent(e,t,n,r){let i=this.getOptions(),a=this.getIntegrationNames();return!t.integrations&&a.length&&(t.integrations=a),this.emit(`preprocessEvent`,e,t),e.type||r.setLastEventId(e.event_id||t.event_id),jn(i,e,t,n,this,r).then(e=>e===null?e:(this.emit(`postprocessEvent`,e,t),e.contexts={trace:{...e.contexts?.trace,...pt(n)},...e.contexts},e.sdkProcessingMetadata={dynamicSamplingContext:Qt(this,n),...e.sdkProcessingMetadata},e))}_captureEvent(t,n={},r=lt(),i=ut()){return e&&Ir(t)&&g.log(`Captured error event \`${vr(t)[0]||`<unknown>`}\``),this._processEvent(t,n,r,i).then(e=>e.event_id,t=>{e&&(Ar(t)?g.log(t.message):kr(t)?g.warn(t.message):g.warn(t))})}_processEvent(e,t,n,r){let i=this.getOptions(),{sampleRate:a}=i,o=Lr(e),s=Ir(e),c=`before send for type \`${e.type||`error`}\``,l=a===void 0?void 0:Dt(a);if(s&&typeof l==`number`&&E()>l)return this.recordDroppedEvent(`sample_rate`,`error`),U(Or(`Discarding event because it's not included in the random sample (sampling rate = ${a})`));let u=Nr(e.type);return this._prepareEvent(e,t,n,r).then(e=>{if(e===null)throw this.recordDroppedEvent(`event_processor`,u),Or("An event processor returned `null`, will not send event.");return t.data?.__sentry__===!0?e:Pr(Fr(this,i,e,t),c)}).then(i=>{if(i===null){if(this.recordDroppedEvent(`before_send`,u),o){let t=1+(e.spans||[]).length;this.recordDroppedEvent(`before_send`,`span`,t)}throw Or(`${c} returned \`null\`, will not send event.`)}let a=n.getSession()||r.getSession();if(s&&a&&this._updateSessionFromEvent(a,i),o){let e=(i.sdkProcessingMetadata?.spanCountBeforeProcessing||0)-(i.spans?i.spans.length:0);e>0&&this.recordDroppedEvent(`before_send`,`span`,e)}let l=i.transaction_info;return o&&l&&i.transaction!==e.transaction&&(i.transaction_info={...l,source:`custom`}),this.sendEvent(i,t),i}).then(null,e=>{throw Ar(e)||kr(e)?e:(this.captureException(e,{mechanism:{handled:!1,type:`internal`},data:{__sentry__:!0},originalException:e}),J(`Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.
7
- Reason: ${e}`))})}_process(e,t){this._numProcessing++,this._promiseBuffer.add(e).then(e=>(this._numProcessing--,e),e=>(this._numProcessing--,e===ur&&this.recordDroppedEvent(`queue_overflow`,t),e))}_clearOutcomes(){let e=this._outcomes;return this._outcomes={},Object.entries(e).map(([e,t])=>{let[n,r]=e.split(`:`);return{reason:n,category:r,quantity:t}})}_flushOutcomes(){e&&g.log(`Flushing outcomes...`);let t=this._clearOutcomes();if(t.length===0){e&&g.log(`No outcomes to send`);return}if(!this._dsn){e&&g.log(`No dsn provided, will not send outcomes`);return}e&&g.log(`Sending outcomes:`,t);let n=_r(t,this._options.tunnel&&z(this._dsn));this.sendEnvelope(n)}};function Nr(e){return e===`replay_event`?`replay`:e||`error`}function Pr(e,t){let n=`${t} must return \`null\` or a valid event.`;if(C(e))return e.then(e=>{if(!x(e)&&e!==null)throw J(n);return e},e=>{throw J(`${t} rejected with ${e}`)});if(!x(e)&&e!==null)throw J(n);return e}function Fr(e,t,n,r){let{beforeSend:i,beforeSendTransaction:a,ignoreSpans:o}=t,s=!en(t.beforeSendSpan)&&t.beforeSendSpan,c=n;if(Ir(c)&&i)return i(c,r);if(Lr(c)){if(s||o){let t=yr(c);if(o?.length&&Gt({description:t.description,op:t.op,attributes:t.data},o))return null;if(s){let e=s(t);e?c=I(n,br(e)):Ht()}if(c.spans){let t=[],n=c.spans;for(let e of n){if(o?.length&&Gt({description:e.description,op:e.op,attributes:e.data},o)){qt(n,e);continue}if(s){let n=s(e);n?t.push(n):(Ht(),t.push(e))}else t.push(e)}let r=c.spans.length-t.length;r&&e.recordDroppedEvent(`before_send`,`span`,r),c.spans=t}}if(a){if(c.spans){let e=c.spans.length;c.sdkProcessingMetadata={...n.sdkProcessingMetadata,spanCountBeforeProcessing:e}}return a(c,r)}}return c}function Ir(e){return e.type===void 0}function Lr(e){return e.type===`transaction`}function Rr(e){let t=0;return e.name&&(t+=e.name.length*2),t+=8,t+Br(e.attributes)}function zr(e){let t=0;return e.message&&(t+=e.message.length*2),t+Br(e.attributes)}function Br(e){if(!e)return 0;let t=0;return Object.values(e).forEach(e=>{Array.isArray(e)?t+=e.length*Vr(e[0]):de(e)?t+=Vr(e):t+=100}),t}function Vr(e){return typeof e==`string`?e.length*2:typeof e==`number`?8:typeof e==`boolean`?4:0}function Hr(e){`aggregates`in e?e.attrs?.ip_address===void 0&&(e.attrs={...e.attrs,ip_address:`{{auto}}`}):e.ipAddress===void 0&&(e.ipAddress=`{{auto}}`)}function Ur(e,t,r=[t],i=`npm`){let a=(e._metadata=e._metadata||{}).sdk=e._metadata.sdk||{};a.name||(a.name=`sentry.javascript.${t}`,a.packages=r.map(e=>({name:`${i}:@sentry/${e}`,version:n})),a.version=n)}function Wr(e){return v(e)&&`__sentry_fetch_url_host__`in e&&typeof e.__sentry_fetch_url_host__==`string`}function Gr(e){return Wr(e)?`${e.message} (${e.__sentry_fetch_url_host__})`:e.message}function Kr(e){return e&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(e.toString())}const Y=t;function qr(e,t){let n=Z(e,t),r={type:$r(t),value:ei(t)};return n.length&&(r.stacktrace={frames:n}),r.type===void 0&&r.value===``&&(r.value=`Unrecoverable error caught`),r}function Jr(e,t,n,r){let i=ft()?.getOptions().normalizeDepth,a=si(t),o={__serialized__:Ce(t,i)};if(a)return{exception:{values:[qr(e,a)]},extra:o};let s={exception:{values:[{type:S(t)?t.constructor.name:r?`UnhandledRejection`:`Error`,value:ai(t,{isUnhandledRejection:r})}]},extra:o};if(n){let t=Z(e,n);t.length&&(s.exception.values[0].stacktrace={frames:t})}return s}function X(e,t){return{exception:{values:[qr(e,t)]}}}function Z(e,t){let n=t.stacktrace||t.stack||``,r=Xr(t),i=Zr(t);try{return e(n,r,i)}catch{}return[]}const Yr=/Minified React error #\d+;/i;function Xr(e){return e&&Yr.test(e.message)?1:0}function Zr(e){return typeof e.framesToPop==`number`?e.framesToPop:0}function Qr(e){return typeof WebAssembly<`u`&&WebAssembly.Exception!==void 0&&e instanceof WebAssembly.Exception}function $r(e){let t=e?.name;return!t&&Qr(e)?e.message&&Array.isArray(e.message)&&e.message.length==2?e.message[0]:`WebAssembly.Exception`:t}function ei(e){let t=e?.message;return Qr(e)?Array.isArray(e.message)&&e.message.length==2?e.message[1]:`wasm exception`:t?t.error&&typeof t.error.message==`string`?Gr(t.error):Gr(e):`No error message`}function ti(e,t,n,r){let i=ri(e,t,n?.syntheticException||void 0,r);return N(i),i.level=`error`,n?.event_id&&(i.event_id=n.event_id),H(i)}function ni(e,t,n=`info`,r,i){let a=ii(e,t,r?.syntheticException||void 0,i);return a.level=n,r?.event_id&&(a.event_id=r.event_id),H(a)}function ri(e,t,n,r,i){let a;if(se(t)&&t.error)return X(e,t.error);if(ce(t)||le(t)){let i=t;if(`stack`in t){a=X(e,t);let i=a.exception?.values?.[0];if(r&&n&&i&&!i.stacktrace){let t=Z(e,n);t.length&&(i.stacktrace={frames:t},N(a,{synthetic:!0}))}}else{let t=i.name||(ce(i)?`DOMError`:`DOMException`),o=i.message?`${t}: ${i.message}`:t;a=ii(e,o,n,r),Ne(a,o)}return`code`in i&&(a.tags={...a.tags,"DOMException.code":`${i.code}`}),a}return v(t)?X(e,t):x(t)||S(t)?(a=Jr(e,t,n,i),N(a,{synthetic:!0}),a):(a=ii(e,t,n,r),Ne(a,`${t}`,void 0),N(a,{synthetic:!0}),a)}function ii(e,t,n,r){let i={};if(r&&n){let r=Z(e,n);r.length&&(i.exception={values:[{value:t,stacktrace:{frames:r}}]}),N(i,{synthetic:!0})}if(ue(t)){let{__sentry_template_string__:e,__sentry_template_values__:n}=t;return i.logentry={message:e,params:n},i}return i.message=t,i}function ai(e,{isUnhandledRejection:t}){let n=ve(e),r=t?`promise rejection`:`exception`;return se(e)?`Event \`ErrorEvent\` captured as ${r} with message \`${e.message}\``:S(e)?`Event \`${oi(e)}\` (type=${e.type}) captured as ${r}`:`Object captured as ${r} with keys: ${n}`}function oi(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function si(e){return Object.values(e).find(e=>e instanceof Error)}var ci=class extends Mr{constructor(e){let t=li(e);Ur(t,`browser`,[`browser`],Y.SENTRY_SDK_SOURCE||Jn()),super(t);let{userInfo:n}=this.getDataCollectionOptions();t._metadata?.sdk&&(t._metadata.sdk.settings={infer_ip:n?`auto`:`never`,...t._metadata.sdk.settings});let{sendClientReports:r}=this._options;Y.document&&Y.document.addEventListener(`visibilitychange`,()=>{Y.document.visibilityState===`hidden`&&(r&&this._flushOutcomes(),queueMicrotask(()=>{this.flush()}))}),n&&this.on(`beforeSendSession`,Hr)}eventFromException(e,t){return ti(this._options.stackParser,e,t,this._options.attachStacktrace)}eventFromMessage(e,t=`info`,n){return ni(this._options.stackParser,e,t,n,this._options.attachStacktrace)}_prepareEvent(e,t,n,r){return e.platform=e.platform||`javascript`,super._prepareEvent(e,t,n,r)}};function li(e){return{release:typeof __SENTRY_RELEASE__==`string`?__SENTRY_RELEASE__:Y.SENTRY_RELEASE?.id,sendClientReports:!0,parentSpanIsAlwaysRootSpan:!0,...e}}const ui=typeof __SENTRY_DEBUG__>`u`||__SENTRY_DEBUG__,Q=t,$={};function di(e){let t=$[e];if(t)return t;let n=Q[e];if(Kr(n))return $[e]=n.bind(Q);let r=Q.document;if(r&&typeof r.createElement==`function`)try{let t=r.createElement(`iframe`);t.hidden=!0,r.head.appendChild(t);let i=t.contentWindow;i?.[e]&&(n=i[e]),r.head.removeChild(t)}catch(t){ui&&g.warn(`Could not create sandbox iframe for ${e} check, bailing to window.${e}: `,t)}return n&&($[e]=n.bind(Q))}function fi(e){$[e]=void 0}function pi(e,t=di(`fetch`)){let n=0,r=0;async function i(i){let a=i.body.length;n+=a,r++;let o={body:i.body,method:`POST`,referrerPolicy:`strict-origin`,headers:e.headers,keepalive:n<=6e4&&r<15,...e.fetchOptions};try{let n=await t(e.url,o);return{statusCode:n.status,headers:{"x-sentry-rate-limits":n.headers.get(`X-Sentry-Rate-Limits`),"retry-after":n.headers.get(`Retry-After`)}}}catch(e){throw fi(`fetch`),e}finally{n-=a,r--}}return gr(e,i,dr(e.bufferSize||40))}function mi(e,t,n,r){let i={filename:e,function:t===`<anonymous>`?`?`:t,in_app:!0};return n!==void 0&&(i.lineno=n),r!==void 0&&(i.colno=r),i}const hi=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,gi=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,_i=/\((\S*)(?::(\d+))(?::(\d+))\)/,vi=/at (.+?) ?\(data:(.+?),/,yi=[30,e=>{let t=e.match(vi);if(t)return{filename:`<data:${t[2]}>`,function:t[1]};let n=hi.exec(e);if(n){let[,e,t,r]=n;return mi(e,`?`,+t,+r)}let r=gi.exec(e);if(r){if(r[2]?.indexOf(`eval`)===0){let e=_i.exec(r[2]);e&&(r[2]=e[1],r[3]=e[2],r[4]=e[3])}let[e,t]=Ci(r[1]||`?`,r[2]);return mi(t,e,r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}}],bi=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,xi=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Si=ne(yi,[50,e=>{let t=bi.exec(e);if(t){if(t[3]&&t[3].indexOf(` > eval`)>-1){let e=xi.exec(t[3]);e&&(t[1]=t[1]||`eval`,t[3]=e[1],t[4]=e[2],t[5]=``)}let e=t[3],n=t[1]||`?`;return[n,e]=Ci(n,e),mi(e,n,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}}]),Ci=(e,t)=>{let n=e.indexOf(`safari-extension`)!==-1,r=e.indexOf(`safari-web-extension`)!==-1;return n||r?[e.indexOf(`@`)===-1?`?`:e.split(`@`)[0],n?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},wi=new Map;function Ti(e){if(!e)return e;try{let t=new URL(e);return t.username=``,t.password=``,t.search=``,t.hash=``,t.toString()}catch{return e.replace(/[?#][^\s)]*/g,``)}}function Ei(e){Reflect.deleteProperty(e,`breadcrumbs`),Reflect.deleteProperty(e,`request`),Reflect.deleteProperty(e,`user`);for(let t of e.exception?.values??[])for(let e of t.stacktrace?.frames??[]){let t=Ti(e.filename);t&&(e.filename=t)}return e}function Di(e,t,n){let r=`${t}:${e}`,i=wi.get(r);if(i)return i;let a=new ci({beforeSend:Ei,dsn:e,environment:t,integrations:[],release:`@lockerverse/sdk@${n}`,sendDefaultPii:!1,stackParser:Si,transport:pi});return a.init(),wi.set(r,a),a}function Oi({context:e,contextName:t,dsn:n,environment:r,error:i}){try{let a=new L;a.setClient(Di(n,r,i.sdkVersion)),a.setTags({"sdk.code":i.code,"sdk.operation":i.operation,"sdk.version":i.sdkVersion,source:`lockerverse-sdk`}),a.setContext(t,e),a.captureException(i)}catch{}}export{Oi as captureSdkError};
7
+ Reason: ${e}`))})}_process(e,t){this._numProcessing++,this._promiseBuffer.add(e).then(e=>(this._numProcessing--,e),e=>(this._numProcessing--,e===ur&&this.recordDroppedEvent(`queue_overflow`,t),e))}_clearOutcomes(){let e=this._outcomes;return this._outcomes={},Object.entries(e).map(([e,t])=>{let[n,r]=e.split(`:`);return{reason:n,category:r,quantity:t}})}_flushOutcomes(){e&&g.log(`Flushing outcomes...`);let t=this._clearOutcomes();if(t.length===0){e&&g.log(`No outcomes to send`);return}if(!this._dsn){e&&g.log(`No dsn provided, will not send outcomes`);return}e&&g.log(`Sending outcomes:`,t);let n=_r(t,this._options.tunnel&&z(this._dsn));this.sendEnvelope(n)}};function Nr(e){return e===`replay_event`?`replay`:e||`error`}function Pr(e,t){let n=`${t} must return \`null\` or a valid event.`;if(C(e))return e.then(e=>{if(!x(e)&&e!==null)throw J(n);return e},e=>{throw J(`${t} rejected with ${e}`)});if(!x(e)&&e!==null)throw J(n);return e}function Fr(e,t,n,r){let{beforeSend:i,beforeSendTransaction:a,ignoreSpans:o}=t,s=!en(t.beforeSendSpan)&&t.beforeSendSpan,c=n;if(Ir(c)&&i)return i(c,r);if(Lr(c)){if(s||o){let t=yr(c);if(o?.length&&Gt({description:t.description,op:t.op,attributes:t.data},o))return null;if(s){let e=s(t);e?c=I(n,br(e)):Ht()}if(c.spans){let t=[],n=c.spans;for(let e of n){if(o?.length&&Gt({description:e.description,op:e.op,attributes:e.data},o)){qt(n,e);continue}if(s){let n=s(e);n?t.push(n):(Ht(),t.push(e))}else t.push(e)}let r=c.spans.length-t.length;r&&e.recordDroppedEvent(`before_send`,`span`,r),c.spans=t}}if(a){if(c.spans){let e=c.spans.length;c.sdkProcessingMetadata={...n.sdkProcessingMetadata,spanCountBeforeProcessing:e}}return a(c,r)}}return c}function Ir(e){return e.type===void 0}function Lr(e){return e.type===`transaction`}function Rr(e){let t=0;return e.name&&(t+=e.name.length*2),t+=8,t+Br(e.attributes)}function zr(e){let t=0;return e.message&&(t+=e.message.length*2),t+Br(e.attributes)}function Br(e){if(!e)return 0;let t=0;return Object.values(e).forEach(e=>{Array.isArray(e)?t+=e.length*Vr(e[0]):de(e)?t+=Vr(e):t+=100}),t}function Vr(e){return typeof e==`string`?e.length*2:typeof e==`number`?8:typeof e==`boolean`?4:0}function Hr(e){`aggregates`in e?e.attrs?.ip_address===void 0&&(e.attrs={...e.attrs,ip_address:`{{auto}}`}):e.ipAddress===void 0&&(e.ipAddress=`{{auto}}`)}function Ur(e,t,r=[t],i=`npm`){let a=(e._metadata=e._metadata||{}).sdk=e._metadata.sdk||{};a.name||(a.name=`sentry.javascript.${t}`,a.packages=r.map(e=>({name:`${i}:@sentry/${e}`,version:n})),a.version=n)}function Wr(e){return v(e)&&`__sentry_fetch_url_host__`in e&&typeof e.__sentry_fetch_url_host__==`string`}function Gr(e){return Wr(e)?`${e.message} (${e.__sentry_fetch_url_host__})`:e.message}function Kr(e){return e&&/^function\s+\w+\(\)\s+\{\s+\[native code\]\s+\}$/.test(e.toString())}const Y=t;function qr(e,t){let n=Z(e,t),r={type:$r(t),value:ei(t)};return n.length&&(r.stacktrace={frames:n}),r.type===void 0&&r.value===``&&(r.value=`Unrecoverable error caught`),r}function Jr(e,t,n,r){let i=ft()?.getOptions().normalizeDepth,a=si(t),o={__serialized__:Ce(t,i)};if(a)return{exception:{values:[qr(e,a)]},extra:o};let s={exception:{values:[{type:S(t)?t.constructor.name:r?`UnhandledRejection`:`Error`,value:ai(t,{isUnhandledRejection:r})}]},extra:o};if(n){let t=Z(e,n);t.length&&(s.exception.values[0].stacktrace={frames:t})}return s}function X(e,t){return{exception:{values:[qr(e,t)]}}}function Z(e,t){let n=t.stacktrace||t.stack||``,r=Xr(t),i=Zr(t);try{return e(n,r,i)}catch{}return[]}const Yr=/Minified React error #\d+;/i;function Xr(e){return e&&Yr.test(e.message)?1:0}function Zr(e){return typeof e.framesToPop==`number`?e.framesToPop:0}function Qr(e){return typeof WebAssembly<`u`&&WebAssembly.Exception!==void 0&&e instanceof WebAssembly.Exception}function $r(e){let t=e?.name;return!t&&Qr(e)?e.message&&Array.isArray(e.message)&&e.message.length==2?e.message[0]:`WebAssembly.Exception`:t}function ei(e){let t=e?.message;return Qr(e)?Array.isArray(e.message)&&e.message.length==2?e.message[1]:`wasm exception`:t?t.error&&typeof t.error.message==`string`?Gr(t.error):Gr(e):`No error message`}function ti(e,t,n,r){let i=ri(e,t,n?.syntheticException||void 0,r);return N(i),i.level=`error`,n?.event_id&&(i.event_id=n.event_id),H(i)}function ni(e,t,n=`info`,r,i){let a=ii(e,t,r?.syntheticException||void 0,i);return a.level=n,r?.event_id&&(a.event_id=r.event_id),H(a)}function ri(e,t,n,r,i){let a;if(se(t)&&t.error)return X(e,t.error);if(ce(t)||le(t)){let i=t;if(`stack`in t){a=X(e,t);let i=a.exception?.values?.[0];if(r&&n&&i&&!i.stacktrace){let t=Z(e,n);t.length&&(i.stacktrace={frames:t},N(a,{synthetic:!0}))}}else{let t=i.name||(ce(i)?`DOMError`:`DOMException`),o=i.message?`${t}: ${i.message}`:t;a=ii(e,o,n,r),Ne(a,o)}return`code`in i&&(a.tags={...a.tags,"DOMException.code":`${i.code}`}),a}return v(t)?X(e,t):x(t)||S(t)?(a=Jr(e,t,n,i),N(a,{synthetic:!0}),a):(a=ii(e,t,n,r),Ne(a,`${t}`,void 0),N(a,{synthetic:!0}),a)}function ii(e,t,n,r){let i={};if(r&&n){let r=Z(e,n);r.length&&(i.exception={values:[{value:t,stacktrace:{frames:r}}]}),N(i,{synthetic:!0})}if(ue(t)){let{__sentry_template_string__:e,__sentry_template_values__:n}=t;return i.logentry={message:e,params:n},i}return i.message=t,i}function ai(e,{isUnhandledRejection:t}){let n=ve(e),r=t?`promise rejection`:`exception`;return se(e)?`Event \`ErrorEvent\` captured as ${r} with message \`${e.message}\``:S(e)?`Event \`${oi(e)}\` (type=${e.type}) captured as ${r}`:`Object captured as ${r} with keys: ${n}`}function oi(e){try{let t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{}}function si(e){return Object.values(e).find(e=>e instanceof Error)}var ci=class extends Mr{constructor(e){let t=li(e);Ur(t,`browser`,[`browser`],Y.SENTRY_SDK_SOURCE||Jn()),super(t);let{userInfo:n}=this.getDataCollectionOptions();t._metadata?.sdk&&(t._metadata.sdk.settings={infer_ip:n?`auto`:`never`,...t._metadata.sdk.settings});let{sendClientReports:r}=this._options;Y.document&&Y.document.addEventListener(`visibilitychange`,()=>{Y.document.visibilityState===`hidden`&&(r&&this._flushOutcomes(),queueMicrotask(()=>{this.flush()}))}),n&&this.on(`beforeSendSession`,Hr)}eventFromException(e,t){return ti(this._options.stackParser,e,t,this._options.attachStacktrace)}eventFromMessage(e,t=`info`,n){return ni(this._options.stackParser,e,t,n,this._options.attachStacktrace)}_prepareEvent(e,t,n,r){return e.platform=e.platform||`javascript`,super._prepareEvent(e,t,n,r)}};function li(e){return{release:typeof __SENTRY_RELEASE__==`string`?__SENTRY_RELEASE__:Y.SENTRY_RELEASE?.id,sendClientReports:!0,parentSpanIsAlwaysRootSpan:!0,...e}}const ui=typeof __SENTRY_DEBUG__>`u`||__SENTRY_DEBUG__,Q=t,$={};function di(e){let t=$[e];if(t)return t;let n=Q[e];if(Kr(n))return $[e]=n.bind(Q);let r=Q.document;if(r&&typeof r.createElement==`function`)try{let t=r.createElement(`iframe`);t.hidden=!0,r.head.appendChild(t);let i=t.contentWindow;i?.[e]&&(n=i[e]),r.head.removeChild(t)}catch(t){ui&&g.warn(`Could not create sandbox iframe for ${e} check, bailing to window.${e}: `,t)}return n&&($[e]=n.bind(Q))}function fi(e){$[e]=void 0}function pi(e,t=di(`fetch`)){let n=0,r=0;async function i(i){let a=i.body.length;n+=a,r++;let o={body:i.body,method:`POST`,referrerPolicy:`strict-origin`,headers:e.headers,keepalive:n<=6e4&&r<15,...e.fetchOptions};try{let n=await t(e.url,o);return{statusCode:n.status,headers:{"x-sentry-rate-limits":n.headers.get(`X-Sentry-Rate-Limits`),"retry-after":n.headers.get(`Retry-After`)}}}catch(e){throw fi(`fetch`),e}finally{n-=a,r--}}return gr(e,i,dr(e.bufferSize||40))}function mi(e,t,n,r){let i={filename:e,function:t===`<anonymous>`?`?`:t,in_app:!0};return n!==void 0&&(i.lineno=n),r!==void 0&&(i.colno=r),i}const hi=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,gi=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,_i=/\((\S*)(?::(\d+))(?::(\d+))\)/,vi=/at (.+?) ?\(data:(.+?),/,yi=[30,e=>{let t=e.match(vi);if(t)return{filename:`<data:${t[2]}>`,function:t[1]};let n=hi.exec(e);if(n){let[,e,t,r]=n;return mi(e,`?`,+t,+r)}let r=gi.exec(e);if(r){if(r[2]?.indexOf(`eval`)===0){let e=_i.exec(r[2]);e&&(r[2]=e[1],r[3]=e[2],r[4]=e[3])}let[e,t]=Ci(r[1]||`?`,r[2]);return mi(t,e,r[3]?+r[3]:void 0,r[4]?+r[4]:void 0)}}],bi=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,xi=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,Si=ne(yi,[50,e=>{let t=bi.exec(e);if(t){if(t[3]&&t[3].indexOf(` > eval`)>-1){let e=xi.exec(t[3]);e&&(t[1]=t[1]||`eval`,t[3]=e[1],t[4]=e[2],t[5]=``)}let e=t[3],n=t[1]||`?`;return[n,e]=Ci(n,e),mi(e,n,t[4]?+t[4]:void 0,t[5]?+t[5]:void 0)}}]),Ci=(e,t)=>{let n=e.indexOf(`safari-extension`)!==-1,r=e.indexOf(`safari-web-extension`)!==-1;return n||r?[e.indexOf(`@`)===-1?`?`:e.split(`@`)[0],n?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},wi=new Map;function Ti(e){if(!e)return e;try{let t=new URL(e);return t.username=``,t.password=``,t.search=``,t.hash=``,t.toString()}catch{return e.replace(/[?#][^\s)]*/g,``)}}function Ei(e){Reflect.deleteProperty(e,`breadcrumbs`),Reflect.deleteProperty(e,`request`),Reflect.deleteProperty(e,`user`);for(let t of e.exception?.values??[])for(let e of t.stacktrace?.frames??[]){let t=Ti(e.filename);t&&(e.filename=t)}return e}function Di(e,t,n){let r=`${t}:${e}`,i=wi.get(r);if(i)return i;let a=new ci({beforeSend:Ei,dsn:e,environment:t,integrations:[],release:`lockerverse-sdk@${n}`,sendDefaultPii:!1,stackParser:Si,transport:pi});return a.init(),wi.set(r,a),a}function Oi({context:e,contextName:t,dsn:n,environment:r,error:i}){try{let a=new L;a.setClient(Di(n,r,i.sdkVersion)),a.setTags({"sdk.code":i.code,"sdk.operation":i.operation,"sdk.version":i.sdkVersion,source:`lockerverse-sdk`}),i.failureKind&&a.setTag(`sdk.failure_kind`,i.failureKind),a.setContext(t,e),a.captureException(i)}catch{}}export{Oi as captureSdkError};
8
8
  //# sourceMappingURL=telemetry.js.map