@rebuy/rebuy 2.30.0 → 2.31.0
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.
- package/dist/index.js +4 -0
- package/dist/index.js.map +2 -2
- package/dist/index.mjs +4 -0
- package/dist/index.mjs.map +2 -2
- package/dist/server/analytics.d.ts +13 -0
- package/dist/server/analytics.d.ts.map +1 -1
- package/dist/server/index.js +13 -1
- package/dist/server/index.js.map +2 -2
- package/dist/server/index.mjs +13 -1
- package/dist/server/index.mjs.map +2 -2
- package/dist/transforms/index.js +4 -0
- package/dist/transforms/index.js.map +2 -2
- package/dist/transforms/index.mjs +4 -0
- package/dist/transforms/index.mjs.map +2 -2
- package/dist/transforms/offerV1/offerCard.d.ts.map +1 -1
- package/package.json +2 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/schema/metadata.ts", "../../src/schema/product.ts", "../../src/schema/offerProduct.ts", "../../src/server/shared.ts", "../../src/schema/cabShopConfig.ts", "../../src/schema/smartCart.ts", "../../src/schema/widgets/checkout-and-beyond/image.ts", "../../src/schema/widgets/checkout-and-beyond/common.ts", "../../src/schema/widgets/checkout-and-beyond/regex.ts", "../../src/schema/widgets/checkout-and-beyond/rule.ts", "../../src/schema/widgets/checkout-and-beyond/shared.ts", "../../src/schema/widgets/checkout-and-beyond/banner.ts", "../../src/schema/widgets/checkout-and-beyond/layout.ts", "../../src/schema/widgets/checkout-and-beyond/button.ts", "../../src/schema/widgets/checkout-and-beyond/text.ts", "../../src/schema/widgets/checkout-and-beyond/utils.ts", "../../src/schema/widgets/checkout-and-beyond/carousel.ts", "../../src/schema/widgets/checkout-and-beyond/offers.ts", "../../src/schema/widgets/checkout-and-beyond/dataSource.ts", "../../src/schema/widgets/checkout-and-beyond/constants.ts", "../../src/schema/widgets/checkout-and-beyond/products.ts", "../../src/schema/widgets/checkout-and-beyond/product.ts", "../../src/schema/widgets/checkout-and-beyond/cartLine.ts", "../../src/schema/widgets/checkout-and-beyond/discount.ts", "../../src/schema/widgets/checkout-and-beyond/monetize.ts", "../../src/schema/widgets/checkout-and-beyond/progressBar.ts", "../../src/schema/widgets/checkout-and-beyond/giftLabels.ts", "../../src/schema/widgets/checkout-and-beyond/quantity.ts", "../../src/schema/widgets/checkout-and-beyond/reviews.ts", "../../src/schema/widgets/checkout-and-beyond/reviewLabels.ts", "../../src/schema/widgets/checkout-and-beyond/variants.ts", "../../src/transforms/contentBlockV1/stripContentBlockHtml.ts", "../../src/transforms/contentBlockV1/convertTextToTiptapParagraph.ts", "../../src/transforms/contentBlockV1/types.ts", "../../src/transforms/contentBlockV1/convertContentBlockImageToV2.ts", "../../src/transforms/contentBlockV1/convertContentBlockTextToV2.ts", "../../src/schema/widgets/checkout-and-beyond/root.ts", "../../src/schema/widgets/checkout-and-beyond/uiLabels.ts", "../../src/transforms/contentBlockV1/convertContentBlockToV2.ts", "../../src/transforms/convertNumericObjects.ts", "../../src/transforms/deepCamelCase.ts", "../../src/transforms/htmlToTiptap/buildDefaultTextStyleMark.ts", "../../src/transforms/htmlToTiptap/closeTag.ts", "../../src/transforms/htmlToTiptap/constants.ts", "../../src/transforms/htmlToTiptap/makeParagraph.ts", "../../src/transforms/htmlToTiptap/flushParagraph.ts", "../../src/transforms/htmlToTiptap/isSkipping.ts", "../../src/transforms/htmlToTiptap/makeDoc.ts", "../../src/transforms/htmlToTiptap/isValidHref.ts", "../../src/transforms/htmlToTiptap/buildLinkMark.ts", "../../src/transforms/htmlToTiptap/decodeEntities.ts", "../../src/transforms/htmlToTiptap/parseAttribs.ts", "../../src/transforms/htmlToTiptap/openTag.ts", "../../src/transforms/htmlToTiptap/pushText.ts", "../../src/transforms/htmlToTiptap/stripHtmlComments.ts", "../../src/transforms/htmlToTiptap/htmlToTiptap.ts", "../../src/transforms/isCABRootSection.ts", "../../src/schema/widgets/checkout-and-beyond/switchLabels.ts", "../../src/transforms/localizedContent.ts", "../../src/transforms/lineItemEditorV1/convertLineItemEditorToV2.ts", "../../src/transforms/lineItemEditorV1/types.ts", "../../src/transforms/normalizeTokens.ts", "../../src/transforms/normalizeTextContent.ts", "../../src/transforms/experiments/resolveExperiment.ts", "../../src/schema/widgets/checkout-and-beyond/offerLabels.ts", "../../src/transforms/offerV1/types.ts", "../../src/transforms/offerV1/offerCard.ts", "../../src/transforms/offerV1/convertOfferToV2.ts", "../../src/transforms/parseShielded.ts", "../../src/transforms/progressBarV1/types.ts", "../../src/transforms/progressBarV1/convertProgressBarToV2.ts", "../../src/transforms/smartCart/convertSmartCartProgressBarToV2.ts", "../../src/transforms/smartCart/extractSmartCartBars.ts", "../../src/server/userConfig.ts", "../../src/utilities.ts", "../../src/server/dataSourceResults.ts", "../../src/server/salvageSections.ts", "../../src/server/widgetSettings.ts", "../../src/gwp/getValidGwpProductIds.ts", "../../src/gwp/hasUnsupportedRuleTypes.ts", "../../src/gwp/isDefinitiveRuleAnswer.ts", "../../src/gwp/shouldRemoveGift.ts", "../../src/server/giftValidation.ts", "../../src/server/adsEngine.ts", "../../src/server/composeOffer.ts", "../../src/server/monetizeOffers.ts", "../../src/server/analytics.ts", "../../src/server/requestSchemas.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod';\n\nimport { CacheInfo, Product } from './product';\n\nconst BaseRule = z.object({\n operator: z.string(),\n type: z.string(),\n value: z.union([z.string(), z.number()]),\n});\n\nconst Rule = BaseRule.extend({\n conditions: z.array(z.object({ type: z.string(), value: z.union([z.string(), z.number()]) })).optional(),\n products: z\n .array(\n z.object({\n productId: z.number(),\n subRules: z.object({ logic: z.array(z.object({ rules: z.array(BaseRule) })) }).optional(),\n variantIds: z.array(z.number()),\n })\n )\n .optional(),\n});\n\nconst Output = z.object({\n channel: z.string().optional(),\n collectionId: z.number().optional(),\n collectionSort: z.string().optional(),\n collectionSortType: z.string().nullish(),\n days: z.string().optional(),\n discount: z.object({ amount: z.string(), type: z.string() }).optional(),\n endpoint: z.string().optional(),\n key: z.string().optional(),\n operator: z.string().optional(),\n productPrice: z.object({ amount: z.string(), type: z.string() }).optional(),\n products: z.array(z.object({ productId: z.number(), variantIds: z.array(z.number()) })).optional(),\n productWithTagsSort: z.string().optional(),\n trendingSort: z.string().optional(),\n type: z.string(),\n value: z.union([z.string(), z.number(), z.boolean()]).optional(),\n});\n\nconst MatchedRule = z.object({\n collapsed: z.boolean().optional(),\n exitIfMatched: z.boolean(),\n index: z.number(),\n logic: z.array(z.object({ rules: z.array(Rule) })),\n output: z.array(Output),\n});\n\n/**\n * The rule-gating verdict the client's `useRule` reads (`metadata.custom.should_show`, camelCased). A\n * data-source evaluated at `limit: 0` returns it; validating the shape server-side lets an unreadable\n * verdict (an engine `custom` rename) be told apart from a rule legitimately evaluating false, which\n * would otherwise hide every gated section on every shop with no signal.\n */\nexport const RuleVerdict = z.object({ custom: z.object({ shouldShow: z.boolean() }) });\n\nexport type RuleVerdict = z.infer<typeof RuleVerdict>;\n\nexport const Metadata = z.object({\n cacheInfo: CacheInfo.optional(),\n cartItems: z.array(z.never()).optional(),\n errors: z.array(z.never()).optional(),\n filteredInputProducts: z.array(z.never()).optional(),\n filteredOosProducts: z.array(Product).optional(),\n globalExcludedProducts: z.array(Product).optional(),\n inputProducts: z.array(z.never()).optional(),\n matchedRules: z.array(MatchedRule).optional(),\n topSellersFilled: z.boolean().optional(),\n unevaluatedRules: z.array(MatchedRule).optional(),\n unmatchedRules: z.array(MatchedRule).optional(),\n widget: z\n .object({\n discount: z.object({ amount: z.string(), type: z.string() }).optional(),\n language: z.record(z.string(), z.string()).optional(),\n })\n .optional(),\n});\n\nexport type Metadata = z.infer<typeof Metadata>;\n", "import { z } from 'zod';\n\nconst zDatetime = z.iso.datetime({ offset: true });\n\nexport const CacheInfo = z.object({\n cachedAtTime: z.union([z.string(), z.number()]),\n cacheExpires: z.union([z.string(), z.number()]).optional(),\n cacheKey: z.string(),\n cacheKeyReadable: z.string(),\n cacheType: z.string().optional(),\n loadedOptions: z.record(z.string(), z.boolean()).optional(),\n});\n\nconst Category = z.object({\n adminGraphqlApiId: z.string(),\n fullName: z.string(),\n name: z.string(),\n});\n\nconst Metafield = z.object({\n key: z.string(),\n namespace: z.string(),\n type: z.string(),\n value: z.string(),\n});\n\nconst Image = z.object({\n adminGraphqlApiId: z.string(),\n alt: z.string().nullable(),\n createdAt: zDatetime.optional(),\n height: z.number(),\n id: z.number(),\n metafields: z.array(Metafield).optional(),\n position: z.number(),\n productId: z.number(),\n src: z.url(),\n updatedAt: zDatetime.optional(),\n variantIds: z.array(z.number()),\n width: z.number(),\n});\n\nconst Media = z.object({\n adminGraphqlApiId: z.string(),\n alt: z.string().nullable(),\n createdAt: zDatetime,\n id: z.number(),\n mediaContentType: z.string(),\n position: z.number(),\n previewImage: z.object({ height: z.number(), src: z.url(), status: z.string(), width: z.number() }),\n productId: z.number(),\n status: z.string(),\n updatedAt: zDatetime,\n variantIds: z.array(z.number()),\n});\n\nconst Option = z.object({\n id: z.number(),\n name: z.string(),\n position: z.number(),\n productId: z.number(),\n values: z.array(z.string()),\n});\n\nexport type Option = z.infer<typeof Option>;\n\nconst PriceAdjustment = z.object({\n orderCount: z.number().optional(),\n position: z.number(),\n value: z.string(),\n valueType: z.string(),\n});\n\nexport type PriceAdjustment = z.infer<typeof PriceAdjustment>;\n\nconst Ratings = z.union([\n z.object({ judgemeAverageStarRating: z.number(), judgemeTotalReviews: z.number() }),\n z.object({ junipAverageStarRating: z.number(), junipTotalReviews: z.number() }),\n z.object({ klaviyoAverageStarRating: z.number(), klaviyoTotalReviews: z.number() }),\n z.object({ looxAverageStarRating: z.number(), looxTotalReviews: z.number() }),\n z.object({ okendoAverageStarRating: z.number(), okendoTotalReviews: z.number() }),\n z.object({ opinewAverageStarRating: z.number(), opinewTotalReviews: z.number() }),\n z.object({ reviewsioAverageStarRating: z.number(), reviewsioTotalReviews: z.number() }),\n z.object({ stampedAverageStarRating: z.number(), stampedTotalReviews: z.number() }),\n z.object({ yotpoAverageStarRating: z.number(), yotpoTotalReviews: z.number() }),\n]);\n\nconst SellingPlan = z.object({\n description: z.string().optional(),\n id: z.number(),\n name: z.string(),\n options: z.array(z.object({ name: z.string(), position: z.number(), value: z.string() })),\n orderIntervalFrequency: z.string().optional(),\n orderIntervalUnitType: z.string().optional(),\n position: z.number().optional(),\n priceAdjustments: z.array(PriceAdjustment),\n shopifyVariantId: z.string().optional(),\n});\n\nexport type SellingPlan = z.infer<typeof SellingPlan>;\n\nconst SellingPlanAllocation = z.object({\n compareAtPrice: z.number(),\n perDeliveryPrice: z.number(),\n price: z.number(),\n priceAdjustments: z.array(PriceAdjustment),\n sellingPlanGroupId: z.string(),\n sellingPlanId: z.number(),\n});\n\nexport type SellingPlanAllocation = z.infer<typeof SellingPlanAllocation>;\n\nexport const SellingPlanGroup = z.object({\n appId: z.string().optional(),\n description: z.string().optional(),\n discountAmount: z.number().optional(),\n discountType: z.string().optional(),\n id: z.string(),\n name: z.string(),\n options: z.array(Option),\n requiresSellingPlan: z.boolean().optional(),\n sellingPlans: z.array(SellingPlan),\n variants: z.array(z.number()),\n});\n\nexport type SellingPlanGroup = z.infer<typeof SellingPlanGroup>;\n\nconst Variant = z.object({\n adminGraphqlApiId: z.string(),\n barcode: z.string().nullable(),\n compareAtPrice: z.string().nullable(),\n createdAt: zDatetime,\n fulfillmentService: z.string().nullish(),\n grams: z.number(),\n id: z.number(),\n imageId: z.number().nullable(),\n inventoryItemId: z.number().optional(),\n inventoryManagement: z.string().nullable(),\n inventoryPolicy: z.string(),\n inventoryQuantity: z.number(),\n link: z.url(),\n oldInventoryQuantity: z.number().optional(),\n option1: z.string(),\n option2: z.string().nullable(),\n option3: z.string().nullable(),\n position: z.number(),\n price: z.string(),\n productId: z.number(),\n requiresShipping: z.boolean(),\n sellingPlanAllocations: z.array(SellingPlanAllocation).optional(),\n sku: z.string().nullable(),\n taxable: z.boolean(),\n taxCode: z.string().optional(),\n title: z.string(),\n updatedAt: zDatetime,\n weight: z.number(),\n weightUnit: z.string().optional(),\n});\n\nexport type Variant = z.infer<typeof Variant>;\n\nexport const Product = z.object({\n adminGraphqlApiId: z.string(),\n bodyHtml: z.string().nullable(),\n cacheInfo: CacheInfo,\n category: Category.nullish(),\n collectionIds: z.array(z.number()),\n createdAt: zDatetime,\n description: z.string(),\n handle: z.string(),\n hasVariantsThatRequiresComponents: z.boolean().optional(),\n id: z.number(),\n image: Image.nullable(),\n images: z.array(Image).nullable(),\n link: z.url(),\n media: z.array(Media).optional(),\n metafields: z.array(Metafield).optional(),\n options: z.array(Option),\n owner: z.union([z.string(), z.number()]),\n productType: z.string(),\n publishedAt: zDatetime.nullable(),\n publishedScope: z.string().optional(),\n purchaseOptions: z.array(z.object({ discountOptions: z.array(z.never()) })).optional(),\n ratings: Ratings.optional(),\n selectedIndexPurchasedOption: z.number().optional(),\n sellingPlanAllocation: SellingPlanAllocation.optional(),\n sellingPlanGroups: z.array(SellingPlanGroup).optional(),\n status: z.string(),\n tags: z.string(),\n templateSuffix: z.string().nullable(),\n title: z.string(),\n updatedAt: zDatetime,\n variantGids: z.array(z.object({ adminGraphqlApiId: z.string(), updatedAt: zDatetime })).optional(),\n variantIds: z.array(z.object({ id: z.number() })).optional(),\n variants: z.array(Variant),\n vendor: z.string(),\n});\n\nexport type Product = z.infer<typeof Product>;\n", "import { z } from 'zod';\n\n/**\n * Per-product discount override a data source can attach \u2014 shaped like the legacy `settings.discount` /\n * `product.discount` (`@rebuy/rebuy/pricing`). Absent on the curated `Product` type, but present on\n * the wire, so the lean offer schema declares it explicitly.\n */\nconst OfferProductDiscount = z.object({\n amount: z.union([z.number(), z.string()]),\n discountedBy: z.string().optional(),\n discountedFrom: z.string().optional(),\n type: z.string(),\n});\n\nconst OfferProductOption = z.object({\n id: z.number(),\n name: z.string(),\n position: z.number(),\n values: z.array(z.string()),\n});\n\n/** Only what `toProduct` (`getIsOutOfStock` + `toPrice` + selection) reads off a variant. */\nconst OfferProductVariant = z.object({\n adminGraphqlApiId: z.string(),\n compareAtPrice: z.string().nullable(),\n id: z.number(),\n inventoryManagement: z.string().nullable(),\n inventoryPolicy: z.string(),\n inventoryQuantity: z.number(),\n link: z.string(),\n option1: z.string(),\n option2: z.string().nullable(),\n option3: z.string().nullable(),\n price: z.string(),\n title: z.string(),\n});\n\n/**\n * The lean server-side offer-product schema \u2014 exactly the fields the extension's `toProduct` consumes,\n * with the over-strict validators of the editor-facing `Product` (required `cacheInfo`, ISO\n * datetimes, `z.url()` links) relaxed to what the wire actually carries. `fetchDataSourceResults`\n * `safeParse`s each product against this and drops the ones that fail, so one malformed product costs\n * one offer card instead of the whole rail. This is also the type CAB imports in place of the loose\n * root `Product`, keeping the extension `any`-free.\n */\nexport const OfferProduct = z.object({\n description: z.string().optional(),\n discount: OfferProductDiscount.optional(),\n id: z.number(),\n image: z.object({ src: z.string() }).nullish(),\n images: z.array(z.object({ src: z.string(), variantIds: z.array(z.number()) })).nullish(),\n link: z.string().optional(),\n metafields: z.array(z.object({ key: z.string(), namespace: z.string(), value: z.string() })).optional(),\n options: z.array(OfferProductOption),\n sellingPlanGroups: z.array(z.object({ requiresSellingPlan: z.boolean().optional() })).optional(),\n title: z.string(),\n variants: z.array(OfferProductVariant),\n});\n\nexport type OfferProduct = z.infer<typeof OfferProduct>;\n", "/**\n * Server-only foundations for the widget-conversion / section-composition orchestrators. This subpath\n * (`@rebuy/rebuy/server`) is never imported by the browser extension \u2014 it owns the logic a thin API\n * service (rebuy-api) delegates to, with the actual network egress injected as {@link UpstreamFetch}.\n */\n\n/** Production engine host; any other host is a staging/ephemeral upstream. */\nexport const REBUY_ENGINE_HOST = 'rebuyengine.com';\n\n/**\n * Calls the legacy Rebuy engine at `https://<host><path>` and returns parsed JSON. Injected by the\n * caller (rebuy-api owns the egress, timeouts, and the `X-Rebuy-Upstream` proxy header); MUST throw\n * {@link UpstreamError} on a non-2xx response so orchestrators can interpret the status.\n *\n * Defaults to GET with `params`/`search` as the query string. Pass `method: 'POST'` with `body` (JSON\n * body) and optional `headers` (e.g. an auth token) for write-style calls like analytics ingest.\n */\nexport type UpstreamFetch = (\n path: string,\n params: Record<string, string>,\n options?: {\n body?: unknown;\n headers?: Record<string, string>;\n host?: string;\n method?: 'GET' | 'POST';\n search?: string;\n }\n) => Promise<unknown>;\n\n/**\n * A drift signal the orchestrators emit when a per-item payload salvage drops something: a malformed\n * offer product, an invalid/unknown section stubbed out, or an unreadable rule verdict. Distinct from a\n * hard {@link UpstreamError} \u2014 the request still succeeds (degraded), so this is the only trace that an\n * upstream contract moved. Optional on {@link ServerContext}; the host (rebuy-api) wires it to its logger.\n */\nexport type ServerDrift = {\n detail: string;\n kind: 'product' | 'ruleVerdict' | 'section';\n};\n\n/** Request-scoped dependencies every orchestrator needs. */\nexport type ServerContext = {\n fetchUpstream: UpstreamFetch;\n host: string;\n /** Buyer request IP forwarded to the ads engine (the checkout worker can't read it; rebuy-api extracts it). Without it DSPs see one datacenter IP for all traffic \u2014 geo/IVT-flagging risk. Monetize only. */\n ipAddress?: string;\n /** Optional sink for {@link ServerDrift} \u2014 a degraded-but-successful payload salvage. */\n reportDrift?: (event: ServerDrift) => void;\n /** Browser user-agent forwarded to the ads engine (the checkout worker can't read it). Monetize only. */\n userAgent?: string;\n};\n\n/** Thrown by the injected {@link UpstreamFetch} when the engine returns a non-2xx response. */\nexport class UpstreamError extends Error {\n readonly body: unknown;\n readonly status: number;\n\n constructor(status: number, body: unknown, message?: string) {\n super(message ?? `Upstream returned ${status}`);\n this.body = body;\n this.name = 'UpstreamError';\n this.status = status;\n }\n}\n\n/** Thrown when the requested widget / shop / data source doesn't exist; the route maps it to 404. */\nexport class NotFoundError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'NotFoundError';\n }\n}\n\n/**\n * The `/cab/*` request-body types. Re-exported from {@link file://./requestSchemas.ts} \u2014 each is now the\n * `z.infer` of a centralized zod request schema (single source of truth) so rebuy-api can validate incoming\n * requests against the exact contract the orchestrators are typed on. Kept re-exported here so the\n * `@rebuy/rebuy/server` type surface is unchanged.\n */\nexport type {\n AnalyticsEventInput,\n AnalyticsInput,\n CartInput,\n CartLineInput,\n DataSourceInput,\n GiftInput,\n GiftValidationInput,\n MonetizeInput,\n MonetizeTransactionItem,\n UserConfigInput,\n WidgetSettingsInput,\n} from '~/server/requestSchemas';\n", "import { z } from 'zod';\n\nimport { SmartCartConfig } from './smartCart';\n\n/**\n * The A/B experiment fields `resolveExperiment` actually reads \u2014 a lean projection of the engine's\n * `activeExperiments`. Peripheral experiment metadata (name, page targeting, alias/CSS/JS inputs) is\n * dropped so a change there can't fail the shared config parse.\n */\nexport const CabActiveExperiment = z.object({\n data: z.array(\n z.object({\n elementId: z.coerce.number(),\n id: z.coerce.number(),\n traffic: z.coerce.number(),\n })\n ),\n id: z.coerce.number(),\n placeholderId: z.coerce.number().nullable(),\n type: z.string(),\n});\n\nexport type CabActiveExperiment = z.infer<typeof CabActiveExperiment>;\n\n/**\n * The lean shop config CAB actually consumes \u2014 the five load-bearing fields, not the ~30 the\n * editor-facing `ShopConfig` carries. `apiKey` stays strict (every offers/monetize/gift/analytics\n * request authenticates with it); the rest use `.catch()` so a peripheral engine change (a renamed\n * field, a new `carousel` enum value like `'css'`, an experiment shape drift) degrades that one field\n * instead of 500-ing the shared `fetchUserConfig` and killing every dynamic CAB rail fleet-wide.\n */\nexport const CabShopConfig = z.object({\n /**\n * Per-element resilient: parse as `unknown[]` (non-array \u2192 `[]`), then keep only the experiments that\n * validate. A single drifted experiment drops itself instead of `.catch`-ing the WHOLE array to `[]` and\n * silently disabling every live A/B test fleet-wide.\n */\n activeExperiments: z\n .array(z.unknown())\n .catch([])\n .default([])\n .transform((experiments) =>\n experiments.flatMap((experiment) => {\n const result = CabActiveExperiment.safeParse(experiment);\n\n return result.success ? [result.data] : [];\n })\n ),\n apiKey: z.string(),\n /**\n * The shop's base-currency ISO code (e.g. `'USD'`). CAB derives the shop minor-unit exponent from it\n * (`currencyDecimals`) so a Functions-applied fixed discount \u2014 whose amount is in shop minor units \u2014\n * converts to the buyer's currency exactly in a cross-decimal market. `.catch()` like its siblings: a\n * missing/renamed currency degrades to \"unknown\" (client falls back to buyer decimals), never a parse fail.\n */\n currency: z.string().optional().catch(undefined),\n monetize: z.object({ publisherKey: z.string().nullable() }).nullish().catch(undefined),\n shopId: z.number().optional().catch(undefined),\n});\n\nexport type CabShopConfig = z.infer<typeof CabShopConfig>;\n\n/**\n * The lean `/api/v1/user/config` projection `fetchUserConfig` parses. `smartFlows` (schema-required on\n * the full `UserConfig` but read by no CAB path) is dropped; `smartCart` keeps its `.catch()`\n * safety bar so a smart-cart shape drift can never fail apiKey resolution.\n */\nexport const CabUserConfig = z.object({\n shop: CabShopConfig,\n smartCart: SmartCartConfig.nullish().catch(undefined),\n});\n\nexport type CabUserConfig = z.infer<typeof CabUserConfig>;\n", "import { z } from 'zod';\n\n/**\n * A gift/product reference attached to a smart-cart tier. Kept loose for S0 (data\n * plumbing) \u2014 S2 (gift mechanics) pins the variant/availability fields it consumes.\n */\nexport const SmartCartTierProduct = z.looseObject({\n handle: z.string().optional(),\n id: z.coerce.number().optional(),\n productId: z.coerce.number().optional(),\n title: z.string().optional(),\n variantIds: z.array(z.coerce.number()).optional(),\n});\n\n/**\n * One reward tier on a smart-cart tiered progress bar. `type` is `product` (gift), `shipping`,\n * `discount` (order discount applied by the order-discount Function, keyed by `_barId`) or\n * `decorative` (cosmetic milestone) \u2014 all four render at checkout. `minimum` is the unlock\n * threshold in shop-currency DOLLARS \u2014 except on `unlockConditionType: 'item_quantity'` tiers,\n * where it is a raw ITEM COUNT; `presentmentCurrencies` carries per-ISO-code CENTS overrides.\n *\n * The `*AmountRemainingLabel*`/`*AmountReachedLabel*` pairs are onsite's per-tier feedback copy\n * (`product_amount_remaining_label_text` etc.): the boolean gates whether the prompt shows, the\n * `*Text` holds the merchant sentence with `{{remaining_amount}}`/`{{product_title}}`/`{{discount_amount}}`\n * tokens. Blank/disabled tiers fall back to the bar-level shipping copy client-side.\n */\nexport const SmartCartTier = z.looseObject({\n allProducts: z.array(SmartCartTierProduct).optional(),\n /** Merchant-set tier label (e.g. \"Free gift\", \"$100 reward\"), shown on the step row when enabled. */\n customTierLabel: z.boolean().optional(),\n customTierLabelText: z.string().optional(),\n decorativeAmountReachedLabel: z.boolean().optional(),\n decorativeAmountReachedLabelText: z.string().optional(),\n decorativeAmountRemainingLabel: z.boolean().optional(),\n decorativeAmountRemainingLabelText: z.string().optional(),\n /** Order-discount reward: `'fixedAmount'` (shop-currency dollars) or `'percentage'` (whole percent). */\n discountAmountFromTotal: z.coerce.number().optional(),\n discountAmountReachedLabel: z.boolean().optional(),\n discountAmountReachedLabelText: z.string().optional(),\n discountAmountRemainingLabel: z.boolean().optional(),\n discountAmountRemainingLabelText: z.string().optional(),\n discountType: z.string().optional(),\n filterOosVariants: z.boolean().optional(),\n id: z.string().optional(),\n minimum: z.coerce.number().optional(),\n presentmentCurrencies: z.looseObject({ enabled: z.boolean().optional() }).optional(),\n productAmountReachedLabel: z.boolean().optional(),\n productAmountReachedLabelText: z.string().optional(),\n productAmountRemainingLabel: z.boolean().optional(),\n productAmountRemainingLabelText: z.string().optional(),\n products: z.array(SmartCartTierProduct).optional(),\n type: z.string().optional(),\n /**\n * onsite's PER-TIER unit switch (`unlock_condition_type`): `'item_quantity'` makes `minimum` an\n * item count (checked before any money handling \u2014 no \u00D7100, no FX, no presentment overrides,\n * mirroring onsite `getTierMinimum`); anything else (or absent) keeps the money semantics.\n */\n unlockConditionType: z.string().optional(),\n});\n\n/**\n * A single smart-cart progress bar (one per geo segment). `countryCodes` +\n * `geolocationEnabled` drive client-side country gating; `tiers` are the unlock steps;\n * `language` holds the bar-level reached/remaining copy.\n */\nexport const SmartCartBar = z.looseObject({\n countryCodes: z.array(z.string()).optional(),\n /**\n * onsite `exclude_discount_in_subtotal`: measure progress against the PRE-discount subtotal so an\n * applied code/order discount doesn't lower progress. The client adds cart discount allocations back.\n */\n excludeDiscountInSubtotal: z.boolean().optional(),\n /** Products excluded from the progress subtotal; the client subtracts their variants' cart cost. */\n excludedProducts: z.array(z.looseObject({ variantIds: z.array(z.coerce.number()).optional() })).optional(),\n freeShippingOnSubscription: z.boolean().optional(),\n geolocationEnabled: z.boolean().optional(),\n id: z.string().optional(),\n language: z\n .looseObject({\n freeShippingReached: z.string().optional(),\n freeShippingRemaining: z.string().optional(),\n giftAreaTitle: z.string().optional(),\n })\n .optional(),\n name: z.string().optional(),\n tiers: z.array(SmartCartTier).optional(),\n});\n\n/** A smart-cart layout component; only `type === 'tiered_progress_bar'` carries the bars we render. */\nexport const SmartCartComponent = z.looseObject({\n settings: z.looseObject({ bars: z.array(SmartCartBar).optional() }).optional(),\n type: z.string().optional(),\n});\n\n/**\n * The subset of the shop's smart-cart config the checkout extension reads: the\n * `tiered_progress_bar` component(s) and their bars/tiers. The rest of the onsite\n * smart-cart config (buy-more-save-more, custom templates/CSS, callbacks) is out of\n * scope \u2014 `looseObject` preserves-but-ignores it. Parsed under `UserConfig.smartCart`\n * with `.catch(undefined)` so a shape drift here can NEVER break apiKey resolution for\n * offers / monetize / analytics / gift validation.\n */\nexport const SmartCartConfig = z.looseObject({\n components: z.array(SmartCartComponent).optional(),\n});\n\nexport type SmartCartBar = z.infer<typeof SmartCartBar>;\nexport type SmartCartConfig = z.infer<typeof SmartCartConfig>;\nexport type SmartCartTier = z.infer<typeof SmartCartTier>;\nexport type SmartCartTierProduct = z.infer<typeof SmartCartTierProduct>;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { buttonFields, ObjectFit, objectFits, SectionType } from './common';\nimport { DYNAMIC_TOKEN_REGEX } from './regex';\nimport { CABRule } from './rule';\nimport { CABBorder, type SectionDetails } from './shared';\nimport { checkForHTML, NO_HTML } from './utils';\n\nexport const CABImageSection = z.object({\n altText: z.string().refine(checkForHTML, NO_HTML).default(''),\n aspectRatio: z.literal(1).nullable().default(null),\n border: z.lazy(() => CABBorder),\n buttonField: z.enum(buttonFields).optional(),\n category: z.enum(['gallery', 'icons', 'payment-methods', 'secure-checkout']).nullable().default(null),\n name: z.string().optional(),\n naturalHeight: z.number().default(0),\n naturalWidth: z.number().default(0),\n /**\n * `contain` (the component default): dimensionless images render in s-image's 1/1 default frame, and\n * `cover` would crop non-square art (payment badges lost their edges \u2014 15993); `contain` letterboxes.\n */\n objectFit: z.enum(objectFits).default(ObjectFit.contain),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.image).default(SectionType.image),\n source: z.union([z.url(), z.literal(''), z.string().regex(DYNAMIC_TOKEN_REGEX)]).default(''),\n width: z.number().default(100),\n});\n\nexport type CABImageSection = z.infer<typeof CABImageSection>;\n\nexport type CABImageSectionProps = CABImageSection & SectionDetails;\n", "export const freezeEnum = <T extends readonly string[]>(values: T) =>\n Object.freeze(Object.fromEntries(values.map((v) => [v, v]))) as { readonly [K in T[number]]: K };\n\nexport const bannerColors = ['info', 'success', 'warning', 'critical'] as const;\nexport const BannerColor = freezeEnum(bannerColors);\nexport type BannerColor = (typeof bannerColors)[number];\n\nexport const borderRadii = ['none', 'small', 'base', 'large', 'fullyRounded'] as const;\nexport const BorderRadius = freezeEnum(borderRadii);\nexport type BorderRadius = (typeof borderRadii)[number];\n\nexport const borderStyles = ['none', 'base', 'dotted', 'dashed'] as const;\nexport const BorderStyle = freezeEnum(borderStyles);\nexport type BorderStyle = (typeof borderStyles)[number];\n\nexport const borderWidths = ['base', 'medium', 'thick'] as const;\nexport const BorderWidth = freezeEnum(borderWidths);\nexport type BorderWidth = (typeof borderWidths)[number];\n\nexport const buttonActions = [\n 'acceptOffer',\n 'addToOrder',\n 'declineAllOffers',\n 'declineOffer',\n 'displayContentInModal',\n 'displayContentInPopover',\n 'goToNextPage',\n 'goToPrevPage',\n 'goToURL',\n 'removeFromOrder',\n 'selectVariant',\n 'showPagination',\n 'switchToSubscription',\n 'undoAddToOrder',\n] as const;\n\nexport const ButtonAction = freezeEnum(buttonActions);\nexport type ButtonAction = (typeof buttonActions)[number];\n\nexport const buttonFields = [\n 'activePage',\n 'addedToCart',\n 'addingToCart',\n 'addToCart',\n 'buttonLabel',\n 'declineAllOffers',\n 'declineOffer',\n 'destinationUrl',\n 'inactivePage',\n 'overlayContent',\n 'payNow',\n 'progressReached',\n 'progressRemaining',\n 'redirectToCheckout',\n 'removeFromOrder',\n 'showVariant',\n 'showVariants',\n 'soldOut',\n 'subscriptionOption',\n 'switchToOneTimePurchase',\n 'switchToSubscriptionNoDiscount',\n 'switchToSubscriptionWithDiscount',\n 'undoAddToOrder',\n] as const;\n\nexport const ButtonField = freezeEnum(buttonFields);\nexport type ButtonField = (typeof buttonFields)[number];\n\nexport const buttonStyles = ['primary', 'secondary', 'plain', 'custom'] as const;\nexport const ButtonStyle = freezeEnum(buttonStyles);\nexport type ButtonStyle = (typeof buttonStyles)[number];\n\nexport const directions = ['columns', 'rows', 'grid'] as const;\nexport const Direction = freezeEnum(directions);\nexport type Direction = (typeof directions)[number];\n\nexport const discountSources = ['price', 'compare_at_price'] as const;\nexport const DiscountSource = freezeEnum(discountSources);\nexport type DiscountSource = (typeof discountSources)[number];\n\nexport const discountTypes = ['none', 'percentage', 'fixed', 'fixed_amount'] as const;\nexport const DiscountType = freezeEnum(discountTypes);\nexport type DiscountType = (typeof discountTypes)[number];\n\nexport const editorModes = [\n 'checkoutExtension',\n 'postPurchaseOffer',\n 'thankYouPage',\n 'orderStatusPage',\n 'ordersIndexPage',\n 'customerProfilePage',\n] as const;\n\nexport const EditorMode = freezeEnum(editorModes);\nexport type EditorMode = (typeof editorModes)[number];\n\nexport const horizontalAlignments = ['start', 'center', 'end'] as const;\nexport const HorizontalAlignment = freezeEnum(horizontalAlignments);\nexport type HorizontalAlignment = (typeof horizontalAlignments)[number];\n\nexport const languageKeys = [\n 'ar',\n 'cs',\n 'da',\n 'de',\n 'en',\n 'es',\n 'fi',\n 'fr',\n 'ga',\n 'he',\n 'hi',\n 'id',\n 'it',\n 'ja',\n 'ko',\n 'nl',\n 'no',\n 'pl',\n 'pt',\n 'ru',\n 'sv',\n 'th',\n 'tr',\n 'uk',\n 'vi',\n 'zh',\n] as const;\n\nexport const LanguageKey = freezeEnum(languageKeys);\nexport type LanguageKey = (typeof languageKeys)[number];\n\nexport const objectFits = ['cover', 'contain'] as const;\nexport const ObjectFit = freezeEnum(objectFits);\nexport type ObjectFit = (typeof objectFits)[number];\n\nexport const popoverPositions = ['inlineStart', 'inlineEnd', 'blockStart', 'blockEnd'] as const;\nexport const PopoverPosition = freezeEnum(popoverPositions);\nexport type PopoverPosition = (typeof popoverPositions)[number];\n\nexport const popoverPositionMap = {\n bottom: 'blockEnd',\n left: 'inlineStart',\n right: 'inlineEnd',\n top: 'blockStart',\n} as const;\n\nexport const productTypes = ['one-time', 'subscription', 'both'] as const;\nexport const ProductType = freezeEnum(productTypes);\nexport type ProductType = (typeof productTypes)[number];\n\nexport const progressTierTypes = ['decorative', 'discount', 'product', 'shipping'] as const;\nexport const ProgressTierType = freezeEnum(progressTierTypes);\nexport type ProgressTierType = (typeof progressTierTypes)[number];\n\nexport const progressTierUnits = ['currency', 'item'] as const;\nexport const ProgressTierUnit = freezeEnum(progressTierUnits);\nexport type ProgressTierUnit = (typeof progressTierUnits)[number];\n\nexport const quantityInputs = ['select', 'number'] as const;\nexport const QuantityInput = freezeEnum(quantityInputs);\nexport type QuantityInput = (typeof quantityInputs)[number];\n\nexport const reviewsSizes = ['small', 'default', 'large'] as const;\nexport const ReviewsSize = freezeEnum(reviewsSizes);\nexport type ReviewsSize = (typeof reviewsSizes)[number];\n\nexport const sectionTypes = [\n 'banner',\n 'button',\n 'carousel',\n 'cartLine',\n 'dataSource',\n 'discount',\n 'image',\n 'layout',\n 'monetize',\n 'offers',\n 'product',\n 'products',\n 'progressBar',\n 'quantity',\n 'reviews',\n 'text',\n 'variants',\n] as const;\n\nexport const SectionType = freezeEnum(sectionTypes);\nexport type SectionType = (typeof sectionTypes)[number];\n\nexport const spacings = ['none', 'extraTight', 'tight', 'base', 'loose', 'extraLoose'] as const;\nexport const Spacing = freezeEnum(spacings);\nexport type Spacing = (typeof spacings)[number];\n\nexport const textAlignments = ['start', 'center', 'end'] as const;\nexport const TextAlignment = freezeEnum(textAlignments);\nexport type TextAlignment = (typeof textAlignments)[number];\n\nexport const textColorNames = ['base', 'subdued', 'accent', 'decorative', 'success', 'warning', 'critical'] as const;\nexport const TextColorName = freezeEnum(textColorNames);\nexport type TextColorName = (typeof textColorNames)[number];\n\nexport const textSizeNames = ['extraSmall', 'small', 'base', 'medium', 'large', 'extraLarge'] as const;\nexport const TextSizeName = freezeEnum(textSizeNames);\nexport type TextSizeName = (typeof textSizeNames)[number];\n\nexport const variantModes = ['multiple', 'single'] as const;\nexport const VariantMode = freezeEnum(variantModes);\nexport type VariantMode = (typeof variantModes)[number];\n\nexport const variantSelectors = ['menu', 'radio', 'button'] as const;\nexport const VariantSelector = freezeEnum(variantSelectors);\nexport type VariantSelector = (typeof variantSelectors)[number];\n\nexport const verticalAlignments = ['top', 'middle', 'bottom'] as const;\nexport const VerticalAlignment = freezeEnum(verticalAlignments);\nexport type VerticalAlignment = (typeof verticalAlignments)[number];\n", "/** Matches a valid array index string (e.g., \"0\", \"1\", \"42\"). */\nexport const ARRAY_INDEX_STRING = /^(0|[1-9]\\d*)$/;\n\n/** Matches a dynamic token. */\nexport const DYNAMIC_TOKEN_REGEX = /^\\{\\{\\s*[A-Za-z]+\\s*\\}\\}$/;\n\n/** Matches a valid hex color code. */\nexport const HEX_COLOR_REGEX = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;\n\n/**\n * Matches a root-relative, same-origin path (single leading slash, e.g. Shopify's\n * `/policies/privacy-policy`). A protocol-relative `//host` is excluded \u2014 it points off-origin.\n */\nexport const ROOT_RELATIVE_PATH_REGEX = /^\\/(?!\\/)/;\n\n/**\n * Matches an HTML-shaped tag: `<` (or `</`) immediately followed by a tag-name letter. This mirrors\n * both the browser `DOMParser` branch of `isHTML` and `stripContentBlockHtml`'s tag regex, so the\n * server-side check agrees with the client and with whatever the sanitizer removes. It deliberately\n * leaves bare comparison brackets alone (`5 < 10 and 10 > 5`) \u2014 those are text, not markup, and the\n * looser `/<\\/?[^>]+>/` it replaced wrongly rejected them and 500'd otherwise-valid content.\n *\n * Keeps the `g` flag because downstream consumers strip ALL tags with `.replace(HTML_TAGS_REGEX, '')`\n * (rebuy-shopify-extensions, admin-nextjs); without it `.replace` would drop only the first tag. The\n * one in-package consumer, `isHTML`, must therefore NOT use `.test()` on it \u2014 a global regex carries a\n * sticky `lastIndex` that makes repeated `.test()` calls flaky. `isHTML` uses `.search()` instead,\n * which ignores and never mutates `lastIndex`.\n */\nexport const HTML_TAGS_REGEX = /<\\/?[a-zA-Z][^>]*>/g;\n", "import { z } from 'zod';\n\nexport const ruleTypes = [\n 'cart',\n 'cart_count',\n 'cart_item_count',\n 'cart_line_count',\n 'cart_subtotal',\n 'collection',\n 'customer',\n 'customer_order_count',\n 'customer_tag',\n 'customer_total_spent',\n 'date',\n 'product',\n 'product_tag',\n 'product_title',\n 'product_type',\n 'product_vendor',\n] as const;\n\nconst ruleType = z.enum(ruleTypes);\n\nexport const RuleType = ruleType.enum;\nexport type RuleType = z.infer<typeof ruleType>;\n\nexport const ruleOperators = [\n 'after',\n 'anything',\n 'before',\n 'contains',\n 'contains_any',\n 'does_not_contain',\n 'does_not_contain_any',\n 'equals',\n 'does_not_equal',\n 'greater_than',\n 'less_than',\n] as const;\n\nconst ruleOperator = z.enum(ruleOperators);\n\nexport const RuleOperator = ruleOperator.enum;\nexport type RuleOperator = z.infer<typeof ruleOperator>;\n\nexport const RuleCondition = z.object({\n operator: z.enum(ruleOperators).default(RuleOperator.anything),\n products: z.union([z.array(z.unknown()), z.strictObject({}).transform(() => [])]).default(() => []),\n type: z.enum(ruleTypes).default(RuleType.cart_subtotal),\n value: z.coerce.string().default(''),\n});\n\nexport type RuleCondition = z.infer<typeof RuleCondition>;\n\nexport const RuleLogicBlock = z.object({\n rules: z.array(RuleCondition).default(() => []),\n});\n\nexport type RuleLogicBlock = z.infer<typeof RuleLogicBlock>;\n\nexport const CABRule = z.object({\n dataSourceId: z.number().nullable().default(null),\n enabled: z.boolean().default(false),\n ruleset: z\n .union([\n z.array(\n z.object({\n exitIfMatched: z.boolean().default(true),\n logic: z.array(RuleLogicBlock).default(() => []),\n output: z\n .array(\n z.object({\n key: z.string().default('should_show'),\n type: z.literal('data_json').default('data_json'),\n value: z.string().default('true'),\n })\n )\n .default(() => [{ key: 'should_show', type: 'data_json' as const, value: 'true' }]),\n })\n ),\n z.strictObject({}).transform(() => []),\n ])\n .default(() => []),\n});\n\nexport type CABRule = z.infer<typeof CABRule>;\n", "import { type FieldArrayPath } from 'react-hook-form';\nimport { z, type ZodType } from 'zod';\n\nimport { CABBannerSection } from './banner';\nimport { CABButtonSection } from './button';\nimport { CABCarouselSection } from './carousel';\nimport { CABCartLineSection } from './cartLine';\nimport { borderRadii, BorderRadius, BorderStyle, borderStyles, BorderWidth, borderWidths } from './common';\nimport { CABDataSourceSection } from './dataSource';\nimport { CABDiscountSection } from './discount';\nimport { CABImageSection } from './image';\nimport { CABLayoutSection } from './layout';\nimport { CABMonetizeSection } from './monetize';\nimport { CABOffersSection } from './offers';\nimport { CABProductSection } from './product';\nimport { CABProductsSection } from './products';\nimport { CABProgressBarSection } from './progressBar';\nimport { CABQuantitySection } from './quantity';\nimport { CABReviewsSection } from './reviews';\nimport { type CABRootSection } from './root';\nimport { CABTextSection } from './text';\nimport { CABVariantsSection } from './variants';\n\nexport const CABBorder = z\n .object({\n radius: z.enum(borderRadii).default(BorderRadius.base),\n style: z.enum(borderStyles).default(BorderStyle.none),\n width: z.enum(borderWidths).default(BorderWidth.base),\n })\n .default({\n radius: BorderRadius.base,\n style: BorderStyle.none,\n width: BorderWidth.base,\n });\n\nexport type CABBorder = z.infer<typeof CABBorder>;\n\nexport const CABSection: ZodType<CABSection> = z.lazy(() =>\n z.discriminatedUnion('sectionType', [\n CABBannerSection,\n CABButtonSection,\n CABCarouselSection,\n CABCartLineSection,\n CABDataSourceSection,\n CABDiscountSection,\n CABImageSection,\n CABLayoutSection,\n CABMonetizeSection,\n CABOffersSection,\n CABProductSection,\n CABProductsSection,\n CABProgressBarSection,\n CABQuantitySection,\n CABReviewsSection,\n CABTextSection,\n CABVariantsSection,\n ])\n);\n\nexport type CABSection =\n | CABBannerSection\n | CABButtonSection\n | CABCarouselSection\n | CABCartLineSection\n | CABDataSourceSection\n | CABDiscountSection\n | CABImageSection\n | CABLayoutSection\n | CABMonetizeSection\n | CABOffersSection\n | CABProductSection\n | CABProductsSection\n | CABProgressBarSection\n | CABQuantitySection\n | CABReviewsSection\n | CABTextSection\n | CABVariantsSection;\n\nexport type SectionId = CABSection['sectionId'];\n\n/* @ts-expect-error: TS2589: Type instantiation _is_ excessively deep and infinite. */\nexport type SectionArrayPath = FieldArrayPath<CABRootSection>;\n\nexport type SectionPrefixPath = `${SectionArrayPath}.${number}` | null;\n\nexport type SectionDetails = {\n /**\n * The full React Hook Form dot-notation path to the section object itself,\n * for use with `register` or `control`, e.g. `sections.0.sections.1`.\n *\n * Returns `null` for the root section.\n */\n fieldArrayPath: SectionArrayPath | null;\n /**\n * The index of the found section within its parent `sections` array.\n *\n * Returns `null` for the root section.\n */\n index: number | null;\n /**\n * The parent `sections` object.\n *\n * Returns `null` for the root section.\n */\n parent: CABSection[] | null;\n /**\n * The parent `sectionId`.\n *\n * Returns `undefined` for the root section.\n */\n parentId: SectionId | undefined;\n /**\n * The full React Hook Form dot-notation path to the section object itself,\n * for use with `register` or `control`, e.g. `sections.0.sections.1`.\n *\n * Returns `null` for the root section.\n */\n prefixPath: SectionPrefixPath | null;\n};\n\nexport type CABSectionProps = CABSection & SectionDetails;\n", "import { z } from 'zod';\n\nimport { bannerColors, buttonFields, SectionType, type BannerColor } from './common';\nimport { CABLayoutSection } from './layout';\nimport { type SectionDetails } from './shared';\n\nexport const CABBannerSection = z.lazy(() =>\n CABLayoutSection.omit({ sectionType: true }).extend({\n buttonField: z.enum(buttonFields).optional(),\n color: z.enum(bannerColors).default('info'),\n dismissible: z.boolean().default(true),\n sectionType: z.literal(SectionType.banner).default(SectionType.banner),\n })\n);\n\nexport type CABBannerSection = Omit<CABLayoutSection, 'sectionType'> & {\n color: BannerColor;\n dismissible: boolean;\n sectionType: 'banner';\n};\n\nexport type CABBannerSectionProps = CABBannerSection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport {\n buttonFields,\n Direction,\n directions,\n HorizontalAlignment,\n horizontalAlignments,\n SectionType,\n Spacing,\n spacings,\n VerticalAlignment,\n verticalAlignments,\n type ButtonField,\n} from './common';\nimport { CABRule } from './rule';\nimport { CABBorder, CABSection, type SectionDetails } from './shared';\n\nexport const GridItem = z.union([z.literal('auto'), z.literal('fill'), z.string().regex(/^\\d+%$/), z.number()]);\nexport type GridItem = z.infer<typeof GridItem>;\n\nexport const CABLayoutSection = z.object({\n alignment: z\n .object({\n horizontal: z.enum(horizontalAlignments).default(HorizontalAlignment.start),\n vertical: z.enum(verticalAlignments).default(VerticalAlignment.top),\n })\n .default({\n horizontal: HorizontalAlignment.start,\n vertical: VerticalAlignment.top,\n }),\n border: z.lazy(() => CABBorder),\n buttonField: z.enum(buttonFields).optional(),\n direction: z.enum(directions).default(Direction.rows),\n grid: z\n .object({\n columns: z.union([z.array(GridItem), z.undefined()]).default(() => ['auto']),\n rows: z.union([z.array(GridItem), z.undefined()]).default(() => ['auto']),\n })\n .default({ columns: ['auto'], rows: ['auto'] })\n .optional(),\n name: z.string().optional(),\n padding: z.enum(spacings).default(Spacing.none),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sections: z.union([z.array(z.lazy(() => CABSection)), z.strictObject({}).transform(() => [])]).default(() => []),\n sectionType: z.literal(SectionType.layout).default(SectionType.layout),\n spacing: z.enum(spacings).default(Spacing.base),\n /** Fire-and-forget impression pixel POSTed once when the section is shown (e.g. a Monetize offer view). */\n viewUrl: z.string().optional(),\n width: z.number().default(100),\n});\n\nexport type CABLayoutSection = {\n alignment: {\n horizontal: HorizontalAlignment;\n vertical: VerticalAlignment;\n };\n border: CABBorder;\n buttonField?: ButtonField;\n direction: Direction;\n grid?: {\n columns: GridItem[];\n rows: GridItem[];\n };\n name?: string;\n padding: Spacing;\n rule?: CABRule;\n sectionId: string;\n sections: CABSection[];\n sectionType: 'layout';\n spacing: Spacing;\n viewUrl?: string;\n width: number;\n};\n\nexport type CABLayoutSectionProps = CABLayoutSection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z, type ZodType } from 'zod';\n\nimport {\n buttonActions,\n ButtonStyle,\n buttonStyles,\n PopoverPosition,\n popoverPositions,\n SectionType,\n TextAlignment,\n textAlignments,\n} from './common';\nimport { CABImageSection } from './image';\nimport { CABLayoutSection } from './layout';\nimport { HEX_COLOR_REGEX } from './regex';\nimport { CABRule } from './rule';\nimport { type SectionDetails } from './shared';\nimport { CABTextSection } from './text';\n\nexport type CABButtonContent = CABImageSection | CABLayoutSection | CABTextSection;\n\nexport const CABButtonContent: ZodType<CABButtonContent> = z.lazy(() =>\n z.discriminatedUnion('sectionType', [CABImageSection, CABLayoutSection, CABTextSection])\n);\n\nexport const CABButtonSection = z.object({\n action: z.union([z.literal(''), z.enum(buttonActions)]).default(''),\n buttonStyle: z.enum(buttonStyles).default(ButtonStyle.primary),\n custom: z\n .object({\n color: z.string().regex(HEX_COLOR_REGEX).default('#005bd3'),\n height: z.number().default(52),\n width: z.number().default(300),\n })\n .default({\n color: '#005bd3',\n height: 52,\n width: 300,\n }),\n disableDowngrade: z.boolean().default(false),\n name: z.string().optional(),\n optionId: z.number().optional(),\n popover: z\n .object({\n alignment: z.enum(textAlignments).default(TextAlignment.center),\n position: z.enum(popoverPositions).default(PopoverPosition.blockStart),\n })\n .optional()\n .default(() => ({\n alignment: TextAlignment.center,\n position: PopoverPosition.blockStart,\n })),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sections: z.union([z.array(CABButtonContent), z.strictObject({}).transform(() => [])]).default(() => []),\n sectionType: z.literal(SectionType.button).default(SectionType.button),\n /** Fire-and-forget pixel POSTed when the button is clicked (e.g. a Monetize decline). */\n trackingUrl: z.string().optional(),\n});\n\nexport type CABButtonSection = z.infer<typeof CABButtonSection>;\n\nexport type CABButtonSectionProps = CABButtonSection & SectionDetails;\n", "import { forEach, isString } from 'es-toolkit/compat';\nimport { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport {\n ButtonField,\n buttonFields,\n progressTierTypes,\n ProgressTierType,\n SectionType,\n Spacing,\n spacings,\n TextAlignment,\n textAlignments,\n TextColorName,\n textColorNames,\n TextSizeName,\n textSizeNames,\n} from './common';\nimport { DYNAMIC_TOKEN_REGEX, ROOT_RELATIVE_PATH_REGEX } from './regex';\nimport { CABRule } from './rule';\nimport { type SectionDetails } from './shared';\nimport { checkForHTML, NO_HTML } from './utils';\n\nconst enumOrOmit = <T extends readonly [string, ...string[]]>(...vals: T) =>\n z\n .string()\n .transform((val) => (vals.includes(val as T[number]) ? (val as T[number]) : undefined))\n .optional();\n\nexport const TiptapText = z.object({\n marks: z\n .union([\n z.array(\n z.discriminatedUnion('type', [\n z.object({ type: z.literal('bold') }),\n z.object({ type: z.literal('italic') }),\n z.object({\n attrs: z.object({\n class: z.string().nullable(),\n href: z.union([\n z.url(),\n z.literal('#'),\n z.string().regex(DYNAMIC_TOKEN_REGEX),\n z.string().regex(ROOT_RELATIVE_PATH_REGEX),\n ]),\n rel: z.string().default('noopener noreferrer nofollow'),\n target: z.string().default('_blank'),\n }),\n type: z.literal('link'),\n }),\n z.object({ type: z.literal('strike') }),\n z.object({\n attrs: z.object({\n color: enumOrOmit(...textColorNames).default(TextColorName.base),\n fontSize: enumOrOmit(...textSizeNames).default(TextSizeName.base),\n }),\n type: z.literal('textStyle'),\n }),\n ])\n ),\n z.strictObject({}).transform(() => []),\n ])\n .optional(),\n text: z.string().default(''),\n type: z.literal('text').default('text'),\n});\n\nexport type TiptapText = z.infer<typeof TiptapText>;\n\nexport const TiptapParagraph = z.object({\n attrs: z\n .object({\n textAlign: enumOrOmit(...textAlignments),\n })\n .default({ textAlign: TextAlignment.start }),\n content: z.union([z.array(TiptapText), z.strictObject({}).transform(() => [])]).default(() => []),\n type: z.literal('paragraph').default('paragraph'),\n});\n\nexport type TiptapParagraph = z.infer<typeof TiptapParagraph>;\n\nexport const TiptapDocument = z.object({\n attrs: z\n .object({\n blockSpacing: enumOrOmit(...spacings),\n })\n .default({ blockSpacing: Spacing.base }),\n content: z\n .union([z.array(TiptapParagraph), z.strictObject({}).transform(() => [])])\n .default(() => [TiptapParagraph.parse({})]),\n type: z.literal('doc').default('doc'),\n});\n\nexport type TiptapDocument = z.infer<typeof TiptapDocument>;\n\n/**\n * A text section's tier reference. On the smart-cart per-tier feedback copy it carries the `tierId`, so\n * the renderer shows this section only while its tier is the active (current/last-reached) one \u2014 the\n * full tier (gift/threshold) lives on progressBar.\n */\nexport const CABTextTier = z.object({\n threshold: z.number().int().nonnegative(),\n thresholds: z.record(z.string(), z.number().int().nonnegative()).default(() => ({})),\n tierId: z.string().optional(),\n tierType: z.enum(progressTierTypes).default(ProgressTierType.shipping),\n});\n\nexport type CABTextTier = z.infer<typeof CABTextTier>;\n\nexport const CABTextSection = z\n .object({\n buttonField: z.enum(buttonFields).optional(),\n content: z\n .record(z.string(), z.union([z.string(), TiptapDocument]).refine(checkForHTML, NO_HTML).optional())\n .default({ en: TiptapDocument.parse({}) })\n .optional(),\n name: z.string().optional(),\n optionId: z.number().optional(),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.text).default(SectionType.text),\n tier: CABTextTier.optional(),\n })\n .superRefine(({ buttonField, content }, ctx) => {\n if (buttonField === ButtonField.destinationUrl && content) {\n forEach(content, (value, lang) => {\n if (value && isString(value)) {\n if (DYNAMIC_TOKEN_REGEX.test(value)) return;\n\n try {\n new URL(value);\n } catch {\n ctx.addIssue({\n code: 'custom',\n message: 'Invalid URL',\n path: ['content', lang],\n });\n }\n }\n });\n }\n });\n\nexport type CABTextSection = z.infer<typeof CABTextSection>;\n\nexport type CABTextSectionProps = CABTextSection & SectionDetails;\n", "import { isPlainObject, mapValues } from 'es-toolkit';\nimport { every, get, isArray, isString, map, size, toPairs } from 'es-toolkit/compat';\n\nimport { type CABBannerSection } from './banner';\nimport { type CABButtonSection } from './button';\nimport { type CABCarouselSection } from './carousel';\nimport { type CABCartLineSection } from './cartLine';\nimport { ButtonField, SectionType } from './common';\nimport { type CABDataSourceSection } from './dataSource';\nimport { type CABDiscountSection } from './discount';\nimport { type CABImageSection } from './image';\nimport { type CABLayoutSection } from './layout';\nimport { type CABMonetizeSection } from './monetize';\nimport { type CABOffersSection } from './offers';\nimport { type CABProductSection } from './product';\nimport { type CABProductsSection } from './products';\nimport { type CABProgressBarSection } from './progressBar';\nimport { type CABQuantitySection } from './quantity';\nimport { ARRAY_INDEX_STRING, HTML_TAGS_REGEX } from './regex';\nimport { type CABReviewsSection } from './reviews';\nimport { type CABTextSection, type TiptapDocument } from './text';\nimport { type CABVariantsSection } from './variants';\n\nexport const isHTML = (html: string | undefined = ''): boolean => {\n if (typeof window !== 'undefined') {\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, 'text/html');\n\n const hasHTML = (nodeList: NodeList) => Array.from(nodeList).some((node) => node.nodeType === 1);\n\n return hasHTML(doc.body.childNodes) || hasHTML(doc.head.childNodes);\n }\n\n // `.search()` (not `.test()`) because HTML_TAGS_REGEX is global for downstream `.replace` callers;\n // `.search()` ignores and never advances `lastIndex`, so repeated calls stay deterministic.\n return html.search(HTML_TAGS_REGEX) !== -1;\n};\n\nexport const hasHTMLInDoc = (doc: TiptapDocument): boolean =>\n doc.content.some(({ content = [] }) => content.some(({ text }) => isHTML(text)));\n\nexport const checkForHTML = (input: string | TiptapDocument): boolean =>\n !((isString(input) && isHTML(input)) || (isPlainObject(input) && hasHTMLInDoc(input as TiptapDocument)));\n\nexport const NO_HTML = { message: 'HTML is not supported' };\n\nexport const isBannerType = (section: unknown): section is CABBannerSection =>\n get(section, 'sectionType') === SectionType.banner;\n\nexport const isButtonType = (section: unknown): section is CABButtonSection =>\n get(section, 'sectionType') === SectionType.button;\n\nexport const isCarouselType = (section: unknown): section is CABCarouselSection =>\n get(section, 'sectionType') === SectionType.carousel;\n\nexport const isCartLineType = (section: unknown): section is CABCartLineSection =>\n get(section, 'sectionType') === SectionType.cartLine;\n\nexport const isDataSourceType = (section: unknown): section is CABDataSourceSection =>\n get(section, 'sectionType') === SectionType.dataSource;\n\nexport const isDiscountType = (section: unknown): section is CABDiscountSection =>\n get(section, 'sectionType') === SectionType.discount;\n\nexport const isImageType = (section: unknown): section is CABImageSection =>\n get(section, 'sectionType') === SectionType.image;\n\nexport const isLayoutType = (section: unknown): section is CABLayoutSection =>\n get(section, 'sectionType') === SectionType.layout;\n\nexport const isMonetizeType = (section: unknown): section is CABMonetizeSection =>\n get(section, 'sectionType') === SectionType.monetize;\n\nexport const isOffersType = (section: unknown): section is CABOffersSection =>\n get(section, 'sectionType') === SectionType.offers;\n\nexport const isOverlayType = (section: unknown): section is CABLayoutSection =>\n isLayoutType(section) && get(section, 'buttonField') === ButtonField.overlayContent;\n\nexport const isProductType = (section: unknown): section is CABProductSection =>\n get(section, 'sectionType') === SectionType.product;\n\nexport const isProductsType = (section: unknown): section is CABProductsSection =>\n get(section, 'sectionType') === SectionType.products;\n\nexport const isProgressBarType = (section: unknown): section is CABProgressBarSection =>\n get(section, 'sectionType') === SectionType.progressBar;\n\nexport const isQuantityType = (section: unknown): section is CABQuantitySection =>\n get(section, 'sectionType') === SectionType.quantity;\n\nexport const isReviewsType = (section: unknown): section is CABReviewsSection =>\n get(section, 'sectionType') === SectionType.reviews;\n\nexport const isTextType = (section: unknown): section is CABTextSection =>\n get(section, 'sectionType') === SectionType.text;\n\nexport const isVariantsType = (section: unknown): section is CABVariantsSection =>\n get(section, 'sectionType') === SectionType.variants;\n\nconst hasOnlyNumericKeys = (input: Record<string, unknown>) =>\n !!size(input) && every(input, (_, key) => ARRAY_INDEX_STRING.test(key) && Number.isSafeInteger(Number(key)));\n\nconst numericObjectToArray = (input: Record<string, unknown>) =>\n toPairs(input)\n .sort(([a], [b]) => Number(a) - Number(b))\n .map(([_, value]) => value);\n\nexport const convertNumericObjects = (input: unknown): unknown => {\n if (isArray(input)) return map(input, convertNumericObjects);\n\n if (isPlainObject(input)) {\n const obj = input as Record<string, unknown>;\n\n return hasOnlyNumericKeys(obj)\n ? map(numericObjectToArray(obj), convertNumericObjects)\n : mapValues(obj, convertNumericObjects);\n }\n\n return input;\n};\n", "import { z } from 'zod';\n\nimport { SectionType } from './common';\nimport { CABLayoutSection } from './layout';\nimport { CABOffersSection } from './offers';\nimport { CABSection, type SectionDetails } from './shared';\n\nexport const CABCarouselSection = z.lazy(() =>\n CABLayoutSection.omit({ sections: true, sectionType: true }).extend({\n autoAdvanceInterval: z.number().default(0),\n itemsAtOnce: z.number().min(1).default(1),\n sections: z\n .union([z.array(z.lazy(() => CABSection)), z.strictObject({}).transform(() => [])])\n .default(() => [CABOffersSection.parse({})]),\n sectionType: z.literal(SectionType.carousel).default(SectionType.carousel),\n })\n);\n\nexport type CABCarouselSection = Omit<CABLayoutSection, 'sectionType'> & {\n autoAdvanceInterval: number;\n itemsAtOnce: number;\n sectionType: 'carousel';\n};\n\nexport type CABCarouselSectionProps = CABCarouselSection & SectionDetails;\n", "import { z } from 'zod';\n\nimport { CABBannerSection } from './banner';\nimport { CABButtonSection } from './button';\nimport { ButtonStyle, SectionType } from './common';\nimport { CABDataSourceSection } from './dataSource';\nimport { CABLayoutSection } from './layout';\nimport { CABProductsSection } from './products';\nimport { CABSection, type SectionDetails } from './shared';\nimport { CABTextSection } from './text';\n\nexport const CABOffersSection = z.lazy(() =>\n CABLayoutSection.omit({ sections: true, sectionType: true }).extend({\n sections: z.union([z.array(z.lazy(() => CABSection)), z.strictObject({}).transform(() => [])]).default(() => [\n CABBannerSection.parse({\n buttonField: 'undoAddToOrder',\n color: 'success',\n dismissible: true,\n name: 'Success Banner',\n sections: [\n CABTextSection.parse({ content: { en: '{{quantity}} {{productTitle}} added to cart.' } }),\n CABButtonSection.parse({ action: 'undoAddToOrder', buttonStyle: ButtonStyle.plain }),\n ],\n }),\n CABDataSourceSection.parse({}),\n CABProductsSection.parse({}),\n ]),\n sectionType: z.literal(SectionType.offers).default(SectionType.offers),\n })\n);\n\nexport type CABOffersSection = Omit<CABLayoutSection, 'sectionType'> & {\n sectionType: 'offers';\n};\n\nexport type CABOffersSectionProps = CABOffersSection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { discountSources, discountTypes, productTypes, SectionType } from './common';\nimport { DEFAULT_ENDPOINTS } from './constants';\nimport { type SectionDetails } from './shared';\n\nexport const CABDiscount = z.object({\n amount: z.union([z.number(), z.string()]).catch(0),\n discountedBy: z.string().optional(),\n discountedFrom: z.enum(discountSources).optional().catch(undefined),\n type: z.enum(discountTypes).catch('none'),\n});\n\nexport type CABDiscount = z.infer<typeof CABDiscount>;\n\nexport const CABIntegrations = z.object({\n judgeme: z.boolean().default(false),\n junip: z.boolean().default(false),\n klaviyo: z.boolean().default(false),\n loox: z.boolean().default(false),\n okendo: z.boolean().default(false),\n opinew: z.boolean().default(false),\n reviewsio: z.boolean().default(false),\n stamped: z.boolean().default(false),\n yotpo: z.boolean().default(false),\n});\n\nexport type CABIntegrations = z.infer<typeof CABIntegrations>;\n\nexport const CABDataSourceSection = z.object({\n dataSourceId: z.number().nullable().default(null),\n dataSourcePath: z.string().default(DEFAULT_ENDPOINTS[0].value),\n discount: CABDiscount.optional(),\n integrations: CABIntegrations.optional(),\n limit: z.number().default(1),\n matchVariant: z.boolean().default(false),\n matchVariantOutOfStock: z.boolean().default(false),\n name: z.string().default(DEFAULT_ENDPOINTS[0].label),\n productType: z.enum(productTypes).optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.dataSource).default(SectionType.dataSource),\n /** Default subscribe-vs-one-time for `productType: both` (legacy `subscription_is_default`). */\n subscriptionIsDefault: z.boolean().default(false),\n treatAsGwp: z.boolean().default(false),\n});\n\nexport type CABDataSourceSection = z.infer<typeof CABDataSourceSection>;\n\nexport type CABDataSourceSectionProps = CABDataSourceSection & SectionDetails;\n", "import { uniqBy } from 'es-toolkit';\n\nimport { EditorMode, freezeEnum } from './common';\nimport { type TargetArea } from './root';\n\nexport const DEFAULT_ENDPOINTS = [\n { label: 'Recommended (AI)', value: '/products/recommended' },\n { label: 'Top Sellers', value: '/products/top_sellers' },\n { label: 'Buy It Again', value: '/products/purchased' },\n { label: 'Recently Viewed', value: '/products/viewed' },\n { label: 'Products Search', value: '/products/search' },\n { label: 'Collection Products', value: '/products/collections' },\n { label: 'Similar Products (AI)', value: '/products/similar_products' },\n] as const;\n\nexport const STATIC_ENDPOINTS = [\n { label: 'Recommended (AI)', value: '/products/recommended' },\n { label: 'Top Sellers', value: '/products/top_sellers' },\n { label: 'Trending Products', value: '/products/trending_products' },\n { label: 'Buy It Again', value: '/products/purchased' },\n { label: 'Collection Products', value: '/products/collections' },\n { label: 'Recently Viewed', value: '/products/viewed' },\n { label: 'Static Products', value: '/products/static' },\n { label: 'Products Search', value: '/products/search' },\n { label: 'Similar Products (AI)', value: '/products/similar_products' },\n] as const;\n\nexport const COMBINED_ENDPOINTS = uniqBy([...DEFAULT_ENDPOINTS, ...STATIC_ENDPOINTS], (item) => item.value);\n\nexport const targetAreas = {\n [EditorMode.checkoutExtension]: [\n { icon: 'splitscreen_top', label: 'Header Area', width: '984px' },\n { icon: 'splitscreen_left', label: 'Main Column', width: '503px' },\n { icon: 'splitscreen_right', label: 'Summary Column', width: '404px' },\n ] satisfies TargetArea[],\n [EditorMode.postPurchaseOffer]: null,\n [EditorMode.thankYouPage]: [\n { icon: 'splitscreen_top', label: 'Header Area', width: '984px' },\n { icon: 'splitscreen_left', label: 'Main Column', width: '503px' },\n { icon: 'splitscreen_right', label: 'Summary Column', width: '404px' },\n ] satisfies TargetArea[],\n [EditorMode.orderStatusPage]: [\n // { fill: true, flip: 'vertical', icon: 'bottom_navigation', label: 'Announcement Bar' },\n { icon: 'splitscreen_top', label: 'Header Area', width: '1124px' },\n { fill: true, icon: 'view_column_2', label: 'Main Area', width: '646px' },\n { icon: 'splitscreen_bottom', label: 'Footer Area', width: '1124px' },\n ] satisfies TargetArea[],\n [EditorMode.ordersIndexPage]: [\n // { fill: true, flip: 'vertical', icon: 'bottom_navigation', label: 'Announcement Bar' },\n { icon: 'splitscreen_top', label: 'Main Area', width: '1124px' },\n ] satisfies TargetArea[],\n [EditorMode.customerProfilePage]: [\n // { fill: true, flip: 'vertical', icon: 'bottom_navigation', label: 'Announcement Bar' },\n { icon: 'splitscreen_top', label: 'Main Area', width: '1124px' },\n ] satisfies TargetArea[],\n} as const;\n\nexport const widgetTypes = [\n 'bundle_builder',\n 'cart',\n 'cart_subscription',\n 'dynamic_bundle',\n 'gift_with_purchase',\n 'pre_purchase',\n 'product',\n 'product_addon',\n 'product_upsell',\n 'recharge_checkout',\n 'recharge_customer_portal',\n 'recharge_post_purchase',\n 'shopify_checkout',\n 'shopify_checkout_extension',\n 'shopify_post_purchase',\n 'shopify_post_purchase_extension',\n 'switch_to_subscription',\n 'ui_extension_ad',\n 'ui_extension_button',\n 'ui_extension_content_block',\n 'ui_extension_line_item_editor',\n 'ui_extension_progress_bar',\n] as const;\n\nexport const WidgetType = freezeEnum(widgetTypes);\nexport type WidgetType = (typeof widgetTypes)[number];\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { SectionType } from './common';\nimport { CABProductSection } from './product';\nimport { type SectionDetails } from './shared';\n\nexport const CABProductsSection = z.object({\n name: z.string().optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sections: z\n .union([z.array(z.lazy(() => CABProductSection)), z.strictObject({}).transform(() => [])])\n .default(() => []),\n sectionType: z.literal(SectionType.products).default(SectionType.products),\n});\n\nexport type CABProductsSection = z.infer<typeof CABProductsSection>;\n\nexport type CABProductsSectionProps = CABProductsSection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z, type ZodType } from 'zod';\n\nimport { CABButtonSection } from './button';\nimport { SectionType, VariantMode, variantModes, VariantSelector, variantSelectors } from './common';\nimport { type SectionDetails } from './shared';\nimport { CABTextSection } from './text';\n\nexport type CABVariantContent = CABButtonSection | CABTextSection;\n\nexport const CABVariantContent: ZodType<CABVariantContent> = z.lazy(() =>\n z.discriminatedUnion('sectionType', [CABButtonSection, CABTextSection])\n);\n\nexport const CABProductSection = z.object({\n name: z.string().optional(),\n productId: z.number().nullable().default(null),\n sectionId: z.uuid().default(() => uuidv7()),\n sections: z.union([z.array(CABVariantContent), z.strictObject({}).transform(() => [])]).default(() => []),\n sectionType: z.literal(SectionType.product).default(SectionType.product),\n selectors: z.record(z.string(), z.enum(variantSelectors).default(VariantSelector.menu)).default(() => ({})),\n variantMode: z.enum(variantModes).default(VariantMode.multiple),\n});\n\nexport type CABProductSection = z.infer<typeof CABProductSection>;\n\nexport type CABProductSectionProps = CABProductSection & SectionDetails;\n", "import { z } from 'zod';\n\nimport { CABButtonSection } from './button';\nimport { ButtonAction, SectionType } from './common';\nimport { CABLayoutSection } from './layout';\nimport { CABSection, type SectionDetails } from './shared';\n\nexport const CABCartLineSection = z.lazy(() =>\n CABLayoutSection.omit({ sections: true, sectionType: true }).extend({\n sections: z\n .union([z.array(z.lazy(() => CABSection)), z.strictObject({}).transform(() => [])])\n .default(() => [CABButtonSection.parse({ action: ButtonAction.switchToSubscription })]),\n sectionType: z.literal(SectionType.cartLine).default(SectionType.cartLine),\n })\n);\n\nexport type CABCartLineSection = Omit<CABLayoutSection, 'sectionType'> & {\n sectionType: 'cartLine';\n};\n\nexport type CABCartLineSectionProps = CABCartLineSection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { discountSources, discountTypes, SectionType } from './common';\nimport { type SectionDetails } from './shared';\n\n/**\n * The widget discount, modeled as its own offers child section (toggled on/off in the editor and\n * rendered nowhere \u2014 it's config-only). Discounting is Shopify Functions-only (Scripts is sunset), so a\n * configured discount always applies via Functions and the amount is in Functions (minor-unit) form for\n * fixed types. `discountedFrom` is the compare-from source; `message` is the Functions discount title.\n */\nexport const CABDiscountSection = z.object({\n amount: z.union([z.number(), z.string()]).catch(0),\n discountedBy: z.string().optional(),\n discountedFrom: z.enum(discountSources).optional().catch(undefined),\n message: z.string().optional(),\n name: z.string().optional(),\n quantity: z.number().default(1),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.discount).default(SectionType.discount),\n type: z.enum(discountTypes).catch('none'),\n});\n\nexport type CABDiscountSection = z.infer<typeof CABDiscountSection>;\n\nexport type CABDiscountSectionProps = CABDiscountSection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { SectionType } from './common';\nimport { CABRule } from './rule';\nimport { type SectionDetails } from './shared';\n\nexport const CABMonetizeSection = z.object({\n name: z.string().optional(),\n /** Privacy Policy footer href (the widget's `privacy_policy_url` setting); the client relays it to `/cab/monetize`. */\n privacyPolicyUrl: z.string().optional(),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.monetize).default(SectionType.monetize),\n});\n\nexport type CABMonetizeSection = z.infer<typeof CABMonetizeSection>;\n\nexport type CABMonetizeSectionProps = CABMonetizeSection & SectionDetails;\n", "import { z } from 'zod';\n\nimport { ProgressTierType, progressTierTypes, ProgressTierUnit, progressTierUnits, SectionType } from './common';\nimport { GIFT_LABELS } from './giftLabels';\nimport { CABLayoutSection } from './layout';\nimport { type SectionDetails } from './shared';\n\nexport const CABProgressTier = z.object({\n /**\n * Order-discount tiers only (onsite `discount`): the reward the order-discount Function applies at\n * cart time, carried so the client can resolve the `{{discountAmount}}` token in this tier's copy.\n * `fixedAmount`: shop-currency CENTS (FX-scaled by the client, like {@link CABProgressTier.threshold});\n * `percentage`: the whole-percent number rendered raw (`{n}%`). Absent on non-discount tiers.\n */\n discount: z.object({ amount: z.number().nonnegative(), type: z.enum(['fixedAmount', 'percentage']) }).optional(),\n /**\n * Smart-cart product (gift) tiers only: the reward unlocked at this tier. The client enriches\n * `productId`/`variantIds` to live variants (availability, price) and adds the chosen one to the cart\n * when the tier is reached (attribution `_tier` = {@link CABProgressTier.tierId}). Absent on shipping\n * tiers and on tiers with no configured product. Cart add/remove is a later stage; carried here so the\n * tree is complete.\n */\n gift: z\n .object({\n productId: z.number().int().positive(),\n title: z.string().optional(),\n variantIds: z.array(z.number().int().positive()).default(() => []),\n })\n .optional(),\n /**\n * The step-row label at this tier's slot (onsite `getTierLabel`): the merchant custom label, else the\n * type default ('Free Shipping' / product title / '{n}% Discount'). Localized content; blank \u21D2 no\n * label under the tier's icon. Plain text \u2014 the step row is a compact icon+label, not rich copy.\n */\n label: z.record(z.string(), z.string()).optional(),\n /**\n * The tier's goal, measured per `unit`. `currency` (default): SHOP-currency cents \u2014 the canonical\n * fallback: when the buyer's presentment currency has no entry in `thresholds`, the client\n * multiplies this by the live FX rate (converter maps the v1 `unlock_price`, e.g. `75` \u2192 `7500`).\n * `item`: a raw item count \u2014 no cents, no FX, no `thresholds` overrides.\n */\n threshold: z.number().int().nonnegative(),\n /**\n * Per-presentment-currency goal overrides \u2014 lowercased ISO currency code \u2192 cents (e.g. `{ cad: 9900 }`).\n * When the buyer's currency has an entry, the client uses it verbatim INSTEAD of FX-converting\n * `threshold`, so merchants show intentional, clean per-market amounts (Shopify Markets) rather than a\n * converted base. Defaults to `{}` \u2014 no overrides means always fall back to `threshold`.\n */\n thresholds: z.record(z.string(), z.number().int().nonnegative()).default(() => ({})),\n /**\n * Smart-cart tier identifier, mirrored onto the gift cart line's `_tier` attribute so the client can\n * match an in-cart gift back to its tier (add on reach, remove on downgrade/decline). Absent on the\n * shipping bar (single unlabeled tier, no gift).\n */\n tierId: z.string().optional(),\n tierType: z.enum(progressTierTypes).default(ProgressTierType.shipping),\n /**\n * What this tier's progress is measured in \u2014 PER TIER (onsite's `unlock_condition_type` model, NOT\n * the React port's bar-level `tiers[0]` shortcut). `currency` compares money cents against the\n * adjusted subtotal; `item` compares the raw quantity sum of non-excluded lines (the SAME exclusion\n * set as the money path). A mixed-unit bar stays coherent tier by tier: reach, fill share, and\n * `{{remainingAmount}}` (count-formatted + item/items-pluralized for `item` tiers) each resolve in\n * their own tier's unit \u2014 cross-tier arithmetic never mixes counts with cents.\n */\n unit: z.enum(progressTierUnits).default(ProgressTierUnit.currency),\n});\n\nexport type CABProgressTier = z.infer<typeof CABProgressTier>;\n\n/**\n * A self-contained progress-bar container. Extends `layout` (alignment/border/spacing/`sections`/\u2026), so it\n * holds ALL its pieces as composable children \u2014 the tier display (a `columns \u2192 rows \u2192 text/image` layout)\n * and the reached/remaining message `text`s \u2014 while the renderer adds the bar fill from `tiers` and shows\n * the active message. Everything is encapsulated under this one named section (and one country/FX gate).\n */\nexport const CABProgressBarSection = z.lazy(() =>\n CABLayoutSection.omit({ sectionType: true }).extend({\n /** Empty = shown everywhere; otherwise uppercase ISO country codes. */\n countryCodes: z.array(z.string().transform((code) => code.trim().toUpperCase())).default(() => []),\n /**\n * Uppercase ISO codes where a higher-precedence geo bar applies, so this (default, non-geo) bar is\n * hidden there \u2014 replicates React `getbar`'s geo-match-over-default precedence. Empty = never excluded.\n */\n excludeCountryCodes: z.array(z.string().transform((code) => code.trim().toUpperCase())).default(() => []),\n /**\n * Measure progress against the PRE-discount subtotal (onsite `exclude_discount_in_subtotal`, and\n * forced on for bars with a discount tier so its own reward can't un-reach the tier). The client\n * adds the cart's discount allocations back to the live subtotal.\n */\n excludeDiscountInSubtotal: z.boolean().default(false),\n /** Variant ids the client subtracts from the adjusted subtotal (React `bar.excluded_products`). */\n excludedVariantIds: z.array(z.number().int().positive()).default(() => []),\n /**\n * When the cart holds a subscription item, treat the bar as reached regardless of subtotal (React\n * `free_shipping_on_subscription(s)`). `freeShippingOnAll` is already a zero-threshold tier instead.\n */\n freeShippingOnSubscription: z.boolean().default(false),\n /** Localized heading over the gift controls (onsite `gift_area_title`, default 'FREE GIFTS'). */\n giftAreaTitle: z.record(z.string(), z.string()).default(() => ({ en: 'FREE GIFTS' })),\n /** Localized gift-control labels (add/remove/heading); a tier's gift `title` beats `yourGift`. */\n giftLabels: z\n .object({\n addGift: z.record(z.string(), z.string()).default(() => ({ ...GIFT_LABELS.addGift })),\n remove: z.record(z.string(), z.string()).default(() => ({ ...GIFT_LABELS.remove })),\n selectOptions: z.record(z.string(), z.string()).default(() => ({ ...GIFT_LABELS.selectOptions })),\n yourGift: z.record(z.string(), z.string()).default(() => ({ ...GIFT_LABELS.yourGift })),\n })\n .default(() => ({\n addGift: { ...GIFT_LABELS.addGift },\n remove: { ...GIFT_LABELS.remove },\n selectOptions: { ...GIFT_LABELS.selectOptions },\n yourGift: { ...GIFT_LABELS.yourGift },\n })),\n /** The bar's a11y label; the merchant names it in the editor, else this default (React parity). */\n name: z.string().default('Order progress'),\n /**\n * Bar fill color. An explicit (widget-authored) value is used verbatim; when absent the server\n * fills it with the live shop theme's `buttonBackground` (React `useRebuyTheme` parity). Still\n * absent after that \u21D2 the theme fetch failed and the client renders its platform-default bar \u2014\n * optional, not defaulted, so \"merchant chose no color\" stays distinguishable from any real value.\n */\n progressColor: z.string().optional(),\n sectionType: z.literal(SectionType.progressBar).default(SectionType.progressBar),\n /**\n * The bar's milestones, in any order \u2014 the renderer sorts by resolved threshold. Drives the fill\n * (even slot per tier) and, for smart-cart product tiers, the gift add/remove. The visual tier\n * display lives in `sections` (composable), NOT here.\n */\n tiers: z.union([z.array(CABProgressTier), z.strictObject({}).transform(() => [])]).default(() => []),\n })\n);\n\nexport type CABProgressBarSection = Omit<CABLayoutSection, 'name' | 'sectionType'> & {\n countryCodes: string[];\n excludeCountryCodes: string[];\n excludeDiscountInSubtotal: boolean;\n excludedVariantIds: number[];\n freeShippingOnSubscription: boolean;\n giftAreaTitle: Record<string, string>;\n giftLabels: Record<'addGift' | 'remove' | 'selectOptions' | 'yourGift', Record<string, string>>;\n name: string;\n progressColor?: string;\n sectionType: 'progressBar';\n tiers: CABProgressTier[];\n};\n\nexport type CABProgressBarSectionProps = CABProgressBarSection & SectionDetails;\n", "/**\n * Default localized labels for the smart-cart gift controls, keyed by slot then locale (same 26 locales\n * as `SWITCH_LABELS`). Schema-default content, never a client dictionary (Peter, 2026-07-06: visible\n * customer strings must be localized). `yourGift` is the generic heading \u2014 a tier's configured gift\n * `title` beats it when present.\n */\nexport const GIFT_LABELS = {\n addGift: {\n ar: '\u0623\u0636\u0641 \u0627\u0644\u0647\u062F\u064A\u0629',\n cs: 'P\u0159idat d\u00E1rek',\n da: 'Tilf\u00F8j gave',\n de: 'Geschenk hinzuf\u00FCgen',\n en: 'Add gift',\n es: 'A\u00F1adir regalo',\n fi: 'Lis\u00E4\u00E4 lahja',\n fr: 'Ajouter le cadeau',\n ga: 'Cuir bronntanas leis',\n he: '\u05D4\u05D5\u05E1\u05E3 \u05DE\u05EA\u05E0\u05D4',\n hi: '\u0909\u092A\u0939\u093E\u0930 \u091C\u094B\u0921\u093C\u0947\u0902',\n id: 'Tambahkan hadiah',\n it: 'Aggiungi regalo',\n ja: '\u30AE\u30D5\u30C8\u3092\u8FFD\u52A0',\n ko: '\uC0AC\uC740\uD488 \uCD94\uAC00',\n nl: 'Cadeau toevoegen',\n no: 'Legg til gave',\n pl: 'Dodaj prezent',\n pt: 'Adicionar presente',\n ru: '\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043F\u043E\u0434\u0430\u0440\u043E\u043A',\n sv: 'L\u00E4gg till g\u00E5va',\n th: '\u0E40\u0E1E\u0E34\u0E48\u0E21\u0E02\u0E2D\u0E07\u0E02\u0E27\u0E31\u0E0D',\n tr: 'Hediye ekle',\n uk: '\u0414\u043E\u0434\u0430\u0442\u0438 \u043F\u043E\u0434\u0430\u0440\u0443\u043D\u043E\u043A',\n vi: 'Th\u00EAm qu\u00E0 t\u1EB7ng',\n zh: '\u6DFB\u52A0\u8D60\u54C1',\n },\n remove: {\n ar: '\u0625\u0632\u0627\u0644\u0629',\n cs: 'Odebrat',\n da: 'Fjern',\n de: 'Entfernen',\n en: 'Remove',\n es: 'Eliminar',\n fi: 'Poista',\n fr: 'Retirer',\n ga: 'Bain',\n he: '\u05D4\u05E1\u05E8',\n hi: '\u0939\u091F\u093E\u090F\u0901',\n id: 'Hapus',\n it: 'Rimuovi',\n ja: '\u524A\u9664',\n ko: '\uC81C\uAC70',\n nl: 'Verwijderen',\n no: 'Fjern',\n pl: 'Usu\u0144',\n pt: 'Remover',\n ru: '\u0423\u0434\u0430\u043B\u0438\u0442\u044C',\n sv: 'Ta bort',\n th: '\u0E19\u0E33\u0E2D\u0E2D\u0E01',\n tr: 'Kald\u0131r',\n uk: '\u0412\u0438\u0434\u0430\u043B\u0438\u0442\u0438',\n vi: 'X\u00F3a',\n zh: '\u79FB\u9664',\n },\n selectOptions: {\n ar: '\u0627\u062E\u062A\u0631 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A',\n cs: 'Vyberte mo\u017Enosti',\n da: 'V\u00E6lg muligheder',\n de: 'Optionen w\u00E4hlen',\n en: 'Select Options',\n es: 'Seleccionar opciones',\n fi: 'Valitse vaihtoehdot',\n fr: 'Choisir les options',\n ga: 'Roghnaigh roghanna',\n he: '\u05D1\u05D7\u05E8 \u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA',\n hi: '\u0935\u093F\u0915\u0932\u094D\u092A \u091A\u0941\u0928\u0947\u0902',\n id: 'Pilih opsi',\n it: 'Seleziona le opzioni',\n ja: '\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u9078\u629E',\n ko: '\uC635\uC158 \uC120\uD0DD',\n nl: 'Opties kiezen',\n no: 'Velg alternativer',\n pl: 'Wybierz opcje',\n pt: 'Selecionar op\u00E7\u00F5es',\n ru: '\u0412\u044B\u0431\u0440\u0430\u0442\u044C \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B',\n sv: 'V\u00E4lj alternativ',\n th: '\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01',\n tr: 'Se\u00E7enekleri se\u00E7',\n uk: '\u0412\u0438\u0431\u0440\u0430\u0442\u0438 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0438',\n vi: 'Ch\u1ECDn t\u00F9y ch\u1ECDn',\n zh: '\u9009\u62E9\u9009\u9879',\n },\n yourGift: {\n ar: '\u0647\u062F\u064A\u062A\u0643',\n cs: 'V\u00E1\u0161 d\u00E1rek',\n da: 'Din gave',\n de: 'Ihr Geschenk',\n en: 'Your gift',\n es: 'Tu regalo',\n fi: 'Lahjasi',\n fr: 'Votre cadeau',\n ga: 'Do bhronntanas',\n he: '\u05D4\u05DE\u05EA\u05E0\u05D4 \u05E9\u05DC\u05DA',\n hi: '\u0906\u092A\u0915\u093E \u0909\u092A\u0939\u093E\u0930',\n id: 'Hadiah Anda',\n it: 'Il tuo regalo',\n ja: '\u3042\u306A\u305F\u306E\u30AE\u30D5\u30C8',\n ko: '\uACE0\uAC1D\uB2D8\uC758 \uC0AC\uC740\uD488',\n nl: 'Uw cadeau',\n no: 'Din gave',\n pl: 'Tw\u00F3j prezent',\n pt: 'Seu presente',\n ru: '\u0412\u0430\u0448 \u043F\u043E\u0434\u0430\u0440\u043E\u043A',\n sv: 'Din g\u00E5va',\n th: '\u0E02\u0E2D\u0E07\u0E02\u0E27\u0E31\u0E0D\u0E02\u0E2D\u0E07\u0E04\u0E38\u0E13',\n tr: 'Hediyeniz',\n uk: '\u0412\u0430\u0448 \u043F\u043E\u0434\u0430\u0440\u0443\u043D\u043E\u043A',\n vi: 'Qu\u00E0 c\u1EE7a b\u1EA1n',\n zh: '\u60A8\u7684\u8D60\u54C1',\n },\n} satisfies Record<string, Record<string, string>>;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { QuantityInput, quantityInputs, SectionType } from './common';\nimport { CABRule } from './rule';\nimport { type SectionDetails } from './shared';\n\nexport const CABQuantitySection = z.object({\n errorMessages: z\n .record(\n z.string(),\n z.object({\n /** `{{step}}` is interpolated at render \u2014 the off-increment message React never gave a merchant key. */\n increment: z.string().optional(),\n max: z.string().optional(),\n min: z.string().optional(),\n neg: z.string().optional(),\n })\n )\n .default({\n en: {\n increment: 'Quantity must be in increments of {{step}}',\n max: 'Maximum quantity allowed is {{max}}',\n min: 'Minimum quantity required is {{min}}',\n neg: 'Quantity cannot be negative',\n },\n }),\n inputType: z.enum(quantityInputs).default(QuantityInput.select),\n max: z.number().min(1).max(100).default(10),\n min: z.number().min(1).default(1),\n /** The a11y label for the quantity control; the merchant names it in the editor, else this default. */\n name: z.string().default('Quantity'),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.quantity).default(SectionType.quantity),\n});\n\nexport type CABQuantitySection = z.infer<typeof CABQuantitySection>;\n\nexport type CABQuantitySectionProps = CABQuantitySection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { ReviewsSize, reviewsSizes, SectionType } from './common';\nimport { REVIEW_LABELS } from './reviewLabels';\nimport { CABRule } from './rule';\nimport { type SectionDetails } from './shared';\n\nexport const CABReviewsSection = z.object({\n color: z.string().default('#fadb14'),\n /**\n * Localized review-count templates (`{{reviewCount}}`), one/other plural forms; the client picks the\n * form via `Intl.PluralRules`. Defaults here (schema-first) so every tree localizes without converter\n * or merchant work.\n */\n countLabels: z\n .object({\n one: z.record(z.string(), z.string()).default(() => ({ ...REVIEW_LABELS.one })),\n other: z.record(z.string(), z.string()).default(() => ({ ...REVIEW_LABELS.other })),\n })\n .default(() => ({ one: { ...REVIEW_LABELS.one }, other: { ...REVIEW_LABELS.other } })),\n name: z.string().optional(),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.reviews).default(SectionType.reviews),\n size: z.enum(reviewsSizes).default(ReviewsSize.default),\n});\n\nexport type CABReviewsSection = z.infer<typeof CABReviewsSection>;\n\nexport type CABReviewsSectionProps = CABReviewsSection & SectionDetails;\n", "/**\n * Default localized review-count templates for the reviews section, keyed by CLDR-ish plural form then\n * locale (same 26 locales as `SWITCH_LABELS`). The client picks `one` vs `other` via `Intl.PluralRules`\n * and interpolates `{{reviewCount}}` \u2014 the two-form simplification maps every non-`one` category\n * (few/many/other) to `other`. Schema-default content, never a client dictionary (Peter, 2026-07-06:\n * visible customer strings must be localized).\n */\nexport const REVIEW_LABELS = {\n one: {\n ar: '({{reviewCount}} \u062A\u0642\u064A\u064A\u0645)',\n cs: '({{reviewCount}} recenze)',\n da: '({{reviewCount}} anmeldelse)',\n de: '({{reviewCount}} Bewertung)',\n en: '({{reviewCount}} review)',\n es: '({{reviewCount}} rese\u00F1a)',\n fi: '({{reviewCount}} arvostelu)',\n fr: '({{reviewCount}} avis)',\n ga: '({{reviewCount}} l\u00E9irmheas)',\n he: '({{reviewCount}} \u05D1\u05D9\u05E7\u05D5\u05E8\u05EA)',\n hi: '({{reviewCount}} \u0938\u092E\u0940\u0915\u094D\u0937\u093E)',\n id: '({{reviewCount}} ulasan)',\n it: '({{reviewCount}} recensione)',\n ja: '({{reviewCount}}\u4EF6\u306E\u30EC\u30D3\u30E5\u30FC)',\n ko: '({{reviewCount}}\uAC1C \uB9AC\uBDF0)',\n nl: '({{reviewCount}} beoordeling)',\n no: '({{reviewCount}} anmeldelse)',\n pl: '({{reviewCount}} opinia)',\n pt: '({{reviewCount}} avalia\u00E7\u00E3o)',\n ru: '({{reviewCount}} \u043E\u0442\u0437\u044B\u0432)',\n sv: '({{reviewCount}} recension)',\n th: '({{reviewCount}} \u0E23\u0E35\u0E27\u0E34\u0E27)',\n tr: '({{reviewCount}} de\u011Ferlendirme)',\n uk: '({{reviewCount}} \u0432\u0456\u0434\u0433\u0443\u043A)',\n vi: '({{reviewCount}} \u0111\u00E1nh gi\u00E1)',\n zh: '({{reviewCount}} \u6761\u8BC4\u4EF7)',\n },\n other: {\n ar: '({{reviewCount}} \u062A\u0642\u064A\u064A\u0645\u0627\u062A)',\n cs: '({{reviewCount}} recenz\u00ED)',\n da: '({{reviewCount}} anmeldelser)',\n de: '({{reviewCount}} Bewertungen)',\n en: '({{reviewCount}} reviews)',\n es: '({{reviewCount}} rese\u00F1as)',\n fi: '({{reviewCount}} arvostelua)',\n fr: '({{reviewCount}} avis)',\n ga: '({{reviewCount}} l\u00E9irmheasanna)',\n he: '({{reviewCount}} \u05D1\u05D9\u05E7\u05D5\u05E8\u05D5\u05EA)',\n hi: '({{reviewCount}} \u0938\u092E\u0940\u0915\u094D\u0937\u093E\u090F\u0901)',\n id: '({{reviewCount}} ulasan)',\n it: '({{reviewCount}} recensioni)',\n ja: '({{reviewCount}}\u4EF6\u306E\u30EC\u30D3\u30E5\u30FC)',\n ko: '({{reviewCount}}\uAC1C \uB9AC\uBDF0)',\n nl: '({{reviewCount}} beoordelingen)',\n no: '({{reviewCount}} anmeldelser)',\n pl: '({{reviewCount}} opinii)',\n pt: '({{reviewCount}} avalia\u00E7\u00F5es)',\n ru: '({{reviewCount}} \u043E\u0442\u0437\u044B\u0432\u043E\u0432)',\n sv: '({{reviewCount}} recensioner)',\n th: '({{reviewCount}} \u0E23\u0E35\u0E27\u0E34\u0E27)',\n tr: '({{reviewCount}} de\u011Ferlendirme)',\n uk: '({{reviewCount}} \u0432\u0456\u0434\u0433\u0443\u043A\u0456\u0432)',\n vi: '({{reviewCount}} \u0111\u00E1nh gi\u00E1)',\n zh: '({{reviewCount}} \u6761\u8BC4\u4EF7)',\n },\n} satisfies Record<'one' | 'other', Record<string, string>>;\n", "import { slice } from 'es-toolkit/compat';\nimport { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { SectionType, VariantMode, variantModes, VariantSelector, variantSelectors } from './common';\nimport { CABRule } from './rule';\nimport { type SectionDetails } from './shared';\n\nexport const CABVariantsSection = z.object({\n hideOutOfStockVariants: z.boolean().default(false),\n name: z.string().optional(),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.variants).default(SectionType.variants),\n selector: z.enum(slice(variantSelectors, 0, 3)).default(VariantSelector.menu),\n variantMode: z.enum(variantModes).default(VariantMode.multiple),\n});\n\nexport type CABVariantsSection = z.infer<typeof CABVariantsSection>;\n\nexport type CABVariantsSectionProps = CABVariantsSection & SectionDetails;\n", "const HTML_COMMENT_RE = /<!--[\\s\\S]*?-->/g;\nconst STRIPPED_ELEMENT_RE = /<(script|style|iframe|object|embed|noscript|template)\\b[^>]*>[\\s\\S]*?(?:<\\/\\1\\s*>|$)/gi;\nconst HTML_TAG_RE = /<\\/?[a-zA-Z][^>]*>/g;\n\nexport const stripContentBlockHtml = (text: string): string =>\n text.replace(HTML_COMMENT_RE, '').replace(STRIPPED_ELEMENT_RE, '').replace(HTML_TAG_RE, '');\n", "import { TiptapParagraph, type TiptapText } from '~/schema/widgets/checkout-and-beyond/text';\nimport { stripContentBlockHtml } from '~/transforms/contentBlockV1/stripContentBlockHtml';\n\ntype ConvertTextToTiptapArgs = {\n color: string;\n fontSize: string;\n marks?: NonNullable<TiptapText['marks']>;\n text: string;\n textAlign: 'start' | 'center' | 'end';\n};\n\nexport const convertTextToTiptapParagraph = ({\n color,\n fontSize,\n marks = [],\n text,\n textAlign,\n}: ConvertTextToTiptapArgs): TiptapParagraph => {\n const sanitizedText = stripContentBlockHtml(text);\n\n return TiptapParagraph.parse({\n attrs: { textAlign },\n content: sanitizedText\n ? [\n {\n marks: [{ attrs: { color, fontSize }, type: 'textStyle' }, ...marks],\n text: sanitizedText,\n type: 'text',\n },\n ]\n : [],\n type: 'paragraph',\n });\n};\n", "/**\n * Minimal v1 content-block input types. The legacy `/widgets/settings` endpoint\n * returns the widget's settings object directly (no envelope), so the converter\n * input is just `{ id, settings }` \u2014 `name` / `owner` aren't in the upstream\n * response and would be set to schema defaults in the produced `CABRootSection`.\n */\n\nexport const SHOPIFY_CHECKOUT_EXTENSION_CONTENT_BLOCK = 'ui_extension_content_block' as const;\n\n/** Pixel threshold above which an aside-placed image is forced to top placement. */\nexport const CONTENT_BLOCK_MAX_IMAGE_WIDTH = 560;\n\nexport type V1ImagePlacement = 'top' | 'right' | 'bottom' | 'left';\n\nexport type V1ImageBlock = {\n altText?: string | null;\n category?: string;\n description?: string | null;\n filename?: string;\n id: string;\n imagePlacement: V1ImagePlacement;\n imageSize: number;\n imageUrl: string;\n index?: number;\n textAlignment?: 'left' | 'center' | 'right';\n textSize?: string;\n};\n\nexport type V1Language = {\n description?: string;\n superTitle?: string;\n title?: string;\n};\n\nexport type V1Settings = {\n blockSpacing?: string;\n imageBlocks?: V1ImageBlock[];\n imageLayout?: 'row' | 'column';\n language?: V1Language;\n location?: 'checkout' | 'order-status' | 'thank-you';\n previewMode?: boolean;\n type: typeof SHOPIFY_CHECKOUT_EXTENSION_CONTENT_BLOCK;\n version: 1;\n};\n\nexport type V1ConvertInput = {\n id: number;\n settings: V1Settings;\n};\n\nexport const isContentBlockV1 = (data: unknown): data is V1Settings => {\n if (!data || typeof data !== 'object') return false;\n\n const obj = data as Record<string, unknown>;\n\n return obj.version === 1 && obj.type === SHOPIFY_CHECKOUT_EXTENSION_CONTENT_BLOCK;\n};\n", "import { CABImageSection } from '~/schema/widgets/checkout-and-beyond/image';\nimport { CABLayoutSection } from '~/schema/widgets/checkout-and-beyond/layout';\nimport { CABTextSection } from '~/schema/widgets/checkout-and-beyond/text';\nimport { convertTextToTiptapParagraph } from '~/transforms/contentBlockV1/convertTextToTiptapParagraph';\nimport { stripContentBlockHtml } from '~/transforms/contentBlockV1/stripContentBlockHtml';\nimport {\n CONTENT_BLOCK_MAX_IMAGE_WIDTH,\n type V1ImageBlock,\n type V1ImagePlacement,\n} from '~/transforms/contentBlockV1/types';\n\nconst V1_TO_CAB_ALIGN = { center: 'center', left: 'start', right: 'end' } as const;\n\n/**\n * When an aside-placed image hits the max width, the legacy renderer forces\n * placement to `top` so the description doesn't get squeezed into a zero-width\n * column. Replicate here so the v2 layout matches what the legacy React widget\n * actually displayed.\n */\nconst resolveEffectivePlacement = (placement: V1ImagePlacement, imageSize: number): V1ImagePlacement => {\n const isAside = placement === 'left' || placement === 'right';\n\n return imageSize >= CONTENT_BLOCK_MAX_IMAGE_WIDTH && isAside ? 'top' : placement;\n};\n\n/**\n * The divisor is the same constant the legacy renderer clamps at (560), so an\n * `imageSize = 560` block renders at 100% \u2014 matching the legacy behavior\n * where 560 was the full layout width.\n */\nconst widthPercentForImageSize = (imageSize: number): number =>\n Math.min(Math.round((imageSize / CONTENT_BLOCK_MAX_IMAGE_WIDTH) * 100), 100);\n\nexport const convertContentBlockImageToV2 = (block: V1ImageBlock): CABImageSection | CABLayoutSection => {\n const { altText, category, description, id, imagePlacement, imageSize, imageUrl, textAlignment, textSize } = block;\n const placement = resolveEffectivePlacement(imagePlacement, imageSize);\n\n const imageSection = CABImageSection.parse({\n altText: stripContentBlockHtml(altText ?? ''),\n category,\n sectionId: id,\n sectionType: 'image',\n source: imageUrl,\n width: widthPercentForImageSize(imageSize),\n });\n\n if (!description) return imageSection;\n\n const textSection = CABTextSection.parse({\n content: {\n en: {\n attrs: { blockSpacing: 'base' },\n content: [\n convertTextToTiptapParagraph({\n color: 'base',\n fontSize: textSize ?? 'base',\n text: description,\n textAlign: textAlignment ? V1_TO_CAB_ALIGN[textAlignment] : 'start',\n }),\n ],\n type: 'doc',\n },\n },\n sectionType: 'text',\n });\n\n return CABLayoutSection.parse({\n alignment: { horizontal: 'center', vertical: 'middle' },\n direction: placement === 'left' || placement === 'right' ? 'columns' : 'rows',\n sections:\n placement === 'left' || placement === 'top' ? [imageSection, textSection] : [textSection, imageSection],\n sectionType: 'layout',\n spacing: 'tight',\n });\n};\n", "import { TiptapDocument } from '~/schema/widgets/checkout-and-beyond/text';\nimport { convertTextToTiptapParagraph } from '~/transforms/contentBlockV1/convertTextToTiptapParagraph';\nimport { type V1Language } from '~/transforms/contentBlockV1/types';\n\nexport const convertContentBlockTextToV2 = (language: V1Language | undefined): TiptapDocument => {\n const description = language?.description;\n const superTitle = language?.superTitle;\n const title = language?.title;\n\n return TiptapDocument.parse({\n attrs: { blockSpacing: 'tight' },\n content: [\n superTitle\n ? convertTextToTiptapParagraph({\n color: 'base',\n fontSize: 'extraLarge',\n marks: [{ type: 'bold' }],\n text: superTitle,\n textAlign: 'center',\n })\n : null,\n title\n ? convertTextToTiptapParagraph({\n color: 'base',\n fontSize: 'medium',\n marks: [{ type: 'bold' }],\n text: title,\n textAlign: 'center',\n })\n : null,\n description\n ? convertTextToTiptapParagraph({\n color: 'base',\n fontSize: 'base',\n text: description,\n textAlign: 'center',\n })\n : null,\n ].filter((p): p is NonNullable<typeof p> => p !== null),\n type: 'doc',\n });\n};\n", "import { z } from 'zod';\n\nimport { EditorMode, editorModes } from './common';\nimport { targetAreas, WidgetType, widgetTypes } from './constants';\nimport { CABLayoutSection } from './layout';\nimport { UI_LABELS } from './uiLabels';\n\n/**\n * A per-slot `Record<locale, string>` defaulted from {@link UI_LABELS}: a missing slot gets the fallback,\n * and a present-but-empty slot (`{}`) is guarded back to the fallback too \u2014 otherwise the per-slot default\n * (which only fires for `undefined`) is bypassed and the client renders a blank aria label.\n */\nconst localized = (fallback: Record<string, string>) =>\n z\n .record(z.string(), z.string())\n .default(() => ({ ...fallback }))\n .transform((labels) => (Object.keys(labels).length > 0 ? labels : { ...fallback }));\n\n/**\n * Localized UI-chrome labels for the tree, defaulted from {@link UI_LABELS} at parse so every widget\n * carries them without converter or merchant work. Per-slot `Record<locale, string>`; the client indexes\n * the buyer language with `selectLanguage`. Lives on the root (not per section) because these strings \u2014\n * spinner/carousel/select-label/variant-state chrome \u2014 are shared across the whole tree.\n */\nexport const CABUILabels = z\n .object({\n currentPage: localized(UI_LABELS.currentPage),\n loadingOptions: localized(UI_LABELS.loadingOptions),\n nextPage: localized(UI_LABELS.nextPage),\n offerDialog: localized(UI_LABELS.offerDialog),\n page: localized(UI_LABELS.page),\n previousPage: localized(UI_LABELS.previousPage),\n selected: localized(UI_LABELS.selected),\n subscriptionOptions: localized(UI_LABELS.subscriptionOptions),\n updating: localized(UI_LABELS.updating),\n })\n .default(() => ({\n currentPage: { ...UI_LABELS.currentPage },\n loadingOptions: { ...UI_LABELS.loadingOptions },\n nextPage: { ...UI_LABELS.nextPage },\n offerDialog: { ...UI_LABELS.offerDialog },\n page: { ...UI_LABELS.page },\n previousPage: { ...UI_LABELS.previousPage },\n selected: { ...UI_LABELS.selected },\n subscriptionOptions: { ...UI_LABELS.subscriptionOptions },\n updating: { ...UI_LABELS.updating },\n }));\n\nexport type CABUILabels = Record<keyof typeof UI_LABELS, Record<string, string>>;\n\nconst TargetArea = z\n .object({\n fill: z.boolean().optional(),\n flip: z.enum(['both', 'horizontal', 'vertical']).optional(),\n icon: z.string(),\n label: z.string(),\n width: z.string(),\n })\n .default(targetAreas[EditorMode.checkoutExtension][1]);\n\nexport type TargetArea = {\n fill?: boolean;\n flip?: 'horizontal' | 'vertical' | 'both';\n icon: string;\n label: string;\n width: string;\n};\n\nexport const CABTracking = z\n .object({\n enableAttribution: z.boolean().default(true),\n enableSource: z.boolean().default(true),\n enableWidget: z.boolean().default(true),\n })\n .default({ enableAttribution: true, enableSource: true, enableWidget: true });\n\nexport type CABTracking = z.infer<typeof CABTracking>;\n\n/**\n * The A/B experiment this tree was selected for, attached server-side when the placeholder widget is an\n * experiment target (else absent). The client renders the chosen variant's tree as usual and emits the\n * `ab-test-viewed` / `ABN.TEST` analytics from these fields \u2014 replicating React's `useAnalyticsEvent`.\n */\nexport const CABExperiment = z.object({\n elementId: z.number(),\n experimentId: z.number(),\n experimentType: z.string(),\n selectedId: z.number(),\n});\n\nexport type CABExperiment = z.infer<typeof CABExperiment>;\n\nexport const CABRootSection = CABLayoutSection.extend({\n editorMode: z.enum(editorModes).default(EditorMode.checkoutExtension),\n experiment: CABExperiment.optional(),\n previewMode: z.boolean().default(false),\n storeId: z.number().nullable().default(null),\n targetArea: TargetArea.nullable(),\n tracking: CABTracking,\n type: z.enum(widgetTypes).default(WidgetType.ui_extension_content_block),\n uiLabels: CABUILabels,\n version: z.literal(2).default(2),\n widgetId: z.number().nullable().default(null),\n});\n\nexport type CABRootSection = CABLayoutSection & {\n editorMode: EditorMode;\n experiment?: CABExperiment;\n previewMode: boolean;\n storeId: number | null;\n targetArea: TargetArea | null;\n tracking: CABTracking;\n type: WidgetType;\n uiLabels: CABUILabels;\n version: number;\n widgetId: number | null;\n};\n", "/**\n * Default UI-chrome labels \u2014 the buyer-visible and screen-reader strings that have no per-section\n * merchant slot: the subscription-frequency select's group label, spinner busy text, carousel control\n * names + current-page semantics, the variant selected-state suffix, and the Monetize offer dialog\n * name. Keyed by slot then locale, shipped in the payload so the client never bundles a dictionary\n * (Peter, 2026-07-06: visible customer strings must be localized). English defaults only \u2014 unlike the\n * merchant-authored `SWITCH_LABELS`/`GIFT_LABELS`, these mirror strings legacy hardcoded in English, so\n * the fix is making them payload-sourced (localizable, zero bundle) rather than inventing 25 unreviewed\n * translations; a merchant or a later localization pass can populate other locales. `{{page}}` in the\n * pagination slots is interpolated per control at render.\n */\nexport const UI_LABELS = {\n currentPage: { en: 'Page {{page}}, current' },\n loadingOptions: { en: 'Loading subscription options' },\n nextPage: { en: 'Next' },\n offerDialog: { en: 'Offer' },\n page: { en: 'Page {{page}}' },\n previousPage: { en: 'Previous' },\n selected: { en: 'selected' },\n subscriptionOptions: { en: 'Subscription Options' },\n updating: { en: 'Updating' },\n} satisfies Record<string, Record<string, string>>;\n", "import { CABRootSection } from '~/schema/widgets/checkout-and-beyond/root';\nimport { convertContentBlockImageToV2 } from '~/transforms/contentBlockV1/convertContentBlockImageToV2';\nimport { convertContentBlockTextToV2 } from '~/transforms/contentBlockV1/convertContentBlockTextToV2';\nimport {\n SHOPIFY_CHECKOUT_EXTENSION_CONTENT_BLOCK,\n type V1ConvertInput,\n type V1Language,\n} from '~/transforms/contentBlockV1/types';\n\nconst LOCATION_TO_EDITOR_MODE = {\n checkout: 'checkoutExtension',\n 'order-status': 'orderStatusPage',\n 'thank-you': 'thankYouPage',\n} as const;\n\nconst hasText = (language: V1Language | undefined): boolean =>\n !!language && !!(language.description || language.superTitle || language.title);\n\n/** Translates a v1 content-block widget into a fully-formed `CABRootSection`. */\nexport const convertContentBlockToV2 = ({ id, settings }: V1ConvertInput): CABRootSection => {\n const imageBlocks = settings.imageBlocks ?? [];\n\n return CABRootSection.parse({\n alignment: { horizontal: 'center', vertical: 'top' },\n direction: 'rows',\n editorMode: LOCATION_TO_EDITOR_MODE[settings.location ?? 'checkout'],\n previewMode: settings.previewMode,\n sections: [\n hasText(settings.language)\n ? {\n content: { en: convertContentBlockTextToV2(settings.language) },\n sectionType: 'text',\n }\n : null,\n imageBlocks.length > 0\n ? {\n // Legacy centers every image block (`InlineLayout inlineAlignment=\"center\"`).\n alignment: { horizontal: 'center', vertical: 'middle' },\n // Legacy: `image_layout === 'row' ? BlockStack : InlineStack` \u2014 an UNSET layout is\n // horizontal (columns), so only an explicit 'row' may stack vertically.\n direction: settings.imageLayout === 'row' ? 'rows' : 'columns',\n sections: imageBlocks.map(convertContentBlockImageToV2),\n sectionType: 'layout',\n spacing: settings.blockSpacing ?? 'extraTight',\n }\n : null,\n ].filter((section): section is NonNullable<typeof section> => section !== null),\n sectionType: 'layout',\n type: SHOPIFY_CHECKOUT_EXTENSION_CONTENT_BLOCK,\n version: 2,\n widgetId: id,\n });\n};\n", "const ARRAY_INDEX_STRING = /^(?:0|[1-9]\\d*)$/;\n\nconst isPlainObject = (input: unknown): input is Record<string, unknown> => {\n if (input === null || typeof input !== 'object') return false;\n\n const proto = Object.getPrototypeOf(input) as object | null;\n\n return proto === Object.prototype || proto === null;\n};\n\nconst hasOnlyNumericKeys = (input: Record<string, unknown>): boolean => {\n const keys = Object.keys(input);\n\n if (keys.length === 0) return false;\n\n if (!keys.every((key) => ARRAY_INDEX_STRING.test(key) && Number.isSafeInteger(Number(key)))) return false;\n\n // Require the indices to form a complete `0..n-1` sequence \u2014 `{ \"10\": \"a\", \"20\": \"b\" }`\n // would otherwise silently collapse into `[\"a\", \"b\"]` and lose its original positions.\n const sorted = keys.map(Number).sort((a, b) => a - b);\n\n return sorted.every((n, i) => n === i);\n};\n\nconst numericObjectToArray = (input: Record<string, unknown>): unknown[] =>\n Object.entries(input)\n .sort(([a], [b]) => Number(a) - Number(b))\n .map(([, value]) => value);\n\n/**\n * Recursively converts objects whose keys are a complete `0..n-1` sequence\n * (PHP-serialized \"sparse\" arrays) into real arrays. Everything else passes\n * through unchanged.\n */\nexport const convertNumericObjects = (input: unknown): unknown => {\n if (Array.isArray(input)) return input.map(convertNumericObjects);\n\n if (isPlainObject(input)) {\n if (hasOnlyNumericKeys(input)) return numericObjectToArray(input).map(convertNumericObjects);\n\n const out: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(input)) out[key] = convertNumericObjects(value);\n\n return out;\n }\n\n return input;\n};\n", "const isPlainObject = (input: unknown): input is Record<string, unknown> => {\n if (input === null || typeof input !== 'object') return false;\n\n const proto = Object.getPrototypeOf(input) as object | null;\n\n return proto === Object.prototype || proto === null;\n};\n\nconst camelCase = (key: string): string =>\n key.replace(/[-_\\s]+(.)?/g, (_, char: string | undefined) => (char ? char.toUpperCase() : ''));\n\nexport type ToCamelCase<S extends string> = S extends `${infer Head}_${infer Tail}` | `${infer Head}-${infer Tail}`\n ? `${Head}${Capitalize<ToCamelCase<Tail>>}`\n : S;\n\nexport type DeepCamelCase<T> = T extends (infer U)[]\n ? DeepCamelCase<U>[]\n : T extends object\n ? { [K in keyof T as ToCamelCase<K & string>]: DeepCamelCase<T[K]> }\n : T;\n\n/**\n * Recursively converts object keys to camelCase. Snake_case and kebab-case\n * are both handled; numeric array indices and primitives pass through\n * unchanged.\n *\n * Language keys used by the CAB schema (`text.content[<lang>]`, etc.) are\n * authored as plain lowercase tags (`en`, `de`, `fr`) by us \u2014 they have no\n * `_` or `-` to convert and survive camelCase as-is.\n */\nexport const deepCamelCase = <T>(input: T): DeepCamelCase<T> => {\n if (Array.isArray(input)) return input.map((item) => deepCamelCase(item)) as DeepCamelCase<T>;\n\n if (isPlainObject(input)) {\n const out: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(input)) {\n out[camelCase(key)] = deepCamelCase(value);\n }\n\n return out as DeepCamelCase<T>;\n }\n\n return input as DeepCamelCase<T>;\n};\n", "import { type TextColorName, type TextSizeName } from '~/schema/widgets/checkout-and-beyond/common';\nimport { type Mark } from '~/transforms/htmlToTiptap/types';\n\nexport const buildDefaultTextStyleMark = (\n style: { color?: TextColorName; fontSize?: TextSizeName } | undefined\n): Mark | null => {\n if (!style || (style.color === undefined && style.fontSize === undefined)) return null;\n\n return {\n attrs: {\n color: style.color ?? 'base',\n fontSize: style.fontSize ?? 'base',\n },\n type: 'textStyle',\n };\n};\n", "import { type StackEntry } from '~/transforms/htmlToTiptap/types';\n\nexport const closeTag = (stack: StackEntry[], name: string): void => {\n for (let index = stack.length - 1; index >= 0; index--) {\n if (stack[index].tag === name) {\n stack.length = index;\n break;\n }\n }\n};\n", "export const TAG_RE = /<(\\/)?([a-zA-Z][a-zA-Z0-9]*)((?:\\s+[^>]*?)?)\\s*(\\/)?>/g;\n\n/**\n * Tags that introduce a paragraph break on both open and close. Container tags\n * like `ul`/`ol`/`dl` are intentionally NOT here \u2014 their child `li`/`dt`/`dd`\n * elements already break, and including the containers would double-flush.\n */\nexport const BLOCK_TAGS = new Set([\n 'article',\n 'aside',\n 'blockquote',\n 'dd',\n 'div',\n 'dt',\n 'figcaption',\n 'figure',\n 'footer',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hr',\n 'li',\n 'main',\n 'nav',\n 'p',\n 'pre',\n 'section',\n]);\n", "import { TiptapParagraph, type TiptapText } from '~/schema/widgets/checkout-and-beyond/text';\n\nexport const makeParagraph = (content: TiptapText[]): TiptapParagraph => TiptapParagraph.parse({ content });\n", "import { makeParagraph } from '~/transforms/htmlToTiptap/makeParagraph';\nimport { type State } from '~/transforms/htmlToTiptap/types';\n\nexport const flushParagraph = (state: State): void => {\n state.paragraphs.push(makeParagraph(state.currentRuns));\n state.currentRuns = [];\n};\n", "import { type StackEntry } from '~/transforms/htmlToTiptap/types';\n\nexport const isSkipping = (stack: StackEntry[] = []): boolean => stack.some(({ skip }) => skip);\n", "import { type Spacing } from '~/schema/widgets/checkout-and-beyond/common';\nimport { TiptapDocument, type TiptapParagraph } from '~/schema/widgets/checkout-and-beyond/text';\n\nexport const makeDoc = (content: TiptapParagraph[], blockSpacing: Spacing): TiptapDocument =>\n TiptapDocument.parse({ attrs: { blockSpacing }, content });\n", "const DYNAMIC_TOKEN_REGEX = /^\\{\\{\\s*[A-Za-z]+\\s*\\}\\}$/;\n\n/**\n * Protocols we'll preserve on `<a href>` when converting HTML to Tiptap. Any URL\n * whose `URL.protocol` falls outside this set (e.g. `javascript:`, `data:`,\n * `file:`, `vbscript:`) is dropped from the link mark \u2014 the text content is\n * kept but the click target is not. Renderers downstream still get to do their\n * own validation, but the package shouldn't be the one preserving an XSS\n * payload through the conversion.\n */\nconst ALLOWED_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'tel:']);\n\n/**\n * Decides whether an `<a href>` value should survive HTML \u2192 Tiptap conversion\n * as a link mark. Allows `#`, dynamic `{{token}}` placeholders, root-relative\n * same-origin paths (e.g. Shopify's `/policies/privacy-policy`), and a fixed\n * allowlist of URL schemes; everything else (including `javascript:`, `data:`,\n * protocol-relative `//host` paths, other relative paths, and malformed URLs)\n * drops the link mark while keeping the surrounding text.\n *\n * @param href - Raw `href` attribute from the source HTML.\n *\n * @returns `true` if the URL should be preserved as a link mark.\n */\nexport const isValidHref = (href: string): boolean => {\n if (!href) return false;\n\n if (href === '#') return true;\n\n if (DYNAMIC_TOKEN_REGEX.test(href)) return true;\n\n /** Root-relative same-origin path (single leading slash); `//host` is protocol-relative, not same-origin. */\n if (href.startsWith('/') && !href.startsWith('//')) return true;\n\n try {\n const url = new URL(href);\n\n return ALLOWED_PROTOCOLS.has(url.protocol);\n } catch {\n return false;\n }\n};\n", "import { isValidHref } from '~/transforms/htmlToTiptap/isValidHref';\nimport { type Mark } from '~/transforms/htmlToTiptap/types';\n\n/**\n * The schema defaults for an `<a>` mark when the source HTML omits them. Match\n * `TiptapText` in `~/schema/widgets/checkout-and-beyond/text` so the sanitizer\n * resolves the same effective values the downstream parse would have used.\n */\nconst DEFAULT_TARGET = '_blank';\nconst DEFAULT_REL = 'noopener noreferrer nofollow';\n\n/**\n * Forces `noopener noreferrer` on every `_blank` link to defend against\n * reverse-tabnabbing (window.opener attacks). When the source omits `rel`\n * entirely, fall back to the schema default (`noopener noreferrer nofollow`).\n * When source `rel` is non-empty, preserve the existing tokens, drop `opener`,\n * and ensure the safe pair is present.\n *\n * Non-`_blank` targets pass through unchanged \u2014 they can't be tabnabbed.\n */\nconst ensureSafeRel = (rel: string, target: string): string => {\n if (target !== '_blank') return rel;\n\n const sourceTokens = (rel ?? '').split(/\\s+/).filter(Boolean);\n\n if (sourceTokens.length === 0) return DEFAULT_REL;\n\n const tokens = new Set(sourceTokens.filter((token) => token.toLowerCase() !== 'opener'));\n\n tokens.add('noopener');\n tokens.add('noreferrer');\n\n return Array.from(tokens).join(' ');\n};\n\nexport const buildLinkMark = (attrs: Record<string, string> = {}): Mark | null => {\n const { href } = attrs;\n\n if (!href || !isValidHref(href)) return null;\n\n // Resolve target BEFORE sanitizing rel so the safety guard sees the same\n // value the downstream schema parse will use.\n const target = attrs.target ?? DEFAULT_TARGET;\n\n return {\n attrs: {\n class: null,\n href,\n rel: ensureSafeRel(attrs.rel, target),\n target,\n },\n type: 'link',\n };\n};\n", "const NAMED_ENTITIES: Record<string, string> = {\n amp: '&',\n apos: \"'\",\n copy: '\u00A9',\n gt: '>',\n hellip: '\u2026',\n ldquo: '\u201C',\n lsquo: '\u2018',\n lt: '<',\n mdash: '\u2014',\n nbsp: ' ',\n ndash: '\u2013',\n quot: '\"',\n rdquo: '\u201D',\n reg: '\u00AE',\n rsquo: '\u2019',\n trade: '\u2122',\n} as const;\n\nexport const decodeEntities = (input: string = ''): string =>\n input.replace(/&(#x[\\da-f]+|#\\d+|[a-z][a-z\\d]*);/gi, (match, code: string) => {\n if (code[0] !== '#') return NAMED_ENTITIES[code.toLowerCase()] ?? match;\n\n const isHex = /^#x/i.test(code);\n const cp = parseInt(code.slice(isHex ? 2 : 1), isHex ? 16 : 10);\n\n return Number.isInteger(cp) && cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : match;\n });\n", "import { decodeEntities } from '~/transforms/htmlToTiptap/decodeEntities';\n\nconst ATTRIB_RE = /([a-zA-Z_:][\\w:.-]*)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'`=<>]+)))?/g;\n\nexport const parseAttribs = (attrString: string): Record<string, string> => {\n const result: Record<string, string> = {};\n let match: RegExpExecArray | null;\n\n ATTRIB_RE.lastIndex = 0;\n\n while ((match = ATTRIB_RE.exec(attrString)) !== null) {\n result[match[1].toLowerCase()] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? '');\n }\n\n return result;\n};\n", "import { type TextSizeName } from '~/schema/widgets/checkout-and-beyond/common';\nimport { buildLinkMark } from '~/transforms/htmlToTiptap/buildLinkMark';\nimport { parseAttribs } from '~/transforms/htmlToTiptap/parseAttribs';\nimport { type Mark, type StackEntry } from '~/transforms/htmlToTiptap/types';\n\nconst INLINE_MARK_TAGS: Record<string, 'bold' | 'italic' | 'strike'> = {\n b: 'bold',\n del: 'strike',\n em: 'italic',\n i: 'italic',\n s: 'strike',\n strike: 'strike',\n strong: 'bold',\n};\n\nconst HEADING_FONT_SIZE: Record<string, TextSizeName> = {\n h1: 'extraLarge',\n h2: 'large',\n h3: 'medium',\n h4: 'base',\n h5: 'small',\n h6: 'small',\n};\n\nconst STRIPPED_TAGS = ['embed', 'iframe', 'noscript', 'object', 'script', 'style', 'template'];\n\nconst marksForTag = (name: string, attrs: string): Mark[] => {\n if (INLINE_MARK_TAGS[name]) return [{ type: INLINE_MARK_TAGS[name] }];\n\n if (HEADING_FONT_SIZE[name]) {\n return [{ type: 'bold' }, { attrs: { color: 'base', fontSize: HEADING_FONT_SIZE[name] }, type: 'textStyle' }];\n }\n\n if (name === 'a') {\n const link = buildLinkMark(parseAttribs(attrs));\n\n return link ? [link] : [];\n }\n\n return [];\n};\n\nexport const openTag = (stack: StackEntry[], name: string, attrs: string): void => {\n stack.push({\n marks: marksForTag(name, attrs),\n skip: STRIPPED_TAGS.includes(name),\n tag: name,\n });\n};\n", "import { TiptapText } from '~/schema/widgets/checkout-and-beyond/text';\n\nimport { decodeEntities } from '~/transforms/htmlToTiptap/decodeEntities';\nimport { flushParagraph } from '~/transforms/htmlToTiptap/flushParagraph';\nimport { isSkipping } from '~/transforms/htmlToTiptap/isSkipping';\nimport { type Mark, type State } from '~/transforms/htmlToTiptap/types';\n\nexport const pushText = (state: State, rawText: string): void => {\n if (!rawText || isSkipping(state.stack)) return;\n\n decodeEntities(rawText)\n .split('\\n')\n .forEach((segment, index) => {\n if (index > 0) flushParagraph(state);\n\n if (!segment) return;\n\n const marks: Mark[] = state.stack.flatMap((entry) => entry.marks);\n\n if (state.defaultTextStyleMark && !marks.some((mark) => mark.type === 'textStyle')) {\n marks.push(state.defaultTextStyleMark);\n }\n\n state.currentRuns.push(TiptapText.parse(marks.length > 0 ? { marks, text: segment } : { text: segment }));\n });\n};\n", "const HTML_COMMENT_RE = /<!--[\\s\\S]*?-->/g;\n\nexport const stripHtmlComments = (html: string = ''): string => html.replace(HTML_COMMENT_RE, '');\n", "import { type Spacing, type TextColorName, type TextSizeName } from '~/schema/widgets/checkout-and-beyond/common';\nimport { type TiptapDocument } from '~/schema/widgets/checkout-and-beyond/text';\nimport { buildDefaultTextStyleMark } from '~/transforms/htmlToTiptap/buildDefaultTextStyleMark';\nimport { closeTag } from '~/transforms/htmlToTiptap/closeTag';\nimport { BLOCK_TAGS, TAG_RE } from '~/transforms/htmlToTiptap/constants';\nimport { flushParagraph } from '~/transforms/htmlToTiptap/flushParagraph';\nimport { isSkipping } from '~/transforms/htmlToTiptap/isSkipping';\nimport { makeDoc } from '~/transforms/htmlToTiptap/makeDoc';\nimport { makeParagraph } from '~/transforms/htmlToTiptap/makeParagraph';\nimport { openTag } from '~/transforms/htmlToTiptap/openTag';\nimport { pushText } from '~/transforms/htmlToTiptap/pushText';\nimport { stripHtmlComments } from '~/transforms/htmlToTiptap/stripHtmlComments';\nimport { type State } from '~/transforms/htmlToTiptap/types';\n\nexport type HtmlToTiptapOptions = {\n blockSpacing?: Spacing;\n defaultTextStyle?: { color?: TextColorName; fontSize?: TextSizeName };\n};\n\nconst maybeFlushParagraph = (state: State): void => {\n if (state.currentRuns.length > 0) flushParagraph(state);\n};\n\nexport const htmlToTiptap = (html: string, options: HtmlToTiptapOptions = {}): TiptapDocument => {\n const state: State = {\n currentRuns: [],\n defaultTextStyleMark: buildDefaultTextStyleMark(options.defaultTextStyle),\n listStack: [],\n paragraphs: [],\n stack: [],\n };\n const blockSpacing = options.blockSpacing ?? 'base';\n\n if (typeof html !== 'string' || !html) return makeDoc([makeParagraph([])], blockSpacing);\n\n const htmlWithoutComments = stripHtmlComments(html);\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n\n TAG_RE.lastIndex = 0;\n\n while ((match = TAG_RE.exec(htmlWithoutComments)) !== null) {\n const [full, slash, rawName, attrs, selfClose] = match;\n\n if (match.index > lastIndex) pushText(state, htmlWithoutComments.slice(lastIndex, match.index));\n\n lastIndex = match.index + full.length;\n\n const name = rawName.toLowerCase();\n\n if (slash) {\n closeTag(state.stack, name);\n\n if (name === 'ul' || name === 'ol') state.listStack.pop();\n\n if (BLOCK_TAGS.has(name) && !isSkipping(state.stack)) maybeFlushParagraph(state);\n } else if (name === 'br') {\n if (!isSkipping(state.stack)) flushParagraph(state);\n } else if (name === 'hr') {\n if (!isSkipping(state.stack)) {\n maybeFlushParagraph(state);\n pushText(state, '\u2014\u2014\u2014');\n flushParagraph(state);\n }\n } else if (!selfClose) {\n if (BLOCK_TAGS.has(name) && !isSkipping(state.stack)) maybeFlushParagraph(state);\n\n if (name === 'ul' || name === 'ol') state.listStack.push({ counter: 0, ordered: name === 'ol' });\n\n openTag(state.stack, name, attrs);\n\n if (name === 'li' && state.listStack.length > 0) {\n const top = state.listStack[state.listStack.length - 1]!;\n\n if (top.ordered) top.counter += 1;\n\n pushText(state, top.ordered ? `${top.counter}. ` : '\u2022 ');\n }\n }\n }\n\n if (lastIndex < htmlWithoutComments.length) pushText(state, htmlWithoutComments.slice(lastIndex));\n\n maybeFlushParagraph(state);\n\n if (state.paragraphs.length === 0) flushParagraph(state);\n\n return makeDoc(state.paragraphs, blockSpacing);\n};\n", "/**\n * True when the input has `version === 2` \u2014 the marker for a current-generation\n * Checkout-and-Beyond root section. The transformer for CAB (`CABRootSection.parse`)\n * should ONLY run on values that pass this check; v1 widget shapes either get\n * converted (e.g. via `convertContentBlockToV2`) or pass through unchanged.\n *\n * @param input - The post-camelCase, post-numeric-fix upstream payload.\n *\n * @returns `true` if `input.version === 2`, otherwise `false`.\n */\nexport const isCABRootSection = (input: unknown): boolean => {\n if (!input || typeof input !== 'object') return false;\n\n return (input as { version?: unknown }).version === 2;\n};\n", "/**\n * Default localized labels for the switch-to-subscription button content, keyed by `buttonField` then locale.\n * The single source of truth shared by the admin editor and the read-time `convertLineItemEditorToV2` transform\n * so a widget renders identically whether migrated in admin or converted on the fly. `{{subscriptionDiscount}}`\n * is substituted per-plan at render \u2014 CAB tokens are camelCase by default; a legacy snake_case token in a v1\n * merchant override still resolves (the client camelCases unknown token keys against its camelCase variables).\n * `subscriptionOption` is the frequency-select option template (legacy\n * `SwitchToSubscriptionLanguageDefaults.subscription_option_label`); the client resolves `{{interval}}`\n * through `Intl.NumberFormat` unit style, so the noun arrives in the buyer's language, pluralized per count\n * from the runtime's CLDR data (English CLDR nouns are lowercase \u2014 an accepted divergence from legacy).\n */\nexport const SWITCH_LABELS = {\n subscriptionOption: {\n ar: '\u064A\u062A\u0645 \u0627\u0644\u062A\u0648\u0635\u064A\u0644 \u0643\u0644 {{frequency}} {{interval}}',\n cs: 'Doru\u010Den\u00ED ka\u017Ed\u00FDch {{frequency}} {{interval}}',\n da: 'Leveres hver {{frequency}} {{interval}}',\n de: 'Lieferung alle {{frequency}} {{interval}}',\n en: 'Delivers every {{frequency}} {{interval}}',\n es: 'Entrega cada {{frequency}} {{interval}}',\n fi: 'Toimitus {{frequency}} {{interval}} v\u00E4lein',\n fr: 'Livraison tous les {{frequency}} {{interval}}',\n ga: 'Seachadtar gach {{frequency}} {{interval}}',\n he: '\u05DE\u05E9\u05DC\u05D5\u05D7 \u05DB\u05DC {{frequency}} {{interval}}',\n hi: '\u0939\u0930 {{frequency}} {{interval}} \u092E\u0947\u0902 \u0921\u093F\u0932\u0940\u0935\u0930\u0940',\n id: 'Dikirim setiap {{frequency}} {{interval}}',\n it: 'Consegna ogni {{frequency}} {{interval}}',\n ja: '{{frequency}} {{interval}}\u3054\u3068\u306B\u304A\u5C4A\u3051',\n ko: '{{frequency}} {{interval}}\uB9C8\uB2E4 \uBC30\uC1A1',\n nl: 'Wordt elke {{frequency}} {{interval}} geleverd',\n no: 'Leveres hver {{frequency}} {{interval}}',\n pl: 'Dostawa co {{frequency}} {{interval}}',\n pt: 'Entrega a cada {{frequency}} {{interval}}',\n ru: '\u0414\u043E\u0441\u0442\u0430\u0432\u043A\u0430 \u043A\u0430\u0436\u0434\u044B\u0435 {{frequency}} {{interval}}',\n sv: 'Levereras var {{frequency}} {{interval}}',\n th: '\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07\u0E17\u0E38\u0E01 {{frequency}} {{interval}}',\n tr: 'Her {{frequency}} {{interval}} aral\u0131\u011F\u0131nda teslimat',\n uk: '\u0414\u043E\u0441\u0442\u0430\u0432\u043A\u0430 \u043A\u043E\u0436\u043D\u0456 {{frequency}} {{interval}}',\n vi: 'Giao h\u00E0ng m\u1ED7i {{frequency}} {{interval}}',\n zh: '\u6BCF {{frequency}} {{interval}} \u914D\u9001\u4E00\u6B21',\n },\n switchToOneTimePurchase: {\n ar: '\u0627\u0644\u062A\u0628\u062F\u064A\u0644 \u0625\u0644\u0649 \u0634\u0631\u0627\u0621 \u0644\u0645\u0631\u0629 \u0648\u0627\u062D\u062F\u0629',\n cs: 'P\u0159epnout na jednor\u00E1zov\u00FD n\u00E1kup',\n da: 'Skift til engangsk\u00F8b',\n de: 'Zu einmaligem Kauf wechseln',\n en: 'Switch to One-time Purchase',\n es: 'Cambiar a compra \u00FAnica',\n fi: 'Vaihda kertaluonteiseen ostoon',\n fr: 'Passer \u00E0 un achat unique',\n ga: 'Athraigh go ceannach aonuaire',\n he: '\u05E2\u05D1\u05D5\u05E8 \u05DC\u05E8\u05DB\u05D9\u05E9\u05D4 \u05D7\u05D3-\u05E4\u05E2\u05DE\u05D9\u05EA',\n hi: '\u090F\u0915 \u092C\u093E\u0930 \u0915\u0940 \u0916\u0930\u0940\u0926 \u092A\u0930 \u0938\u094D\u0935\u093F\u091A \u0915\u0930\u0947\u0902',\n id: 'Beralih ke pembelian satu kali',\n it: 'Passa all\u2019acquisto una tantum',\n ja: '1\u56DE\u9650\u308A\u306E\u8CFC\u5165\u306B\u5207\u308A\u66FF\u3048\u308B',\n ko: '\uC77C\uD68C\uC131 \uAD6C\uB9E4\uB85C \uC804\uD658',\n nl: 'Overschakelen naar eenmalige aankoop',\n no: 'Bytt til engangskj\u00F8p',\n pl: 'Prze\u0142\u0105cz na jednorazowy zakup',\n pt: 'Mudar para compra \u00FAnica',\n ru: '\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043D\u0430 \u0440\u0430\u0437\u043E\u0432\u0443\u044E \u043F\u043E\u043A\u0443\u043F\u043A\u0443',\n sv: 'Byt till eng\u00E5ngsk\u00F6p',\n th: '\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E40\u0E1B\u0E47\u0E19\u0E01\u0E32\u0E23\u0E0B\u0E37\u0E49\u0E2D\u0E04\u0E23\u0E31\u0E49\u0E07\u0E40\u0E14\u0E35\u0E22\u0E27',\n tr: 'Tek seferlik sat\u0131n almaya ge\u00E7',\n uk: '\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u0438\u0441\u044F \u043D\u0430 \u043E\u0434\u043D\u043E\u0440\u0430\u0437\u043E\u0432\u0443 \u043F\u043E\u043A\u0443\u043F\u043A\u0443',\n vi: 'Chuy\u1EC3n sang mua m\u1ED9t l\u1EA7n',\n zh: '\u5207\u6362\u4E3A\u4E00\u6B21\u6027\u8D2D\u4E70',\n },\n switchToSubscriptionNoDiscount: {\n ar: '\u0627\u0644\u062A\u0628\u062F\u064A\u0644 \u0625\u0644\u0649 \u0627\u0634\u062A\u0631\u0627\u0643',\n cs: 'P\u0159epnout na p\u0159edplatn\u00E9',\n da: 'Skift til abonnement',\n de: 'Zu einem Abonnement wechseln',\n en: 'Switch to Subscription',\n es: 'Cambiar a suscripci\u00F3n',\n fi: 'Vaihda tilaukseen',\n fr: 'Passer \u00E0 un abonnement',\n ga: 'Athraigh go s\u00EDnti\u00FAs',\n he: '\u05E2\u05D1\u05D5\u05E8 \u05DC\u05DE\u05E0\u05D5\u05D9',\n hi: '\u0938\u0926\u0938\u094D\u092F\u0924\u093E \u092A\u0930 \u0938\u094D\u0935\u093F\u091A \u0915\u0930\u0947\u0902',\n id: 'Beralih ke langganan',\n it: 'Passa all\u2019abbonamento',\n ja: '\u5B9A\u671F\u8CFC\u5165\u306B\u5207\u308A\u66FF\u3048\u308B',\n ko: '\uAD6C\uB3C5\uC73C\uB85C \uC804\uD658',\n nl: 'Overschakelen naar abonnement',\n no: 'Bytt til abonnement',\n pl: 'Prze\u0142\u0105cz na subskrypcj\u0119',\n pt: 'Mudar para assinatura',\n ru: '\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043D\u0430 \u043F\u043E\u0434\u043F\u0438\u0441\u043A\u0443',\n sv: 'Byt till prenumeration',\n th: '\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E40\u0E1B\u0E47\u0E19\u0E01\u0E32\u0E23\u0E2A\u0E21\u0E31\u0E04\u0E23\u0E2A\u0E21\u0E32\u0E0A\u0E34\u0E01',\n tr: 'Aboneli\u011Fe ge\u00E7',\n uk: '\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u0438\u0441\u044F \u043D\u0430 \u043F\u0456\u0434\u043F\u0438\u0441\u043A\u0443',\n vi: 'Chuy\u1EC3n sang \u0111\u0103ng k\u00FD',\n zh: '\u5207\u6362\u4E3A\u8BA2\u9605',\n },\n switchToSubscriptionWithDiscount: {\n ar: '\u0627\u0644\u062A\u0628\u062F\u064A\u0644 \u0625\u0644\u0649 \u0627\u0634\u062A\u0631\u0627\u0643 \u0648\u062A\u0648\u0641\u064A\u0631 {{subscriptionDiscount}}%',\n cs: 'P\u0159epnout na p\u0159edplatn\u00E9 a u\u0161et\u0159it {{subscriptionDiscount}} %',\n da: 'Skift til abonnement og spar {{subscriptionDiscount}}%',\n de: 'Zu einem Abonnement wechseln und {{subscriptionDiscount}} % sparen',\n en: 'Switch to Subscription & Save {{subscriptionDiscount}}%',\n es: 'Cambiar a suscripci\u00F3n y ahorrar {{subscriptionDiscount}}%',\n fi: 'Vaihda tilaukseen ja s\u00E4\u00E4st\u00E4 {{subscriptionDiscount}} %',\n fr: 'Passer \u00E0 un abonnement et \u00E9conomiser {{subscriptionDiscount}} %',\n ga: 'Athraigh go s\u00EDnti\u00FAs agus s\u00E1bh\u00E1il {{subscriptionDiscount}}%',\n he: '\u05E2\u05D1\u05D5\u05E8 \u05DC\u05DE\u05E0\u05D5\u05D9 \u05D5\u05D7\u05E1\u05D5\u05DA {{subscriptionDiscount}}%',\n hi: '\u0938\u0926\u0938\u094D\u092F\u0924\u093E \u092A\u0930 \u0938\u094D\u0935\u093F\u091A \u0915\u0930\u0947\u0902 \u0914\u0930 {{subscriptionDiscount}}% \u092C\u091A\u093E\u090F\u0902',\n id: 'Beralih ke langganan dan hemat {{subscriptionDiscount}}%',\n it: 'Passa all\u2019abbonamento e risparmia {{subscriptionDiscount}}%',\n ja: '\u5B9A\u671F\u8CFC\u5165\u306B\u5207\u308A\u66FF\u3048\u3066{{subscriptionDiscount}}%\u304A\u5F97',\n ko: '\uAD6C\uB3C5\uC73C\uB85C \uC804\uD658\uD558\uACE0 {{subscriptionDiscount}}% \uC808\uC57D',\n nl: 'Overschakelen naar abonnement en {{subscriptionDiscount}}% besparen',\n no: 'Bytt til abonnement og spar {{subscriptionDiscount}}%',\n pl: 'Prze\u0142\u0105cz na subskrypcj\u0119 i oszcz\u0119d\u017A {{subscriptionDiscount}}%',\n pt: 'Mudar para assinatura e economizar {{subscriptionDiscount}}%',\n ru: '\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043D\u0430 \u043F\u043E\u0434\u043F\u0438\u0441\u043A\u0443 \u0438 \u0441\u044D\u043A\u043E\u043D\u043E\u043C\u0438\u0442\u044C {{subscriptionDiscount}}%',\n sv: 'Byt till prenumeration och spara {{subscriptionDiscount}}%',\n th: '\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E40\u0E1B\u0E47\u0E19\u0E01\u0E32\u0E23\u0E2A\u0E21\u0E31\u0E04\u0E23\u0E2A\u0E21\u0E32\u0E0A\u0E34\u0E01\u0E41\u0E25\u0E30\u0E1B\u0E23\u0E30\u0E2B\u0E22\u0E31\u0E14 {{subscriptionDiscount}}%',\n tr: 'Aboneli\u011Fe ge\u00E7 ve {{subscriptionDiscount}}% tasarruf et',\n uk: '\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u0438\u0441\u044F \u043D\u0430 \u043F\u0456\u0434\u043F\u0438\u0441\u043A\u0443 \u0442\u0430 \u0437\u0430\u043E\u0449\u0430\u0434\u0438\u0442\u0438 {{subscriptionDiscount}}%',\n vi: 'Chuy\u1EC3n sang \u0111\u0103ng k\u00FD v\u00E0 ti\u1EBFt ki\u1EC7m {{subscriptionDiscount}}%',\n zh: '\u5207\u6362\u4E3A\u8BA2\u9605\u5E76\u8282\u7701 {{subscriptionDiscount}}%',\n },\n} as const satisfies Record<string, Record<string, string>>;\n", "import { stripContentBlockHtml } from '~/transforms/contentBlockV1/stripContentBlockHtml';\n\n/**\n * The v1 label-override policy shared by the offer-card and line-item-editor converters: a defined v1\n * label ALWAYS passes through verbatim as the `en` entry over the localized defaults \u2014 existing widget\n * language is never rewritten (product owner, 2026-07-02); blank/whitespace falls back to the full\n * default locale set (legacy `getLabelWithFallback` parity). HTML the merchant typed into a label is\n * stripped first \u2014 `CABTextSection.content` rejects tag-shaped strings at parse, so a raw `<b>`-style\n * label would otherwise 500 the whole widget.\n */\nexport const localizedContent = (defaults: Record<string, string>, override: string | undefined) => {\n const trimmed = stripContentBlockHtml(override ?? '').trim();\n\n return trimmed ? { ...defaults, en: trimmed } : defaults;\n};\n", "import { WidgetType } from '~/schema/widgets/checkout-and-beyond/constants';\nimport { CABRootSection } from '~/schema/widgets/checkout-and-beyond/root';\nimport { SWITCH_LABELS } from '~/schema/widgets/checkout-and-beyond/switchLabels';\nimport { type LineItemEditorSwitchLanguageV1 } from '~/schema/widgets/lineItemEditor';\nimport { type V1LineItemEditorConvertInput } from '~/transforms/lineItemEditorV1/types';\nimport { localizedContent } from '~/transforms/localizedContent';\n\n/** The v1 `switchToSubscription.language` key that overrides each `buttonField`'s English label. */\nconst OVERRIDE_KEY = {\n subscriptionOption: 'subscriptionOptionLabel',\n switchToOneTimePurchase: 'downgradeToOneTimeLabel',\n switchToSubscriptionNoDiscount: 'upgradeToSubscriptionWithoutDiscountLabel',\n switchToSubscriptionWithDiscount: 'upgradeToSubscriptionLabel',\n} as const satisfies Record<keyof typeof SWITCH_LABELS, keyof LineItemEditorSwitchLanguageV1>;\n\n/**\n * Translate a v1 line-item-editor widget into a `CABRootSection`: a `cartLine` section holding a\n * switch-to-subscription button, whose `buttonField`-tagged text labels use the shared localized\n * `SWITCH_LABELS` defaults with the v1 `switchToSubscription.language` value overriding `en` (same output the\n * admin editor produces, so runtime-converted and admin-migrated widgets render identically). The button is\n * omitted when the widget's switch is disabled.\n */\nconst BUTTON_KINDS = ['plain', 'primary', 'secondary'] as const;\n\nexport const convertLineItemEditorToV2 = ({ id, settings }: V1LineItemEditorConvertInput): CABRootSection => {\n const { switchToSubscription, switchToSubscriptionEnabled, tracking } = settings;\n const kind = settings.button?.kind;\n const buttonStyle = BUTTON_KINDS.includes(kind as (typeof BUTTON_KINDS)[number]) ? kind : 'plain';\n\n const labelSections = (Object.keys(SWITCH_LABELS) as (keyof typeof SWITCH_LABELS)[]).map((buttonField) => ({\n buttonField,\n content: localizedContent(\n SWITCH_LABELS[buttonField],\n switchToSubscription?.language?.[OVERRIDE_KEY[buttonField]]\n ),\n sectionType: 'text',\n }));\n\n return CABRootSection.parse({\n previewMode: settings.previewMode,\n sections: [\n {\n sections: switchToSubscriptionEnabled\n ? [\n {\n action: 'switchToSubscription',\n buttonStyle,\n disableDowngrade: switchToSubscription?.disableDowngrade ?? false,\n sections: labelSections,\n sectionType: 'button',\n },\n ]\n : [],\n sectionType: 'cartLine',\n },\n ],\n sectionType: 'layout',\n tracking: {\n enableAttribution: tracking?.enableAttribution ?? true,\n enableSource: tracking?.enableSource ?? true,\n enableWidget: tracking?.enableWidget ?? true,\n },\n type: WidgetType.ui_extension_line_item_editor,\n version: 2,\n widgetId: id,\n });\n};\n", "import { WidgetType } from '~/schema/widgets/checkout-and-beyond/constants';\nimport { type LineItemEditorV1 } from '~/schema/widgets/lineItemEditor';\n\n/**\n * The legacy `/widgets/settings` endpoint returns the widget's settings object directly (no envelope), so\n * the converter input is just `{ id, settings }` \u2014 the settings shape lives in the schema\n * (`LineItemEditorV1`) and is derived here, never re-declared.\n */\nexport type V1LineItemEditorConvertInput = {\n id: number;\n settings: LineItemEditorV1;\n};\n\n/** Identifies a v1 line-item-editor payload by version + type (mirrors `isContentBlockV1`). */\nexport const isLineItemEditorV1 = (data: unknown): data is LineItemEditorV1 => {\n if (!data || typeof data !== 'object') return false;\n\n const obj = data as Record<string, unknown>;\n\n return obj.version === 1 && obj.type === WidgetType.ui_extension_line_item_editor;\n};\n", "const DEFAULT_KNOWN_TOKENS = ['firstName', 'lastName', 'email'] as const;\n\nconst escapeForRegex = (literal: string): string => literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/**\n * Rewrites legacy personalization tokens into the CAB-canonical `{{tokenName}}`\n * form expected by the client's `replaceVariables`. Specifically:\n *\n * - `{firstName}` (single brace) \u2192 `{{firstName}}`\n * - `{FirstName}` / `{FIRSTNAME}` (case variants) \u2192 `{{firstName}}`\n * - `{ firstName }` (internal whitespace) \u2192 `{{firstName}}`\n * - `{{firstName}}` (already canonical) \u2192 unchanged\n *\n * Pass `knownTokens` to control which names are normalized; anything not in the\n * list (e.g., an unrelated `{{foo}}` token) passes through untouched.\n */\nexport const normalizeTokens = (text: string, knownTokens: readonly string[] = DEFAULT_KNOWN_TOKENS): string => {\n if (typeof text !== 'string') return text;\n\n return knownTokens.reduce((acc, token) => {\n /**\n * Tokens standardize on camelCase; `_?` before each capital also matches the legacy snake_case\n * spelling ({remaining_amount} \u2192 {{remainingAmount}}).\n */\n const snakeTolerant = escapeForRegex(token).replace(/([A-Z])/g, '_?$1');\n const pattern = new RegExp(`\\\\{{1,2}\\\\s*${snakeTolerant}\\\\s*\\\\}{1,2}`, 'gi');\n\n return acc.replace(pattern, `{{${token}}}`);\n }, text);\n};\n", "import { htmlToTiptap } from '~/transforms/htmlToTiptap/htmlToTiptap';\nimport { normalizeTokens } from '~/transforms/normalizeTokens';\n\nconst HTML_TAG_RE = /<[a-zA-Z]/;\n\nconst containsHtml = (text: string): boolean => HTML_TAG_RE.test(text);\n\nconst isObject = (x: unknown): x is Record<string, unknown> => x !== null && typeof x === 'object' && !Array.isArray(x);\n\nconst normalizeLangValue = (value: unknown): unknown => {\n if (typeof value !== 'string') return value;\n\n const tokenized = normalizeTokens(value);\n\n return containsHtml(tokenized) ? htmlToTiptap(tokenized) : tokenized;\n};\n\n/**\n * Walks an untyped CABRootSection-shaped object (post deepCamelCase, pre schema\n * parse) and rewrites `text` sections' `content[lang]` strings so that:\n *\n * - `{firstName}` (single brace) becomes `{{firstName}}` (canonical), and\n * - HTML-laden strings become a fully-formed `TiptapDocument`.\n *\n * Plain strings pass through unchanged. Non-text sections only recurse into\n * their `sections` array; Tiptap docs and other nested objects are not walked.\n */\nexport const normalizeTextContent = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(normalizeTextContent);\n\n if (!isObject(node)) return node;\n\n if (node.sectionType === 'text' && isObject(node.content)) {\n const nextContent: Record<string, unknown> = {};\n\n for (const [lang, value] of Object.entries(node.content)) {\n nextContent[lang] = normalizeLangValue(value);\n }\n\n return { ...node, content: nextContent };\n }\n\n if (Array.isArray(node.sections)) {\n return { ...node, sections: node.sections.map(normalizeTextContent) };\n }\n\n return node;\n};\n", "import { type CabShopConfig } from '~/schema/cabShopConfig';\n\nexport type ActiveExperiment = CabShopConfig['activeExperiments'][number];\n\n/** What the client needs to render the chosen variant and emit the A/B analytics. */\nexport type ResolvedExperiment = {\n /** The widget whose settings actually render \u2014 the chosen variant (not the placeholder). */\n elementId: number;\n experimentId: number;\n /** The experiment's raw engine type (e.g. `CheckoutOffer`); the analytics layer snake-cases it. */\n experimentType: string;\n /** The variant's experiment-element id \u2014 `abTestViewed`'s `defined_noun_id` half. */\n selectedId: number;\n};\n\n/**\n * Deterministic [0, 100) bucket from a seed string (FNV-1a \u2192 two-decimal percent). Replaces React's\n * `Math.random() * 100`: hashing `visitorId:experimentId` keeps a visitor in the SAME variant across\n * requests WITHOUT a client-stored selection \u2014 the server can't read the client's storage, so\n * stickiness has to come from a stable input it is handed (the visitor id).\n */\nconst rollPercent = (seed: string): number => {\n let hash = 0x811c9dc5;\n\n for (let index = 0; index < seed.length; index++) {\n hash ^= seed.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n\n return ((hash >>> 0) % 10000) / 100;\n};\n\n/**\n * Picks the A/B variant for the placeholder widget `placeholderId`, or `undefined` when no experiment\n * targets it (the common case \u2014 render the placeholder itself). Walks the variants by cumulative\n * `traffic` weight against a visitor-stable roll, mirroring React's `useABTesting` selection but\n * server-side and deterministic. Falls back to the first variant when the weights under-cover the roll.\n */\nexport const resolveExperiment = (\n experiments: ActiveExperiment[],\n placeholderId: number,\n visitorId: string\n): ResolvedExperiment | undefined => {\n const experiment = experiments.find((candidate) => candidate.placeholderId === placeholderId);\n\n if (!experiment || experiment.data.length === 0) return undefined;\n\n const roll = rollPercent(`${visitorId}:${experiment.id}`);\n let cumulative = 0;\n\n const variant =\n experiment.data.find((candidate) => {\n cumulative += candidate.traffic;\n\n // Half-open roll [0, 100) with `<` (not `<=`): a 0-traffic bucket is never entered (so a paused\n // head can't capture the roll-0 visitor), and boundaries split evenly (50/50 \u2192 5000/5000).\n return roll < cumulative;\n }) ?? experiment.data[0];\n\n return {\n elementId: variant.elementId,\n experimentId: experiment.id,\n experimentType: experiment.type,\n selectedId: variant.id,\n };\n};\n", "/**\n * Default localized labels for the offer card's add-to-order button states and the opt-in undo banner,\n * keyed by slot then locale (same 26 locales as `SWITCH_LABELS`). The converter overlays a defined v1\n * merchant value as the `en` entry (verbatim) and falls back to these for blank/absent values, so a\n * migrated widget keeps its copy while new/unset widgets localize. `addedToCartMessage` tokens are\n * camelCase (CAB default); legacy snake_case tokens in merchant overrides still resolve client-side.\n */\nexport const OFFER_LABELS = {\n addedToCart: {\n ar: '\u062A\u0645\u062A \u0627\u0644\u0625\u0636\u0627\u0641\u0629!',\n cs: 'P\u0159id\u00E1no!',\n da: 'Tilf\u00F8jet!',\n de: 'Hinzugef\u00FCgt!',\n en: 'Added!',\n es: '\u00A1A\u00F1adido!',\n fi: 'Lis\u00E4tty!',\n fr: 'Ajout\u00E9 !',\n ga: 'Curtha leis!',\n he: '\u05E0\u05D5\u05E1\u05E3!',\n hi: '\u091C\u094B\u0921\u093C\u093E \u0917\u092F\u093E!',\n id: 'Ditambahkan!',\n it: 'Aggiunto!',\n ja: '\u8FFD\u52A0\u3057\u307E\u3057\u305F\uFF01',\n ko: '\uCD94\uAC00\uB428!',\n nl: 'Toegevoegd!',\n no: 'Lagt til!',\n pl: 'Dodano!',\n pt: 'Adicionado!',\n ru: '\u0414\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u043E!',\n sv: 'Tillagd!',\n th: '\u0E40\u0E1E\u0E34\u0E48\u0E21\u0E41\u0E25\u0E49\u0E27!',\n tr: 'Eklendi!',\n uk: '\u0414\u043E\u0434\u0430\u043D\u043E!',\n vi: '\u0110\u00E3 th\u00EAm!',\n zh: '\u5DF2\u6DFB\u52A0\uFF01',\n },\n addedToCartMessage: {\n ar: '\u062A\u0645\u062A \u0625\u0636\u0627\u0641\u0629 {{quantity}} {{productTitle}} \u0625\u0644\u0649 \u0627\u0644\u0633\u0644\u0629.',\n cs: '{{quantity}} {{productTitle}} p\u0159id\u00E1no do ko\u0161\u00EDku.',\n da: '{{quantity}} {{productTitle}} lagt i kurven.',\n de: '{{quantity}} {{productTitle}} zum Warenkorb hinzugef\u00FCgt.',\n en: '{{quantity}} {{productTitle}} successfully added to cart.',\n es: '{{quantity}} {{productTitle}} a\u00F1adido al carrito.',\n fi: '{{quantity}} {{productTitle}} lis\u00E4tty ostoskoriin.',\n fr: '{{quantity}} {{productTitle}} ajout\u00E9 au panier.',\n ga: 'Cuireadh {{quantity}} {{productTitle}} sa chairt.',\n he: '{{quantity}} {{productTitle}} \u05E0\u05D5\u05E1\u05E3 \u05DC\u05E2\u05D2\u05DC\u05D4.',\n hi: '{{quantity}} {{productTitle}} \u0915\u093E\u0930\u094D\u091F \u092E\u0947\u0902 \u091C\u094B\u0921\u093C\u093E \u0917\u092F\u093E\u0964',\n id: '{{quantity}} {{productTitle}} ditambahkan ke keranjang.',\n it: '{{quantity}} {{productTitle}} aggiunto al carrello.',\n ja: '{{quantity}} {{productTitle}}\u3092\u30AB\u30FC\u30C8\u306B\u8FFD\u52A0\u3057\u307E\u3057\u305F\u3002',\n ko: '{{quantity}} {{productTitle}}\uC774(\uAC00) \uC7A5\uBC14\uAD6C\uB2C8\uC5D0 \uCD94\uAC00\uB418\uC5C8\uC2B5\uB2C8\uB2E4.',\n nl: '{{quantity}} {{productTitle}} toegevoegd aan winkelwagen.',\n no: '{{quantity}} {{productTitle}} lagt i handlekurven.',\n pl: '{{quantity}} {{productTitle}} dodano do koszyka.',\n pt: '{{quantity}} {{productTitle}} adicionado ao carrinho.',\n ru: '{{quantity}} {{productTitle}} \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u043E \u0432 \u043A\u043E\u0440\u0437\u0438\u043D\u0443.',\n sv: '{{quantity}} {{productTitle}} har lagts i varukorgen.',\n th: '\u0E40\u0E1E\u0E34\u0E48\u0E21 {{quantity}} {{productTitle}} \u0E25\u0E07\u0E15\u0E30\u0E01\u0E23\u0E49\u0E32\u0E41\u0E25\u0E49\u0E27',\n tr: '{{quantity}} {{productTitle}} sepete eklendi.',\n uk: '{{quantity}} {{productTitle}} \u0434\u043E\u0434\u0430\u043D\u043E \u0434\u043E \u043A\u043E\u0448\u0438\u043A\u0430.',\n vi: '\u0110\u00E3 th\u00EAm {{quantity}} {{productTitle}} v\u00E0o gi\u1ECF h\u00E0ng.',\n zh: '{{quantity}} {{productTitle}} \u5DF2\u52A0\u5165\u8D2D\u7269\u8F66\u3002',\n },\n addingToCart: {\n ar: '\u062C\u0627\u0631\u064D \u0627\u0644\u0625\u0636\u0627\u0641\u0629...',\n cs: 'P\u0159id\u00E1v\u00E1n\u00ED...',\n da: 'Tilf\u00F8jer...',\n de: 'Wird hinzugef\u00FCgt...',\n en: 'Adding...',\n es: 'A\u00F1adiendo...',\n fi: 'Lis\u00E4t\u00E4\u00E4n...',\n fr: 'Ajout en cours...',\n ga: '\u00C1 chur leis...',\n he: '\u05DE\u05D5\u05E1\u05D9\u05E3...',\n hi: '\u091C\u094B\u0921\u093C\u093E \u091C\u093E \u0930\u0939\u093E \u0939\u0948...',\n id: 'Menambahkan...',\n it: 'Aggiunta in corso...',\n ja: '\u8FFD\u52A0\u4E2D...',\n ko: '\uCD94\uAC00 \uC911...',\n nl: 'Toevoegen...',\n no: 'Legger til...',\n pl: 'Dodawanie...',\n pt: 'Adicionando...',\n ru: '\u0414\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u0438\u0435...',\n sv: 'L\u00E4gger till...',\n th: '\u0E01\u0E33\u0E25\u0E31\u0E07\u0E40\u0E1E\u0E34\u0E48\u0E21...',\n tr: 'Ekleniyor...',\n uk: '\u0414\u043E\u0434\u0430\u0432\u0430\u043D\u043D\u044F...',\n vi: '\u0110ang th\u00EAm...',\n zh: '\u6B63\u5728\u6DFB\u52A0...',\n },\n addToCart: {\n ar: '\u0623\u0636\u0641 \u0625\u0644\u0649 \u0627\u0644\u0633\u0644\u0629',\n cs: 'P\u0159idat do ko\u0161\u00EDku',\n da: 'L\u00E6g i kurv',\n de: 'In den Warenkorb',\n en: 'Add to cart',\n es: 'A\u00F1adir al carrito',\n fi: 'Lis\u00E4\u00E4 ostoskoriin',\n fr: 'Ajouter au panier',\n ga: 'Cuir sa chairt',\n he: '\u05D4\u05D5\u05E1\u05E3 \u05DC\u05E2\u05D2\u05DC\u05D4',\n hi: '\u0915\u093E\u0930\u094D\u091F \u092E\u0947\u0902 \u091C\u094B\u0921\u093C\u0947\u0902',\n id: 'Tambahkan ke keranjang',\n it: 'Aggiungi al carrello',\n ja: '\u30AB\u30FC\u30C8\u306B\u8FFD\u52A0',\n ko: '\uC7A5\uBC14\uAD6C\uB2C8\uC5D0 \uCD94\uAC00',\n nl: 'In winkelwagen',\n no: 'Legg i handlekurven',\n pl: 'Dodaj do koszyka',\n pt: 'Adicionar ao carrinho',\n ru: '\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0432 \u043A\u043E\u0440\u0437\u0438\u043D\u0443',\n sv: 'L\u00E4gg i varukorgen',\n th: '\u0E40\u0E1E\u0E34\u0E48\u0E21\u0E25\u0E07\u0E15\u0E30\u0E01\u0E23\u0E49\u0E32',\n tr: 'Sepete ekle',\n uk: '\u0414\u043E\u0434\u0430\u0442\u0438 \u0432 \u043A\u043E\u0448\u0438\u043A',\n vi: 'Th\u00EAm v\u00E0o gi\u1ECF h\u00E0ng',\n zh: '\u52A0\u5165\u8D2D\u7269\u8F66',\n },\n redirectToCheckout: {\n ar: '\u0627\u0644\u062F\u0641\u0639',\n cs: 'Pokladna',\n da: 'Til kassen',\n de: 'Zur Kasse',\n en: 'Checkout',\n es: 'Finalizar compra',\n fi: 'Kassalle',\n fr: 'Paiement',\n ga: 'Seice\u00E1il amach',\n he: '\u05DC\u05EA\u05E9\u05DC\u05D5\u05DD',\n hi: '\u091A\u0947\u0915\u0906\u0909\u091F',\n id: 'Checkout',\n it: 'Cassa',\n ja: '\u30C1\u30A7\u30C3\u30AF\u30A2\u30A6\u30C8',\n ko: '\uACB0\uC81C\uD558\uAE30',\n nl: 'Afrekenen',\n no: 'Til kassen',\n pl: 'Do kasy',\n pt: 'Finalizar compra',\n ru: '\u041E\u0444\u043E\u0440\u043C\u0438\u0442\u044C \u0437\u0430\u043A\u0430\u0437',\n sv: 'Till kassan',\n th: '\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19',\n tr: '\u00D6deme',\n uk: '\u041E\u0444\u043E\u0440\u043C\u0438\u0442\u0438 \u0437\u0430\u043C\u043E\u0432\u043B\u0435\u043D\u043D\u044F',\n vi: 'Thanh to\u00E1n',\n zh: '\u7ED3\u8D26',\n },\n soldOut: {\n ar: '\u0646\u0641\u062F\u062A \u0627\u0644\u0643\u0645\u064A\u0629',\n cs: 'Vyprod\u00E1no',\n da: 'Udsolgt',\n de: 'Ausverkauft',\n en: 'Sold out',\n es: 'Agotado',\n fi: 'Loppuunmyyty',\n fr: '\u00C9puis\u00E9',\n ga: 'D\u00EDolta amach',\n he: '\u05D0\u05D6\u05DC \u05DE\u05D4\u05DE\u05DC\u05D0\u05D9',\n hi: '\u0938\u094D\u091F\u0949\u0915 \u0916\u093C\u0924\u094D\u092E',\n id: 'Habis terjual',\n it: 'Esaurito',\n ja: '\u58F2\u308A\u5207\u308C',\n ko: '\uD488\uC808',\n nl: 'Uitverkocht',\n no: 'Utsolgt',\n pl: 'Wyprzedane',\n pt: 'Esgotado',\n ru: '\u0420\u0430\u0441\u043F\u0440\u043E\u0434\u0430\u043D\u043E',\n sv: 'Sluts\u00E5ld',\n th: '\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32\u0E2B\u0E21\u0E14',\n tr: 'T\u00FCkendi',\n uk: '\u0420\u043E\u0437\u043F\u0440\u043E\u0434\u0430\u043D\u043E',\n vi: 'H\u1EBFt h\u00E0ng',\n zh: '\u5DF2\u552E\u7F44',\n },\n undo: {\n ar: '\u062A\u0631\u0627\u062C\u0639',\n cs: 'Zp\u011Bt',\n da: 'Fortryd',\n de: 'R\u00FCckg\u00E4ngig',\n en: 'Undo',\n es: 'Deshacer',\n fi: 'Kumoa',\n fr: 'Annuler',\n ga: 'Cealaigh',\n he: '\u05D1\u05D8\u05DC',\n hi: '\u092A\u0942\u0930\u094D\u0935\u0935\u0924 \u0915\u0930\u0947\u0902',\n id: 'Urungkan',\n it: 'Annulla',\n ja: '\u5143\u306B\u623B\u3059',\n ko: '\uC2E4\uD589 \uCDE8\uC18C',\n nl: 'Ongedaan maken',\n no: 'Angre',\n pl: 'Cofnij',\n pt: 'Desfazer',\n ru: '\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C',\n sv: '\u00C5ngra',\n th: '\u0E40\u0E25\u0E34\u0E01\u0E17\u0E33',\n tr: 'Geri al',\n uk: '\u0421\u043A\u0430\u0441\u0443\u0432\u0430\u0442\u0438',\n vi: 'Ho\u00E0n t\u00E1c',\n zh: '\u64A4\u9500',\n },\n} as const satisfies Record<string, Record<string, string>>;\n", "/**\n * Minimal v1 Offer (Checkout Offers / product recommendations) input types.\n * The legacy widget's settings `type` is the generic `shopify_checkout_extension`\n * (the offer is the \"base\" checkout-extension type; other widgets carry\n * `ui_extension_*`), which uniquely identifies it at the settings level.\n */\nimport { type TiptapDocument } from '~/schema/widgets/checkout-and-beyond/text';\n\nexport const SHOPIFY_CHECKOUT_EXTENSION = 'shopify_checkout_extension' as const;\n\nexport type V1OfferLanguage = {\n addedToCart?: string;\n addingToCart?: string;\n addToCart?: string;\n /** Subscribe \u2192 one-time label for the offers `switchToSubscription` button. */\n cartSwitchToOnetime?: string;\n /** One-time \u2192 subscribe label (carries `{{subscription_discount}}`) for the `switchToSubscription` button. */\n cartSwitchToSubscription?: string;\n description?: string;\n /** Buy Now link label on off-checkout surfaces (thank-you / order-status), real key `redirect_to_checkout`. */\n redirectToCheckout?: string;\n /** Real payload key is `sold_out_label` \u2192 `soldOutLabel` (NOT `soldOut`). */\n soldOutLabel?: string;\n /** Opt-in undo banner shown after a buyer adds a recommended product. */\n successBannerEnabled?: boolean;\n successBannerMessageRte?: TiptapDocument | string;\n superTitle?: string;\n title?: string;\n /** Legacy \"Upgrade to Subscription and Save {{subscription_discount}}%\" upsell label. */\n upgradeToSubscription?: string;\n};\n\n/** v1 per-product text styling; `textSize` is the CAB `textSizeNames` enum verbatim. */\nexport type V1TextStyle = {\n textEmphasis?: 'base' | 'bold' | 'italic';\n textSize?: 'extraSmall' | 'small' | 'base' | 'medium' | 'large' | 'extraLarge';\n};\n\n/** v1 `displaySettings` \u2014 the controls behind product/variant/image/review presentation. */\nexport type V1OfferDisplaySettings = {\n image?: { imageFit?: 'contain' | 'cover' };\n product?: V1TextStyle;\n reviews?: { color?: string; size?: 'small' | 'default' | 'large' };\n variant?: V1TextStyle;\n};\n\n/**\n * v1 layout is per-breakpoint; CAB has no breakpoints, so the converter collapses them.\n * `style` drives orientation: list \u2192 rows, line \u2192 columns, grid \u2192 grid (none \u2192 rows).\n */\nexport type V1OfferBreakpointLayout = {\n carousel?: boolean;\n columns?: number;\n showPaginations?: boolean;\n style?: 'grid' | 'line' | 'list' | 'none';\n};\n\nexport type V1OfferSettings = {\n /** Free-form in real payloads; the converter safelists to the CAB enum (junk \u2192 'primary'). */\n button?: { kind?: string };\n /** `showSavingAmount` false hides the compare-at (sale) price; `amount`/`type`/`discountedFrom`/`discountedBy` drive the discount-setting price computation (emitted onto the offers section for the client's pricing pass). */\n discount?: {\n amount?: number | string;\n discountedBy?: string;\n discountedFrom?: string;\n /** Merchant-facing promo label (e.g. \"Enjoy 10% off!\") \u2192 carried onto the data-source discount. */\n message?: string;\n /** How many items the discount applies to (defaults to 1) \u2192 carried onto the discount section. */\n quantity?: number;\n showSavingAmount?: boolean;\n type?: string;\n };\n /** Per-product/variant/image/review presentation controls. */\n displaySettings?: V1OfferDisplaySettings;\n /** Engine path appended to `/api/v1` (e.g. '/products/recommended'). */\n endpoint?: string | null;\n images?: { source?: 'product' | 'variant' };\n /**\n * Nominally boolean, but legacy data carries \"yes\"/\"no\" strings (reviewsio, in prod) and numeric\n * 1/0 (PHP serialization) \u2014 the converter coerces both so neither throws at the schema boolean.\n */\n integrations?: Record<string, boolean | number | string>;\n language?: V1OfferLanguage;\n layout?: { large?: V1OfferBreakpointLayout; medium?: V1OfferBreakpointLayout; small?: V1OfferBreakpointLayout };\n limit?: number;\n location?: 'checkout' | 'order-status' | 'thank-you';\n /** The legacy widget's name, present in the settings payload; carried to the converted root. */\n name?: string;\n previewMode?: boolean;\n productOptions?: {\n hideOutOfStockVariants?: boolean;\n matchVariant?: boolean;\n matchVariantOutOfStock?: boolean;\n /** 'hide' (or absent) hides the per-card product description; any other value shows it. */\n showProductDescription?: string;\n showVariantOptions?: 'always' | 'default' | 'never';\n showVariantsAsProducts?: boolean;\n /** 'hide' (or absent) hides the selected-variant title line; any other value shows it. */\n showVariantTitle?: string;\n };\n productType?: 'both' | 'one-time' | 'subscription';\n quantityInputs?: {\n enabled?: boolean;\n /** Custom over-max error copy \u2192 CAB `errorMessages.en.max`. */\n maxError?: string;\n maxValue?: number;\n /** Custom under-min error copy \u2192 CAB `errorMessages.en.min`. */\n minError?: string;\n minValue?: number;\n /** Custom negative-value error copy \u2192 CAB `errorMessages.en.neg`. */\n negativeError?: string;\n /** Stepper kind ('dropdown-select' | 'buttons-manual-input') \u2192 CAB `inputType` (select | number). */\n type?: string;\n };\n /** Default subscribe-vs-one-time when `productType` is `both`. */\n subscriptionIsDefault?: boolean;\n tracking?: { enableAttribution?: boolean; enableSource?: boolean; enableWidget?: boolean };\n treatAsGwp?: boolean;\n type: typeof SHOPIFY_CHECKOUT_EXTENSION;\n /** Absent on real checkout-offers payloads; only `type` is the reliable discriminator. */\n version?: 1;\n /** v1 `viewOptions`: `displayActions === false` hides the variant selector (legacy `getVariantSelect`). */\n viewOptions?: { displayActions?: boolean; variantSelector?: 'select' | 'radio' | 'button' };\n};\n\nexport type V1OfferConvertInput = {\n id: number;\n /** The legacy widget's name; set on the converted root (the admin save schema requires it). */\n name?: string;\n settings: V1OfferSettings;\n};\n\n/**\n * The offer's settings `type` uniquely identifies it. Unlike the `ui_extension_*` widgets, the legacy\n * checkout-offers payload carries NO top-level `version` \u2014 so we must NOT gate on it (doing so silently\n * dropped real offers to the passthrough branch). `version: 2` payloads are already claimed upstream by\n * `isCABRootSection`, so they never reach here.\n */\nexport const isOfferV1 = (data: unknown): data is V1OfferSettings => {\n if (!data || typeof data !== 'object') return false;\n\n return (data as Record<string, unknown>).type === SHOPIFY_CHECKOUT_EXTENSION;\n};\n", "import { OFFER_LABELS } from '~/schema/widgets/checkout-and-beyond/offerLabels';\nimport { SWITCH_LABELS } from '~/schema/widgets/checkout-and-beyond/switchLabels';\nimport { localizedContent } from '~/transforms/localizedContent';\nimport { type V1OfferSettings, type V1TextStyle } from '~/transforms/offerV1/types';\n\n/** v1 `viewOptions.variantSelector` \u2192 CAB `variants.selector` ('select' is the v1 name for a dropdown menu). */\nconst VARIANT_SELECTOR = { button: 'button', radio: 'radio', select: 'menu' } as const;\n\n/**\n * A single-token Tiptap doc carrying a v1 text style: `textSize` is the CAB `fontSize`\n * verbatim (identical enums); `textEmphasis` adds a bold/italic mark ('base' adds none).\n */\nconst buildStyledText = (token: string, style: V1TextStyle | undefined, color = 'base') => {\n const marks: Record<string, unknown>[] = [\n { attrs: { color, fontSize: style?.textSize ?? 'base' }, type: 'textStyle' },\n ];\n\n if (style?.textEmphasis === 'bold') marks.push({ type: 'bold' });\n\n if (style?.textEmphasis === 'italic') marks.push({ type: 'italic' });\n\n return { content: [{ content: [{ marks, text: token, type: 'text' }], type: 'paragraph' }], type: 'doc' };\n};\n\n/**\n * The price line: the variant price, optionally followed by a strikethrough,\n * subdued compare-at price. The extension resolves `{{variantCompareAtPrice}}`\n * to '' off-sale, so the strikethrough disappears unless the variant is genuinely\n * discounted. `discount.showSavingAmount` false drops the compare-at node entirely.\n */\nconst buildPriceContent = (settings: V1OfferSettings) => {\n const content: Record<string, unknown>[] = [{ text: '{{variantPrice}}', type: 'text' }];\n\n if (settings.discount?.showSavingAmount !== false) {\n content.push(\n { text: ' ', type: 'text' },\n {\n marks: [{ type: 'strike' }, { attrs: { color: 'subdued' }, type: 'textStyle' }],\n text: '{{variantCompareAtPrice}}',\n type: 'text',\n }\n );\n }\n\n return { content: [{ content, type: 'paragraph' }], type: 'doc' };\n};\n\n/** A `reviews` star section, emitted only when the merchant has a review integration enabled. */\nconst buildReviews = (settings: V1OfferSettings): Record<string, unknown>[] => {\n if (!settings.integrations || !Object.values(settings.integrations).some(Boolean)) return [];\n\n const reviews = settings.displaySettings?.reviews;\n\n return [\n {\n ...(reviews?.color && { color: reviews.color }),\n sectionType: 'reviews',\n ...(reviews?.size && { size: reviews.size }),\n },\n ];\n};\n\n/** The recommended product's image; objectFit comes from v1 `displaySettings.image.imageFit`. */\nconst buildImage = (settings: V1OfferSettings): Record<string, unknown> => ({\n ...(settings.displaySettings?.image?.imageFit && {\n objectFit: settings.displaySettings.image.imageFit,\n }),\n sectionType: 'image',\n source: settings.images?.source === 'product' ? '{{productImage}}' : '{{variantImage}}',\n width: 100,\n});\n\n/** The product title text, styled from v1 `displaySettings.product`. */\nconst buildTitle = (settings: V1OfferSettings): Record<string, unknown> => ({\n content: { en: buildStyledText('{{productTitle}}', settings.displaySettings?.product) },\n sectionType: 'text',\n});\n\n/** The price line (variant price + on-sale compare-at strikethrough). */\nconst buildPrice = (settings: V1OfferSettings): Record<string, unknown> => ({\n content: { en: buildPriceContent(settings) },\n sectionType: 'text',\n});\n\n/** The selected-variant title line, gated by `productOptions.showVariantTitle` ('hide'/absent = off). */\nconst buildVariantTitle = (settings: V1OfferSettings): Record<string, unknown>[] => {\n const show = settings.productOptions?.showVariantTitle;\n\n if (!show || show === 'hide') return [];\n\n return [\n {\n content: { en: buildStyledText('{{variantTitle}}', settings.displaySettings?.variant) },\n sectionType: 'text',\n },\n ];\n};\n\n/** The per-card product description, gated by `productOptions.showProductDescription` ('hide'/absent = off). */\nconst buildDescription = (settings: V1OfferSettings): Record<string, unknown>[] => {\n const show = settings.productOptions?.showProductDescription;\n\n if (!show || show === 'hide') return [];\n\n return [{ content: { en: buildStyledText('{{productDescription}}', undefined) }, sectionType: 'text' }];\n};\n\n/** The variant selector, unless the merchant hid variant options or turned actions off entirely. */\nconst buildVariants = (settings: V1OfferSettings): Record<string, unknown>[] => {\n /** Legacy `getVariantSelect`: `view_options.display_actions === false` suppresses the selector. */\n if (settings.viewOptions?.displayActions === false) return [];\n\n if (settings.productOptions?.showVariantOptions === 'never') return [];\n\n const selector = settings.viewOptions?.variantSelector;\n\n return [\n {\n hideOutOfStockVariants: !!settings.productOptions?.hideOutOfStockVariants,\n ...(selector && { selector: VARIANT_SELECTOR[selector] }),\n sectionType: 'variants',\n },\n ];\n};\n\n/** v1 stepper kind \u2192 CAB `inputType`. Unknown/absent \u2192 omitted so the schema default ('select') applies. */\nconst QUANTITY_INPUT_TYPE: Record<string, 'number' | 'select'> = {\n 'buttons-manual-input': 'number',\n 'dropdown-select': 'select',\n};\n\n/** Custom quantity error copy \u2192 CAB `errorMessages.en.{min,max,neg}`; omitted entirely when none is set. */\nconst buildQuantityErrors = (quantity: NonNullable<V1OfferSettings['quantityInputs']>) => {\n const en = {\n ...(quantity.maxError && { max: quantity.maxError }),\n ...(quantity.minError && { min: quantity.minError }),\n ...(quantity.negativeError && { neg: quantity.negativeError }),\n };\n\n return Object.keys(en).length ? { errorMessages: { en } } : {};\n};\n\n/** The quantity stepper, when the merchant enabled quantity input. */\nconst buildQuantity = (settings: V1OfferSettings): Record<string, unknown>[] => {\n const quantity = settings.quantityInputs;\n\n if (!quantity?.enabled) return [];\n\n const inputType = quantity.type ? QUANTITY_INPUT_TYPE[quantity.type] : undefined;\n\n // Legacy quantity had no upper bound (DefaultQuantityRule.MAX = null) and allowed 0; the CAB\n // schema pins `max` to [1, 100] and `min` to >= 1. Clamp instead of passing through so a legacy\n // `maxValue: 250` (or a 0) degrades to a valid widget rather than throwing at parse.\n const max = Math.min(Math.max(quantity.maxValue ?? 10, 1), 100);\n // Also cap `min` at `max` \u2014 the schema has no cross-field refine, so a legacy `min > max` (e.g.\n // {maxValue: 5, minValue: 8}) would parse but render a degenerate stepper (REB #766).\n const min = Math.min(Math.max(quantity.minValue ?? 1, 1), max);\n\n return [\n {\n ...buildQuantityErrors(quantity),\n ...(inputType && { inputType }),\n max,\n min,\n sectionType: 'quantity',\n },\n ];\n};\n\n/**\n * The in-card subscribe / one-time toggle: a `switchToSubscription` button with its four label slots\n * (the same `SWITCH_LABELS` slot set as the line-item editor, including the `subscriptionOption`\n * frequency template, so the frequency select localizes). Emitted when the merchant offers\n * subscriptions (`productType` both/subscription); the extension shows it per-product by selling-plan\n * availability. v1 carries the with-discount upsell (`upgradeToSubscription`) plus the cart switch\n * labels; anything blank/absent falls back to the shared localized defaults.\n */\nconst buildSubscriptionButton = (settings: V1OfferSettings): Record<string, unknown>[] => {\n if (settings.productType !== 'both' && settings.productType !== 'subscription') return [];\n\n const language = settings.language;\n\n const slot = (buttonField: keyof typeof SWITCH_LABELS, override: string | undefined) => ({\n buttonField,\n content: localizedContent(SWITCH_LABELS[buttonField], override),\n sectionType: 'text',\n });\n\n return [\n {\n action: 'switchToSubscription',\n buttonStyle: 'plain',\n sections: [\n slot('subscriptionOption', undefined),\n slot('switchToOneTimePurchase', language?.cartSwitchToOnetime),\n slot('switchToSubscriptionNoDiscount', language?.cartSwitchToSubscription),\n slot('switchToSubscriptionWithDiscount', language?.upgradeToSubscription),\n ],\n sectionType: 'button',\n },\n ];\n};\n\n/** v1 stores free-form `button.kind`; anything outside the CAB enum falls back to the legacy 'primary'. */\nconst BUTTON_KINDS = ['plain', 'primary', 'secondary'] as const;\n\n/** The add-to-order button with its four label slots (add / adding / added / sold-out). */\nconst buildAddButton = (settings: V1OfferSettings): Record<string, unknown> => {\n const kind = settings.button?.kind;\n\n const slot = (\n buttonField: 'addedToCart' | 'addingToCart' | 'addToCart' | 'redirectToCheckout' | 'soldOut',\n override?: string\n ) => ({\n buttonField,\n content: localizedContent(OFFER_LABELS[buttonField], override),\n sectionType: 'text',\n });\n\n return {\n action: 'addToOrder',\n buttonStyle: BUTTON_KINDS.includes(kind as (typeof BUTTON_KINDS)[number]) ? kind : 'primary',\n sections: [\n slot('addToCart', settings.language?.addToCart),\n slot('addingToCart', settings.language?.addingToCart),\n slot('addedToCart', settings.language?.addedToCart),\n slot('soldOut', settings.language?.soldOutLabel),\n // Off-checkout Buy Now: the label the button shows once it links to the created checkout.\n slot('redirectToCheckout', settings.language?.redirectToCheckout),\n ],\n sectionType: 'button',\n };\n};\n\n/** A `rows` layout wrapping sections into one grid cell (so they stack within a column of the card). */\nconst rowsLayout = (sections: Record<string, unknown>[]): Record<string, unknown> => ({\n direction: 'rows',\n sections,\n sectionType: 'layout',\n});\n\n/**\n * The per-offer product card: the sections rendered once per recommended product (the\n * offers renderer mounts a product context, so the `{{...}}` tokens resolve per product).\n *\n * `horizontal` mirrors the v1 layout orientation (see `convertOfferToV2`):\n * - horizontal (v1 `list`/default, vertical-stacked products): a 3-column grid card \u2014\n * image | title/price/reviews/variants | actions \u2014 matching the compact V1 row.\n * - vertical (v1 `grid`/`line`, side-by-side products): a flat top-to-bottom stack\n * (image \u2192 title \u2192 price \u2192 \u2026 \u2192 button), the narrow column card.\n *\n * Quantity is a full-width row beneath the card in the horizontal layout; in the vertical\n * layout it sits inline in the stack. NOT carried: the savings-amount badge (no live v1\n * control) and variant text styling (no CAB field).\n */\nexport const buildOfferCard = (settings: V1OfferSettings, horizontal: boolean): Record<string, unknown>[] => {\n const image = buildImage(settings);\n const title = buildTitle(settings);\n const variantTitle = buildVariantTitle(settings);\n const price = buildPrice(settings);\n const description = buildDescription(settings);\n const reviews = buildReviews(settings);\n const variants = buildVariants(settings);\n const quantity = buildQuantity(settings);\n const subscription = buildSubscriptionButton(settings);\n const addButton = buildAddButton(settings);\n\n if (!horizontal) {\n return [\n image,\n title,\n ...variantTitle,\n price,\n ...description,\n ...reviews,\n ...variants,\n ...quantity,\n ...subscription,\n addButton,\n ];\n }\n\n const info = rowsLayout([title, ...variantTitle, price, ...description, ...reviews, ...variants]);\n const actions = [...subscription, addButton];\n const actionsCell = actions.length === 1 ? actions[0] : rowsLayout(actions);\n\n const card = {\n direction: 'grid',\n grid: { columns: ['15%', 'fill', 'auto'], rows: ['auto'] },\n sections: [image, info, actionsCell],\n sectionType: 'layout',\n };\n\n return [card, ...quantity];\n};\n", "import { OFFER_LABELS } from '~/schema/widgets/checkout-and-beyond/offerLabels';\nimport { CABRootSection } from '~/schema/widgets/checkout-and-beyond/root';\nimport { convertContentBlockTextToV2 } from '~/transforms/contentBlockV1/convertContentBlockTextToV2';\nimport { stripContentBlockHtml } from '~/transforms/contentBlockV1/stripContentBlockHtml';\nimport { buildOfferCard } from '~/transforms/offerV1/offerCard';\nimport {\n SHOPIFY_CHECKOUT_EXTENSION,\n type V1OfferBreakpointLayout,\n type V1OfferConvertInput,\n type V1OfferSettings,\n} from '~/transforms/offerV1/types';\n\nconst LOCATION_TO_EDITOR_MODE = {\n checkout: 'checkoutExtension',\n 'order-status': 'orderStatusPage',\n 'thank-you': 'thankYouPage',\n} as const;\n\n/**\n * v1 per-breakpoint `layout.style` \u2192 CAB product-list `direction`. This is the product-TO-product\n * orientation and the card orientation flips with it (see `convertOfferToV2`):\n * - `grid`/`line` \u2192 products sit side-by-side (`grid`/`columns`); each card is a vertical stack.\n * - `list`/`none`/absent \u2192 products stack vertically (`rows`); each card is a horizontal row.\n * The v1 carousel toggle writes exactly these two: VERTICAL \u2192 `list`, HORIZONTAL \u2192 `grid`.\n */\nconst STYLE_TO_DIRECTION = {\n grid: 'grid',\n line: 'columns',\n list: 'rows',\n none: 'rows',\n} as const;\n\nconst directionForStyle = (style: V1OfferBreakpointLayout['style']) => (style ? STYLE_TO_DIRECTION[style] : 'rows');\n\n/**\n * The product-to-product layout \u2014 it belongs on the CONTAINER that holds the offers (the carousel\n * wrapper), NOT on the offers section. The renderer repeats the offers layout per product into its\n * parent's stack/grid, so a `grid` direction with N `'fill'` columns lays the products out N-across;\n * `list`/`none` stay a vertical stack.\n *\n * `'fill'` (equal share) \u2014 NOT `'auto'` (sizes to content), which yields unequal columns and so\n * unequal `objectFit: contain` image heights across products.\n */\nconst buildProductListLayout = (direction: string, columns: number) =>\n direction === 'grid'\n ? { direction, grid: { columns: Array.from({ length: Math.max(columns, 1) }, () => 'fill'), rows: ['auto'] } }\n : { direction };\n\nconst hasHeaderText = (language: V1OfferSettings['language']): boolean =>\n !!(language?.title || language?.superTitle || language?.description);\n\n/**\n * v1 `discountedFrom` \u2192 CAB `discountSources`. v1's \"Discounted From\" / \"Compare Price With\" select\n * stores `price` / `compare_at_price` directly; the legacy `original_price` (written in Shopify-Functions\n * mode) is the regular price, i.e. `price`. Unknown values are omitted (the CAB enum would reject them).\n */\nconst DISCOUNTED_FROM: Record<string, 'compare_at_price' | 'price'> = {\n compare_at_price: 'compare_at_price',\n original_price: 'price',\n price: 'price',\n};\n\n/**\n * The active widget-level discount as the `CABDiscount` carried on the DATA-SOURCE section \u2014 the field\n * the extension's price forecast actually reads (`dataSource.discount` \u2192 `priceVariant`); a discount\n * emitted anywhere else never reaches the card price. Undefined when there's no active discount;\n * `showSavingAmount` is a card-display concern handled in `buildOfferCard`.\n */\nconst dataSourceDiscount = (discount: V1OfferSettings['discount']): Record<string, unknown> | undefined => {\n if (!discount?.type || discount.type === 'none') return undefined;\n\n const discountedFrom = discount.discountedFrom ? DISCOUNTED_FROM[discount.discountedFrom] : undefined;\n\n return {\n amount: discount.amount ?? 0,\n ...(discount.discountedBy && { discountedBy: discount.discountedBy }),\n ...(discountedFrom && { discountedFrom }),\n type: discount.type,\n };\n};\n\n/**\n * The same discount as the config-only `discount` section just above the undo banner \u2014 the editor-facing\n * home of the FULL v1 shape (`message`/`quantity` have no `CABDiscount` counterpart). Both projections\n * come from the one v1 input in the same pass, so they cannot drift apart.\n */\nconst buildDiscountSection = (discount: V1OfferSettings['discount']): Record<string, unknown>[] => {\n const base = dataSourceDiscount(discount);\n\n if (!base) return [];\n\n return [\n {\n ...base,\n ...(discount?.message && { message: discount.message }),\n ...(discount?.quantity != null && { quantity: discount.quantity }),\n sectionType: 'discount',\n },\n ];\n};\n\n/**\n * The banner's success message content: a defined v1 message overrides `en`, absent falls back to the\n * localized defaults (P4 language policy). A string message is sanitized (a raw-HTML label would fail\n * `CABTextSection.content` and 500 the widget); an RTE doc passes through as authored. A string that\n * sanitizes to empty falls back to the defaults, same as absent.\n */\nconst bannerMessageContent = (message: NonNullable<V1OfferSettings['language']>['successBannerMessageRte']) => {\n const sanitized = typeof message === 'string' ? stripContentBlockHtml(message) : message;\n\n return sanitized ? { ...OFFER_LABELS.addedToCartMessage, en: sanitized } : OFFER_LABELS.addedToCartMessage;\n};\n\n/**\n * Legacy integrations values are nominally boolean but prod data carries \"yes\"/\"no\" strings\n * (React special-cased exactly this for reviewsio: only 'true'/'yes' count as enabled) and numeric\n * 1/0 (legacy PHP serialization). Coerce every value so neither a string nor a number can throw at\n * the schema's `z.boolean()` and kill the widget: only 'true'/'yes' and 1 count as enabled.\n */\nconst coerceIntegrations = (integrations: Record<string, boolean | number | string>): Record<string, boolean> =>\n Object.fromEntries(\n Object.entries(integrations).map(([key, value]) => {\n if (typeof value === 'string') return [key, ['true', 'yes'].includes(value.toLowerCase())];\n\n if (typeof value === 'number') return [key, value === 1];\n\n return [key, value];\n })\n );\n\n/** The opt-in undo banner: a success `banner` of the message + a plain undo button. */\nconst buildBanner = (language: V1OfferSettings['language']): Record<string, unknown>[] =>\n language?.successBannerEnabled\n ? [\n {\n /**\n * The banner-level tag is the extraction/routing key on BOTH renderers (React CAB's\n * `isBannerType` + marker check; the Preact extension's `isUndoBanner`) \u2014 without it\n * the banner renders per card as an always-visible plain success banner and the\n * cart-scoped undo rail never runs. The schema's default offers tree carries it too.\n */\n buttonField: 'undoAddToOrder',\n color: 'success',\n dismissible: true,\n sections: [\n {\n content: bannerMessageContent(language.successBannerMessageRte),\n sectionType: 'text',\n },\n {\n action: 'undoAddToOrder',\n buttonStyle: 'plain',\n /**\n * Tagged `undoAddToOrder`, never `buttonLabel` \u2014 the renderers (React CAB and\n * the Preact extension) and the schema's default offers tree resolve that slot.\n */\n sections: [\n { buttonField: 'undoAddToOrder', content: OFFER_LABELS.undo, sectionType: 'text' },\n ],\n sectionType: 'button',\n },\n ],\n sectionType: 'banner',\n },\n ]\n : [];\n\n/**\n * Translates a v1 Offer (Checkout Offers / product recommendations) widget into\n * a `CABRootSection`: an optional header (title/superTitle/description, reusing\n * the content-block text converter) over a `carousel` wrapper that ALWAYS contains\n * the `offers` section (the carousel is the required structural parent; it only\n * paginates when the v1 layout has carousel on). The offers section's `dataSource`\n * child carries the engine fetch config; its remaining children are the\n * per-offer card (see `buildOfferCard`).\n *\n * v1 `layout` is per-breakpoint; CAB has none, so the converter collapses to\n * the largest provided breakpoint. A widget-level discount lands on the data\n * source's `discount` field (what the extension prices cards from) plus a\n * config-only `discount` section, and an opt-in undo `banner` is appended after\n * the data source (discount above, banner pinned last) when each is configured.\n */\nexport const convertOfferToV2 = ({ id, name, settings }: V1OfferConvertInput): CABRootSection => {\n const layout = settings.layout?.large ?? settings.layout?.medium ?? settings.layout?.small;\n const columns = layout?.columns ?? 1;\n const direction = directionForStyle(layout?.style);\n const listLayout = buildProductListLayout(direction, columns);\n\n // The card orientation is the inverse of the product-list orientation: vertically-stacked\n // products (`rows`) carry a compact horizontal card (image | info | add); side-by-side products\n // (`grid`/`columns`) carry a narrow vertical card (image \u2192 info \u2192 add).\n const horizontalCard = direction === 'rows';\n\n const discount = dataSourceDiscount(settings.discount);\n\n const dataSource = {\n ...(settings.endpoint && { dataSourcePath: settings.endpoint }),\n ...(discount && { discount }),\n ...(settings.integrations && { integrations: coerceIntegrations(settings.integrations) }),\n ...(settings.limit !== undefined && { limit: settings.limit }),\n matchVariant: !!settings.productOptions?.matchVariant,\n matchVariantOutOfStock: !!settings.productOptions?.matchVariantOutOfStock,\n ...(settings.productType && { productType: settings.productType }),\n sectionType: 'dataSource',\n ...(settings.subscriptionIsDefault && { subscriptionIsDefault: true }),\n ...(settings.treatAsGwp && { treatAsGwp: true }),\n };\n\n // The visible card sections come first so their indices stay contiguous from\n // the top (the admin UI prepends newly-added visible sections). The trailing\n // config-only sections are never rendered per-card: data source (engine fetch\n // config), then the optional discount, then the undo banner pinned to the very\n // bottom. `offers` keeps the default `rows` direction; the card's own\n // orientation is baked into the sections `buildOfferCard` returns.\n const offers = {\n sections: [\n ...buildOfferCard(settings, horizontalCard),\n dataSource,\n ...buildDiscountSection(settings.discount),\n ...buildBanner(settings.language),\n ],\n sectionType: 'offers',\n };\n\n // Offers ALWAYS live inside a `carousel` section \u2014 it's the structural wrapper the CAB offers\n // architecture requires, regardless of whether the widget actually paginates (the name is\n // historical). It only shows pagination when there are more products than `itemsAtOnce`, so a\n // non-carousel v1 widget sets `itemsAtOnce` to the full limit and shows everything at once. The\n // product-list layout (direction/grid from the v1 style + columns) rides on this wrapper.\n const display = {\n autoAdvanceInterval: 0,\n // `itemsAtOnce` feeds the carousel schema's `.min(1)`; a legacy `columns`/`limit` of 0 would\n // otherwise throw at parse, so floor it at 1 (the carousel still shows a product per page).\n itemsAtOnce: Math.max(layout?.carousel ? columns : (settings.limit ?? columns), 1),\n ...listLayout,\n sections: [offers],\n sectionType: 'carousel',\n };\n\n return CABRootSection.parse({\n direction: 'rows',\n editorMode: LOCATION_TO_EDITOR_MODE[settings.location ?? 'checkout'],\n // The widget name is required by the admin save schema; carry the legacy widget's name through.\n ...(name && { name }),\n previewMode: settings.previewMode,\n sections: [\n ...(hasHeaderText(settings.language)\n ? [{ content: { en: convertContentBlockTextToV2(settings.language) }, sectionType: 'text' }]\n : []),\n display,\n ],\n tracking: {\n enableAttribution: settings.tracking?.enableAttribution ?? true,\n enableSource: settings.tracking?.enableSource ?? true,\n enableWidget: settings.tracking?.enableWidget ?? true,\n },\n type: SHOPIFY_CHECKOUT_EXTENSION,\n version: 2,\n widgetId: id,\n });\n};\n", "import { type z } from 'zod';\n\nimport { convertNumericObjects } from '~/transforms/convertNumericObjects';\nimport { deepCamelCase } from '~/transforms/deepCamelCase';\n\n/**\n * Runs the shielded-CDN response through the canonical pipeline:\n *\n * raw \u2192 deepCamelCase \u2192 convertNumericObjects \u2192 transform? \u2192 schema.parse\n *\n * `schema.parse` hydrates `.default(...)` values and surfaces any drift as a\n * ZodError. The optional `transform` step is for normalization that must run\n * before* validation \u2014 e.g. converting HTML-laden text content into Tiptap\n * documents (since the canonical CAB schema rejects HTML strings outright).\n *\n * @param schema - The canonical Zod schema to validate against.\n * @param raw - Untrusted upstream JSON.\n * @param transform - Optional pre-parse transform (defaults to identity).\n *\n * @returns The parsed-and-default-hydrated `z.infer<S>`.\n */\nexport const parseShielded = <S extends z.ZodType>(\n schema: S,\n raw: unknown,\n transform: (input: unknown) => unknown = (input) => input\n): z.infer<S> => schema.parse(transform(convertNumericObjects(deepCamelCase(raw))));\n", "export const UI_EXTENSION_PROGRESS_BAR = 'ui_extension_progress_bar' as const;\n\n/**\n * Per-currency free-shipping thresholds as production actually writes them: each amount is a FLAT sibling\n * key (CENTS, ISO code any casing) alongside `enabled`, while `currencies` is the admin's array of enabled\n * code strings \u2014 NOT a code\u2192amount map. The onsite reader indexes it flat (`presentment[code]`), same as the\n * smart-cart tier shape.\n */\nexport type V1PresentmentCurrencies = {\n [code: string]: number | string | string[] | boolean | undefined;\n currencies?: string[];\n enabled?: boolean;\n};\n\nexport type V1ProgressBarSettings = {\n barSettings: {\n barType: 'shipping' | 'smart-cart';\n configLabelsAndText?: {\n /** v1 field name carries this typo. Supports `{{remaining_amount}}`. */\n amoundRemaining?: string;\n amountReached?: string;\n };\n countryCodes?: string[];\n freeShippingOptions?: {\n freeShippingOnAll?: boolean;\n freeShippingOnSubscriptions?: boolean;\n presentmentCurrencies?: V1PresentmentCurrencies;\n };\n limitCountries?: boolean;\n /** Shop-currency DOLLARS (e.g. 75 for $75). */\n unlockPrice?: number;\n };\n location?: 'checkout' | 'order-status' | 'thank-you';\n previewMode?: boolean;\n type: typeof UI_EXTENSION_PROGRESS_BAR;\n version: 1;\n};\n\nexport type V1ProgressBarConvertInput = {\n id: number;\n /** The shop theme's `buttonBackground` (bar fill), resolved by the caller; stays absent when unresolved. */\n progressColor?: string;\n settings: V1ProgressBarSettings;\n};\n\nexport const isProgressBarV1 = (data: unknown): data is V1ProgressBarSettings => {\n if (!data || typeof data !== 'object') return false;\n\n const obj = data as Record<string, unknown>;\n\n return (\n obj.version === 1 &&\n obj.type === UI_EXTENSION_PROGRESS_BAR &&\n !!obj.barSettings &&\n typeof obj.barSettings === 'object'\n );\n};\n\n/**\n * Only `barType: 'shipping'` carries its full config in the widget settings.\n * Smart-cart bars reference settings that live in the smart-cart config (a\n * separate fetch in the old runtime) \u2014 they pass through unconverted until a\n * server-side source for that config exists.\n */\nexport const isConvertibleProgressBarV1 = (data: unknown): data is V1ProgressBarSettings =>\n isProgressBarV1(data) && data.barSettings.barType === 'shipping';\n", "import { CABRootSection } from '~/schema/widgets/checkout-and-beyond/root';\nimport { normalizeTextContent } from '~/transforms/normalizeTextContent';\nimport { normalizeTokens } from '~/transforms/normalizeTokens';\nimport {\n UI_EXTENSION_PROGRESS_BAR,\n type V1PresentmentCurrencies,\n type V1ProgressBarConvertInput,\n} from '~/transforms/progressBarV1/types';\n\nconst LOCATION_TO_EDITOR_MODE = {\n checkout: 'checkoutExtension',\n 'order-status': 'orderStatusPage',\n 'thank-you': 'thankYouPage',\n} as const;\n\nconst DEFAULT_REMAINING = 'Spend {{remainingAmount}} more to unlock free shipping!';\nconst DEFAULT_REACHED = \"Congratulations! You've unlocked free shipping!\";\n\n/**\n * Lowercased per-currency thresholds (cents) harvested from the FLAT presentment keys as production writes\n * them (`{ enabled, currencies: ['cad'], cad: 9900 }`) \u2014 `currencies` is the admin's enabled-code ARRAY, not\n * a code\u2192amount map, so amounts sit as flat siblings. Drops `enabled`, `currencies`, and malformed values.\n * Mirrors the onsite reader (`presentment[code]`) and the smart-cart tier converter.\n */\nconst toThresholds = (presentment?: V1PresentmentCurrencies): Record<string, number> => {\n if (!presentment?.enabled) return {};\n\n const thresholds: Record<string, number> = {};\n\n for (const [code, cents] of Object.entries(presentment)) {\n if (code === 'enabled' || code === 'currencies') continue;\n\n const value = Math.round(Number(cents));\n\n if (Number.isFinite(value) && value >= 0) thresholds[code.toLowerCase()] = value;\n }\n\n return thresholds;\n};\n\ntype TextSectionInput = Record<string, unknown>;\n\n/**\n * The progress-bar widget layout blueprint (decided 2026-06-12): a `rows`\n * layout with the progress bar in the first row, a `columns` layout of the\n * tiers' labels in the second row (omitted when no tier has a label), and any\n * other labels as further rows. The v1 SHIPPING bar has a single unlabeled\n * tier, so it emits just the bar row \u2014 the multi-tier smart-cart conversion\n * reuses this builder when its settings source exists.\n */\nexport const buildProgressBarLayout = (\n progressBar: Record<string, unknown>,\n tierLabels: TextSectionInput[],\n extraRows: TextSectionInput[] = []\n) => ({\n direction: 'rows',\n sections: [\n progressBar,\n ...(tierLabels.length > 0 ? [{ direction: 'columns', sections: tierLabels, sectionType: 'layout' }] : []),\n ...extraRows,\n ],\n sectionType: 'layout',\n});\n\n/**\n * `freeShippingOnAll` maps to a zero threshold (always reached). `freeShippingOnSubscriptions` rides on the\n * section so the client treats the bar as reached when the cart holds a subscription item (a live-cart\n * condition the server can't precompute).\n */\nexport const convertProgressBarToV2 = ({ id, progressColor, settings }: V1ProgressBarConvertInput): CABRootSection => {\n const { barSettings } = settings;\n const labels = barSettings.configLabelsAndText;\n const alwaysReached = barSettings.freeShippingOptions?.freeShippingOnAll === true;\n\n const progressBar = {\n /**\n * `limit_countries` enabled with an EMPTY list hid the bar everywhere in React (country \u2208 []\n * is never true), but the schema reads an empty countryCodes as UNRESTRICTED \u2014 that\n * misconfiguration would flip the bar visible. 'XX' (ISO 3166 user-assigned, never a real\n * buyer country) preserves the hide-everywhere reading without a schema change.\n */\n countryCodes: barSettings.limitCountries\n ? barSettings.countryCodes?.length\n ? barSettings.countryCodes\n : ['XX']\n : [],\n freeShippingOnSubscription: barSettings.freeShippingOptions?.freeShippingOnSubscriptions === true,\n ...(progressColor && { progressColor }),\n sections: [\n {\n buttonField: 'progressRemaining',\n content: { en: normalizeTokens(labels?.amoundRemaining || DEFAULT_REMAINING, ['remainingAmount']) },\n sectionType: 'text',\n },\n {\n buttonField: 'progressReached',\n content: { en: labels?.amountReached || DEFAULT_REACHED },\n sectionType: 'text',\n },\n ],\n sectionType: 'progressBar',\n tiers: [\n {\n threshold: alwaysReached ? 0 : Math.round((Number(barSettings.unlockPrice) || 0) * 100),\n thresholds: alwaysReached ? {} : toThresholds(barSettings.freeShippingOptions?.presentmentCurrencies),\n tierType: 'shipping',\n },\n ],\n };\n\n /** Merchant copy can carry HTML \u2014 the canonical pipeline converts it to Tiptap BEFORE the parse. */\n return CABRootSection.parse(\n normalizeTextContent({\n ...buildProgressBarLayout(progressBar, []),\n editorMode: LOCATION_TO_EDITOR_MODE[settings.location ?? 'checkout'],\n previewMode: settings.previewMode,\n type: UI_EXTENSION_PROGRESS_BAR,\n version: 2,\n widgetId: id,\n })\n );\n};\n", "import { type SmartCartBar, type SmartCartTier } from '~/schema/smartCart';\nimport { CABProgressTier } from '~/schema/widgets/checkout-and-beyond/progressBar';\nimport { CABRootSection } from '~/schema/widgets/checkout-and-beyond/root';\nimport { normalizeTextContent } from '~/transforms/normalizeTextContent';\nimport { normalizeTokens } from '~/transforms/normalizeTokens';\nimport { UI_EXTENSION_PROGRESS_BAR, type V1ProgressBarSettings } from '~/transforms/progressBarV1/types';\n\nconst LOCATION_TO_EDITOR_MODE = {\n checkout: 'checkoutExtension',\n 'order-status': 'orderStatusPage',\n 'thank-you': 'thankYouPage',\n} as const;\n\nconst DEFAULT_REMAINING = 'Spend {{remainingAmount}} more to unlock your reward!';\nconst DEFAULT_REACHED = \"Congratulations! You've unlocked your reward!\";\n\n/** All four onsite tier types render at checkout (discount/decorative migrated per the P12 re-scope). */\nconst IN_SCOPE_TIER_TYPES = new Set(['decorative', 'discount', 'product', 'shipping']);\n\nconst inScope = (tier: SmartCartTier): boolean => IN_SCOPE_TIER_TYPES.has(tier.type ?? '');\n\ntype TierType = 'decorative' | 'discount' | 'product' | 'shipping';\n\n/** The tier's `CABProgressTier` type \u2014 its config `type` when one of the four, else `product`. */\nconst tierTypeOf = (tier: SmartCartTier): TierType =>\n tier.type === 'shipping' || tier.type === 'discount' || tier.type === 'decorative' ? tier.type : 'product';\n\n/** The tier's threshold in its own unit: a raw item count for `item_quantity` tiers, shop-currency cents otherwise. */\nconst thresholdOf = (tier: SmartCartTier): number =>\n tier.unlockConditionType === 'item_quantity'\n ? Math.round(tier.minimum ?? 0)\n : Math.round((tier.minimum ?? 0) * 100);\n\n/**\n * Smart-cart tiers key per-currency thresholds as FLAT siblings on `presentmentCurrencies`\n * (`{ enabled, usd: 5000, \u2026 }`) \u2014 the same flat shape the shipping bar's `toThresholds` reads (that one\n * also carries a `currencies` code array). Returns lowercased ISO \u2192 cents, dropping `enabled` and malformed values.\n */\nconst tierThresholds = (tier: SmartCartTier): Record<string, number> => {\n const presentment = tier.presentmentCurrencies;\n\n if (!presentment?.enabled) return {};\n\n const thresholds: Record<string, number> = {};\n\n for (const [code, cents] of Object.entries(presentment)) {\n if (code === 'enabled') continue;\n\n const value = Math.round(Number(cents));\n\n if (Number.isFinite(value) && value >= 0) thresholds[code.toLowerCase()] = value;\n }\n\n return thresholds;\n};\n\n/**\n * The onsite `getTierLabel` step-row label (blank \u2192 no label under the icon): the merchant custom label\n * (always used for `decorative`), else the type default \u2014 'Free Shipping', the discount amount\n * (`{n}% Discount`, or `{{discountAmount}} Off` whose fixed amount the client resolves FX-aware per tier),\n * or the gift product title / 'Free Product'. Plain text \u2014 the compact step label is not rich copy.\n */\nconst tierLabel = (tier: SmartCartTier): string => {\n const type = tierTypeOf(tier);\n\n if ((tier.customTierLabel || type === 'decorative') && tier.customTierLabelText) return tier.customTierLabelText;\n\n if (type === 'decorative') return tier.customTierLabelText ?? '';\n\n if (type === 'shipping') return 'Free Shipping';\n\n if (type === 'discount')\n return tier.discountType === 'fixedAmount'\n ? '{{discountAmount}} Off'\n : `${tier.discountAmountFromTotal ?? 0}% Discount`;\n\n return tier.products?.[0]?.title ?? tier.allProducts?.[0]?.title ?? 'Free Product';\n};\n\n/**\n * The order-discount reward on a `discount` tier, carried so the client resolves `{{discountAmount}}`:\n * `fixedAmount` in shop-currency CENTS (FX-scaled client-side like the threshold), else the raw percent.\n */\nconst discountOf = (tier: SmartCartTier) => {\n if (tier.type !== 'discount') return undefined;\n\n const amount = tier.discountAmountFromTotal ?? 0;\n\n return tier.discountType === 'fixedAmount'\n ? { amount: Math.round(amount * 100), type: 'fixedAmount' as const }\n : { amount, type: 'percentage' as const };\n};\n\n/** The gift reward for a product tier (the first configured product), or undefined for shipping / unset. */\nconst giftOf = (tier: SmartCartTier) => {\n if (tier.type !== 'product') return undefined;\n\n const product = tier.products?.[0] ?? tier.allProducts?.[0];\n\n if (!product) return undefined;\n\n const productId = product.productId ?? product.id;\n\n if (productId === undefined) return undefined;\n\n return {\n productId,\n title: product.title,\n // One junk (non-positive) variant id must not fail the whole tier's schema \u2014 drop only the bad ids.\n variantIds: (product.variantIds ?? []).filter((id) => Number.isInteger(id) && id > 0),\n };\n};\n\n/**\n * A tier \u2192 its `CABProgressTier` metadata on the bar (threshold/gift/tierType/unit \u2014 NOT visual\n * content). Units resolve PER TIER (onsite `getTierMinimum`): an `item_quantity` tier's minimum is a\n * raw item count checked BEFORE any money handling \u2014 no \u00D7100, no presentment overrides (rounded only\n * because the schema pins counts to integers; onsite compares the raw value, so an integer count is\n * identical and junk fractional data degrades to the nearest count instead of a parse failure).\n */\nconst toTierMeta = (tier: SmartCartTier) => {\n const discount = discountOf(tier);\n const gift = giftOf(tier);\n const isItemCount = tier.unlockConditionType === 'item_quantity';\n const label = tierLabel(tier);\n const type = tierTypeOf(tier);\n\n return {\n ...(discount && { discount }),\n ...(gift && { gift }),\n ...(label && { label: { en: label } }),\n threshold: thresholdOf(tier),\n thresholds: !isItemCount && type === 'shipping' ? tierThresholds(tier) : {},\n ...(tier.id && { tierId: tier.id }),\n tierType: type,\n ...(isItemCount && { unit: 'item' }),\n };\n};\n\n/**\n * The renderable tiers of a bar: in scope (one of the four types) AND whose built `CABProgressTier` meta\n * passes the strict schema. A tier whose meta would fail (negative threshold, non-positive gift id, \u2026) is\n * dropped here rather than thrown by the final `CABRootSection.parse` \u2014 keeping the widget fail-safe against\n * numerically-valid-but-out-of-domain values that the loose `SmartCartTier` schema lets through.\n */\nconst renderableTiers = (bar: SmartCartBar): SmartCartTier[] =>\n (bar.tiers ?? []).filter((tier) => inScope(tier) && CABProgressTier.safeParse(toTierMeta(tier)).success);\n\nconst PRODUCT_TOKENS = ['productTitle', 'remainingAmount'];\nconst DISCOUNT_TOKENS = ['discountAmount', 'remainingAmount'];\nconst DECORATIVE_TOKENS = ['remainingAmount'];\n\ntype TierCopy = {\n reached?: boolean;\n reachedText?: string;\n remaining?: boolean;\n remainingText?: string;\n tokens: string[];\n};\n\n/** onsite's per-tier feedback copy for a non-shipping tier (shipping uses the bar-level free-shipping pair). */\nconst tierCopy = (tier: SmartCartTier): TierCopy => {\n switch (tierTypeOf(tier)) {\n case 'discount':\n return {\n reached: tier.discountAmountReachedLabel,\n reachedText: tier.discountAmountReachedLabelText,\n remaining: tier.discountAmountRemainingLabel,\n remainingText: tier.discountAmountRemainingLabelText,\n tokens: DISCOUNT_TOKENS,\n };\n case 'decorative':\n return {\n reached: tier.decorativeAmountReachedLabel,\n reachedText: tier.decorativeAmountReachedLabelText,\n remaining: tier.decorativeAmountRemainingLabel,\n remainingText: tier.decorativeAmountRemainingLabelText,\n tokens: DECORATIVE_TOKENS,\n };\n default:\n return {\n reached: tier.productAmountReachedLabel,\n reachedText: tier.productAmountReachedLabelText,\n remaining: tier.productAmountRemainingLabel,\n remainingText: tier.productAmountRemainingLabelText,\n tokens: PRODUCT_TOKENS,\n };\n }\n};\n\n/**\n * Per-tier feedback `text` sections (onsite `getTierFeedbackText`/`getTierCompletedText`): one for the\n * remaining prompt, one for the reached prompt, each tagged with the tier's id so the renderer shows it\n * only while that tier is the active one \u2014 falling back to the bar-level pair when a tier's copy is\n * blank/disabled (F-05). O-B3 is NOT replicated: the remaining prompt uses the remaining field, never the\n * reached one. Shipping tiers (and tiers with no id) emit nothing; the bar-level pair speaks for them.\n */\nconst toTierFeedback = (tier: SmartCartTier) => {\n if (tierTypeOf(tier) === 'shipping' || !tier.id) return [];\n\n const copy = tierCopy(tier);\n const meta = { threshold: thresholdOf(tier), tierId: tier.id, tierType: tierTypeOf(tier) };\n const sections: Record<string, unknown>[] = [];\n\n if (copy.remaining && copy.remainingText)\n sections.push({\n buttonField: 'progressRemaining',\n content: { en: normalizeTokens(copy.remainingText, copy.tokens) },\n sectionType: 'text',\n tier: meta,\n });\n\n if (copy.reached && copy.reachedText)\n sections.push({\n buttonField: 'progressReached',\n content: { en: normalizeTokens(copy.reachedText, copy.tokens) },\n sectionType: 'text',\n tier: meta,\n });\n\n return sections;\n};\n\n/**\n * A bar + its in-scope tiers \u2192 a self-contained `progressBar` container (a `rows` layout): the tier display\n * (if any) and the reached/remaining copy as children, the milestones on `tiers`. The renderer adds the bar\n * fill + active message; the country/FX gate covers the whole thing since it's one section. The caller\n * (`dedupeBars`) decides `countryCodes`/`excludeCountryCodes` so the rendered set matches React `getbar`.\n */\nconst toProgressBarSection = (\n bar: SmartCartBar,\n tiers: SmartCartTier[],\n countryCodes: string[],\n excludeCountryCodes: string[],\n progressColor?: string\n) => ({\n countryCodes,\n direction: 'rows',\n excludeCountryCodes,\n /** Discount tiers force the pre-discount subtotal so the tier's own reward can't un-reach it (F-08). */\n excludeDiscountInSubtotal:\n (bar.excludeDiscountInSubtotal ?? false) || tiers.some((tier) => tier.type === 'discount'),\n // Bar-level ids (not covered by the per-tier safeParse): drop non-positive ones so one junk id can't\n // fail `excludedVariantIds`' strict `.int().positive()` schema and 500 the whole widget.\n excludedVariantIds: (bar.excludedProducts ?? [])\n .flatMap((product) => product.variantIds ?? [])\n .filter((id) => Number.isInteger(id) && id > 0),\n freeShippingOnSubscription: bar.freeShippingOnSubscription ?? false,\n /** Absent \u21D2 omit so the section schema's `.default({ en: 'FREE GIFTS' })` is the single source of the fallback. */\n ...(bar.language?.giftAreaTitle && { giftAreaTitle: { en: bar.language.giftAreaTitle } }),\n ...(progressColor && { progressColor }),\n sections: [\n ...tiers.flatMap(toTierFeedback),\n {\n buttonField: 'progressRemaining',\n // Token-normalized here; any HTML in the copy is coerced to Tiptap by the text schema on parse.\n // `productTitle` resolves client-side to the active tier's gift (`{{product_title}}` parity).\n content: {\n en: normalizeTokens(bar.language?.freeShippingRemaining || DEFAULT_REMAINING, [\n 'productTitle',\n 'remainingAmount',\n ]),\n },\n sectionType: 'text',\n },\n {\n buttonField: 'progressReached',\n // `remainingAmount` normalized too (F24) \u2014 onsite reached copy can carry `{{remaining_amount}}`.\n content: {\n en: normalizeTokens(bar.language?.freeShippingReached || DEFAULT_REACHED, [\n 'productTitle',\n 'remainingAmount',\n ]),\n },\n sectionType: 'text',\n },\n ],\n sectionType: 'progressBar',\n tiers: tiers.map(toTierMeta),\n});\n\ntype BarEntry = { bar: SmartCartBar; tiers: SmartCartTier[] };\ntype RenderedBar = { countryCodes: string[]; entry: BarEntry; excludeCountryCodes: string[] };\n\n/** A bar's country codes, uppercased + de-duplicated (empty when unset). */\nconst barCountries = (bar: SmartCartBar): string[] => [\n ...new Set((bar.countryCodes ?? []).map((code) => code.trim().toUpperCase()).filter(Boolean)),\n];\n\n/**\n * Decide each bar's country gate to mirror React `getbar`, which renders exactly ONE bar per country: a geo\n * bar owns only the countries no EARLIER geo bar already claimed \u2014 and drops when it has none left (including\n * a geo bar that lists no countries, which `getbar` never matches); only the FIRST default (non-geo) bar\n * renders, gated to hide wherever any geo bar applies. Returns the bars that render, in order, with gates.\n *\n * A geo bar CLAIMS (shadows) its countries even when it has no renderable tiers \u2014 so an unrenderable geo bar\n * still hides the default (and any later geo bar) there, matching `getbar` one-bar-per-country precedence \u2014\n * but such a shadowing-only bar is not itself pushed (it renders nothing). Likewise an empty default never\n * consumes the default slot: the first default WITH tiers wins.\n */\nconst dedupeBars = (entries: BarEntry[]): RenderedBar[] => {\n const geoCountries = [\n ...new Set(entries.filter((entry) => entry.bar.geolocationEnabled).flatMap((entry) => barCountries(entry.bar))),\n ];\n const claimed = new Set<string>();\n const rendered: RenderedBar[] = [];\n let defaultUsed = false;\n\n for (const entry of entries) {\n if (entry.bar.geolocationEnabled) {\n const own = barCountries(entry.bar).filter((code) => !claimed.has(code));\n\n if (own.length === 0) continue;\n\n own.forEach((code) => claimed.add(code));\n\n if (entry.tiers.length > 0) rendered.push({ countryCodes: own, entry, excludeCountryCodes: [] });\n } else if (!defaultUsed && entry.tiers.length > 0) {\n defaultUsed = true;\n rendered.push({ countryCodes: [], entry, excludeCountryCodes: geoCountries });\n }\n }\n\n return rendered;\n};\n\n/**\n * Converts a smart-cart progress-bar widget into a CAB tree: a `rows` layout holding one self-contained\n * `progressBar` container per configured bar (tiers come from the shop's smart-cart config \u2014 see\n * `extractSmartCartBars`). Each container holds its tier display (composable `columns \u2192 rows \u2192 text/image`)\n * + copy as children, with milestones on `tiers` (server-precomputed per tier: cents \u2014 base +\n * per-presentment-currency for shipping tiers \u2014 or a raw item count for `item_quantity` tiers) so the\n * client only compares each tier against its own unit's progress, mirroring the shipping bar. DISPLAY\n * ONLY \u2014 gift add/remove is a later stage. Tiers whose meta fails the strict schema are dropped (never\n * thrown); a bar left with no renderable tier renders nothing \u2014 but a geo bar still shadows its countries\n * (so the default can't leak into them) even when it renders nothing.\n */\nexport const convertSmartCartProgressBarToV2 = (input: {\n bars: SmartCartBar[];\n id: number;\n /** The shop theme's `buttonBackground` (bar fill), resolved by the caller; schema-defaulted when absent. */\n progressColor?: string;\n settings: V1ProgressBarSettings;\n}): CABRootSection => {\n // NOT pre-filtered by renderable tiers: `dedupeBars` must see every geo bar so an unrenderable one\n // still claims (shadows) its countries; it only pushes bars that actually have tiers to render.\n const entries = input.bars.map((bar) => ({ bar, tiers: renderableTiers(bar) }));\n\n const sections = dedupeBars(entries).map(({ countryCodes, entry, excludeCountryCodes }) =>\n toProgressBarSection(entry.bar, entry.tiers, countryCodes, excludeCountryCodes, input.progressColor)\n );\n\n /** Merchant copy/labels can carry HTML \u2014 the canonical pipeline converts it to Tiptap BEFORE the parse. */\n return CABRootSection.parse(\n normalizeTextContent({\n direction: 'rows',\n editorMode: LOCATION_TO_EDITOR_MODE[input.settings.location ?? 'checkout'],\n previewMode: input.settings.previewMode,\n sections,\n sectionType: 'layout',\n type: UI_EXTENSION_PROGRESS_BAR,\n version: 2,\n widgetId: input.id,\n })\n );\n};\n", "import { type SmartCartBar, type SmartCartConfig } from '~/schema/smartCart';\n\n/** Component `type` value that carries the checkout smart-cart progress-bar tiers. */\nexport const SMART_CART_TIERED_PROGRESS_BAR = 'tiered_progress_bar' as const;\n\n/**\n * Pulls the progress-bar bars out of a shop's smart-cart config: the first\n * `tiered_progress_bar` component's `settings.bars`. Returns `[]` when smart cart is\n * absent / disabled / has no such component \u2014 the caller then renders nothing, matching\n * the legacy runtime (which only shows a smart-cart bar when one is configured).\n *\n * One bar per geo segment is returned as-is; country selection happens downstream via\n * each bar's `countryCodes` gate (parity with the shipping bar \u2014 no buyer country is\n * known at conversion time).\n */\nexport const extractSmartCartBars = (smartCart: SmartCartConfig | null | undefined): SmartCartBar[] => {\n const component = smartCart?.components?.find((entry) => entry.type === SMART_CART_TIERED_PROGRESS_BAR);\n\n return component?.settings?.bars ?? [];\n};\n", "import { CabUserConfig } from '~/schema/cabShopConfig';\nimport { NotFoundError, type ServerContext, UpstreamError, type UserConfigInput } from '~/server/shared';\nimport { parseShielded } from '~/transforms';\n\nconst unwrapData = (body: unknown): unknown =>\n body && typeof body === 'object' && 'data' in body ? (body as { data: unknown }).data : body;\n\nconst isEmptyObject = (x: unknown): boolean =>\n x == null || (typeof x === 'object' && !Array.isArray(x) && Object.keys(x as object).length === 0);\n\n/** Inactive/missing shops come back as `{ data: { shop: null } }` or `{ data: {} }`. */\nconst isMissingShopPayload = (data: unknown): boolean => {\n if (data == null || typeof data !== 'object' || Array.isArray(data)) return true;\n\n return isEmptyObject((data as { shop?: unknown }).shop);\n};\n\n/**\n * Resolves the shop's normalized config (publishable key, currency, integrations, \u2026) from the engine's\n * `/api/v1/user/config`. Throws {@link NotFoundError} for inactive/unknown shops.\n */\nexport const fetchUserConfig = async (input: UserConfigInput, ctx: ServerContext): Promise<CabUserConfig> => {\n let upstream: unknown;\n\n try {\n upstream = await ctx.fetchUpstream('/api/v1/user/config', { shop: input.shop }, { host: ctx.host });\n } catch (err) {\n /** Legacy `/api/v1/user/config` returns 404 for \"Shop is not active\"; treat 410 the same. */\n if (err instanceof UpstreamError && (err.status === 404 || err.status === 410)) {\n throw new NotFoundError(`Shop config not found: ${input.shop}`);\n }\n\n throw err;\n }\n\n const data = unwrapData(upstream);\n\n if (isMissingShopPayload(data)) throw new NotFoundError(`Shop config not found: ${input.shop}`);\n\n return parseShielded(CabUserConfig, data);\n};\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Returns true if the string is a valid base64 encoded string.\n *\n * @param {string} str - The string to check.\n *\n * @returns {boolean} True if the string is a valid base64 encoded string.\n */\nexport function isBase64Encoded(str: string): boolean {\n const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n\n return base64Regex.test(str) ? true : false;\n}\n\n/**\n * Returns a string as a JSON object.\n *\n * @param {string} data - The string to convert to a JSON object.\n * @param {boolean} decode - Whether to decode the string. *\n *\n * @returns {any} The JSON object.\n */\nexport function stringToData(data: string, decode: boolean): any {\n let response = data;\n\n // Base64 decode\n if (decode === true) {\n response = atob(response);\n }\n\n try {\n response = JSON.parse(response);\n } catch (e) {\n // failure to parse cookie\n response = data;\n }\n\n return response;\n}\n\n/**\n * Returns a JSON object as a string.\n *\n * @param {any} data - The JSON object to convert to a string.\n * @param {boolean} encode - Whether to encode the string. *\n *\n * @returns {string} The string.\n */\nexport function dataToString(data: any, encode: boolean): string {\n let response = data;\n\n if (typeof response != 'string') {\n response = JSON.stringify(response);\n }\n\n // Base64 encode\n if (encode === true) {\n response = btoa(response);\n }\n\n return response;\n}\n\n/**\n * Returns a string with HTML tags removed.\n *\n * @param {string} str - The string to strip HTML tags from.\n *\n * @returns {string} The string with HTML tags removed.\n */\nexport function stripHtml(str: string): string {\n return str?.replace(/<(.|\\n)*?>/g, '') ?? '';\n}\n\n/**\n * Returns the ID from a GraphQL URL.\n *\n * @param {string} graphId - The GraphQL URL.\n * @param {string} objectType - The object type.\n *\n * @returns {number | null} The ID.\n */\nexport function getIdFromGraphUrl(graphId: string, objectType: string): number | null {\n let id: number | null = null;\n\n const regex = new RegExp(`gid://shopify/${objectType}/(.*)`);\n const matches = graphId.match(regex);\n\n if (matches != null) {\n const matchedId = matches[1];\n\n if (!isNaN(Number(matchedId))) {\n id = Number(matchedId);\n }\n }\n\n return id;\n}\n\n/**\n * Returns true if the variant is available.\n *\n * @param {any} variant - The variant.\n *\n * @returns {boolean} True if the variant is available.\n */\nexport function variantAvailable(variant: any): boolean {\n return !(variant.inventory_management && variant.inventory_policy === 'deny' && variant.inventory_quantity <= 0);\n}\n\n/**\n * Returns the first available variant.\n *\n * @param {any} product - The product.\n *\n * @returns {any} The first available variant.\n */\nexport function firstAvailableVariant(product: any): any {\n // Select first variant\n let selectedVariant = product.variants[0];\n\n // Upgrade to first available\n for (let i = 0; i < product.variants.length; i++) {\n if (variantAvailable(product.variants[i])) {\n selectedVariant = product.variants[i];\n break;\n }\n }\n\n return selectedVariant;\n}\n\n/**\n * Returns a UUID.\n *\n * @returns {string} The UUID.\n */\nexport function uuid(): string {\n let d = new Date().getTime();\n let d2 = (performance && performance.now && performance.now() * 1000) || 0;\n\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n let r = Math.random() * 16;\n\n if (d > 0) {\n r = ((d + r) % 16) | 0;\n d = Math.floor(d / 16);\n } else {\n r = ((d2 + r) % 16) | 0;\n d2 = Math.floor(d2 / 16);\n }\n\n return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\n/**\n * Returns a session ID.\n *\n * @returns {string} The session ID.\n */\nexport function sessionId(): string {\n const config = {\n chars: '0123456789',\n length: 12,\n };\n\n let sessionId = '';\n const sessionStart = new Date().getTime();\n\n for (let i = config.length; i > 0; i--) {\n sessionId += config.chars[Math.floor(Math.random() * config.chars.length)];\n }\n\n return `REBUY.${sessionStart}.${sessionId}`;\n}\n\n/**\n * Converts a product to the storefront format.\n *\n * @param {any} product - The product.\n *\n * @returns {any} The product in the storefront format.\n */\nexport function convertProductToStorefrontFormat(product: any): any {\n const defaultVariant = firstAvailableVariant(product);\n const minVariantPrice = variantMinMaxPriceObject(product, 'price', 'min');\n const maxVariantPrice = variantMinMaxPriceObject(product, 'price', 'max');\n const minVariantCompareAtPrice = variantMinMaxPriceObject(product, 'compare_at_price', 'min');\n const maxVariantCompareAtPrice = variantMinMaxPriceObject(product, 'compare_at_price', 'max');\n const selectedOptions = selectedVariantOptions(product, defaultVariant);\n\n const variants = product.variants.map((variant: any) => convertVariantToStorefrontFormat(product, variant));\n\n return {\n collections: null,\n compareAtPriceRange: {\n maxVariantCompareAtPrice,\n minVariantCompareAtPrice,\n },\n description: stripHtml(product.body_html),\n descriptionHtml: product.body_html,\n featuredImage: productImageObject(product, null),\n handle: product.handle,\n id: `gid://shopify/Product/${product.id}`,\n images: null,\n media: [],\n metafields: [],\n options: [\n ...product.options.map((option: any) => {\n return { name: option.name, values: option.values };\n }),\n ],\n priceRange: {\n maxVariantPrice,\n minVariantPrice,\n },\n selectedOptions,\n selectedSellingPlan: null,\n selectedSellingPlanAllocation: null,\n sellingPlanGroups: [],\n seo: { description: null, title: null },\n title: product.title,\n variants: convertToNodes(variants),\n vendor: product.vendor,\n };\n}\n\n/**\n * Converts an array to a nodes object.\n *\n * @param {any} arr - The array to convert to a nodes object.\n *\n * @returns {any} The nodes object.\n */\nexport function convertToNodes(arr: any): any {\n return {\n edges: [\n ...arr.map((node: any) => {\n return { node };\n }),\n ],\n };\n}\n\n/**\n * Converts a variant to the storefront format.\n *\n * @param {any} product - The product.\n * @param {any} variant - The variant.\n *\n * @returns {any} The variant in the storefront format.\n */\nexport function convertVariantToStorefrontFormat(product: any, variant: any): any {\n const selectedOptions = selectedVariantOptions(product, variant);\n const image = productImageObject(product, variant.image_id);\n\n return {\n availableForSale: variantAvailable(variant),\n compareAtPriceV2: variantPriceObject(variant, 'compare_at_price'),\n id: `gid://shopify/ProductVariant/${variant.id}`,\n image: image,\n priceV2: variantPriceObject(variant, 'price'),\n product: {\n handle: product.handle,\n id: product.id,\n title: product.title,\n vendor: product.vendor,\n },\n selectedOptions: [selectedOptions],\n sku: variant.sku,\n title: variant.title,\n };\n}\n\n/**\n * Returns the minimum or maximum price object for a variant.\n *\n * @param {any} product - The product.\n * @param {string} key - The key to get the price object for.\n * @param {string} operator - The operator to use. *\n *\n * @returns {any} The price object.\n */\nexport function variantMinMaxPriceObject(product: any, key: string = 'price', operator: string = 'min'): any {\n let priceObject = variantPriceObject(product.variants[0], key);\n\n for (let i = 0; i < product.variants.length; i++) {\n const variantPrice = variantPriceObject(product.variants[i], key);\n\n if (variantPrice != null) {\n const variantPriceAmount = Number(variantPrice.amount);\n const currentPriceAmount = priceObject != null ? Number(priceObject.amount) : null;\n\n if (\n currentPriceAmount == null ||\n (operator === 'min' && variantPriceAmount < currentPriceAmount) ||\n (operator === 'max' && variantPriceAmount > currentPriceAmount)\n ) {\n priceObject = variantPrice;\n }\n }\n }\n\n return priceObject;\n}\n\n/**\n * Returns the price object for a variant.\n *\n * @param {any} variant - The variant.\n * @param {string} key - The key to get the price object for.\n *\n * @returns {any} The price object.\n */\nexport function variantPriceObject(variant: any, key: string = 'price'): any {\n if (variant[key] != null) {\n return {\n amount: variant[key],\n currencyCode: 'USD',\n };\n }\n\n return null;\n}\n\n/**\n * Returns the selected variant options.\n *\n * @param {any} product - The product.\n * @param {any} variant - The variant.\n *\n * @returns {any} The selected variant options.\n */\nexport function selectedVariantOptions(product: any, variant: any): any {\n const selectedOptions: Record<string, any> = {};\n\n if (variant.option1 != null) {\n selectedOptions[product.options[0].name] = variant.option1;\n }\n\n if (variant.option2 != null) {\n selectedOptions[product.options[1].name] = variant.option2;\n }\n\n if (variant.option3 != null) {\n selectedOptions[product.options[2].name] = variant.option3;\n }\n\n return selectedOptions;\n}\n\n/**\n * Returns the product image object.\n *\n * @param {any} product - The product.\n * @param {number | null} id - The ID of the image. *\n *\n * @returns {any} The product image object.\n */\nexport function productImageObject(product: any, id: number | null): any {\n let image = null;\n\n if (product.image) {\n image = {\n altText: product.image.alt,\n height: product.image.height,\n id: `gid://shopify/ProductImage/${product.image.id}`,\n url: product.image.src,\n width: product.image.width,\n };\n }\n\n if (product.images && product.images.length > 0 && id != null) {\n const matchingImage = product.images.find((i: any) => i.id === id);\n\n if (matchingImage) {\n image = {\n altText: matchingImage.alt,\n height: matchingImage.height,\n id: `gid://shopify/ProductImage/${matchingImage.id}`,\n url: matchingImage.src,\n width: matchingImage.width,\n };\n }\n }\n\n return image;\n}\n\n/**\n * Returns a query string as an object.\n *\n * @param {string} str - The query string to convert to an object.\n *\n * @returns {any} The object.\n */\nexport function queryStringToObject(str: string): any {\n const params = new URLSearchParams(str);\n\n return Object.fromEntries(params.entries());\n}\n\n/**\n * Returns a UTM object from a string.\n *\n * @param {string} str - The string to convert to a UTM object.\n *\n * @returns {any} The UTM object.\n */\nexport function utmObjectFromString(str: string): any {\n const utmKeys = ['utm_campaign', 'utm_medium', 'utm_source', 'utm_term', 'utm_content'];\n\n const matches: Record<string, any> = {};\n\n const url = new URL(str);\n const queryObject = queryStringToObject(url.search);\n\n for (const [key, value] of Object.entries(queryObject)) {\n if (utmKeys.includes(key)) {\n matches[key] = value;\n }\n }\n\n return Object.keys(matches).length > 0 ? matches : null;\n}\n\n/**\n * Returns the amount in cents.\n *\n * @param {number} amount - The amount to convert to cents.\n *\n * @returns {number} The amount in cents.\n */\nexport function amountToCents(amount: number | string): number {\n let normalizedAmount: number = 0;\n\n if (typeof amount === 'string') {\n if (amount.indexOf('.') !== -1) {\n normalizedAmount = Math.round(parseFloat(amount) * 100);\n } else {\n normalizedAmount = parseInt(amount, 10);\n }\n } else if (typeof amount === 'number') {\n normalizedAmount = Math.round(amount * 100);\n }\n\n if (isNaN(normalizedAmount)) {\n normalizedAmount = 0;\n }\n\n return normalizedAmount;\n}\n\n/**\n * Serializes an object.\n *\n * @param {Record<string, unknown>} obj - The object to serialize.\n *\n * @returns {string} The serialized object.\n */\nexport function serialize(obj: Record<string, unknown>): string {\n const serialized: string[] = [];\n\n const add = (key: string, value: any) => {\n value = typeof value === 'function' ? value() : value;\n value = value === null ? '' : value === undefined ? '' : value;\n serialized[serialized.length] = encodeURIComponent(key) + '=' + encodeURIComponent(value);\n };\n\n const buildParameters = (prefix: string, obj: any) => {\n let i, key, len;\n\n if (prefix) {\n if (Array.isArray(obj)) {\n for (i = 0, len = obj.length; i < len; i++) {\n buildParameters(prefix + '[' + (typeof obj[i] === 'object' && obj[i] ? i : '') + ']', obj[i]);\n }\n } else if (Object.prototype.toString.call(obj) === '[object Object]') {\n for (key in obj) {\n buildParameters(prefix + '[' + key + ']', obj[key]);\n }\n } else {\n add(prefix, obj);\n }\n } else if (Array.isArray(obj)) {\n for (i = 0, len = obj.length; i < len; i++) {\n add(obj[i].name, obj[i].value);\n }\n } else {\n for (key in obj) {\n buildParameters(key, obj[key]);\n }\n }\n\n return serialized;\n };\n\n return buildParameters('', obj).join('&');\n}\n", "import { RuleVerdict } from '~/schema/metadata';\nimport { OfferProduct } from '~/schema/offerProduct';\n\nimport {\n type DataSourceInput,\n NotFoundError,\n type ServerContext,\n type ServerDrift,\n UpstreamError,\n} from '~/server/shared';\nimport { fetchUserConfig } from '~/server/userConfig';\nimport { deepCamelCase } from '~/transforms';\nimport { serialize } from '~/utilities';\n\ntype Reporter = (event: ServerDrift) => void;\n\nexport type DataSourceResults = {\n metadata: unknown;\n products: unknown[];\n /**\n * The shop's base-currency ISO code (from the already-resolved shop config), so the client can derive\n * the shop minor-unit exponent and forecast a Functions fixed discount exactly in a cross-decimal market.\n * Undefined when the engine omits it \u2014 the client then falls back to the buyer currency's decimals.\n */\n shopCurrency?: string;\n};\n\n/**\n * Encode a key/value list the way the engine expects (React `getEncodedAttributes`): a `{key: value}` object,\n * JSON-stringified, then URL-encoded ONCE here. `serialize()` URL-encodes the whole value again when it builds\n * the query string, so the wire is double-encoded \u2014 matching what the SmartCart SDK sends (`cart[attributes]=%257B%257D`).\n */\nconst encodeAttributes = (pairs: { key: string; value?: string }[] = []): string =>\n encodeURIComponent(JSON.stringify(Object.fromEntries(pairs.map(({ key, value }) => [key, value ?? '']))));\n\n/**\n * Translate the camelCase input into the legacy engine's contract: snake_case keys, PHP-bracket query\n * serialization, derived aggregates (item/line counts, id CSVs), and the shop's publishable key. The\n * extension never carries any of this.\n */\nexport const buildEngineParams = (input: DataSourceInput, key: string): Record<string, unknown> => {\n const { cart, customerId, filterInputs, integrations, limit, productType, shop, visitorId } = input;\n\n const items = cart.items.map(({ productId, properties, quantity, subscriptionId, variantId }) => ({\n product_id: productId,\n properties: encodeAttributes(properties),\n quantity,\n ...(subscriptionId && { subscription_id: subscriptionId }),\n variant_id: variantId,\n }));\n\n const itemCount = cart.items.reduce((total, { quantity }) => total + quantity, 0);\n\n /**\n * Rule thresholds are authored in SHOP currency and evaluate against actual spend: subtract\n * cart-level discounts (React `useSearchParams`), then divide out the presentment FX rate (onsite\n * `convertToShopCurrency`). A missing or degenerate rate means the cart is already shop-currency.\n *\n * `subtotal`/`discountTotal` arrive in the buyer's presentment currency as integer minor units\n * (the \u00D7100 Shopify-cents convention the client sends); `currencyRate` is a MAJOR-unit ratio\n * (presentment \u00F7 shop). Dividing minor-unit presentment by the major-unit rate yields shop minor\n * units \u2014 the \u00D7100 cancels dimensionally, for any currency (e.g. \u00A5735000 \u00F7 147 = 5000\u00A2). Getting the\n * unit of one side wrong is the #117 class; keep both sides minor-vs-major as documented here.\n */\n const currencyRate = cart.currencyRate ?? 1;\n const rate = Number.isFinite(currencyRate) && currencyRate > 0 ? currencyRate : 1;\n const subtotal = Math.round((cart.subtotal - (cart.discountTotal ?? 0)) / rate);\n\n return {\n cart: {\n attributes: encodeAttributes(cart.attributes),\n /** `discount_code` rules match against this; React sends raw `useDiscountCodes()` as `[{code}]`. */\n ...(cart.discountCodes?.length && { discount_codes: cart.discountCodes.map((code) => ({ code })) }),\n item_count: itemCount,\n items,\n line_count: items.length,\n subtotal,\n },\n cart_count: items.length,\n cart_item_count: itemCount,\n cart_line_count: items.length,\n cart_subtotal: subtotal,\n ...(filterInputs && { filter_inputs: filterInputs }),\n key,\n limit,\n metafields: Object.values(integrations ?? {}).some(Boolean) ? 'yes' : 'no',\n // Only subscription-bearing product types request selling-plan data; absent/one-time send 'no'\n // to match the legacy engine contract (an absent `productType` must not opt a widget into plans).\n selling_plans: productType === 'subscription' || productType === 'both' ? 'yes' : 'no',\n shop,\n ...(customerId && { shopify_customer_id: customerId }),\n shopify_product_ids: items.map(({ product_id: id }) => id).join(','),\n shopify_variant_ids: items.map(({ variant_id: id }) => id).join(','),\n ...(visitorId && { uuid: visitorId }),\n };\n};\n\n/**\n * Keep an engine product only when it has the shape `toProduct` needs (options/variants present, prices\n * readable). One product missing them would throw and take the whole offers rail down; dropping it with a\n * drift signal costs one card instead. The valid product passes through as-is (extra engine fields intact).\n */\nconst keepValidProduct = (product: unknown, report?: Reporter): boolean => {\n const parse = OfferProduct.safeParse(product);\n\n if (parse.success) return true;\n\n /**\n * Name the first drifted field (e.g. `variants`) so ops can tell a missing-options product from an\n * unreadable-price one. Built by joining the first issue path in \u2014 an empty issues list (never emitted\n * by a failed zod parse) degrades to the bare message rather than throwing.\n */\n const detail = [\n 'offer product failed validation',\n ...parse.error.issues.slice(0, 1).map((issue) => issue.path.join('.')),\n ].join(': ');\n\n report?.({ detail, kind: 'product' });\n\n return false;\n};\n\n/** A definitive GWP rule answer (`matchedRules`/`unmatchedRules`) \u2014 the OTHER `limit: 0` metadata shape. */\nconst isRuleAnswer = (metadata: Record<string, unknown>): boolean =>\n metadata.matchedRules != null || metadata.unmatchedRules != null;\n\n/**\n * At `limit: 0` the metadata is either a rule-gating verdict (`custom.shouldShow`) or a GWP rule answer.\n * A non-null verdict-shaped payload that carries NEITHER a readable `shouldShow` NOR rule arrays means the\n * engine's verdict contract drifted \u2014 which would otherwise hide every gated section fleet-wide with no\n * signal. Emit a distinguishable drift so ops can tell it from a rule legitimately evaluating false.\n */\nconst reportUnreadableVerdict = (metadata: unknown, report?: Reporter): void => {\n if (metadata == null || typeof metadata !== 'object' || Array.isArray(metadata)) return;\n\n if (RuleVerdict.safeParse(metadata).success || isRuleAnswer(metadata as Record<string, unknown>)) return;\n\n report?.({ detail: 'rule verdict lacks readable custom.shouldShow', kind: 'ruleVerdict' });\n};\n\n/** Engine responses can repeat a product across rule outputs; first one wins. */\nconst dedupeById = (products: unknown[]): unknown[] => {\n const seen = new Set<unknown>();\n\n return products.filter((product) => {\n const id = (product as { id?: unknown }).id;\n\n if (seen.has(id)) return false;\n\n seen.add(id);\n\n return true;\n });\n};\n\n/**\n * Evaluates a data source against the live cart: resolves the shop's publishable key, GETs the engine\n * endpoint with the translated params, and returns camelCased, id-deduplicated products plus rule\n * metadata. `limit: 0` returns metadata only.\n */\nexport const fetchDataSourceResults = async (\n input: DataSourceInput,\n ctx: ServerContext\n): Promise<DataSourceResults> => {\n const { shop } = await fetchUserConfig({ shop: input.shop }, ctx);\n\n let upstream: unknown;\n\n try {\n upstream = await ctx.fetchUpstream(\n `/api/v1${input.dataSourcePath}`,\n {},\n { host: ctx.host, search: serialize(buildEngineParams(input, shop.apiKey)) }\n );\n } catch (err) {\n if (err instanceof UpstreamError && (err.status === 404 || err.status === 410)) {\n throw new NotFoundError(`Data source not found: ${input.dataSourcePath}`);\n }\n\n throw err;\n }\n\n const raw = upstream && typeof upstream === 'object' ? (upstream as { data?: unknown; metadata?: unknown }) : {};\n const rawProducts = Array.isArray(raw.data) ? (deepCamelCase(raw.data) as unknown[]) : [];\n const metadata = raw.metadata == null ? null : deepCamelCase(raw.metadata);\n\n if (input.limit === 0) reportUnreadableVerdict(metadata, ctx.reportDrift);\n\n return {\n metadata,\n products: dedupeById(rawProducts.filter((product) => keepValidProduct(product, ctx.reportDrift))),\n shopCurrency: shop.currency,\n };\n};\n", "import { v7 as uuidv7 } from 'uuid';\n\nimport { sectionTypes } from '~/schema/widgets/checkout-and-beyond/common';\nimport { CABRootSection } from '~/schema/widgets/checkout-and-beyond/root';\nimport { CABSection } from '~/schema/widgets/checkout-and-beyond/shared';\nimport { type ServerDrift } from '~/server/shared';\n\n/**\n * Parse orchestration, deliberately independent of the schema shapes it calls (so R3's zod-v4 getter\n * migration leaves it untouched): a whole-tree `CABRootSection.parse` makes ONE unknown/invalid section\n * fatal to the entire widget, and the client's graceful `UnknownSection` rail \u2014 which renders an\n * unrecognized `sectionType` as `null` \u2014 never gets the chance to run because the server 500s first.\n * Salvaging per section instead lets one bad section cost one section.\n */\n\ntype Reporter = (event: ServerDrift) => void;\n\n/** A section this build won't recognize, so the client dispatches it to `null` (maintainer choice over drop). */\nconst STUB_SECTION_TYPE = 'unknown';\n\nconst knownSectionTypes = new Set<string>(sectionTypes);\n\nconst hasSectionsArray = (raw: unknown): raw is { sections: unknown[] } =>\n typeof raw === 'object' && raw !== null && Array.isArray((raw as { sections?: unknown }).sections);\n\n/**\n * The non-renderable replacement for an unsalvageable section. A genuinely unknown `sectionType` is\n * preserved so the client's `unknown-section` analytics report the real drift; a known-but-invalid one\n * (bad data under a recognized type) is masked behind the sentinel so the client can't try to render it.\n */\nconst stubSection = (raw: unknown, report?: Reporter): { sectionId: string; sectionType: string } => {\n const record = typeof raw === 'object' && raw !== null ? (raw as Record<string, unknown>) : {};\n const original = record.sectionType;\n const rawId = record.sectionId;\n\n report?.({\n detail: `invalid section (${typeof original === 'string' ? original : 'no sectionType'})`,\n kind: 'section',\n });\n\n return {\n sectionId: typeof rawId === 'string' && rawId ? rawId : uuidv7(),\n sectionType: typeof original === 'string' && !knownSectionTypes.has(original) ? original : STUB_SECTION_TYPE,\n };\n};\n\n/**\n * Salvage one section: a section that parses whole is kept (defaults hydrated); a container whose own\n * fields are valid is rebuilt from its parsed shell with each child salvaged individually (so a bad\n * grandchild costs the grandchild, not the whole container); anything else becomes a stub. The shell is\n * recovered against the discriminated union \u2014 dispatched by the section's OWN `sectionType` to the matching\n * member (`offers`/`carousel`/`products`/\u2026 not always `layout`), so a drifted grandchild in a non-layout\n * rail no longer sinks the whole rail to a null-rendering stub.\n */\nconst salvageSection = (raw: unknown, report?: Reporter): unknown => {\n const parsed = CABSection.safeParse(raw);\n\n if (parsed.success) return parsed.data;\n\n if (hasSectionsArray(raw)) {\n const shell = CABSection.safeParse({ ...raw, sections: [] });\n\n if (shell.success)\n return { ...shell.data, sections: raw.sections.map((child) => salvageSection(child, report)) };\n }\n\n return stubSection(raw, report);\n};\n\n/**\n * Salvage-parse a v2-authored CAB tree: hydrate the root's own fields, then salvage each section. A root\n * whose OWN fields are invalid (not just its children) still throws \u2014 a fundamentally broken widget is a\n * real error, whereas section-level drift degrades gracefully.\n */\nexport const salvageRootSection = (raw: unknown, report?: Reporter): unknown => {\n const shell = CABRootSection.safeParse(hasSectionsArray(raw) ? { ...raw, sections: [] } : raw);\n\n if (!shell.success) return CABRootSection.parse(raw);\n\n const sections = hasSectionsArray(raw) ? raw.sections.map((child) => salvageSection(child, report)) : [];\n\n return { ...shell.data, sections };\n};\n", "import { type SmartCartBar } from '~/schema/smartCart';\nimport { SectionType } from '~/schema/widgets/checkout-and-beyond/common';\n\nimport { salvageRootSection } from '~/server/salvageSections';\nimport {\n NotFoundError,\n type ServerContext,\n type ServerDrift,\n UpstreamError,\n type WidgetSettingsInput,\n} from '~/server/shared';\nimport { fetchUserConfig } from '~/server/userConfig';\nimport {\n convertContentBlockToV2,\n convertLineItemEditorToV2,\n convertNumericObjects,\n convertOfferToV2,\n convertProgressBarToV2,\n convertSmartCartProgressBarToV2,\n deepCamelCase,\n extractSmartCartBars,\n isCABRootSection,\n isContentBlockV1,\n isConvertibleProgressBarV1,\n isLineItemEditorV1,\n isOfferV1,\n isProgressBarV1,\n normalizeTextContent,\n} from '~/transforms';\nimport { resolveExperiment, type ResolvedExperiment } from '~/transforms/experiments/resolveExperiment';\n\nconst unwrapData = (body: unknown): unknown =>\n body && typeof body === 'object' && 'data' in body ? (body as { data: unknown }).data : body;\n\n/**\n * The legacy shielded CDN returns `200 { data: null }` (or `{ data: {} }`) for deleted/missing widgets \u2014\n * it doesn't emit `404`. Treat both shapes as \"widget not found\".\n */\nconst isMissingUpstreamPayload = (data: unknown): boolean =>\n data == null || (typeof data === 'object' && !Array.isArray(data) && Object.keys(data as object).length === 0);\n\n/**\n * Routes a normalized (camelCased + numeric-fixed) upstream payload to the right transform by shape:\n * `version: 2` \u2192 CAB parse; a v1 content block \u2192 `convertContentBlockToV2`; a v1 line-item editor \u2192\n * `convertLineItemEditorToV2`; a v1 offer (`type: shopify_checkout_extension`, checked LAST \u2014 it has no\n * `version` discriminator) \u2192 `convertOfferToV2`. Progress bars route in {@link convertWidgetSettings}\n * (their conversion needs an async theme fetch). Every other widget type passes through unchanged \u2014 its\n * converter slots in here in the phase that introduces it.\n */\nconst dispatchWidgetTransform = (id: number, normalized: unknown, report?: (event: ServerDrift) => void): unknown => {\n if (isCABRootSection(normalized)) return salvageRootSection(normalizeTextContent(normalized), report);\n\n if (isContentBlockV1(normalized)) return convertContentBlockToV2({ id, settings: normalized });\n\n if (isLineItemEditorV1(normalized)) return convertLineItemEditorToV2({ id, settings: normalized });\n\n if (isOfferV1(normalized)) return convertOfferToV2({ id, name: normalized.name, settings: normalized });\n\n return normalized;\n};\n\n/**\n * The shop config + theme-derived bar fill color, degraded independently: a config-fetch failure \u21D2 `{}`\n * (no config \u21D2 no bars), guarded on its own; the theme color is best-effort ({@link fetchThemeColor}\n * self-catches to `undefined`) so a theme failure yields a colorless-but-present bar and can NEVER drop\n * the bars. A progress bar must never 404 the widget or break checkout.\n */\nconst fetchProgressBarContext = async (\n shop: string,\n ctx: ServerContext\n): Promise<{ bars?: SmartCartBar[]; progressColor?: string }> => {\n const config = await fetchUserConfig({ shop }, ctx).catch(() => undefined);\n\n if (!config) return {};\n\n return {\n bars: extractSmartCartBars(config.smartCart),\n progressColor: await fetchThemeColor(config.shop.shopId, ctx),\n };\n};\n\n/** The shop theme's `buttonBackground` \u2014 the bar fill React reads (`useRebuyTheme`); undefined on any failure. */\nconst fetchThemeColor = async (shopId: number | undefined, ctx: ServerContext): Promise<string | undefined> => {\n if (!shopId) return undefined;\n\n try {\n const theme = await ctx.fetchUpstream(`/admin/api/v1/shop/theme/${shopId}`, {}, { host: ctx.host });\n const color = (theme as { theme?: { settings?: { buttonBackground?: unknown } } }).theme?.settings\n ?.buttonBackground;\n\n return typeof color === 'string' && color ? color : undefined;\n } catch {\n return undefined;\n }\n};\n\ntype WalkableSection = { progressColor?: string; sections?: unknown[]; sectionType?: string };\n\n/**\n * Depth-first: the progress-bar sections of a parsed tree that lack an explicit fill color \u2014 the ones\n * whose color falls back to the live shop theme.\n */\nconst colorlessProgressBars = (section: WalkableSection): WalkableSection[] => {\n const own = section.sectionType === SectionType.progressBar && section.progressColor === undefined;\n const nested = (section.sections ?? []).flatMap((child) => colorlessProgressBars(child as WalkableSection));\n\n return own ? [section, ...nested] : nested;\n};\n\n/**\n * Fetch ONE widget's raw settings from the engine and convert them to a CAB section tree (or pass a\n * non-CAB widget through). Throws {@link NotFoundError} for deleted/missing widgets. `id` may be the\n * requested widget or an A/B-selected variant element; the rest of the params are shop-scoped.\n */\nconst fetchAndConvert = async (id: number, input: WidgetSettingsInput, ctx: ServerContext): Promise<unknown> => {\n const params: Record<string, string> = { id: String(id), shop: input.shop };\n\n if (input.cacheKey != null) params.cache_key = String(input.cacheKey);\n\n if (input.key) params.key = input.key;\n\n let upstream: unknown;\n\n try {\n upstream = await ctx.fetchUpstream('/api/v1/widgets/settings', params, { host: ctx.host });\n } catch (err) {\n // The legacy controller returns 4xx (e.g. 400 \"Invalid widget ID (probably deleted)\") for missing\n // widgets; treat any 4xx as \"not found\" \u2014 malformed input is already blocked upstream by Zod.\n if (err instanceof UpstreamError && err.status >= 400 && err.status < 500) {\n throw new NotFoundError(`Widget not found: ${id}`);\n }\n\n throw err;\n }\n\n const data = unwrapData(upstream);\n\n if (isMissingUpstreamPayload(data)) throw new NotFoundError(`Widget not found: ${id}`);\n\n const normalized = convertNumericObjects(deepCamelCase(data));\n\n /**\n * Smart-cart bars carry only `barType` in their widget settings \u2014 the tiers live in the shop's\n * smart-cart config (a second fetch through the same injected upstream). Both bar types also pull\n * the theme's bar fill color. Degrade on any config/theme failure: a non-critical progress bar must\n * never 404 the widget or break checkout.\n */\n if (isProgressBarV1(normalized) && normalized.barSettings.barType === 'smart-cart') {\n const { bars, progressColor } = await fetchProgressBarContext(input.shop, ctx);\n\n return convertSmartCartProgressBarToV2({ bars: bars ?? [], id, progressColor, settings: normalized });\n }\n\n /** Shipping bars carry their full config in the widget settings; only the fill color needs the shop. */\n if (isConvertibleProgressBarV1(normalized)) {\n const { progressColor } = await fetchProgressBarContext(input.shop, ctx);\n\n return convertProgressBarToV2({ id, progressColor, settings: normalized });\n }\n\n const converted = dispatchWidgetTransform(id, normalized, ctx.reportDrift);\n\n /**\n * v2-authored trees: an explicit `progressColor` is used verbatim; a bar without one gets the live\n * theme color (the same fallback the v1 conversion above applies), fetched once per widget.\n */\n const colorless = isCABRootSection(normalized) ? colorlessProgressBars(converted as WalkableSection) : [];\n\n if (colorless.length > 0) {\n const { progressColor: color } = await fetchProgressBarContext(input.shop, ctx);\n\n if (color) for (const bar of colorless) bar.progressColor = color;\n }\n\n return converted;\n};\n\n/**\n * The sticky A/B variant for the requested widget, or `undefined` when none targets it / no visitor id.\n * Experiments are non-critical: any failure resolving the shop config degrades to \"no experiment\" rather\n * than breaking the widget.\n */\nconst resolveWidgetExperiment = async (\n input: WidgetSettingsInput,\n ctx: ServerContext\n): Promise<ResolvedExperiment | undefined> => {\n if (!input.visitorId) return undefined;\n\n try {\n const { shop } = await fetchUserConfig({ shop: input.shop }, ctx);\n\n return resolveExperiment(shop.activeExperiments, input.id, input.visitorId);\n } catch {\n return undefined;\n }\n};\n\n/**\n * A converted result is a CAB tree (vs a passed-through non-CAB widget) when it carries `version: 2`.\n * `fetchAndConvert` always returns a non-null object (or throws), so reading `.version` is safe here.\n */\nconst isCABTree = (result: unknown): result is { version: number } => (result as { version?: unknown }).version === 2;\n\n/**\n * Resolve a widget's CAB section tree, applying server-side A/B selection: when the requested widget is\n * an experiment placeholder and a `visitorId` is supplied, the sticky-chosen variant's tree is fetched\n * instead and the experiment metadata is attached for the client's analytics. Without an experiment this\n * is a plain fetch-and-convert. Throws {@link NotFoundError} for deleted/missing widgets.\n */\nexport const convertWidgetSettings = async (input: WidgetSettingsInput, ctx: ServerContext): Promise<unknown> => {\n const experiment = await resolveWidgetExperiment(input, ctx);\n const result = await fetchAndConvert(experiment?.elementId ?? input.id, input, ctx);\n\n /** Only CAB trees can carry the experiment; a passed-through variant renders without A/B analytics. */\n return experiment && isCABTree(result) ? { ...result, experiment } : result;\n};\n", "import { type MatchedRule } from '~/gwp/types';\n\n/**\n * The product ids a widget's matched rules currently qualify \u2014 ported from the React\n * extension's `getValidGwpProductIds` (camelCased engine shape). A gift whose product is\n * not in this set no longer qualifies and should be removed.\n */\nexport const getValidGwpProductIds = (matchedRules: MatchedRule[] = []): Set<number> =>\n new Set(\n matchedRules\n .flatMap((rule) => rule.output ?? [])\n .flatMap((output) => output.products ?? [])\n .map((product) => Number(product.productId))\n .filter((id) => Number.isFinite(id))\n );\n", "import { type GwpMetadata, type MatchedRule } from '~/gwp/types';\n\n/**\n * Rule types the engine can't evaluate correctly in the cart/data-source context (no page URL,\n * no order) \u2014 ported from the React extension. When a widget's rules use these, the matched output\n * is unreliable, so the validator must NOT remove the gift.\n */\nconst UNSUPPORTED_RULE_TYPES = ['url', 'order_tag'];\n\nconst ruleHasUnsupportedType = (rule: MatchedRule): boolean =>\n (rule.logic ?? []).some((group) =>\n (group.rules ?? []).some((item) => UNSUPPORTED_RULE_TYPES.includes(item.type ?? ''))\n );\n\n/**\n * Whether any matched OR unmatched rule uses an unsupported type \u2014 the bail signal: the gift's\n * qualification can't be trusted, so keep it (never remove on uncertainty).\n */\nexport const hasUnsupportedRuleTypes = (metadata?: GwpMetadata | null): boolean =>\n [...(metadata?.matchedRules ?? []), ...(metadata?.unmatchedRules ?? [])].some(ruleHasUnsupportedType);\n", "import { type GwpMetadata } from '~/gwp/types';\n\n/**\n * Whether the engine metadata is a definitive rule answer the validator may act on. Removal is only\n * safe downstream of a parsed 2xx that actually evaluated rules (onsite-js standard: every degraded\n * path is a no-op): metadata missing entirely \u2014 the tolerated-empty-2xx path \u2014 or carrying NEITHER\n * `matchedRules` NOR `unmatchedRules` is uncertainty, so keep the gifts. `matchedRules: []` alongside\n * `unmatchedRules` IS definitive \u2014 the engine answered and nothing qualifies.\n */\nexport const isDefinitiveRuleAnswer = (metadata?: GwpMetadata | null): metadata is GwpMetadata =>\n metadata != null && (metadata.matchedRules != null || metadata.unmatchedRules != null);\n", "import { type GwpGift } from '~/gwp/types';\n\n/**\n * Whether a gift line should be removed: either its product no longer qualifies (\u2209 `validIds`),\n * OR it lost its Shopify Function discount (`!discounted && cost > 0`). The Function can't remove\n * a line it failed to discount, so the client must \u2014 this is the complete removal decision the\n * server returns as a receipt (see the rebuy-discount-architecture / GWP E2 notes).\n */\nexport const shouldRemoveGift = (\n gift: Pick<GwpGift, 'cost' | 'discounted' | 'productId'>,\n validIds: Set<number>\n): boolean => !validIds.has(gift.productId) || (!gift.discounted && gift.cost > 0);\n", "import {\n getValidGwpProductIds,\n type GwpMetadata,\n hasUnsupportedRuleTypes,\n isDefinitiveRuleAnswer,\n shouldRemoveGift,\n} from '~/gwp';\n\nimport { fetchDataSourceResults } from '~/server/dataSourceResults';\nimport { type GiftInput, type GiftValidationInput, type ServerContext } from '~/server/shared';\nimport { deepCamelCase } from '~/transforms';\n\n/** A widget's data-source path from its RAW settings `endpoint` (uniform across widget types). */\nconst resolveDataSourcePath = async (\n widgetId: number,\n shop: string,\n ctx: ServerContext\n): Promise<string | undefined> => {\n const raw = await ctx.fetchUpstream('/api/v1/widgets/settings', { id: String(widgetId), shop }, { host: ctx.host });\n const data = raw && typeof raw === 'object' && 'data' in raw ? (raw as { data: unknown }).data : raw;\n /** A deleted widget returns `{ data: null }`; `deepCamelCase(null)` is null, so guard the read (fail-open by design, not by a lucky TypeError). */\n const endpoint = (deepCamelCase(data) as { endpoint?: unknown } | null)?.endpoint;\n\n return typeof endpoint === 'string' && endpoint ? endpoint : undefined;\n};\n\nconst groupByWidget = (gifts: GiftInput[]): Map<number, GiftInput[]> => {\n const byWidget = new Map<number, GiftInput[]>();\n\n for (const gift of gifts) {\n byWidget.set(gift.widgetId, [...(byWidget.get(gift.widgetId) ?? []), gift]);\n }\n\n return byWidget;\n};\n\n/**\n * Validates gift lines per widget and returns the cart-line ids to remove (the complete receipt).\n * Per widget: resolve its data-source path, evaluate its rules against the cart (`limit: 0`), then\n * drop gifts that no longer qualify OR lost their discount. **Fail-safe**: any error, a missing\n * endpoint, a non-definitive rule answer (no metadata, or metadata with neither rule array \u2014 the\n * tolerated-empty-2xx path), or unsupported rule types (`url`/`order_tag`) \u2192 skip that widget (never\n * remove on uncertainty). A definitive answer that omits a gift \u2014 even `matchedRules: []` \u2014 removes it.\n *\n * **Every degraded path is a no-op by design** \u2014 this includes the discount-lost case (a gift whose\n * Function discount lapsed, so the buyer is being charged). React removed that on any successful fetch;\n * here it too is gated behind a definitive rule answer, so under a degraded response the gift stays and the\n * buyer may keep paying. Deliberate: falsely removing a genuinely-qualified gift is judged worse than\n * briefly leaving a lapsed-discount gift, and the client re-validates on the next cart change.\n */\nexport const validateGifts = async (input: GiftValidationInput, ctx: ServerContext): Promise<{ remove: string[] }> => {\n const perWidget = await Promise.all(\n [...groupByWidget(input.gifts)].map(async ([widgetId, gifts]) => {\n try {\n const dataSourcePath = await resolveDataSourcePath(widgetId, input.shop, ctx);\n\n if (!dataSourcePath) return [];\n\n const { metadata } = await fetchDataSourceResults(\n {\n cart: input.cart,\n customerId: input.customerId,\n dataSourcePath,\n /** The gift being validated is in the cart \u2014 input filtering would erase it from the answer. */\n filterInputs: 'no',\n /**\n * `limit: 0` fetches NO products \u2014 only the rule verdict is needed. Safe because the engine\n * derives `matchedRules` from rule-config evaluation, not from fetched results (traced through\n * `api.php`), so the metadata is complete at limit 0. Don't raise it to \"fix\" a non-bug.\n */\n limit: 0,\n shop: input.shop,\n visitorId: input.visitorId,\n },\n ctx\n );\n\n const meta = (metadata ?? undefined) as GwpMetadata | undefined;\n\n if (!isDefinitiveRuleAnswer(meta) || hasUnsupportedRuleTypes(meta)) return [];\n\n const validIds = getValidGwpProductIds(meta.matchedRules);\n\n return gifts.filter((gift) => shouldRemoveGift(gift, validIds)).map((gift) => gift.lineId);\n } catch {\n return [];\n }\n })\n );\n\n return { remove: perWidget.flat() };\n};\n", "import { z } from 'zod';\n\nimport { type MonetizeInput, REBUY_ENGINE_HOST, type ServerContext } from '~/server/shared';\nimport { fetchUserConfig } from '~/server/userConfig';\n\n/** Ads-engine supply (SSP) keys \u2014 public identifiers picked by environment, not credentials. */\nconst SUPPLY_KEY = { production: 'AQF5RKLR', staging: 'Z56LQ7PS' } as const;\n\n/** The ads engine sizes for a handful of offers; the carousel + modal chain expect the same. */\nconst OFFER_LIMIT = 4;\n\n/**\n * Countries the public ad network is allowed to serve. The ad server's `AdRequest.Validate()` 400s any\n * `country_code` outside this set, so we hard-gate here (mirroring the extension's `isSupportedCountry`).\n */\nconst SUPPORTED_COUNTRIES = new Set(['US', 'CA']);\n\n/** Max `transaction_items` the engine accepts before it truncates; we cap first (React parity). */\nconst MAX_TRANSACTION_ITEMS = 50;\n\n/**\n * Rebuy QA's customer email \u2014 a checkout with it is flagged `testing` so the engine excludes it from\n * billing/reporting (mirrors admin-api's `RebuyMonetizeService::TEST_EMAIL`). Compared lower-cased.\n */\nconst TEST_CUSTOMER_EMAIL = 'test@rebuyengine.com';\n\n/** The ads `transaction_items` \u2014 rich per-line detail when the client sent it, else `{id, quantity}` from the cart. */\nconst transactionItems = (input: MonetizeInput): Record<string, number | string>[] =>\n (\n input.transactionItems?.map(({ id, priceCents, quantity, title, type }) => ({\n id,\n price_cents: priceCents,\n quantity,\n title,\n type,\n })) ?? input.cart.items.map(({ productId, quantity }) => ({ id: productId, quantity }))\n ).slice(0, MAX_TRANSACTION_ITEMS);\n\n/**\n * A single ads-engine offer. The `*_url` fields are tracking endpoints the engine returns fully\n * built (impression/decline/click) \u2014 the composer wires them onto the card verbatim.\n */\nexport const AdsEngineOffer = z.object({\n click_url: z.string(),\n cta: z.string(),\n /** `omitempty` on the ad server \u2014 a bid without it must not fail the parse and drop the whole batch (composeOffer falls back to 'No Thanks'). */\n decline_cta: z.string().catch(''),\n decline_url: z.string(),\n description: z.string(),\n headline: z.string(),\n id: z.string(),\n image_url: z.string().optional(),\n view_url: z.string(),\n});\n\nexport type AdsEngineOffer = z.infer<typeof AdsEngineOffer>;\n\n/**\n * Per-offer resilient: parse the batch as `unknown[]` then keep only the offers that validate, so one\n * offer missing a required field (e.g. `click_url`) drops itself rather than throwing away the whole batch.\n */\nconst AdsEngineResponse = z.object({\n offers: z\n .array(z.unknown())\n .default([])\n .transform((offers) =>\n offers.flatMap((offer) => {\n const result = AdsEngineOffer.safeParse(offer);\n\n return result.success ? [result.data] : [];\n })\n ),\n});\n\n/** The ads engine lives on the `offers.` subdomain of the resolved engine host. */\nconst adsHost = (host: string): string => `offers.${host}`;\n\n/**\n * True when the request should be flagged `testing` (kept out of billing/reporting): a non-prod\n * upstream, the client's editor/QA indicator, or Rebuy's QA customer email \u2014 React's staging-OR-editor-\n * OR-test-email fold, split so the environment half stays host-derived and the rest travel on the input.\n */\nexport const isTestingRequest = (input: MonetizeInput, isProduction: boolean): boolean =>\n !isProduction || !!input.testing || input.customerEmail?.toLowerCase() === TEST_CUSTOMER_EMAIL;\n\n/**\n * Translate the extension's context into the ads-engine query contract. Publisher/supply keys and the\n * testing flag are server-decided; `session_id` prefers the rolling session id (React parity), falling\n * back to the visitor id (truthy `||`, so an empty-string `sessionId` still yields the visitor id rather\n * than an empty `session_id` the ad server 400s on); cart lines become `transaction_items`/`transaction_total`\n * (total preferred over subtotal). Empty values are omitted.\n */\nexport const buildAdsParams = (\n input: MonetizeInput,\n publisherKey: string,\n supplyKey: string,\n testing: boolean,\n userAgent?: string,\n ipAddress?: string\n): Record<string, string> => {\n const items = transactionItems(input);\n\n return {\n limit: String(OFFER_LIMIT),\n placement: input.placement,\n publisher_key: publisherKey,\n supply_key: supplyKey,\n testing: String(testing),\n transaction_total: String(input.transactionTotal ?? input.cart.subtotal),\n ...(items.length > 0 && { transaction_items: JSON.stringify(items) }),\n ...(input.country && { country_code: input.country }),\n ...(input.currency && { currency_code: input.currency }),\n ...(input.customerEmail && { customer_email: input.customerEmail }),\n ...(input.customerId && { customer_id: input.customerId }),\n ...(input.customerFirstName && { first_name: input.customerFirstName }),\n ...(input.customerLastName && { last_name: input.customerLastName }),\n ...(input.language && { language: input.language }),\n ...(input.timezone && { timezone: input.timezone }),\n ...(input.transactionId && { transaction_id: input.transactionId }),\n ...(input.zipCode && { zip_code: input.zipCode }),\n ...(ipAddress && { ip_address: ipAddress }),\n ...((input.sessionId || input.visitorId) && { session_id: input.sessionId || input.visitorId! }),\n ...(userAgent && { user_agent: userAgent }),\n };\n};\n\n/**\n * Fetch live ad offers from the Rebuy ads engine. Resolves the shop's publisher key server-side (and\n * returns `[]` when the shop isn't enrolled \u2014 no ads, not an error). A non-prod upstream sends the\n * staging supply key; a non-prod/editor/QA-email request is flagged `testing` (excluded from billing).\n */\nexport const fetchAdsEngineOffers = async (input: MonetizeInput, ctx: ServerContext): Promise<AdsEngineOffer[]> => {\n /**\n * The ad server 400s an unsupported `country_code` or a request with no session id, so short-circuit\n * BEFORE `fetchUserConfig` (saving that upstream call too). `[]` means \"no offers\", never an error \u2014\n * the same hard gate the extension applies with `isSupportedCountry`.\n */\n if (!input.country || !SUPPORTED_COUNTRIES.has(input.country.toUpperCase())) return [];\n\n if (!(input.sessionId || input.visitorId)) return [];\n\n const { shop } = await fetchUserConfig({ shop: input.shop }, ctx);\n const publisherKey = shop.monetize?.publisherKey;\n\n if (!publisherKey) return [];\n\n const isProduction = ctx.host === REBUY_ENGINE_HOST;\n const supplyKey = isProduction ? SUPPLY_KEY.production : SUPPLY_KEY.staging;\n\n const upstream = await ctx.fetchUpstream(\n '/api/v1/offers',\n buildAdsParams(\n input,\n publisherKey,\n supplyKey,\n isTestingRequest(input, isProduction),\n ctx.userAgent,\n ctx.ipAddress\n ),\n { host: adsHost(ctx.host) }\n );\n\n return AdsEngineResponse.parse(upstream).offers;\n};\n", "import {\n ButtonAction,\n ButtonField,\n ButtonStyle,\n CABLayoutSection,\n type CABSection,\n SectionType,\n} from '~/schema/widgets/checkout-and-beyond';\n\nimport { type AdsEngineOffer } from '~/server/adsEngine';\nimport { type MonetizeInput } from '~/server/shared';\nimport { normalizeTextContent } from '~/transforms/normalizeTextContent';\n\n/** Empty engine CTA/decline labels fall back to these (React `normalizeAdsEngineOffer` parity). */\nconst ACCEPT_FALLBACK = 'Accept';\nconst DECLINE_FALLBACK = 'No Thanks';\n\n/** A button's visible label is a nested `text` slot tagged `buttonLabel`. */\nconst label = (text: string) => ({\n buttonField: ButtonField.buttonLabel,\n content: { en: text },\n sectionType: SectionType.text,\n});\n\n/** A plain-text content section (English ad copy \u2014 the engine speaks one language per placement). */\nconst text = (content: string) => ({ content: { en: content }, sectionType: SectionType.text });\n\n/** The Monetize header shop name: the shop's config carries none here, so derive it from the domain (React fallback). */\nconst shopName = (shop: string): string => shop.replace(/\\.myshopify\\.com$/, '') || 'store';\n\n/**\n * Compose one ads-engine offer into a renderable CAB card: a `layout` whose `viewUrl` is the\n * impression pixel, holding the (optional) image, the headline, the HTML body (coerced to Tiptap by\n * the text-content schema on parse), and the two CTA buttons. `acceptOffer` links out to the advertiser (`destinationUrl` = `click_url`,\n * which self-tracks); `declineOffer` fires the decline pixel (`trackingUrl`) and advances. Parsing\n * through the schema fills defaults (section ids, layout direction) and validates the shape.\n */\nexport const composeOfferCard = (offer: AdsEngineOffer, privacyPolicyUrl?: string): CABSection | undefined => {\n /** Ad copy can carry HTML \u2014 the canonical pipeline converts it to Tiptap BEFORE the parse. */\n const result = CABLayoutSection.safeParse(\n normalizeTextContent({\n sections: [\n ...(offer.image_url\n ? [\n {\n /** Image alt must be PLAIN \u2014 a DSP headline like `Get <b>50%</b> off` would trip the image NO_HTML refine and bleed fill; the visible `text(offer.headline)` still gets the HTML\u2192Tiptap pipeline. */\n altText: offer.headline.replace(/<[^>]*>/g, ''),\n sectionType: SectionType.image,\n source: offer.image_url,\n },\n ]\n : []),\n text(offer.headline),\n text(offer.description),\n {\n action: ButtonAction.acceptOffer,\n buttonStyle: ButtonStyle.primary,\n sections: [\n label(offer.cta || ACCEPT_FALLBACK),\n {\n buttonField: ButtonField.destinationUrl,\n content: { en: offer.click_url },\n sectionType: SectionType.text,\n },\n ],\n sectionType: SectionType.button,\n },\n {\n action: ButtonAction.declineOffer,\n buttonStyle: ButtonStyle.secondary,\n sections: [label(offer.decline_cta || DECLINE_FALLBACK)],\n sectionType: SectionType.button,\n trackingUrl: offer.decline_url,\n },\n /** Ad-unit Privacy Policy footer (compliance); a valid href is required for the Tiptap link mark. */\n ...(privacyPolicyUrl ? [text(`<a href=\"${privacyPolicyUrl}\">Privacy Policy</a>`)] : []),\n ],\n viewUrl: offer.view_url,\n })\n );\n\n /** A single un-composable offer (e.g. a malformed `image_url`) drops just itself, not the whole batch. */\n return result.success ? result.data : undefined;\n};\n\n/**\n * The Monetize header shown ABOVE the inline offer only (never inside the accept modal \u2014 same reason\n * React keeps it out of `RebuyMonetizeModal`): the concluded experiment's winning copy (\"Congratulations!\n * / Your {shop} purchase unlocked a bonus:\") plus the \"Order \u2026 Confirmed\" line. Composed server-side so\n * the extension renders it as ordinary localized content.\n */\nexport const composeMonetizeHeader = (input: MonetizeInput): CABSection =>\n CABLayoutSection.parse(\n normalizeTextContent({\n sections: [\n text('Congratulations!'),\n text(`Your ${shopName(input.shop)} purchase unlocked a bonus:`),\n text(input.orderName ? `Order ${input.orderName} Confirmed` : 'Order Confirmed'),\n ],\n })\n );\n", "import { type CABSection } from '~/schema/widgets/checkout-and-beyond';\n\nimport { fetchAdsEngineOffers } from '~/server/adsEngine';\nimport { composeMonetizeHeader, composeOfferCard } from '~/server/composeOffer';\nimport { type MonetizeInput, type ServerContext } from '~/server/shared';\n\n/** `header` is the inline chrome (experiment copy + order-confirmed line); present only when there's an offer. */\nexport type MonetizeOffers = { header?: CABSection; offers: CABSection[] };\n\n/**\n * The monetize-offers orchestrator: fetch live ad offers from the engine and compose each into a CAB\n * offer card the extension renders directly, plus the inline header chrome. Empty (no card, no header)\n * when the shop isn't ad-enrolled.\n */\nexport const fetchMonetizeOffers = async (input: MonetizeInput, ctx: ServerContext): Promise<MonetizeOffers> => {\n const offers = (await fetchAdsEngineOffers(input, ctx))\n .map((offer) => composeOfferCard(offer, input.privacyPolicyUrl))\n /** Drop any offer that failed to compose (safeParse \u2192 undefined) so one bad bid can't lose the batch. */\n .filter((card): card is CABSection => card !== undefined);\n\n return { offers, ...(offers.length > 0 && { header: composeMonetizeHeader(input) }) };\n};\n", "import { type AnalyticsEventInput, type AnalyticsInput, type ServerContext } from '~/server/shared';\nimport { fetchUserConfig } from '~/server/userConfig';\n\n/** The legacy engine's analytics event shape (`POST /api/v2/analytics/event/bulk`). */\ntype EngineEvent = {\n aggregator?: string;\n cart_token?: string;\n defined_noun_id?: string;\n event_time?: string;\n meta?: Record<string, boolean | string>;\n noun: 'cart' | 'checkout-extension' | 'widget';\n shopify_checkout_token?: string;\n subject: 'abtest' | 'user';\n tags?: string[];\n uuid: string;\n verb: 'added-from' | 'tracking' | 'viewed';\n widget_id?: string;\n};\n\ntype Taxonomy = {\n buildDefinedNounId?: (properties: Record<string, unknown>) => string | undefined;\n buildMeta?: (properties: Record<string, unknown>) => Record<string, boolean | string>;\n buildTags?: (properties: Record<string, unknown>) => string[] | undefined;\n /** Overrides which id lands in `widget_id` (default: the request's `widgetId`). */\n buildWidgetId?: (properties: Record<string, unknown>, input: AnalyticsInput) => string | undefined;\n noun: EngineEvent['noun'];\n subject: EngineEvent['subject'];\n usesWidgetId: boolean;\n verb: EngineEvent['verb'];\n};\n\n/** Raw engine experiment type \u2192 the snake_case form the engine expects in A/B meta (React parity). */\nconst EXPERIMENT_TYPE_MAP: Record<string, string> = {\n CheckoutOffer: 'checkout_offer',\n Generic: 'generic',\n GlobalSmartFlow: 'smart_flow',\n SmartCart: 'smart_cart',\n Widget: 'widget',\n};\n\n/** The `ABN.TEST.<experimentId>` tag React attaches to every experiment-attributed event, or none. */\nconst experimentTags = ({ experimentId }: Record<string, unknown>): string[] | undefined =>\n experimentId != null ? [`ABN.TEST.${experimentId}`] : undefined;\n\n/**\n * Maps a generic client event `name` \u2192 the engine's (noun, verb, subject) taxonomy, verbatim from the\n * React extension. Names with no entry are dropped (analytics is fire-and-forget; never error a buyer).\n */\nconst TAXONOMY = {\n 'ab-test-viewed': {\n // Only when BOTH ids are present \u2014 otherwise the template literal would emit \"undefined.undefined\".\n buildDefinedNounId: ({ experimentId, selectedId }) =>\n experimentId != null && selectedId != null ? `${experimentId}.${selectedId}` : undefined,\n buildMeta: ({ elementId, experimentType }) => ({\n element_id: String(elementId ?? ''),\n experiment_type: EXPERIMENT_TYPE_MAP[String(experimentType ?? '')] ?? '',\n }),\n buildTags: experimentTags,\n noun: 'cart',\n subject: 'abtest',\n usesWidgetId: false,\n verb: 'tracking',\n },\n 'added-to-cart': {\n /** React credits the add to the A/B-selected variant (`defined_noun_id: selectedId`). */\n buildDefinedNounId: ({ selectedId }) => (selectedId != null ? String(selectedId) : undefined),\n buildMeta: ({ productId, variantId }) => ({\n ...(productId != null && { [`product_id:${productId}`]: true }),\n ...(variantId != null && { [`variant_id:${variantId}`]: true }),\n }),\n buildTags: experimentTags,\n /** Under an experiment the add belongs to the VARIANT element, not the placeholder (React parity). */\n buildWidgetId: ({ elementId }, input) => (elementId != null ? String(elementId) : input.widgetId),\n noun: 'widget',\n subject: 'user',\n usesWidgetId: true,\n verb: 'added-from',\n },\n 'checkout-viewed': {\n /** React's random hex shard key (\"used instead of widget_id for aggregation\"). */\n buildDefinedNounId: () => Math.floor(Math.random() * 16).toString(16),\n buildMeta: () => ({ has_widget: true }),\n noun: 'checkout-extension',\n subject: 'user',\n usesWidgetId: false,\n verb: 'viewed',\n },\n // Forward-compat diagnostic (no React precedent): a deployed extension rendered a sectionType it\n // didn't recognize. Generic `tracking` verb; the unknown type rides in meta so we can spot schema drift.\n 'unknown-section': {\n buildMeta: ({ sectionType }) => ({ [`section_type:${String(sectionType ?? 'unknown')}`]: true }),\n noun: 'widget',\n subject: 'user',\n usesWidgetId: true,\n verb: 'tracking',\n },\n 'widget-viewed': { buildTags: experimentTags, noun: 'widget', subject: 'user', usesWidgetId: true, verb: 'viewed' },\n} satisfies Record<string, Taxonomy>;\n\n/**\n * The client analytics event names the server knows how to translate \u2014 the typed contract R5's analytics\n * work targets instead of the stringly-typed one. Derived from the taxonomy so the two never drift.\n */\nexport type CabAnalyticsEventName = keyof typeof TAXONOMY;\n\nconst isKnownEvent = (name: string): name is CabAnalyticsEventName => name in TAXONOMY;\n\n/** Translate one client event into an engine event, or `null` if its `name` isn't in the taxonomy. */\nexport const translateAnalyticsEvent = (event: AnalyticsEventInput, input: AnalyticsInput): EngineEvent | null => {\n if (!isKnownEvent(event.name)) return null;\n\n /** `satisfies` narrows each entry to its own literal shape; widen back to the optional-method contract. */\n const taxonomy: Taxonomy = TAXONOMY[event.name];\n\n const properties = event.properties ?? {};\n const meta = taxonomy.buildMeta?.(properties);\n const tags = taxonomy.buildTags?.(properties);\n const definedNounId = taxonomy.buildDefinedNounId?.(properties);\n const widgetId = taxonomy.buildWidgetId?.(properties, input) ?? input.widgetId;\n\n return {\n noun: taxonomy.noun,\n subject: taxonomy.subject,\n uuid: input.visitorId,\n verb: taxonomy.verb,\n // Aggregate by checkout identity (Rebuy cart token + Shopify checkout token); else the visitor id (React parity).\n ...(event.sentAt && { event_time: event.sentAt }),\n ...(input.cartToken && { cart_token: input.cartToken }),\n ...(input.checkoutToken && { shopify_checkout_token: input.checkoutToken }),\n ...(!input.cartToken && !input.checkoutToken && { aggregator: input.visitorId }),\n ...(taxonomy.usesWidgetId && widgetId && { widget_id: widgetId }),\n ...(definedNounId && { defined_noun_id: definedNounId }),\n ...(meta && Object.keys(meta).length > 0 && { meta }),\n ...(tags && tags.length > 0 && { tags }),\n };\n};\n\n/** The engine's bulk endpoint 400s (dropping the WHOLE batch) above this size, so we POST in slices of it. */\nconst MAX_ANALYTICS_EVENTS = 100;\n\n/**\n * Translate a batch of client events to the engine contract and POST them to the analytics bulk\n * endpoint with the shop's publishable key (resolved server-side, never sent by the client). No-ops\n * when nothing maps. Chunks into POSTs of at most {@link MAX_ANALYTICS_EVENTS} so an oversized batch\n * isn't rejected wholesale. Returns the total count forwarded.\n */\nexport const postAnalyticsEvents = async (input: AnalyticsInput, ctx: ServerContext): Promise<{ accepted: number }> => {\n const events = input.events\n .map((event) => translateAnalyticsEvent(event, input))\n .filter((event): event is EngineEvent => event !== null);\n\n if (events.length === 0) return { accepted: 0 };\n\n const { shop } = await fetchUserConfig({ shop: input.shop }, ctx);\n\n for (let index = 0; index < events.length; index += MAX_ANALYTICS_EVENTS) {\n await ctx.fetchUpstream(\n '/api/v2/analytics/event/bulk',\n {},\n {\n body: events.slice(index, index + MAX_ANALYTICS_EVENTS),\n headers: { 'X-Rebuy-User-Token': shop.apiKey },\n host: ctx.host,\n method: 'POST',\n }\n );\n }\n\n return { accepted: events.length };\n};\n", "/**\n * Zod schemas for the `/cab/*` REQUEST bodies the orchestrators accept. Centralized here so rebuy-api can\n * validate incoming requests against the same contract the orchestrators are typed on \u2014 the hand-written\n * `*Input` twins in `./shared` are now `z.infer` of these schemas (single source of truth, no drift).\n *\n * These model the wire shape only: no `.default()`s (a request field is either sent or omitted \u2014 defaulting\n * would diverge `z.infer` from the twin it replaces and hide a missing field), and unknown keys are stripped\n * by the plain `z.object`, which is the intended lenient request-parse behavior.\n */\nimport { z } from 'zod';\n\n/** A raw key/value pair (line-item / cart attribute); the engine receives these JSON-encoded. */\nconst KeyValue = z.object({ key: z.string(), value: z.string().optional() });\n\n/** A cart line in the live-cart context the engine evaluates against. */\nexport const CartLineInputSchema = z.object({\n productId: z.string(),\n properties: z.array(KeyValue).optional(),\n quantity: z.number(),\n subscriptionId: z.string().optional(),\n variantId: z.string(),\n});\n\n/** The live cart context shared by the data-source, gift-validation, and monetize inputs. */\nexport const CartInputSchema = z.object({\n attributes: z.array(KeyValue).optional(),\n /**\n * Presentment-per-shop-currency FX rate (buyer price \u00F7 shop price, e.g. `1.35` for a USD shop\n * selling in CAD). Money rule thresholds are authored in SHOP currency, so the engine subtotal is\n * divided by this before evaluation. Omit (or send 1) when the cart is already in the shop's currency.\n */\n currencyRate: z.number().optional(),\n /** Applied discount codes; the engine evaluates `discount_code` rules against them (sent as `[{code}]`). */\n discountCodes: z.array(z.string()).optional(),\n /** Presentment cents of cart-level discount allocations, subtracted from `subtotal` for the engine. */\n discountTotal: z.number().optional(),\n items: z.array(CartLineInputSchema),\n /** Presentment subtotal in cents. */\n subtotal: z.number(),\n});\n\n/** Input for `convertWidgetSettings`. */\nexport const WidgetSettingsInputSchema = z.object({\n cacheKey: z.number().optional(),\n id: z.number(),\n key: z.string().optional(),\n shop: z.string(),\n /** Stable per-buyer id; when present, enables sticky server-side A/B variant selection. */\n visitorId: z.string().optional(),\n});\n\n/** Input for `fetchUserConfig`. */\nexport const UserConfigInputSchema = z.object({ shop: z.string() });\n\n/** Input for `fetchDataSourceResults`. */\nexport const DataSourceInputSchema = z.object({\n cart: CartInputSchema,\n customerId: z.string().optional(),\n dataSourcePath: z.string(),\n /**\n * Engine `filter_inputs` override: `'no'` keeps in-cart (input) products in the results/rule\n * outputs \u2014 gift validation sends it so a gift's own product can appear in its answer. Omitted = the\n * engine's default filtering.\n */\n filterInputs: z.enum(['no', 'yes']).optional(),\n integrations: z.record(z.string(), z.boolean()).optional(),\n limit: z.number(),\n productType: z.enum(['both', 'one-time', 'subscription']).optional(),\n shop: z.string(),\n visitorId: z.string().optional(),\n});\n\n/** A gift line the gift-validation watcher asks the server to validate. */\nexport const GiftInputSchema = z.object({\n cost: z.number(),\n discounted: z.boolean(),\n lineId: z.string(),\n productId: z.number(),\n widgetId: z.number(),\n});\n\n/** Input for `validateGifts`. */\nexport const GiftValidationInputSchema = z.object({\n cart: CartInputSchema,\n customerId: z.string().optional(),\n gifts: z.array(GiftInputSchema),\n shop: z.string(),\n visitorId: z.string().optional(),\n});\n\n/**\n * A rich transaction line the ads engine prices/targets on \u2014 the full per-line detail React sends. Distinct\n * from a cart line: it carries the merchandise title/type/unit-price the rule-evaluation cart context omits.\n */\nexport const MonetizeTransactionItemSchema = z.object({\n id: z.string(),\n priceCents: z.number(),\n quantity: z.number(),\n title: z.string(),\n type: z.string(),\n});\n\n/** Input for `fetchMonetizeOffers`. */\nexport const MonetizeInputSchema = z.object({\n cart: CartInputSchema,\n country: z.string().optional(),\n currency: z.string().optional(),\n /** Ads-targeting identity/geo/locale fields (React parity); folded into the engine query verbatim. */\n customerEmail: z.string().optional(),\n customerFirstName: z.string().optional(),\n customerId: z.string().optional(),\n customerLastName: z.string().optional(),\n language: z.string().optional(),\n /** Buyer-facing order name (e.g. `#1001`) for the server-composed \"Order \u2026 Confirmed\" chrome line. */\n orderName: z.string().optional(),\n placement: z.enum(['order_status', 'thank_you_page']),\n /** Privacy Policy footer href \u2014 the Monetize widget's `privacy_policy_url` setting (React parity). */\n privacyPolicyUrl: z.string().optional(),\n /** 30-min rolling session id (React parity); used for the ads `session_id`, else the visitor id. */\n sessionId: z.string().optional(),\n shop: z.string(),\n /** Editor/QA indicator; OR-ed into the ads-engine `testing` flag so it stays out of billing/reporting. */\n testing: z.boolean().optional(),\n timezone: z.string().optional(),\n /** Decorated (numeric) order id \u2192 the ads `transaction_id`. */\n transactionId: z.string().optional(),\n /** Rich per-line ads items; capped at 50 server-side (engine contract). Preferred over `cart.items`. */\n transactionItems: z.array(MonetizeTransactionItemSchema).optional(),\n /** Order total in presentment cents (React prefers total over subtotal); else `cart.subtotal`. */\n transactionTotal: z.number().optional(),\n visitorId: z.string().optional(),\n zipCode: z.string().optional(),\n});\n\n/** A generic analytics event from the extension; the server maps `name` \u2192 the engine's noun/verb/subject. */\nexport const AnalyticsEventInputSchema = z.object({\n name: z.string(),\n properties: z.record(z.string(), z.unknown()).optional(),\n sentAt: z.string().optional(),\n});\n\n/** Input for `postAnalyticsEvents`: a batch of events plus the request-scoped identity fields. */\nexport const AnalyticsInputSchema = z.object({\n /** Rebuy cart token (the `r_cart_token` cart attribute), when available \u2014 primary aggregation key. */\n cartToken: z.string().optional(),\n /** Shopify checkout token, when available \u2014 drives cart/checkout aggregation downstream. */\n checkoutToken: z.string().optional(),\n events: z.array(AnalyticsEventInputSchema),\n shop: z.string(),\n visitorId: z.string(),\n /** The widget id (smartBlockId) the events belong to. */\n widgetId: z.string().optional(),\n});\n\nexport type AnalyticsEventInput = z.infer<typeof AnalyticsEventInputSchema>;\nexport type AnalyticsInput = z.infer<typeof AnalyticsInputSchema>;\nexport type CartInput = z.infer<typeof CartInputSchema>;\nexport type CartLineInput = z.infer<typeof CartLineInputSchema>;\nexport type DataSourceInput = z.infer<typeof DataSourceInputSchema>;\nexport type GiftInput = z.infer<typeof GiftInputSchema>;\nexport type GiftValidationInput = z.infer<typeof GiftValidationInputSchema>;\nexport type MonetizeInput = z.infer<typeof MonetizeInputSchema>;\nexport type MonetizeTransactionItem = z.infer<typeof MonetizeTransactionItemSchema>;\nexport type UserConfigInput = z.infer<typeof UserConfigInputSchema>;\nexport type WidgetSettingsInput = z.infer<typeof WidgetSettingsInputSchema>;\n"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,KAAAA,UAAS;;;ACAlB,SAAS,SAAS;AAElB,IAAM,YAAY,EAAE,I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M,4BAA4BA,IAAE,OAAO;AAAA,EAC9C,MAAMA,IAAE,OAAO;AAAA,EACf,YAAYA,IAAE,OAAOA,IAAE,OAAO,GAAGA,IAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACvD,QAAQA,IAAE,OAAO,EAAE,SAAS;AAChC,CAAC;AAGM,IAAM,uBAAuBA,IAAE,OAAO;AAAA;AAAA,EAEzC,WAAWA,IAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAE/B,eAAeA,IAAE,OAAO,EAAE,SAAS;AAAA,EACnC,QAAQA,IAAE,MAAM,yBAAyB;AAAA,EACzC,MAAMA,IAAE,OAAO;AAAA,EACf,WAAWA,IAAE,OAAO;AAAA;AAAA,EAEpB,UAAUA,IAAE,OAAO,EAAE,SAAS;AAClC,CAAC;",
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod';\n\nimport { CacheInfo, Product } from './product';\n\nconst BaseRule = z.object({\n operator: z.string(),\n type: z.string(),\n value: z.union([z.string(), z.number()]),\n});\n\nconst Rule = BaseRule.extend({\n conditions: z.array(z.object({ type: z.string(), value: z.union([z.string(), z.number()]) })).optional(),\n products: z\n .array(\n z.object({\n productId: z.number(),\n subRules: z.object({ logic: z.array(z.object({ rules: z.array(BaseRule) })) }).optional(),\n variantIds: z.array(z.number()),\n })\n )\n .optional(),\n});\n\nconst Output = z.object({\n channel: z.string().optional(),\n collectionId: z.number().optional(),\n collectionSort: z.string().optional(),\n collectionSortType: z.string().nullish(),\n days: z.string().optional(),\n discount: z.object({ amount: z.string(), type: z.string() }).optional(),\n endpoint: z.string().optional(),\n key: z.string().optional(),\n operator: z.string().optional(),\n productPrice: z.object({ amount: z.string(), type: z.string() }).optional(),\n products: z.array(z.object({ productId: z.number(), variantIds: z.array(z.number()) })).optional(),\n productWithTagsSort: z.string().optional(),\n trendingSort: z.string().optional(),\n type: z.string(),\n value: z.union([z.string(), z.number(), z.boolean()]).optional(),\n});\n\nconst MatchedRule = z.object({\n collapsed: z.boolean().optional(),\n exitIfMatched: z.boolean(),\n index: z.number(),\n logic: z.array(z.object({ rules: z.array(Rule) })),\n output: z.array(Output),\n});\n\n/**\n * The rule-gating verdict the client's `useRule` reads (`metadata.custom.should_show`, camelCased). A\n * data-source evaluated at `limit: 0` returns it; validating the shape server-side lets an unreadable\n * verdict (an engine `custom` rename) be told apart from a rule legitimately evaluating false, which\n * would otherwise hide every gated section on every shop with no signal.\n */\nexport const RuleVerdict = z.object({ custom: z.object({ shouldShow: z.boolean() }) });\n\nexport type RuleVerdict = z.infer<typeof RuleVerdict>;\n\nexport const Metadata = z.object({\n cacheInfo: CacheInfo.optional(),\n cartItems: z.array(z.never()).optional(),\n errors: z.array(z.never()).optional(),\n filteredInputProducts: z.array(z.never()).optional(),\n filteredOosProducts: z.array(Product).optional(),\n globalExcludedProducts: z.array(Product).optional(),\n inputProducts: z.array(z.never()).optional(),\n matchedRules: z.array(MatchedRule).optional(),\n topSellersFilled: z.boolean().optional(),\n unevaluatedRules: z.array(MatchedRule).optional(),\n unmatchedRules: z.array(MatchedRule).optional(),\n widget: z\n .object({\n discount: z.object({ amount: z.string(), type: z.string() }).optional(),\n language: z.record(z.string(), z.string()).optional(),\n })\n .optional(),\n});\n\nexport type Metadata = z.infer<typeof Metadata>;\n", "import { z } from 'zod';\n\nconst zDatetime = z.iso.datetime({ offset: true });\n\nexport const CacheInfo = z.object({\n cachedAtTime: z.union([z.string(), z.number()]),\n cacheExpires: z.union([z.string(), z.number()]).optional(),\n cacheKey: z.string(),\n cacheKeyReadable: z.string(),\n cacheType: z.string().optional(),\n loadedOptions: z.record(z.string(), z.boolean()).optional(),\n});\n\nconst Category = z.object({\n adminGraphqlApiId: z.string(),\n fullName: z.string(),\n name: z.string(),\n});\n\nconst Metafield = z.object({\n key: z.string(),\n namespace: z.string(),\n type: z.string(),\n value: z.string(),\n});\n\nconst Image = z.object({\n adminGraphqlApiId: z.string(),\n alt: z.string().nullable(),\n createdAt: zDatetime.optional(),\n height: z.number(),\n id: z.number(),\n metafields: z.array(Metafield).optional(),\n position: z.number(),\n productId: z.number(),\n src: z.url(),\n updatedAt: zDatetime.optional(),\n variantIds: z.array(z.number()),\n width: z.number(),\n});\n\nconst Media = z.object({\n adminGraphqlApiId: z.string(),\n alt: z.string().nullable(),\n createdAt: zDatetime,\n id: z.number(),\n mediaContentType: z.string(),\n position: z.number(),\n previewImage: z.object({ height: z.number(), src: z.url(), status: z.string(), width: z.number() }),\n productId: z.number(),\n status: z.string(),\n updatedAt: zDatetime,\n variantIds: z.array(z.number()),\n});\n\nconst Option = z.object({\n id: z.number(),\n name: z.string(),\n position: z.number(),\n productId: z.number(),\n values: z.array(z.string()),\n});\n\nexport type Option = z.infer<typeof Option>;\n\nconst PriceAdjustment = z.object({\n orderCount: z.number().optional(),\n position: z.number(),\n value: z.string(),\n valueType: z.string(),\n});\n\nexport type PriceAdjustment = z.infer<typeof PriceAdjustment>;\n\nconst Ratings = z.union([\n z.object({ judgemeAverageStarRating: z.number(), judgemeTotalReviews: z.number() }),\n z.object({ junipAverageStarRating: z.number(), junipTotalReviews: z.number() }),\n z.object({ klaviyoAverageStarRating: z.number(), klaviyoTotalReviews: z.number() }),\n z.object({ looxAverageStarRating: z.number(), looxTotalReviews: z.number() }),\n z.object({ okendoAverageStarRating: z.number(), okendoTotalReviews: z.number() }),\n z.object({ opinewAverageStarRating: z.number(), opinewTotalReviews: z.number() }),\n z.object({ reviewsioAverageStarRating: z.number(), reviewsioTotalReviews: z.number() }),\n z.object({ stampedAverageStarRating: z.number(), stampedTotalReviews: z.number() }),\n z.object({ yotpoAverageStarRating: z.number(), yotpoTotalReviews: z.number() }),\n]);\n\nconst SellingPlan = z.object({\n description: z.string().optional(),\n id: z.number(),\n name: z.string(),\n options: z.array(z.object({ name: z.string(), position: z.number(), value: z.string() })),\n orderIntervalFrequency: z.string().optional(),\n orderIntervalUnitType: z.string().optional(),\n position: z.number().optional(),\n priceAdjustments: z.array(PriceAdjustment),\n shopifyVariantId: z.string().optional(),\n});\n\nexport type SellingPlan = z.infer<typeof SellingPlan>;\n\nconst SellingPlanAllocation = z.object({\n compareAtPrice: z.number(),\n perDeliveryPrice: z.number(),\n price: z.number(),\n priceAdjustments: z.array(PriceAdjustment),\n sellingPlanGroupId: z.string(),\n sellingPlanId: z.number(),\n});\n\nexport type SellingPlanAllocation = z.infer<typeof SellingPlanAllocation>;\n\nexport const SellingPlanGroup = z.object({\n appId: z.string().optional(),\n description: z.string().optional(),\n discountAmount: z.number().optional(),\n discountType: z.string().optional(),\n id: z.string(),\n name: z.string(),\n options: z.array(Option),\n requiresSellingPlan: z.boolean().optional(),\n sellingPlans: z.array(SellingPlan),\n variants: z.array(z.number()),\n});\n\nexport type SellingPlanGroup = z.infer<typeof SellingPlanGroup>;\n\nconst Variant = z.object({\n adminGraphqlApiId: z.string(),\n barcode: z.string().nullable(),\n compareAtPrice: z.string().nullable(),\n createdAt: zDatetime,\n fulfillmentService: z.string().nullish(),\n grams: z.number(),\n id: z.number(),\n imageId: z.number().nullable(),\n inventoryItemId: z.number().optional(),\n inventoryManagement: z.string().nullable(),\n inventoryPolicy: z.string(),\n inventoryQuantity: z.number(),\n link: z.url(),\n oldInventoryQuantity: z.number().optional(),\n option1: z.string(),\n option2: z.string().nullable(),\n option3: z.string().nullable(),\n position: z.number(),\n price: z.string(),\n productId: z.number(),\n requiresShipping: z.boolean(),\n sellingPlanAllocations: z.array(SellingPlanAllocation).optional(),\n sku: z.string().nullable(),\n taxable: z.boolean(),\n taxCode: z.string().optional(),\n title: z.string(),\n updatedAt: zDatetime,\n weight: z.number(),\n weightUnit: z.string().optional(),\n});\n\nexport type Variant = z.infer<typeof Variant>;\n\nexport const Product = z.object({\n adminGraphqlApiId: z.string(),\n bodyHtml: z.string().nullable(),\n cacheInfo: CacheInfo,\n category: Category.nullish(),\n collectionIds: z.array(z.number()),\n createdAt: zDatetime,\n description: z.string(),\n handle: z.string(),\n hasVariantsThatRequiresComponents: z.boolean().optional(),\n id: z.number(),\n image: Image.nullable(),\n images: z.array(Image).nullable(),\n link: z.url(),\n media: z.array(Media).optional(),\n metafields: z.array(Metafield).optional(),\n options: z.array(Option),\n owner: z.union([z.string(), z.number()]),\n productType: z.string(),\n publishedAt: zDatetime.nullable(),\n publishedScope: z.string().optional(),\n purchaseOptions: z.array(z.object({ discountOptions: z.array(z.never()) })).optional(),\n ratings: Ratings.optional(),\n selectedIndexPurchasedOption: z.number().optional(),\n sellingPlanAllocation: SellingPlanAllocation.optional(),\n sellingPlanGroups: z.array(SellingPlanGroup).optional(),\n status: z.string(),\n tags: z.string(),\n templateSuffix: z.string().nullable(),\n title: z.string(),\n updatedAt: zDatetime,\n variantGids: z.array(z.object({ adminGraphqlApiId: z.string(), updatedAt: zDatetime })).optional(),\n variantIds: z.array(z.object({ id: z.number() })).optional(),\n variants: z.array(Variant),\n vendor: z.string(),\n});\n\nexport type Product = z.infer<typeof Product>;\n", "import { z } from 'zod';\n\n/**\n * Per-product discount override a data source can attach \u2014 shaped like the legacy `settings.discount` /\n * `product.discount` (`@rebuy/rebuy/pricing`). Absent on the curated `Product` type, but present on\n * the wire, so the lean offer schema declares it explicitly.\n */\nconst OfferProductDiscount = z.object({\n amount: z.union([z.number(), z.string()]),\n discountedBy: z.string().optional(),\n discountedFrom: z.string().optional(),\n type: z.string(),\n});\n\nconst OfferProductOption = z.object({\n id: z.number(),\n name: z.string(),\n position: z.number(),\n values: z.array(z.string()),\n});\n\n/** Only what `toProduct` (`getIsOutOfStock` + `toPrice` + selection) reads off a variant. */\nconst OfferProductVariant = z.object({\n adminGraphqlApiId: z.string(),\n compareAtPrice: z.string().nullable(),\n id: z.number(),\n inventoryManagement: z.string().nullable(),\n inventoryPolicy: z.string(),\n inventoryQuantity: z.number(),\n link: z.string(),\n option1: z.string(),\n option2: z.string().nullable(),\n option3: z.string().nullable(),\n price: z.string(),\n title: z.string(),\n});\n\n/**\n * The lean server-side offer-product schema \u2014 exactly the fields the extension's `toProduct` consumes,\n * with the over-strict validators of the editor-facing `Product` (required `cacheInfo`, ISO\n * datetimes, `z.url()` links) relaxed to what the wire actually carries. `fetchDataSourceResults`\n * `safeParse`s each product against this and drops the ones that fail, so one malformed product costs\n * one offer card instead of the whole rail. This is also the type CAB imports in place of the loose\n * root `Product`, keeping the extension `any`-free.\n */\nexport const OfferProduct = z.object({\n description: z.string().optional(),\n discount: OfferProductDiscount.optional(),\n id: z.number(),\n image: z.object({ src: z.string() }).nullish(),\n images: z.array(z.object({ src: z.string(), variantIds: z.array(z.number()) })).nullish(),\n link: z.string().optional(),\n metafields: z.array(z.object({ key: z.string(), namespace: z.string(), value: z.string() })).optional(),\n options: z.array(OfferProductOption),\n sellingPlanGroups: z.array(z.object({ requiresSellingPlan: z.boolean().optional() })).optional(),\n title: z.string(),\n variants: z.array(OfferProductVariant),\n});\n\nexport type OfferProduct = z.infer<typeof OfferProduct>;\n", "/**\n * Server-only foundations for the widget-conversion / section-composition orchestrators. This subpath\n * (`@rebuy/rebuy/server`) is never imported by the browser extension \u2014 it owns the logic a thin API\n * service (rebuy-api) delegates to, with the actual network egress injected as {@link UpstreamFetch}.\n */\n\n/** Production engine host; any other host is a staging/ephemeral upstream. */\nexport const REBUY_ENGINE_HOST = 'rebuyengine.com';\n\n/**\n * Calls the legacy Rebuy engine at `https://<host><path>` and returns parsed JSON. Injected by the\n * caller (rebuy-api owns the egress, timeouts, and the `X-Rebuy-Upstream` proxy header); MUST throw\n * {@link UpstreamError} on a non-2xx response so orchestrators can interpret the status.\n *\n * Defaults to GET with `params`/`search` as the query string. Pass `method: 'POST'` with `body` (JSON\n * body) and optional `headers` (e.g. an auth token) for write-style calls like analytics ingest.\n */\nexport type UpstreamFetch = (\n path: string,\n params: Record<string, string>,\n options?: {\n body?: unknown;\n headers?: Record<string, string>;\n host?: string;\n method?: 'GET' | 'POST';\n search?: string;\n }\n) => Promise<unknown>;\n\n/**\n * A drift signal the orchestrators emit when a per-item payload salvage drops something: a malformed\n * offer product, an invalid/unknown section stubbed out, or an unreadable rule verdict. Distinct from a\n * hard {@link UpstreamError} \u2014 the request still succeeds (degraded), so this is the only trace that an\n * upstream contract moved. Optional on {@link ServerContext}; the host (rebuy-api) wires it to its logger.\n */\nexport type ServerDrift = {\n detail: string;\n kind: 'product' | 'ruleVerdict' | 'section';\n};\n\n/** Request-scoped dependencies every orchestrator needs. */\nexport type ServerContext = {\n fetchUpstream: UpstreamFetch;\n host: string;\n /** Buyer request IP forwarded to the ads engine (the checkout worker can't read it; rebuy-api extracts it). Without it DSPs see one datacenter IP for all traffic \u2014 geo/IVT-flagging risk. Monetize only. */\n ipAddress?: string;\n /** Optional sink for {@link ServerDrift} \u2014 a degraded-but-successful payload salvage. */\n reportDrift?: (event: ServerDrift) => void;\n /** Browser user-agent forwarded to the ads engine (the checkout worker can't read it). Monetize only. */\n userAgent?: string;\n};\n\n/** Thrown by the injected {@link UpstreamFetch} when the engine returns a non-2xx response. */\nexport class UpstreamError extends Error {\n readonly body: unknown;\n readonly status: number;\n\n constructor(status: number, body: unknown, message?: string) {\n super(message ?? `Upstream returned ${status}`);\n this.body = body;\n this.name = 'UpstreamError';\n this.status = status;\n }\n}\n\n/** Thrown when the requested widget / shop / data source doesn't exist; the route maps it to 404. */\nexport class NotFoundError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'NotFoundError';\n }\n}\n\n/**\n * The `/cab/*` request-body types. Re-exported from {@link file://./requestSchemas.ts} \u2014 each is now the\n * `z.infer` of a centralized zod request schema (single source of truth) so rebuy-api can validate incoming\n * requests against the exact contract the orchestrators are typed on. Kept re-exported here so the\n * `@rebuy/rebuy/server` type surface is unchanged.\n */\nexport type {\n AnalyticsEventInput,\n AnalyticsInput,\n CartInput,\n CartLineInput,\n DataSourceInput,\n GiftInput,\n GiftValidationInput,\n MonetizeInput,\n MonetizeTransactionItem,\n UserConfigInput,\n WidgetSettingsInput,\n} from '~/server/requestSchemas';\n", "import { z } from 'zod';\n\nimport { SmartCartConfig } from './smartCart';\n\n/**\n * The A/B experiment fields `resolveExperiment` actually reads \u2014 a lean projection of the engine's\n * `activeExperiments`. Peripheral experiment metadata (name, page targeting, alias/CSS/JS inputs) is\n * dropped so a change there can't fail the shared config parse.\n */\nexport const CabActiveExperiment = z.object({\n data: z.array(\n z.object({\n elementId: z.coerce.number(),\n id: z.coerce.number(),\n traffic: z.coerce.number(),\n })\n ),\n id: z.coerce.number(),\n placeholderId: z.coerce.number().nullable(),\n type: z.string(),\n});\n\nexport type CabActiveExperiment = z.infer<typeof CabActiveExperiment>;\n\n/**\n * The lean shop config CAB actually consumes \u2014 the five load-bearing fields, not the ~30 the\n * editor-facing `ShopConfig` carries. `apiKey` stays strict (every offers/monetize/gift/analytics\n * request authenticates with it); the rest use `.catch()` so a peripheral engine change (a renamed\n * field, a new `carousel` enum value like `'css'`, an experiment shape drift) degrades that one field\n * instead of 500-ing the shared `fetchUserConfig` and killing every dynamic CAB rail fleet-wide.\n */\nexport const CabShopConfig = z.object({\n /**\n * Per-element resilient: parse as `unknown[]` (non-array \u2192 `[]`), then keep only the experiments that\n * validate. A single drifted experiment drops itself instead of `.catch`-ing the WHOLE array to `[]` and\n * silently disabling every live A/B test fleet-wide.\n */\n activeExperiments: z\n .array(z.unknown())\n .catch([])\n .default([])\n .transform((experiments) =>\n experiments.flatMap((experiment) => {\n const result = CabActiveExperiment.safeParse(experiment);\n\n return result.success ? [result.data] : [];\n })\n ),\n apiKey: z.string(),\n /**\n * The shop's base-currency ISO code (e.g. `'USD'`). CAB derives the shop minor-unit exponent from it\n * (`currencyDecimals`) so a Functions-applied fixed discount \u2014 whose amount is in shop minor units \u2014\n * converts to the buyer's currency exactly in a cross-decimal market. `.catch()` like its siblings: a\n * missing/renamed currency degrades to \"unknown\" (client falls back to buyer decimals), never a parse fail.\n */\n currency: z.string().optional().catch(undefined),\n monetize: z.object({ publisherKey: z.string().nullable() }).nullish().catch(undefined),\n shopId: z.number().optional().catch(undefined),\n});\n\nexport type CabShopConfig = z.infer<typeof CabShopConfig>;\n\n/**\n * The lean `/api/v1/user/config` projection `fetchUserConfig` parses. `smartFlows` (schema-required on\n * the full `UserConfig` but read by no CAB path) is dropped; `smartCart` keeps its `.catch()`\n * safety bar so a smart-cart shape drift can never fail apiKey resolution.\n */\nexport const CabUserConfig = z.object({\n shop: CabShopConfig,\n smartCart: SmartCartConfig.nullish().catch(undefined),\n});\n\nexport type CabUserConfig = z.infer<typeof CabUserConfig>;\n", "import { z } from 'zod';\n\n/**\n * A gift/product reference attached to a smart-cart tier. Kept loose for S0 (data\n * plumbing) \u2014 S2 (gift mechanics) pins the variant/availability fields it consumes.\n */\nexport const SmartCartTierProduct = z.looseObject({\n handle: z.string().optional(),\n id: z.coerce.number().optional(),\n productId: z.coerce.number().optional(),\n title: z.string().optional(),\n variantIds: z.array(z.coerce.number()).optional(),\n});\n\n/**\n * One reward tier on a smart-cart tiered progress bar. `type` is `product` (gift), `shipping`,\n * `discount` (order discount applied by the order-discount Function, keyed by `_barId`) or\n * `decorative` (cosmetic milestone) \u2014 all four render at checkout. `minimum` is the unlock\n * threshold in shop-currency DOLLARS \u2014 except on `unlockConditionType: 'item_quantity'` tiers,\n * where it is a raw ITEM COUNT; `presentmentCurrencies` carries per-ISO-code CENTS overrides.\n *\n * The `*AmountRemainingLabel*`/`*AmountReachedLabel*` pairs are onsite's per-tier feedback copy\n * (`product_amount_remaining_label_text` etc.): the boolean gates whether the prompt shows, the\n * `*Text` holds the merchant sentence with `{{remaining_amount}}`/`{{product_title}}`/`{{discount_amount}}`\n * tokens. Blank/disabled tiers fall back to the bar-level shipping copy client-side.\n */\nexport const SmartCartTier = z.looseObject({\n allProducts: z.array(SmartCartTierProduct).optional(),\n /** Merchant-set tier label (e.g. \"Free gift\", \"$100 reward\"), shown on the step row when enabled. */\n customTierLabel: z.boolean().optional(),\n customTierLabelText: z.string().optional(),\n decorativeAmountReachedLabel: z.boolean().optional(),\n decorativeAmountReachedLabelText: z.string().optional(),\n decorativeAmountRemainingLabel: z.boolean().optional(),\n decorativeAmountRemainingLabelText: z.string().optional(),\n /** Order-discount reward: `'fixedAmount'` (shop-currency dollars) or `'percentage'` (whole percent). */\n discountAmountFromTotal: z.coerce.number().optional(),\n discountAmountReachedLabel: z.boolean().optional(),\n discountAmountReachedLabelText: z.string().optional(),\n discountAmountRemainingLabel: z.boolean().optional(),\n discountAmountRemainingLabelText: z.string().optional(),\n discountType: z.string().optional(),\n filterOosVariants: z.boolean().optional(),\n id: z.string().optional(),\n minimum: z.coerce.number().optional(),\n presentmentCurrencies: z.looseObject({ enabled: z.boolean().optional() }).optional(),\n productAmountReachedLabel: z.boolean().optional(),\n productAmountReachedLabelText: z.string().optional(),\n productAmountRemainingLabel: z.boolean().optional(),\n productAmountRemainingLabelText: z.string().optional(),\n products: z.array(SmartCartTierProduct).optional(),\n type: z.string().optional(),\n /**\n * onsite's PER-TIER unit switch (`unlock_condition_type`): `'item_quantity'` makes `minimum` an\n * item count (checked before any money handling \u2014 no \u00D7100, no FX, no presentment overrides,\n * mirroring onsite `getTierMinimum`); anything else (or absent) keeps the money semantics.\n */\n unlockConditionType: z.string().optional(),\n});\n\n/**\n * A single smart-cart progress bar (one per geo segment). `countryCodes` +\n * `geolocationEnabled` drive client-side country gating; `tiers` are the unlock steps;\n * `language` holds the bar-level reached/remaining copy.\n */\nexport const SmartCartBar = z.looseObject({\n countryCodes: z.array(z.string()).optional(),\n /**\n * onsite `exclude_discount_in_subtotal`: measure progress against the PRE-discount subtotal so an\n * applied code/order discount doesn't lower progress. The client adds cart discount allocations back.\n */\n excludeDiscountInSubtotal: z.boolean().optional(),\n /** Products excluded from the progress subtotal; the client subtracts their variants' cart cost. */\n excludedProducts: z.array(z.looseObject({ variantIds: z.array(z.coerce.number()).optional() })).optional(),\n freeShippingOnSubscription: z.boolean().optional(),\n geolocationEnabled: z.boolean().optional(),\n id: z.string().optional(),\n language: z\n .looseObject({\n freeShippingReached: z.string().optional(),\n freeShippingRemaining: z.string().optional(),\n giftAreaTitle: z.string().optional(),\n })\n .optional(),\n name: z.string().optional(),\n tiers: z.array(SmartCartTier).optional(),\n});\n\n/** A smart-cart layout component; only `type === 'tiered_progress_bar'` carries the bars we render. */\nexport const SmartCartComponent = z.looseObject({\n settings: z.looseObject({ bars: z.array(SmartCartBar).optional() }).optional(),\n type: z.string().optional(),\n});\n\n/**\n * The subset of the shop's smart-cart config the checkout extension reads: the\n * `tiered_progress_bar` component(s) and their bars/tiers. The rest of the onsite\n * smart-cart config (buy-more-save-more, custom templates/CSS, callbacks) is out of\n * scope \u2014 `looseObject` preserves-but-ignores it. Parsed under `UserConfig.smartCart`\n * with `.catch(undefined)` so a shape drift here can NEVER break apiKey resolution for\n * offers / monetize / analytics / gift validation.\n */\nexport const SmartCartConfig = z.looseObject({\n components: z.array(SmartCartComponent).optional(),\n});\n\nexport type SmartCartBar = z.infer<typeof SmartCartBar>;\nexport type SmartCartConfig = z.infer<typeof SmartCartConfig>;\nexport type SmartCartTier = z.infer<typeof SmartCartTier>;\nexport type SmartCartTierProduct = z.infer<typeof SmartCartTierProduct>;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { buttonFields, ObjectFit, objectFits, SectionType } from './common';\nimport { DYNAMIC_TOKEN_REGEX } from './regex';\nimport { CABRule } from './rule';\nimport { CABBorder, type SectionDetails } from './shared';\nimport { checkForHTML, NO_HTML } from './utils';\n\nexport const CABImageSection = z.object({\n altText: z.string().refine(checkForHTML, NO_HTML).default(''),\n aspectRatio: z.literal(1).nullable().default(null),\n border: z.lazy(() => CABBorder),\n buttonField: z.enum(buttonFields).optional(),\n category: z.enum(['gallery', 'icons', 'payment-methods', 'secure-checkout']).nullable().default(null),\n name: z.string().optional(),\n naturalHeight: z.number().default(0),\n naturalWidth: z.number().default(0),\n /**\n * `contain` (the component default): dimensionless images render in s-image's 1/1 default frame, and\n * `cover` would crop non-square art (payment badges lost their edges \u2014 15993); `contain` letterboxes.\n */\n objectFit: z.enum(objectFits).default(ObjectFit.contain),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.image).default(SectionType.image),\n source: z.union([z.url(), z.literal(''), z.string().regex(DYNAMIC_TOKEN_REGEX)]).default(''),\n width: z.number().default(100),\n});\n\nexport type CABImageSection = z.infer<typeof CABImageSection>;\n\nexport type CABImageSectionProps = CABImageSection & SectionDetails;\n", "export const freezeEnum = <T extends readonly string[]>(values: T) =>\n Object.freeze(Object.fromEntries(values.map((v) => [v, v]))) as { readonly [K in T[number]]: K };\n\nexport const bannerColors = ['info', 'success', 'warning', 'critical'] as const;\nexport const BannerColor = freezeEnum(bannerColors);\nexport type BannerColor = (typeof bannerColors)[number];\n\nexport const borderRadii = ['none', 'small', 'base', 'large', 'fullyRounded'] as const;\nexport const BorderRadius = freezeEnum(borderRadii);\nexport type BorderRadius = (typeof borderRadii)[number];\n\nexport const borderStyles = ['none', 'base', 'dotted', 'dashed'] as const;\nexport const BorderStyle = freezeEnum(borderStyles);\nexport type BorderStyle = (typeof borderStyles)[number];\n\nexport const borderWidths = ['base', 'medium', 'thick'] as const;\nexport const BorderWidth = freezeEnum(borderWidths);\nexport type BorderWidth = (typeof borderWidths)[number];\n\nexport const buttonActions = [\n 'acceptOffer',\n 'addToOrder',\n 'declineAllOffers',\n 'declineOffer',\n 'displayContentInModal',\n 'displayContentInPopover',\n 'goToNextPage',\n 'goToPrevPage',\n 'goToURL',\n 'removeFromOrder',\n 'selectVariant',\n 'showPagination',\n 'switchToSubscription',\n 'undoAddToOrder',\n] as const;\n\nexport const ButtonAction = freezeEnum(buttonActions);\nexport type ButtonAction = (typeof buttonActions)[number];\n\nexport const buttonFields = [\n 'activePage',\n 'addedToCart',\n 'addingToCart',\n 'addToCart',\n 'buttonLabel',\n 'declineAllOffers',\n 'declineOffer',\n 'destinationUrl',\n 'inactivePage',\n 'overlayContent',\n 'payNow',\n 'progressReached',\n 'progressRemaining',\n 'redirectToCheckout',\n 'removeFromOrder',\n 'showVariant',\n 'showVariants',\n 'soldOut',\n 'subscriptionOption',\n 'switchToOneTimePurchase',\n 'switchToSubscriptionNoDiscount',\n 'switchToSubscriptionWithDiscount',\n 'undoAddToOrder',\n] as const;\n\nexport const ButtonField = freezeEnum(buttonFields);\nexport type ButtonField = (typeof buttonFields)[number];\n\nexport const buttonStyles = ['primary', 'secondary', 'plain', 'custom'] as const;\nexport const ButtonStyle = freezeEnum(buttonStyles);\nexport type ButtonStyle = (typeof buttonStyles)[number];\n\nexport const directions = ['columns', 'rows', 'grid'] as const;\nexport const Direction = freezeEnum(directions);\nexport type Direction = (typeof directions)[number];\n\nexport const discountSources = ['price', 'compare_at_price'] as const;\nexport const DiscountSource = freezeEnum(discountSources);\nexport type DiscountSource = (typeof discountSources)[number];\n\nexport const discountTypes = ['none', 'percentage', 'fixed', 'fixed_amount'] as const;\nexport const DiscountType = freezeEnum(discountTypes);\nexport type DiscountType = (typeof discountTypes)[number];\n\nexport const editorModes = [\n 'checkoutExtension',\n 'postPurchaseOffer',\n 'thankYouPage',\n 'orderStatusPage',\n 'ordersIndexPage',\n 'customerProfilePage',\n] as const;\n\nexport const EditorMode = freezeEnum(editorModes);\nexport type EditorMode = (typeof editorModes)[number];\n\nexport const horizontalAlignments = ['start', 'center', 'end'] as const;\nexport const HorizontalAlignment = freezeEnum(horizontalAlignments);\nexport type HorizontalAlignment = (typeof horizontalAlignments)[number];\n\nexport const languageKeys = [\n 'ar',\n 'cs',\n 'da',\n 'de',\n 'en',\n 'es',\n 'fi',\n 'fr',\n 'ga',\n 'he',\n 'hi',\n 'id',\n 'it',\n 'ja',\n 'ko',\n 'nl',\n 'no',\n 'pl',\n 'pt',\n 'ru',\n 'sv',\n 'th',\n 'tr',\n 'uk',\n 'vi',\n 'zh',\n] as const;\n\nexport const LanguageKey = freezeEnum(languageKeys);\nexport type LanguageKey = (typeof languageKeys)[number];\n\nexport const objectFits = ['cover', 'contain'] as const;\nexport const ObjectFit = freezeEnum(objectFits);\nexport type ObjectFit = (typeof objectFits)[number];\n\nexport const popoverPositions = ['inlineStart', 'inlineEnd', 'blockStart', 'blockEnd'] as const;\nexport const PopoverPosition = freezeEnum(popoverPositions);\nexport type PopoverPosition = (typeof popoverPositions)[number];\n\nexport const popoverPositionMap = {\n bottom: 'blockEnd',\n left: 'inlineStart',\n right: 'inlineEnd',\n top: 'blockStart',\n} as const;\n\nexport const productTypes = ['one-time', 'subscription', 'both'] as const;\nexport const ProductType = freezeEnum(productTypes);\nexport type ProductType = (typeof productTypes)[number];\n\nexport const progressTierTypes = ['decorative', 'discount', 'product', 'shipping'] as const;\nexport const ProgressTierType = freezeEnum(progressTierTypes);\nexport type ProgressTierType = (typeof progressTierTypes)[number];\n\nexport const progressTierUnits = ['currency', 'item'] as const;\nexport const ProgressTierUnit = freezeEnum(progressTierUnits);\nexport type ProgressTierUnit = (typeof progressTierUnits)[number];\n\nexport const quantityInputs = ['select', 'number'] as const;\nexport const QuantityInput = freezeEnum(quantityInputs);\nexport type QuantityInput = (typeof quantityInputs)[number];\n\nexport const reviewsSizes = ['small', 'default', 'large'] as const;\nexport const ReviewsSize = freezeEnum(reviewsSizes);\nexport type ReviewsSize = (typeof reviewsSizes)[number];\n\nexport const sectionTypes = [\n 'banner',\n 'button',\n 'carousel',\n 'cartLine',\n 'dataSource',\n 'discount',\n 'image',\n 'layout',\n 'monetize',\n 'offers',\n 'product',\n 'products',\n 'progressBar',\n 'quantity',\n 'reviews',\n 'text',\n 'variants',\n] as const;\n\nexport const SectionType = freezeEnum(sectionTypes);\nexport type SectionType = (typeof sectionTypes)[number];\n\nexport const spacings = ['none', 'extraTight', 'tight', 'base', 'loose', 'extraLoose'] as const;\nexport const Spacing = freezeEnum(spacings);\nexport type Spacing = (typeof spacings)[number];\n\nexport const textAlignments = ['start', 'center', 'end'] as const;\nexport const TextAlignment = freezeEnum(textAlignments);\nexport type TextAlignment = (typeof textAlignments)[number];\n\nexport const textColorNames = ['base', 'subdued', 'accent', 'decorative', 'success', 'warning', 'critical'] as const;\nexport const TextColorName = freezeEnum(textColorNames);\nexport type TextColorName = (typeof textColorNames)[number];\n\nexport const textSizeNames = ['extraSmall', 'small', 'base', 'medium', 'large', 'extraLarge'] as const;\nexport const TextSizeName = freezeEnum(textSizeNames);\nexport type TextSizeName = (typeof textSizeNames)[number];\n\nexport const variantModes = ['multiple', 'single'] as const;\nexport const VariantMode = freezeEnum(variantModes);\nexport type VariantMode = (typeof variantModes)[number];\n\nexport const variantSelectors = ['menu', 'radio', 'button'] as const;\nexport const VariantSelector = freezeEnum(variantSelectors);\nexport type VariantSelector = (typeof variantSelectors)[number];\n\nexport const verticalAlignments = ['top', 'middle', 'bottom'] as const;\nexport const VerticalAlignment = freezeEnum(verticalAlignments);\nexport type VerticalAlignment = (typeof verticalAlignments)[number];\n", "/** Matches a valid array index string (e.g., \"0\", \"1\", \"42\"). */\nexport const ARRAY_INDEX_STRING = /^(0|[1-9]\\d*)$/;\n\n/** Matches a dynamic token. */\nexport const DYNAMIC_TOKEN_REGEX = /^\\{\\{\\s*[A-Za-z]+\\s*\\}\\}$/;\n\n/** Matches a valid hex color code. */\nexport const HEX_COLOR_REGEX = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;\n\n/**\n * Matches a root-relative, same-origin path (single leading slash, e.g. Shopify's\n * `/policies/privacy-policy`). A protocol-relative `//host` is excluded \u2014 it points off-origin.\n */\nexport const ROOT_RELATIVE_PATH_REGEX = /^\\/(?!\\/)/;\n\n/**\n * Matches an HTML-shaped tag: `<` (or `</`) immediately followed by a tag-name letter. This mirrors\n * both the browser `DOMParser` branch of `isHTML` and `stripContentBlockHtml`'s tag regex, so the\n * server-side check agrees with the client and with whatever the sanitizer removes. It deliberately\n * leaves bare comparison brackets alone (`5 < 10 and 10 > 5`) \u2014 those are text, not markup, and the\n * looser `/<\\/?[^>]+>/` it replaced wrongly rejected them and 500'd otherwise-valid content.\n *\n * Keeps the `g` flag because downstream consumers strip ALL tags with `.replace(HTML_TAGS_REGEX, '')`\n * (rebuy-shopify-extensions, admin-nextjs); without it `.replace` would drop only the first tag. The\n * one in-package consumer, `isHTML`, must therefore NOT use `.test()` on it \u2014 a global regex carries a\n * sticky `lastIndex` that makes repeated `.test()` calls flaky. `isHTML` uses `.search()` instead,\n * which ignores and never mutates `lastIndex`.\n */\nexport const HTML_TAGS_REGEX = /<\\/?[a-zA-Z][^>]*>/g;\n", "import { z } from 'zod';\n\nexport const ruleTypes = [\n 'cart',\n 'cart_count',\n 'cart_item_count',\n 'cart_line_count',\n 'cart_subtotal',\n 'collection',\n 'customer',\n 'customer_order_count',\n 'customer_tag',\n 'customer_total_spent',\n 'date',\n 'product',\n 'product_tag',\n 'product_title',\n 'product_type',\n 'product_vendor',\n] as const;\n\nconst ruleType = z.enum(ruleTypes);\n\nexport const RuleType = ruleType.enum;\nexport type RuleType = z.infer<typeof ruleType>;\n\nexport const ruleOperators = [\n 'after',\n 'anything',\n 'before',\n 'contains',\n 'contains_any',\n 'does_not_contain',\n 'does_not_contain_any',\n 'equals',\n 'does_not_equal',\n 'greater_than',\n 'less_than',\n] as const;\n\nconst ruleOperator = z.enum(ruleOperators);\n\nexport const RuleOperator = ruleOperator.enum;\nexport type RuleOperator = z.infer<typeof ruleOperator>;\n\nexport const RuleCondition = z.object({\n operator: z.enum(ruleOperators).default(RuleOperator.anything),\n products: z.union([z.array(z.unknown()), z.strictObject({}).transform(() => [])]).default(() => []),\n type: z.enum(ruleTypes).default(RuleType.cart_subtotal),\n value: z.coerce.string().default(''),\n});\n\nexport type RuleCondition = z.infer<typeof RuleCondition>;\n\nexport const RuleLogicBlock = z.object({\n rules: z.array(RuleCondition).default(() => []),\n});\n\nexport type RuleLogicBlock = z.infer<typeof RuleLogicBlock>;\n\nexport const CABRule = z.object({\n dataSourceId: z.number().nullable().default(null),\n enabled: z.boolean().default(false),\n ruleset: z\n .union([\n z.array(\n z.object({\n exitIfMatched: z.boolean().default(true),\n logic: z.array(RuleLogicBlock).default(() => []),\n output: z\n .array(\n z.object({\n key: z.string().default('should_show'),\n type: z.literal('data_json').default('data_json'),\n value: z.string().default('true'),\n })\n )\n .default(() => [{ key: 'should_show', type: 'data_json' as const, value: 'true' }]),\n })\n ),\n z.strictObject({}).transform(() => []),\n ])\n .default(() => []),\n});\n\nexport type CABRule = z.infer<typeof CABRule>;\n", "import { type FieldArrayPath } from 'react-hook-form';\nimport { z, type ZodType } from 'zod';\n\nimport { CABBannerSection } from './banner';\nimport { CABButtonSection } from './button';\nimport { CABCarouselSection } from './carousel';\nimport { CABCartLineSection } from './cartLine';\nimport { borderRadii, BorderRadius, BorderStyle, borderStyles, BorderWidth, borderWidths } from './common';\nimport { CABDataSourceSection } from './dataSource';\nimport { CABDiscountSection } from './discount';\nimport { CABImageSection } from './image';\nimport { CABLayoutSection } from './layout';\nimport { CABMonetizeSection } from './monetize';\nimport { CABOffersSection } from './offers';\nimport { CABProductSection } from './product';\nimport { CABProductsSection } from './products';\nimport { CABProgressBarSection } from './progressBar';\nimport { CABQuantitySection } from './quantity';\nimport { CABReviewsSection } from './reviews';\nimport { type CABRootSection } from './root';\nimport { CABTextSection } from './text';\nimport { CABVariantsSection } from './variants';\n\nexport const CABBorder = z\n .object({\n radius: z.enum(borderRadii).default(BorderRadius.base),\n style: z.enum(borderStyles).default(BorderStyle.none),\n width: z.enum(borderWidths).default(BorderWidth.base),\n })\n .default({\n radius: BorderRadius.base,\n style: BorderStyle.none,\n width: BorderWidth.base,\n });\n\nexport type CABBorder = z.infer<typeof CABBorder>;\n\nexport const CABSection: ZodType<CABSection> = z.lazy(() =>\n z.discriminatedUnion('sectionType', [\n CABBannerSection,\n CABButtonSection,\n CABCarouselSection,\n CABCartLineSection,\n CABDataSourceSection,\n CABDiscountSection,\n CABImageSection,\n CABLayoutSection,\n CABMonetizeSection,\n CABOffersSection,\n CABProductSection,\n CABProductsSection,\n CABProgressBarSection,\n CABQuantitySection,\n CABReviewsSection,\n CABTextSection,\n CABVariantsSection,\n ])\n);\n\nexport type CABSection =\n | CABBannerSection\n | CABButtonSection\n | CABCarouselSection\n | CABCartLineSection\n | CABDataSourceSection\n | CABDiscountSection\n | CABImageSection\n | CABLayoutSection\n | CABMonetizeSection\n | CABOffersSection\n | CABProductSection\n | CABProductsSection\n | CABProgressBarSection\n | CABQuantitySection\n | CABReviewsSection\n | CABTextSection\n | CABVariantsSection;\n\nexport type SectionId = CABSection['sectionId'];\n\n/* @ts-expect-error: TS2589: Type instantiation _is_ excessively deep and infinite. */\nexport type SectionArrayPath = FieldArrayPath<CABRootSection>;\n\nexport type SectionPrefixPath = `${SectionArrayPath}.${number}` | null;\n\nexport type SectionDetails = {\n /**\n * The full React Hook Form dot-notation path to the section object itself,\n * for use with `register` or `control`, e.g. `sections.0.sections.1`.\n *\n * Returns `null` for the root section.\n */\n fieldArrayPath: SectionArrayPath | null;\n /**\n * The index of the found section within its parent `sections` array.\n *\n * Returns `null` for the root section.\n */\n index: number | null;\n /**\n * The parent `sections` object.\n *\n * Returns `null` for the root section.\n */\n parent: CABSection[] | null;\n /**\n * The parent `sectionId`.\n *\n * Returns `undefined` for the root section.\n */\n parentId: SectionId | undefined;\n /**\n * The full React Hook Form dot-notation path to the section object itself,\n * for use with `register` or `control`, e.g. `sections.0.sections.1`.\n *\n * Returns `null` for the root section.\n */\n prefixPath: SectionPrefixPath | null;\n};\n\nexport type CABSectionProps = CABSection & SectionDetails;\n", "import { z } from 'zod';\n\nimport { bannerColors, buttonFields, SectionType, type BannerColor } from './common';\nimport { CABLayoutSection } from './layout';\nimport { type SectionDetails } from './shared';\n\nexport const CABBannerSection = z.lazy(() =>\n CABLayoutSection.omit({ sectionType: true }).extend({\n buttonField: z.enum(buttonFields).optional(),\n color: z.enum(bannerColors).default('info'),\n dismissible: z.boolean().default(true),\n sectionType: z.literal(SectionType.banner).default(SectionType.banner),\n })\n);\n\nexport type CABBannerSection = Omit<CABLayoutSection, 'sectionType'> & {\n color: BannerColor;\n dismissible: boolean;\n sectionType: 'banner';\n};\n\nexport type CABBannerSectionProps = CABBannerSection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport {\n buttonFields,\n Direction,\n directions,\n HorizontalAlignment,\n horizontalAlignments,\n SectionType,\n Spacing,\n spacings,\n VerticalAlignment,\n verticalAlignments,\n type ButtonField,\n} from './common';\nimport { CABRule } from './rule';\nimport { CABBorder, CABSection, type SectionDetails } from './shared';\n\nexport const GridItem = z.union([z.literal('auto'), z.literal('fill'), z.string().regex(/^\\d+%$/), z.number()]);\nexport type GridItem = z.infer<typeof GridItem>;\n\nexport const CABLayoutSection = z.object({\n alignment: z\n .object({\n horizontal: z.enum(horizontalAlignments).default(HorizontalAlignment.start),\n vertical: z.enum(verticalAlignments).default(VerticalAlignment.top),\n })\n .default({\n horizontal: HorizontalAlignment.start,\n vertical: VerticalAlignment.top,\n }),\n border: z.lazy(() => CABBorder),\n buttonField: z.enum(buttonFields).optional(),\n direction: z.enum(directions).default(Direction.rows),\n grid: z\n .object({\n columns: z.union([z.array(GridItem), z.undefined()]).default(() => ['auto']),\n rows: z.union([z.array(GridItem), z.undefined()]).default(() => ['auto']),\n })\n .default({ columns: ['auto'], rows: ['auto'] })\n .optional(),\n name: z.string().optional(),\n padding: z.enum(spacings).default(Spacing.none),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sections: z.union([z.array(z.lazy(() => CABSection)), z.strictObject({}).transform(() => [])]).default(() => []),\n sectionType: z.literal(SectionType.layout).default(SectionType.layout),\n spacing: z.enum(spacings).default(Spacing.base),\n /** Fire-and-forget impression pixel POSTed once when the section is shown (e.g. a Monetize offer view). */\n viewUrl: z.string().optional(),\n width: z.number().default(100),\n});\n\nexport type CABLayoutSection = {\n alignment: {\n horizontal: HorizontalAlignment;\n vertical: VerticalAlignment;\n };\n border: CABBorder;\n buttonField?: ButtonField;\n direction: Direction;\n grid?: {\n columns: GridItem[];\n rows: GridItem[];\n };\n name?: string;\n padding: Spacing;\n rule?: CABRule;\n sectionId: string;\n sections: CABSection[];\n sectionType: 'layout';\n spacing: Spacing;\n viewUrl?: string;\n width: number;\n};\n\nexport type CABLayoutSectionProps = CABLayoutSection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z, type ZodType } from 'zod';\n\nimport {\n buttonActions,\n ButtonStyle,\n buttonStyles,\n PopoverPosition,\n popoverPositions,\n SectionType,\n TextAlignment,\n textAlignments,\n} from './common';\nimport { CABImageSection } from './image';\nimport { CABLayoutSection } from './layout';\nimport { HEX_COLOR_REGEX } from './regex';\nimport { CABRule } from './rule';\nimport { type SectionDetails } from './shared';\nimport { CABTextSection } from './text';\n\nexport type CABButtonContent = CABImageSection | CABLayoutSection | CABTextSection;\n\nexport const CABButtonContent: ZodType<CABButtonContent> = z.lazy(() =>\n z.discriminatedUnion('sectionType', [CABImageSection, CABLayoutSection, CABTextSection])\n);\n\nexport const CABButtonSection = z.object({\n action: z.union([z.literal(''), z.enum(buttonActions)]).default(''),\n buttonStyle: z.enum(buttonStyles).default(ButtonStyle.primary),\n custom: z\n .object({\n color: z.string().regex(HEX_COLOR_REGEX).default('#005bd3'),\n height: z.number().default(52),\n width: z.number().default(300),\n })\n .default({\n color: '#005bd3',\n height: 52,\n width: 300,\n }),\n disableDowngrade: z.boolean().default(false),\n name: z.string().optional(),\n optionId: z.number().optional(),\n popover: z\n .object({\n alignment: z.enum(textAlignments).default(TextAlignment.center),\n position: z.enum(popoverPositions).default(PopoverPosition.blockStart),\n })\n .optional()\n .default(() => ({\n alignment: TextAlignment.center,\n position: PopoverPosition.blockStart,\n })),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sections: z.union([z.array(CABButtonContent), z.strictObject({}).transform(() => [])]).default(() => []),\n sectionType: z.literal(SectionType.button).default(SectionType.button),\n /** Fire-and-forget pixel POSTed when the button is clicked (e.g. a Monetize decline). */\n trackingUrl: z.string().optional(),\n});\n\nexport type CABButtonSection = z.infer<typeof CABButtonSection>;\n\nexport type CABButtonSectionProps = CABButtonSection & SectionDetails;\n", "import { forEach, isString } from 'es-toolkit/compat';\nimport { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport {\n ButtonField,\n buttonFields,\n progressTierTypes,\n ProgressTierType,\n SectionType,\n Spacing,\n spacings,\n TextAlignment,\n textAlignments,\n TextColorName,\n textColorNames,\n TextSizeName,\n textSizeNames,\n} from './common';\nimport { DYNAMIC_TOKEN_REGEX, ROOT_RELATIVE_PATH_REGEX } from './regex';\nimport { CABRule } from './rule';\nimport { type SectionDetails } from './shared';\nimport { checkForHTML, NO_HTML } from './utils';\n\nconst enumOrOmit = <T extends readonly [string, ...string[]]>(...vals: T) =>\n z\n .string()\n .transform((val) => (vals.includes(val as T[number]) ? (val as T[number]) : undefined))\n .optional();\n\nexport const TiptapText = z.object({\n marks: z\n .union([\n z.array(\n z.discriminatedUnion('type', [\n z.object({ type: z.literal('bold') }),\n z.object({ type: z.literal('italic') }),\n z.object({\n attrs: z.object({\n class: z.string().nullable(),\n href: z.union([\n z.url(),\n z.literal('#'),\n z.string().regex(DYNAMIC_TOKEN_REGEX),\n z.string().regex(ROOT_RELATIVE_PATH_REGEX),\n ]),\n rel: z.string().default('noopener noreferrer nofollow'),\n target: z.string().default('_blank'),\n }),\n type: z.literal('link'),\n }),\n z.object({ type: z.literal('strike') }),\n z.object({\n attrs: z.object({\n color: enumOrOmit(...textColorNames).default(TextColorName.base),\n fontSize: enumOrOmit(...textSizeNames).default(TextSizeName.base),\n }),\n type: z.literal('textStyle'),\n }),\n ])\n ),\n z.strictObject({}).transform(() => []),\n ])\n .optional(),\n text: z.string().default(''),\n type: z.literal('text').default('text'),\n});\n\nexport type TiptapText = z.infer<typeof TiptapText>;\n\nexport const TiptapParagraph = z.object({\n attrs: z\n .object({\n textAlign: enumOrOmit(...textAlignments),\n })\n .default({ textAlign: TextAlignment.start }),\n content: z.union([z.array(TiptapText), z.strictObject({}).transform(() => [])]).default(() => []),\n type: z.literal('paragraph').default('paragraph'),\n});\n\nexport type TiptapParagraph = z.infer<typeof TiptapParagraph>;\n\nexport const TiptapDocument = z.object({\n attrs: z\n .object({\n blockSpacing: enumOrOmit(...spacings),\n })\n .default({ blockSpacing: Spacing.base }),\n content: z\n .union([z.array(TiptapParagraph), z.strictObject({}).transform(() => [])])\n .default(() => [TiptapParagraph.parse({})]),\n type: z.literal('doc').default('doc'),\n});\n\nexport type TiptapDocument = z.infer<typeof TiptapDocument>;\n\n/**\n * A text section's tier reference. On the smart-cart per-tier feedback copy it carries the `tierId`, so\n * the renderer shows this section only while its tier is the active (current/last-reached) one \u2014 the\n * full tier (gift/threshold) lives on progressBar.\n */\nexport const CABTextTier = z.object({\n threshold: z.number().int().nonnegative(),\n thresholds: z.record(z.string(), z.number().int().nonnegative()).default(() => ({})),\n tierId: z.string().optional(),\n tierType: z.enum(progressTierTypes).default(ProgressTierType.shipping),\n});\n\nexport type CABTextTier = z.infer<typeof CABTextTier>;\n\nexport const CABTextSection = z\n .object({\n buttonField: z.enum(buttonFields).optional(),\n content: z\n .record(z.string(), z.union([z.string(), TiptapDocument]).refine(checkForHTML, NO_HTML).optional())\n .default({ en: TiptapDocument.parse({}) })\n .optional(),\n name: z.string().optional(),\n optionId: z.number().optional(),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.text).default(SectionType.text),\n tier: CABTextTier.optional(),\n })\n .superRefine(({ buttonField, content }, ctx) => {\n if (buttonField === ButtonField.destinationUrl && content) {\n forEach(content, (value, lang) => {\n if (value && isString(value)) {\n if (DYNAMIC_TOKEN_REGEX.test(value)) return;\n\n try {\n new URL(value);\n } catch {\n ctx.addIssue({\n code: 'custom',\n message: 'Invalid URL',\n path: ['content', lang],\n });\n }\n }\n });\n }\n });\n\nexport type CABTextSection = z.infer<typeof CABTextSection>;\n\nexport type CABTextSectionProps = CABTextSection & SectionDetails;\n", "import { isPlainObject, mapValues } from 'es-toolkit';\nimport { every, get, isArray, isString, map, size, toPairs } from 'es-toolkit/compat';\n\nimport { type CABBannerSection } from './banner';\nimport { type CABButtonSection } from './button';\nimport { type CABCarouselSection } from './carousel';\nimport { type CABCartLineSection } from './cartLine';\nimport { ButtonField, SectionType } from './common';\nimport { type CABDataSourceSection } from './dataSource';\nimport { type CABDiscountSection } from './discount';\nimport { type CABImageSection } from './image';\nimport { type CABLayoutSection } from './layout';\nimport { type CABMonetizeSection } from './monetize';\nimport { type CABOffersSection } from './offers';\nimport { type CABProductSection } from './product';\nimport { type CABProductsSection } from './products';\nimport { type CABProgressBarSection } from './progressBar';\nimport { type CABQuantitySection } from './quantity';\nimport { ARRAY_INDEX_STRING, HTML_TAGS_REGEX } from './regex';\nimport { type CABReviewsSection } from './reviews';\nimport { type CABTextSection, type TiptapDocument } from './text';\nimport { type CABVariantsSection } from './variants';\n\nexport const isHTML = (html: string | undefined = ''): boolean => {\n if (typeof window !== 'undefined') {\n const parser = new DOMParser();\n const doc = parser.parseFromString(html, 'text/html');\n\n const hasHTML = (nodeList: NodeList) => Array.from(nodeList).some((node) => node.nodeType === 1);\n\n return hasHTML(doc.body.childNodes) || hasHTML(doc.head.childNodes);\n }\n\n // `.search()` (not `.test()`) because HTML_TAGS_REGEX is global for downstream `.replace` callers;\n // `.search()` ignores and never advances `lastIndex`, so repeated calls stay deterministic.\n return html.search(HTML_TAGS_REGEX) !== -1;\n};\n\nexport const hasHTMLInDoc = (doc: TiptapDocument): boolean =>\n doc.content.some(({ content = [] }) => content.some(({ text }) => isHTML(text)));\n\nexport const checkForHTML = (input: string | TiptapDocument): boolean =>\n !((isString(input) && isHTML(input)) || (isPlainObject(input) && hasHTMLInDoc(input as TiptapDocument)));\n\nexport const NO_HTML = { message: 'HTML is not supported' };\n\nexport const isBannerType = (section: unknown): section is CABBannerSection =>\n get(section, 'sectionType') === SectionType.banner;\n\nexport const isButtonType = (section: unknown): section is CABButtonSection =>\n get(section, 'sectionType') === SectionType.button;\n\nexport const isCarouselType = (section: unknown): section is CABCarouselSection =>\n get(section, 'sectionType') === SectionType.carousel;\n\nexport const isCartLineType = (section: unknown): section is CABCartLineSection =>\n get(section, 'sectionType') === SectionType.cartLine;\n\nexport const isDataSourceType = (section: unknown): section is CABDataSourceSection =>\n get(section, 'sectionType') === SectionType.dataSource;\n\nexport const isDiscountType = (section: unknown): section is CABDiscountSection =>\n get(section, 'sectionType') === SectionType.discount;\n\nexport const isImageType = (section: unknown): section is CABImageSection =>\n get(section, 'sectionType') === SectionType.image;\n\nexport const isLayoutType = (section: unknown): section is CABLayoutSection =>\n get(section, 'sectionType') === SectionType.layout;\n\nexport const isMonetizeType = (section: unknown): section is CABMonetizeSection =>\n get(section, 'sectionType') === SectionType.monetize;\n\nexport const isOffersType = (section: unknown): section is CABOffersSection =>\n get(section, 'sectionType') === SectionType.offers;\n\nexport const isOverlayType = (section: unknown): section is CABLayoutSection =>\n isLayoutType(section) && get(section, 'buttonField') === ButtonField.overlayContent;\n\nexport const isProductType = (section: unknown): section is CABProductSection =>\n get(section, 'sectionType') === SectionType.product;\n\nexport const isProductsType = (section: unknown): section is CABProductsSection =>\n get(section, 'sectionType') === SectionType.products;\n\nexport const isProgressBarType = (section: unknown): section is CABProgressBarSection =>\n get(section, 'sectionType') === SectionType.progressBar;\n\nexport const isQuantityType = (section: unknown): section is CABQuantitySection =>\n get(section, 'sectionType') === SectionType.quantity;\n\nexport const isReviewsType = (section: unknown): section is CABReviewsSection =>\n get(section, 'sectionType') === SectionType.reviews;\n\nexport const isTextType = (section: unknown): section is CABTextSection =>\n get(section, 'sectionType') === SectionType.text;\n\nexport const isVariantsType = (section: unknown): section is CABVariantsSection =>\n get(section, 'sectionType') === SectionType.variants;\n\nconst hasOnlyNumericKeys = (input: Record<string, unknown>) =>\n !!size(input) && every(input, (_, key) => ARRAY_INDEX_STRING.test(key) && Number.isSafeInteger(Number(key)));\n\nconst numericObjectToArray = (input: Record<string, unknown>) =>\n toPairs(input)\n .sort(([a], [b]) => Number(a) - Number(b))\n .map(([_, value]) => value);\n\nexport const convertNumericObjects = (input: unknown): unknown => {\n if (isArray(input)) return map(input, convertNumericObjects);\n\n if (isPlainObject(input)) {\n const obj = input as Record<string, unknown>;\n\n return hasOnlyNumericKeys(obj)\n ? map(numericObjectToArray(obj), convertNumericObjects)\n : mapValues(obj, convertNumericObjects);\n }\n\n return input;\n};\n", "import { z } from 'zod';\n\nimport { SectionType } from './common';\nimport { CABLayoutSection } from './layout';\nimport { CABOffersSection } from './offers';\nimport { CABSection, type SectionDetails } from './shared';\n\nexport const CABCarouselSection = z.lazy(() =>\n CABLayoutSection.omit({ sections: true, sectionType: true }).extend({\n autoAdvanceInterval: z.number().default(0),\n itemsAtOnce: z.number().min(1).default(1),\n sections: z\n .union([z.array(z.lazy(() => CABSection)), z.strictObject({}).transform(() => [])])\n .default(() => [CABOffersSection.parse({})]),\n sectionType: z.literal(SectionType.carousel).default(SectionType.carousel),\n })\n);\n\nexport type CABCarouselSection = Omit<CABLayoutSection, 'sectionType'> & {\n autoAdvanceInterval: number;\n itemsAtOnce: number;\n sectionType: 'carousel';\n};\n\nexport type CABCarouselSectionProps = CABCarouselSection & SectionDetails;\n", "import { z } from 'zod';\n\nimport { CABBannerSection } from './banner';\nimport { CABButtonSection } from './button';\nimport { ButtonStyle, SectionType } from './common';\nimport { CABDataSourceSection } from './dataSource';\nimport { CABLayoutSection } from './layout';\nimport { CABProductsSection } from './products';\nimport { CABSection, type SectionDetails } from './shared';\nimport { CABTextSection } from './text';\n\nexport const CABOffersSection = z.lazy(() =>\n CABLayoutSection.omit({ sections: true, sectionType: true }).extend({\n sections: z.union([z.array(z.lazy(() => CABSection)), z.strictObject({}).transform(() => [])]).default(() => [\n CABBannerSection.parse({\n buttonField: 'undoAddToOrder',\n color: 'success',\n dismissible: true,\n name: 'Success Banner',\n sections: [\n CABTextSection.parse({ content: { en: '{{quantity}} {{productTitle}} added to cart.' } }),\n CABButtonSection.parse({ action: 'undoAddToOrder', buttonStyle: ButtonStyle.plain }),\n ],\n }),\n CABDataSourceSection.parse({}),\n CABProductsSection.parse({}),\n ]),\n sectionType: z.literal(SectionType.offers).default(SectionType.offers),\n })\n);\n\nexport type CABOffersSection = Omit<CABLayoutSection, 'sectionType'> & {\n sectionType: 'offers';\n};\n\nexport type CABOffersSectionProps = CABOffersSection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { discountSources, discountTypes, productTypes, SectionType } from './common';\nimport { DEFAULT_ENDPOINTS } from './constants';\nimport { type SectionDetails } from './shared';\n\nexport const CABDiscount = z.object({\n amount: z.union([z.number(), z.string()]).catch(0),\n discountedBy: z.string().optional(),\n discountedFrom: z.enum(discountSources).optional().catch(undefined),\n type: z.enum(discountTypes).catch('none'),\n});\n\nexport type CABDiscount = z.infer<typeof CABDiscount>;\n\nexport const CABIntegrations = z.object({\n judgeme: z.boolean().default(false),\n junip: z.boolean().default(false),\n klaviyo: z.boolean().default(false),\n loox: z.boolean().default(false),\n okendo: z.boolean().default(false),\n opinew: z.boolean().default(false),\n reviewsio: z.boolean().default(false),\n stamped: z.boolean().default(false),\n yotpo: z.boolean().default(false),\n});\n\nexport type CABIntegrations = z.infer<typeof CABIntegrations>;\n\nexport const CABDataSourceSection = z.object({\n dataSourceId: z.number().nullable().default(null),\n dataSourcePath: z.string().default(DEFAULT_ENDPOINTS[0].value),\n discount: CABDiscount.optional(),\n integrations: CABIntegrations.optional(),\n limit: z.number().default(1),\n matchVariant: z.boolean().default(false),\n matchVariantOutOfStock: z.boolean().default(false),\n name: z.string().default(DEFAULT_ENDPOINTS[0].label),\n productType: z.enum(productTypes).optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.dataSource).default(SectionType.dataSource),\n /** Default subscribe-vs-one-time for `productType: both` (legacy `subscription_is_default`). */\n subscriptionIsDefault: z.boolean().default(false),\n treatAsGwp: z.boolean().default(false),\n});\n\nexport type CABDataSourceSection = z.infer<typeof CABDataSourceSection>;\n\nexport type CABDataSourceSectionProps = CABDataSourceSection & SectionDetails;\n", "import { uniqBy } from 'es-toolkit';\n\nimport { EditorMode, freezeEnum } from './common';\nimport { type TargetArea } from './root';\n\nexport const DEFAULT_ENDPOINTS = [\n { label: 'Recommended (AI)', value: '/products/recommended' },\n { label: 'Top Sellers', value: '/products/top_sellers' },\n { label: 'Buy It Again', value: '/products/purchased' },\n { label: 'Recently Viewed', value: '/products/viewed' },\n { label: 'Products Search', value: '/products/search' },\n { label: 'Collection Products', value: '/products/collections' },\n { label: 'Similar Products (AI)', value: '/products/similar_products' },\n] as const;\n\nexport const STATIC_ENDPOINTS = [\n { label: 'Recommended (AI)', value: '/products/recommended' },\n { label: 'Top Sellers', value: '/products/top_sellers' },\n { label: 'Trending Products', value: '/products/trending_products' },\n { label: 'Buy It Again', value: '/products/purchased' },\n { label: 'Collection Products', value: '/products/collections' },\n { label: 'Recently Viewed', value: '/products/viewed' },\n { label: 'Static Products', value: '/products/static' },\n { label: 'Products Search', value: '/products/search' },\n { label: 'Similar Products (AI)', value: '/products/similar_products' },\n] as const;\n\nexport const COMBINED_ENDPOINTS = uniqBy([...DEFAULT_ENDPOINTS, ...STATIC_ENDPOINTS], (item) => item.value);\n\nexport const targetAreas = {\n [EditorMode.checkoutExtension]: [\n { icon: 'splitscreen_top', label: 'Header Area', width: '984px' },\n { icon: 'splitscreen_left', label: 'Main Column', width: '503px' },\n { icon: 'splitscreen_right', label: 'Summary Column', width: '404px' },\n ] satisfies TargetArea[],\n [EditorMode.postPurchaseOffer]: null,\n [EditorMode.thankYouPage]: [\n { icon: 'splitscreen_top', label: 'Header Area', width: '984px' },\n { icon: 'splitscreen_left', label: 'Main Column', width: '503px' },\n { icon: 'splitscreen_right', label: 'Summary Column', width: '404px' },\n ] satisfies TargetArea[],\n [EditorMode.orderStatusPage]: [\n // { fill: true, flip: 'vertical', icon: 'bottom_navigation', label: 'Announcement Bar' },\n { icon: 'splitscreen_top', label: 'Header Area', width: '1124px' },\n { fill: true, icon: 'view_column_2', label: 'Main Area', width: '646px' },\n { icon: 'splitscreen_bottom', label: 'Footer Area', width: '1124px' },\n ] satisfies TargetArea[],\n [EditorMode.ordersIndexPage]: [\n // { fill: true, flip: 'vertical', icon: 'bottom_navigation', label: 'Announcement Bar' },\n { icon: 'splitscreen_top', label: 'Main Area', width: '1124px' },\n ] satisfies TargetArea[],\n [EditorMode.customerProfilePage]: [\n // { fill: true, flip: 'vertical', icon: 'bottom_navigation', label: 'Announcement Bar' },\n { icon: 'splitscreen_top', label: 'Main Area', width: '1124px' },\n ] satisfies TargetArea[],\n} as const;\n\nexport const widgetTypes = [\n 'bundle_builder',\n 'cart',\n 'cart_subscription',\n 'dynamic_bundle',\n 'gift_with_purchase',\n 'pre_purchase',\n 'product',\n 'product_addon',\n 'product_upsell',\n 'recharge_checkout',\n 'recharge_customer_portal',\n 'recharge_post_purchase',\n 'shopify_checkout',\n 'shopify_checkout_extension',\n 'shopify_post_purchase',\n 'shopify_post_purchase_extension',\n 'switch_to_subscription',\n 'ui_extension_ad',\n 'ui_extension_button',\n 'ui_extension_content_block',\n 'ui_extension_line_item_editor',\n 'ui_extension_progress_bar',\n] as const;\n\nexport const WidgetType = freezeEnum(widgetTypes);\nexport type WidgetType = (typeof widgetTypes)[number];\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { SectionType } from './common';\nimport { CABProductSection } from './product';\nimport { type SectionDetails } from './shared';\n\nexport const CABProductsSection = z.object({\n name: z.string().optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sections: z\n .union([z.array(z.lazy(() => CABProductSection)), z.strictObject({}).transform(() => [])])\n .default(() => []),\n sectionType: z.literal(SectionType.products).default(SectionType.products),\n});\n\nexport type CABProductsSection = z.infer<typeof CABProductsSection>;\n\nexport type CABProductsSectionProps = CABProductsSection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z, type ZodType } from 'zod';\n\nimport { CABButtonSection } from './button';\nimport { SectionType, VariantMode, variantModes, VariantSelector, variantSelectors } from './common';\nimport { type SectionDetails } from './shared';\nimport { CABTextSection } from './text';\n\nexport type CABVariantContent = CABButtonSection | CABTextSection;\n\nexport const CABVariantContent: ZodType<CABVariantContent> = z.lazy(() =>\n z.discriminatedUnion('sectionType', [CABButtonSection, CABTextSection])\n);\n\nexport const CABProductSection = z.object({\n name: z.string().optional(),\n productId: z.number().nullable().default(null),\n sectionId: z.uuid().default(() => uuidv7()),\n sections: z.union([z.array(CABVariantContent), z.strictObject({}).transform(() => [])]).default(() => []),\n sectionType: z.literal(SectionType.product).default(SectionType.product),\n selectors: z.record(z.string(), z.enum(variantSelectors).default(VariantSelector.menu)).default(() => ({})),\n variantMode: z.enum(variantModes).default(VariantMode.multiple),\n});\n\nexport type CABProductSection = z.infer<typeof CABProductSection>;\n\nexport type CABProductSectionProps = CABProductSection & SectionDetails;\n", "import { z } from 'zod';\n\nimport { CABButtonSection } from './button';\nimport { ButtonAction, SectionType } from './common';\nimport { CABLayoutSection } from './layout';\nimport { CABSection, type SectionDetails } from './shared';\n\nexport const CABCartLineSection = z.lazy(() =>\n CABLayoutSection.omit({ sections: true, sectionType: true }).extend({\n sections: z\n .union([z.array(z.lazy(() => CABSection)), z.strictObject({}).transform(() => [])])\n .default(() => [CABButtonSection.parse({ action: ButtonAction.switchToSubscription })]),\n sectionType: z.literal(SectionType.cartLine).default(SectionType.cartLine),\n })\n);\n\nexport type CABCartLineSection = Omit<CABLayoutSection, 'sectionType'> & {\n sectionType: 'cartLine';\n};\n\nexport type CABCartLineSectionProps = CABCartLineSection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { discountSources, discountTypes, SectionType } from './common';\nimport { type SectionDetails } from './shared';\n\n/**\n * The widget discount, modeled as its own offers child section (toggled on/off in the editor and\n * rendered nowhere \u2014 it's config-only). Discounting is Shopify Functions-only (Scripts is sunset), so a\n * configured discount always applies via Functions and the amount is in Functions (minor-unit) form for\n * fixed types. `discountedFrom` is the compare-from source; `message` is the Functions discount title.\n */\nexport const CABDiscountSection = z.object({\n amount: z.union([z.number(), z.string()]).catch(0),\n discountedBy: z.string().optional(),\n discountedFrom: z.enum(discountSources).optional().catch(undefined),\n message: z.string().optional(),\n name: z.string().optional(),\n quantity: z.number().default(1),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.discount).default(SectionType.discount),\n type: z.enum(discountTypes).catch('none'),\n});\n\nexport type CABDiscountSection = z.infer<typeof CABDiscountSection>;\n\nexport type CABDiscountSectionProps = CABDiscountSection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { SectionType } from './common';\nimport { CABRule } from './rule';\nimport { type SectionDetails } from './shared';\n\nexport const CABMonetizeSection = z.object({\n name: z.string().optional(),\n /** Privacy Policy footer href (the widget's `privacy_policy_url` setting); the client relays it to `/cab/monetize`. */\n privacyPolicyUrl: z.string().optional(),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.monetize).default(SectionType.monetize),\n});\n\nexport type CABMonetizeSection = z.infer<typeof CABMonetizeSection>;\n\nexport type CABMonetizeSectionProps = CABMonetizeSection & SectionDetails;\n", "import { z } from 'zod';\n\nimport { ProgressTierType, progressTierTypes, ProgressTierUnit, progressTierUnits, SectionType } from './common';\nimport { GIFT_LABELS } from './giftLabels';\nimport { CABLayoutSection } from './layout';\nimport { type SectionDetails } from './shared';\n\nexport const CABProgressTier = z.object({\n /**\n * Order-discount tiers only (onsite `discount`): the reward the order-discount Function applies at\n * cart time, carried so the client can resolve the `{{discountAmount}}` token in this tier's copy.\n * `fixedAmount`: shop-currency CENTS (FX-scaled by the client, like {@link CABProgressTier.threshold});\n * `percentage`: the whole-percent number rendered raw (`{n}%`). Absent on non-discount tiers.\n */\n discount: z.object({ amount: z.number().nonnegative(), type: z.enum(['fixedAmount', 'percentage']) }).optional(),\n /**\n * Smart-cart product (gift) tiers only: the reward unlocked at this tier. The client enriches\n * `productId`/`variantIds` to live variants (availability, price) and adds the chosen one to the cart\n * when the tier is reached (attribution `_tier` = {@link CABProgressTier.tierId}). Absent on shipping\n * tiers and on tiers with no configured product. Cart add/remove is a later stage; carried here so the\n * tree is complete.\n */\n gift: z\n .object({\n productId: z.number().int().positive(),\n title: z.string().optional(),\n variantIds: z.array(z.number().int().positive()).default(() => []),\n })\n .optional(),\n /**\n * The step-row label at this tier's slot (onsite `getTierLabel`): the merchant custom label, else the\n * type default ('Free Shipping' / product title / '{n}% Discount'). Localized content; blank \u21D2 no\n * label under the tier's icon. Plain text \u2014 the step row is a compact icon+label, not rich copy.\n */\n label: z.record(z.string(), z.string()).optional(),\n /**\n * The tier's goal, measured per `unit`. `currency` (default): SHOP-currency cents \u2014 the canonical\n * fallback: when the buyer's presentment currency has no entry in `thresholds`, the client\n * multiplies this by the live FX rate (converter maps the v1 `unlock_price`, e.g. `75` \u2192 `7500`).\n * `item`: a raw item count \u2014 no cents, no FX, no `thresholds` overrides.\n */\n threshold: z.number().int().nonnegative(),\n /**\n * Per-presentment-currency goal overrides \u2014 lowercased ISO currency code \u2192 cents (e.g. `{ cad: 9900 }`).\n * When the buyer's currency has an entry, the client uses it verbatim INSTEAD of FX-converting\n * `threshold`, so merchants show intentional, clean per-market amounts (Shopify Markets) rather than a\n * converted base. Defaults to `{}` \u2014 no overrides means always fall back to `threshold`.\n */\n thresholds: z.record(z.string(), z.number().int().nonnegative()).default(() => ({})),\n /**\n * Smart-cart tier identifier, mirrored onto the gift cart line's `_tier` attribute so the client can\n * match an in-cart gift back to its tier (add on reach, remove on downgrade/decline). Absent on the\n * shipping bar (single unlabeled tier, no gift).\n */\n tierId: z.string().optional(),\n tierType: z.enum(progressTierTypes).default(ProgressTierType.shipping),\n /**\n * What this tier's progress is measured in \u2014 PER TIER (onsite's `unlock_condition_type` model, NOT\n * the React port's bar-level `tiers[0]` shortcut). `currency` compares money cents against the\n * adjusted subtotal; `item` compares the raw quantity sum of non-excluded lines (the SAME exclusion\n * set as the money path). A mixed-unit bar stays coherent tier by tier: reach, fill share, and\n * `{{remainingAmount}}` (count-formatted + item/items-pluralized for `item` tiers) each resolve in\n * their own tier's unit \u2014 cross-tier arithmetic never mixes counts with cents.\n */\n unit: z.enum(progressTierUnits).default(ProgressTierUnit.currency),\n});\n\nexport type CABProgressTier = z.infer<typeof CABProgressTier>;\n\n/**\n * A self-contained progress-bar container. Extends `layout` (alignment/border/spacing/`sections`/\u2026), so it\n * holds ALL its pieces as composable children \u2014 the tier display (a `columns \u2192 rows \u2192 text/image` layout)\n * and the reached/remaining message `text`s \u2014 while the renderer adds the bar fill from `tiers` and shows\n * the active message. Everything is encapsulated under this one named section (and one country/FX gate).\n */\nexport const CABProgressBarSection = z.lazy(() =>\n CABLayoutSection.omit({ sectionType: true }).extend({\n /** Empty = shown everywhere; otherwise uppercase ISO country codes. */\n countryCodes: z.array(z.string().transform((code) => code.trim().toUpperCase())).default(() => []),\n /**\n * Uppercase ISO codes where a higher-precedence geo bar applies, so this (default, non-geo) bar is\n * hidden there \u2014 replicates React `getbar`'s geo-match-over-default precedence. Empty = never excluded.\n */\n excludeCountryCodes: z.array(z.string().transform((code) => code.trim().toUpperCase())).default(() => []),\n /**\n * Measure progress against the PRE-discount subtotal (onsite `exclude_discount_in_subtotal`, and\n * forced on for bars with a discount tier so its own reward can't un-reach the tier). The client\n * adds the cart's discount allocations back to the live subtotal.\n */\n excludeDiscountInSubtotal: z.boolean().default(false),\n /** Variant ids the client subtracts from the adjusted subtotal (React `bar.excluded_products`). */\n excludedVariantIds: z.array(z.number().int().positive()).default(() => []),\n /**\n * When the cart holds a subscription item, treat the bar as reached regardless of subtotal (React\n * `free_shipping_on_subscription(s)`). `freeShippingOnAll` is already a zero-threshold tier instead.\n */\n freeShippingOnSubscription: z.boolean().default(false),\n /** Localized heading over the gift controls (onsite `gift_area_title`, default 'FREE GIFTS'). */\n giftAreaTitle: z.record(z.string(), z.string()).default(() => ({ en: 'FREE GIFTS' })),\n /** Localized gift-control labels (add/remove/heading); a tier's gift `title` beats `yourGift`. */\n giftLabels: z\n .object({\n addGift: z.record(z.string(), z.string()).default(() => ({ ...GIFT_LABELS.addGift })),\n remove: z.record(z.string(), z.string()).default(() => ({ ...GIFT_LABELS.remove })),\n selectOptions: z.record(z.string(), z.string()).default(() => ({ ...GIFT_LABELS.selectOptions })),\n yourGift: z.record(z.string(), z.string()).default(() => ({ ...GIFT_LABELS.yourGift })),\n })\n .default(() => ({\n addGift: { ...GIFT_LABELS.addGift },\n remove: { ...GIFT_LABELS.remove },\n selectOptions: { ...GIFT_LABELS.selectOptions },\n yourGift: { ...GIFT_LABELS.yourGift },\n })),\n /** The bar's a11y label; the merchant names it in the editor, else this default (React parity). */\n name: z.string().default('Order progress'),\n /**\n * Bar fill color. An explicit (widget-authored) value is used verbatim; when absent the server\n * fills it with the live shop theme's `buttonBackground` (React `useRebuyTheme` parity). Still\n * absent after that \u21D2 the theme fetch failed and the client renders its platform-default bar \u2014\n * optional, not defaulted, so \"merchant chose no color\" stays distinguishable from any real value.\n */\n progressColor: z.string().optional(),\n sectionType: z.literal(SectionType.progressBar).default(SectionType.progressBar),\n /**\n * The bar's milestones, in any order \u2014 the renderer sorts by resolved threshold. Drives the fill\n * (even slot per tier) and, for smart-cart product tiers, the gift add/remove. The visual tier\n * display lives in `sections` (composable), NOT here.\n */\n tiers: z.union([z.array(CABProgressTier), z.strictObject({}).transform(() => [])]).default(() => []),\n })\n);\n\nexport type CABProgressBarSection = Omit<CABLayoutSection, 'name' | 'sectionType'> & {\n countryCodes: string[];\n excludeCountryCodes: string[];\n excludeDiscountInSubtotal: boolean;\n excludedVariantIds: number[];\n freeShippingOnSubscription: boolean;\n giftAreaTitle: Record<string, string>;\n giftLabels: Record<'addGift' | 'remove' | 'selectOptions' | 'yourGift', Record<string, string>>;\n name: string;\n progressColor?: string;\n sectionType: 'progressBar';\n tiers: CABProgressTier[];\n};\n\nexport type CABProgressBarSectionProps = CABProgressBarSection & SectionDetails;\n", "/**\n * Default localized labels for the smart-cart gift controls, keyed by slot then locale (same 26 locales\n * as `SWITCH_LABELS`). Schema-default content, never a client dictionary (Peter, 2026-07-06: visible\n * customer strings must be localized). `yourGift` is the generic heading \u2014 a tier's configured gift\n * `title` beats it when present.\n */\nexport const GIFT_LABELS = {\n addGift: {\n ar: '\u0623\u0636\u0641 \u0627\u0644\u0647\u062F\u064A\u0629',\n cs: 'P\u0159idat d\u00E1rek',\n da: 'Tilf\u00F8j gave',\n de: 'Geschenk hinzuf\u00FCgen',\n en: 'Add gift',\n es: 'A\u00F1adir regalo',\n fi: 'Lis\u00E4\u00E4 lahja',\n fr: 'Ajouter le cadeau',\n ga: 'Cuir bronntanas leis',\n he: '\u05D4\u05D5\u05E1\u05E3 \u05DE\u05EA\u05E0\u05D4',\n hi: '\u0909\u092A\u0939\u093E\u0930 \u091C\u094B\u0921\u093C\u0947\u0902',\n id: 'Tambahkan hadiah',\n it: 'Aggiungi regalo',\n ja: '\u30AE\u30D5\u30C8\u3092\u8FFD\u52A0',\n ko: '\uC0AC\uC740\uD488 \uCD94\uAC00',\n nl: 'Cadeau toevoegen',\n no: 'Legg til gave',\n pl: 'Dodaj prezent',\n pt: 'Adicionar presente',\n ru: '\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u043F\u043E\u0434\u0430\u0440\u043E\u043A',\n sv: 'L\u00E4gg till g\u00E5va',\n th: '\u0E40\u0E1E\u0E34\u0E48\u0E21\u0E02\u0E2D\u0E07\u0E02\u0E27\u0E31\u0E0D',\n tr: 'Hediye ekle',\n uk: '\u0414\u043E\u0434\u0430\u0442\u0438 \u043F\u043E\u0434\u0430\u0440\u0443\u043D\u043E\u043A',\n vi: 'Th\u00EAm qu\u00E0 t\u1EB7ng',\n zh: '\u6DFB\u52A0\u8D60\u54C1',\n },\n remove: {\n ar: '\u0625\u0632\u0627\u0644\u0629',\n cs: 'Odebrat',\n da: 'Fjern',\n de: 'Entfernen',\n en: 'Remove',\n es: 'Eliminar',\n fi: 'Poista',\n fr: 'Retirer',\n ga: 'Bain',\n he: '\u05D4\u05E1\u05E8',\n hi: '\u0939\u091F\u093E\u090F\u0901',\n id: 'Hapus',\n it: 'Rimuovi',\n ja: '\u524A\u9664',\n ko: '\uC81C\uAC70',\n nl: 'Verwijderen',\n no: 'Fjern',\n pl: 'Usu\u0144',\n pt: 'Remover',\n ru: '\u0423\u0434\u0430\u043B\u0438\u0442\u044C',\n sv: 'Ta bort',\n th: '\u0E19\u0E33\u0E2D\u0E2D\u0E01',\n tr: 'Kald\u0131r',\n uk: '\u0412\u0438\u0434\u0430\u043B\u0438\u0442\u0438',\n vi: 'X\u00F3a',\n zh: '\u79FB\u9664',\n },\n selectOptions: {\n ar: '\u0627\u062E\u062A\u0631 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A',\n cs: 'Vyberte mo\u017Enosti',\n da: 'V\u00E6lg muligheder',\n de: 'Optionen w\u00E4hlen',\n en: 'Select Options',\n es: 'Seleccionar opciones',\n fi: 'Valitse vaihtoehdot',\n fr: 'Choisir les options',\n ga: 'Roghnaigh roghanna',\n he: '\u05D1\u05D7\u05E8 \u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA',\n hi: '\u0935\u093F\u0915\u0932\u094D\u092A \u091A\u0941\u0928\u0947\u0902',\n id: 'Pilih opsi',\n it: 'Seleziona le opzioni',\n ja: '\u30AA\u30D7\u30B7\u30E7\u30F3\u3092\u9078\u629E',\n ko: '\uC635\uC158 \uC120\uD0DD',\n nl: 'Opties kiezen',\n no: 'Velg alternativer',\n pl: 'Wybierz opcje',\n pt: 'Selecionar op\u00E7\u00F5es',\n ru: '\u0412\u044B\u0431\u0440\u0430\u0442\u044C \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B',\n sv: 'V\u00E4lj alternativ',\n th: '\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01',\n tr: 'Se\u00E7enekleri se\u00E7',\n uk: '\u0412\u0438\u0431\u0440\u0430\u0442\u0438 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u0438',\n vi: 'Ch\u1ECDn t\u00F9y ch\u1ECDn',\n zh: '\u9009\u62E9\u9009\u9879',\n },\n yourGift: {\n ar: '\u0647\u062F\u064A\u062A\u0643',\n cs: 'V\u00E1\u0161 d\u00E1rek',\n da: 'Din gave',\n de: 'Ihr Geschenk',\n en: 'Your gift',\n es: 'Tu regalo',\n fi: 'Lahjasi',\n fr: 'Votre cadeau',\n ga: 'Do bhronntanas',\n he: '\u05D4\u05DE\u05EA\u05E0\u05D4 \u05E9\u05DC\u05DA',\n hi: '\u0906\u092A\u0915\u093E \u0909\u092A\u0939\u093E\u0930',\n id: 'Hadiah Anda',\n it: 'Il tuo regalo',\n ja: '\u3042\u306A\u305F\u306E\u30AE\u30D5\u30C8',\n ko: '\uACE0\uAC1D\uB2D8\uC758 \uC0AC\uC740\uD488',\n nl: 'Uw cadeau',\n no: 'Din gave',\n pl: 'Tw\u00F3j prezent',\n pt: 'Seu presente',\n ru: '\u0412\u0430\u0448 \u043F\u043E\u0434\u0430\u0440\u043E\u043A',\n sv: 'Din g\u00E5va',\n th: '\u0E02\u0E2D\u0E07\u0E02\u0E27\u0E31\u0E0D\u0E02\u0E2D\u0E07\u0E04\u0E38\u0E13',\n tr: 'Hediyeniz',\n uk: '\u0412\u0430\u0448 \u043F\u043E\u0434\u0430\u0440\u0443\u043D\u043E\u043A',\n vi: 'Qu\u00E0 c\u1EE7a b\u1EA1n',\n zh: '\u60A8\u7684\u8D60\u54C1',\n },\n} satisfies Record<string, Record<string, string>>;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { QuantityInput, quantityInputs, SectionType } from './common';\nimport { CABRule } from './rule';\nimport { type SectionDetails } from './shared';\n\nexport const CABQuantitySection = z.object({\n errorMessages: z\n .record(\n z.string(),\n z.object({\n /** `{{step}}` is interpolated at render \u2014 the off-increment message React never gave a merchant key. */\n increment: z.string().optional(),\n max: z.string().optional(),\n min: z.string().optional(),\n neg: z.string().optional(),\n })\n )\n .default({\n en: {\n increment: 'Quantity must be in increments of {{step}}',\n max: 'Maximum quantity allowed is {{max}}',\n min: 'Minimum quantity required is {{min}}',\n neg: 'Quantity cannot be negative',\n },\n }),\n inputType: z.enum(quantityInputs).default(QuantityInput.select),\n max: z.number().min(1).max(100).default(10),\n min: z.number().min(1).default(1),\n /** The a11y label for the quantity control; the merchant names it in the editor, else this default. */\n name: z.string().default('Quantity'),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.quantity).default(SectionType.quantity),\n});\n\nexport type CABQuantitySection = z.infer<typeof CABQuantitySection>;\n\nexport type CABQuantitySectionProps = CABQuantitySection & SectionDetails;\n", "import { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { ReviewsSize, reviewsSizes, SectionType } from './common';\nimport { REVIEW_LABELS } from './reviewLabels';\nimport { CABRule } from './rule';\nimport { type SectionDetails } from './shared';\n\nexport const CABReviewsSection = z.object({\n color: z.string().default('#fadb14'),\n /**\n * Localized review-count templates (`{{reviewCount}}`), one/other plural forms; the client picks the\n * form via `Intl.PluralRules`. Defaults here (schema-first) so every tree localizes without converter\n * or merchant work.\n */\n countLabels: z\n .object({\n one: z.record(z.string(), z.string()).default(() => ({ ...REVIEW_LABELS.one })),\n other: z.record(z.string(), z.string()).default(() => ({ ...REVIEW_LABELS.other })),\n })\n .default(() => ({ one: { ...REVIEW_LABELS.one }, other: { ...REVIEW_LABELS.other } })),\n name: z.string().optional(),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.reviews).default(SectionType.reviews),\n size: z.enum(reviewsSizes).default(ReviewsSize.default),\n});\n\nexport type CABReviewsSection = z.infer<typeof CABReviewsSection>;\n\nexport type CABReviewsSectionProps = CABReviewsSection & SectionDetails;\n", "/**\n * Default localized review-count templates for the reviews section, keyed by CLDR-ish plural form then\n * locale (same 26 locales as `SWITCH_LABELS`). The client picks `one` vs `other` via `Intl.PluralRules`\n * and interpolates `{{reviewCount}}` \u2014 the two-form simplification maps every non-`one` category\n * (few/many/other) to `other`. Schema-default content, never a client dictionary (Peter, 2026-07-06:\n * visible customer strings must be localized).\n */\nexport const REVIEW_LABELS = {\n one: {\n ar: '({{reviewCount}} \u062A\u0642\u064A\u064A\u0645)',\n cs: '({{reviewCount}} recenze)',\n da: '({{reviewCount}} anmeldelse)',\n de: '({{reviewCount}} Bewertung)',\n en: '({{reviewCount}} review)',\n es: '({{reviewCount}} rese\u00F1a)',\n fi: '({{reviewCount}} arvostelu)',\n fr: '({{reviewCount}} avis)',\n ga: '({{reviewCount}} l\u00E9irmheas)',\n he: '({{reviewCount}} \u05D1\u05D9\u05E7\u05D5\u05E8\u05EA)',\n hi: '({{reviewCount}} \u0938\u092E\u0940\u0915\u094D\u0937\u093E)',\n id: '({{reviewCount}} ulasan)',\n it: '({{reviewCount}} recensione)',\n ja: '({{reviewCount}}\u4EF6\u306E\u30EC\u30D3\u30E5\u30FC)',\n ko: '({{reviewCount}}\uAC1C \uB9AC\uBDF0)',\n nl: '({{reviewCount}} beoordeling)',\n no: '({{reviewCount}} anmeldelse)',\n pl: '({{reviewCount}} opinia)',\n pt: '({{reviewCount}} avalia\u00E7\u00E3o)',\n ru: '({{reviewCount}} \u043E\u0442\u0437\u044B\u0432)',\n sv: '({{reviewCount}} recension)',\n th: '({{reviewCount}} \u0E23\u0E35\u0E27\u0E34\u0E27)',\n tr: '({{reviewCount}} de\u011Ferlendirme)',\n uk: '({{reviewCount}} \u0432\u0456\u0434\u0433\u0443\u043A)',\n vi: '({{reviewCount}} \u0111\u00E1nh gi\u00E1)',\n zh: '({{reviewCount}} \u6761\u8BC4\u4EF7)',\n },\n other: {\n ar: '({{reviewCount}} \u062A\u0642\u064A\u064A\u0645\u0627\u062A)',\n cs: '({{reviewCount}} recenz\u00ED)',\n da: '({{reviewCount}} anmeldelser)',\n de: '({{reviewCount}} Bewertungen)',\n en: '({{reviewCount}} reviews)',\n es: '({{reviewCount}} rese\u00F1as)',\n fi: '({{reviewCount}} arvostelua)',\n fr: '({{reviewCount}} avis)',\n ga: '({{reviewCount}} l\u00E9irmheasanna)',\n he: '({{reviewCount}} \u05D1\u05D9\u05E7\u05D5\u05E8\u05D5\u05EA)',\n hi: '({{reviewCount}} \u0938\u092E\u0940\u0915\u094D\u0937\u093E\u090F\u0901)',\n id: '({{reviewCount}} ulasan)',\n it: '({{reviewCount}} recensioni)',\n ja: '({{reviewCount}}\u4EF6\u306E\u30EC\u30D3\u30E5\u30FC)',\n ko: '({{reviewCount}}\uAC1C \uB9AC\uBDF0)',\n nl: '({{reviewCount}} beoordelingen)',\n no: '({{reviewCount}} anmeldelser)',\n pl: '({{reviewCount}} opinii)',\n pt: '({{reviewCount}} avalia\u00E7\u00F5es)',\n ru: '({{reviewCount}} \u043E\u0442\u0437\u044B\u0432\u043E\u0432)',\n sv: '({{reviewCount}} recensioner)',\n th: '({{reviewCount}} \u0E23\u0E35\u0E27\u0E34\u0E27)',\n tr: '({{reviewCount}} de\u011Ferlendirme)',\n uk: '({{reviewCount}} \u0432\u0456\u0434\u0433\u0443\u043A\u0456\u0432)',\n vi: '({{reviewCount}} \u0111\u00E1nh gi\u00E1)',\n zh: '({{reviewCount}} \u6761\u8BC4\u4EF7)',\n },\n} satisfies Record<'one' | 'other', Record<string, string>>;\n", "import { slice } from 'es-toolkit/compat';\nimport { v7 as uuidv7 } from 'uuid';\nimport { z } from 'zod';\n\nimport { SectionType, VariantMode, variantModes, VariantSelector, variantSelectors } from './common';\nimport { CABRule } from './rule';\nimport { type SectionDetails } from './shared';\n\nexport const CABVariantsSection = z.object({\n hideOutOfStockVariants: z.boolean().default(false),\n name: z.string().optional(),\n rule: CABRule.optional(),\n sectionId: z.uuid().default(() => uuidv7()),\n sectionType: z.literal(SectionType.variants).default(SectionType.variants),\n selector: z.enum(slice(variantSelectors, 0, 3)).default(VariantSelector.menu),\n variantMode: z.enum(variantModes).default(VariantMode.multiple),\n});\n\nexport type CABVariantsSection = z.infer<typeof CABVariantsSection>;\n\nexport type CABVariantsSectionProps = CABVariantsSection & SectionDetails;\n", "const HTML_COMMENT_RE = /<!--[\\s\\S]*?-->/g;\nconst STRIPPED_ELEMENT_RE = /<(script|style|iframe|object|embed|noscript|template)\\b[^>]*>[\\s\\S]*?(?:<\\/\\1\\s*>|$)/gi;\nconst HTML_TAG_RE = /<\\/?[a-zA-Z][^>]*>/g;\n\nexport const stripContentBlockHtml = (text: string): string =>\n text.replace(HTML_COMMENT_RE, '').replace(STRIPPED_ELEMENT_RE, '').replace(HTML_TAG_RE, '');\n", "import { TiptapParagraph, type TiptapText } from '~/schema/widgets/checkout-and-beyond/text';\nimport { stripContentBlockHtml } from '~/transforms/contentBlockV1/stripContentBlockHtml';\n\ntype ConvertTextToTiptapArgs = {\n color: string;\n fontSize: string;\n marks?: NonNullable<TiptapText['marks']>;\n text: string;\n textAlign: 'start' | 'center' | 'end';\n};\n\nexport const convertTextToTiptapParagraph = ({\n color,\n fontSize,\n marks = [],\n text,\n textAlign,\n}: ConvertTextToTiptapArgs): TiptapParagraph => {\n const sanitizedText = stripContentBlockHtml(text);\n\n return TiptapParagraph.parse({\n attrs: { textAlign },\n content: sanitizedText\n ? [\n {\n marks: [{ attrs: { color, fontSize }, type: 'textStyle' }, ...marks],\n text: sanitizedText,\n type: 'text',\n },\n ]\n : [],\n type: 'paragraph',\n });\n};\n", "/**\n * Minimal v1 content-block input types. The legacy `/widgets/settings` endpoint\n * returns the widget's settings object directly (no envelope), so the converter\n * input is just `{ id, settings }` \u2014 `name` / `owner` aren't in the upstream\n * response and would be set to schema defaults in the produced `CABRootSection`.\n */\n\nexport const SHOPIFY_CHECKOUT_EXTENSION_CONTENT_BLOCK = 'ui_extension_content_block' as const;\n\n/** Pixel threshold above which an aside-placed image is forced to top placement. */\nexport const CONTENT_BLOCK_MAX_IMAGE_WIDTH = 560;\n\nexport type V1ImagePlacement = 'top' | 'right' | 'bottom' | 'left';\n\nexport type V1ImageBlock = {\n altText?: string | null;\n category?: string;\n description?: string | null;\n filename?: string;\n id: string;\n imagePlacement: V1ImagePlacement;\n imageSize: number;\n imageUrl: string;\n index?: number;\n textAlignment?: 'left' | 'center' | 'right';\n textSize?: string;\n};\n\nexport type V1Language = {\n description?: string;\n superTitle?: string;\n title?: string;\n};\n\nexport type V1Settings = {\n blockSpacing?: string;\n imageBlocks?: V1ImageBlock[];\n imageLayout?: 'row' | 'column';\n language?: V1Language;\n location?: 'checkout' | 'order-status' | 'thank-you';\n previewMode?: boolean;\n type: typeof SHOPIFY_CHECKOUT_EXTENSION_CONTENT_BLOCK;\n version: 1;\n};\n\nexport type V1ConvertInput = {\n id: number;\n settings: V1Settings;\n};\n\nexport const isContentBlockV1 = (data: unknown): data is V1Settings => {\n if (!data || typeof data !== 'object') return false;\n\n const obj = data as Record<string, unknown>;\n\n return obj.version === 1 && obj.type === SHOPIFY_CHECKOUT_EXTENSION_CONTENT_BLOCK;\n};\n", "import { CABImageSection } from '~/schema/widgets/checkout-and-beyond/image';\nimport { CABLayoutSection } from '~/schema/widgets/checkout-and-beyond/layout';\nimport { CABTextSection } from '~/schema/widgets/checkout-and-beyond/text';\nimport { convertTextToTiptapParagraph } from '~/transforms/contentBlockV1/convertTextToTiptapParagraph';\nimport { stripContentBlockHtml } from '~/transforms/contentBlockV1/stripContentBlockHtml';\nimport {\n CONTENT_BLOCK_MAX_IMAGE_WIDTH,\n type V1ImageBlock,\n type V1ImagePlacement,\n} from '~/transforms/contentBlockV1/types';\n\nconst V1_TO_CAB_ALIGN = { center: 'center', left: 'start', right: 'end' } as const;\n\n/**\n * When an aside-placed image hits the max width, the legacy renderer forces\n * placement to `top` so the description doesn't get squeezed into a zero-width\n * column. Replicate here so the v2 layout matches what the legacy React widget\n * actually displayed.\n */\nconst resolveEffectivePlacement = (placement: V1ImagePlacement, imageSize: number): V1ImagePlacement => {\n const isAside = placement === 'left' || placement === 'right';\n\n return imageSize >= CONTENT_BLOCK_MAX_IMAGE_WIDTH && isAside ? 'top' : placement;\n};\n\n/**\n * The divisor is the same constant the legacy renderer clamps at (560), so an\n * `imageSize = 560` block renders at 100% \u2014 matching the legacy behavior\n * where 560 was the full layout width.\n */\nconst widthPercentForImageSize = (imageSize: number): number =>\n Math.min(Math.round((imageSize / CONTENT_BLOCK_MAX_IMAGE_WIDTH) * 100), 100);\n\nexport const convertContentBlockImageToV2 = (block: V1ImageBlock): CABImageSection | CABLayoutSection => {\n const { altText, category, description, id, imagePlacement, imageSize, imageUrl, textAlignment, textSize } = block;\n const placement = resolveEffectivePlacement(imagePlacement, imageSize);\n\n const imageSection = CABImageSection.parse({\n altText: stripContentBlockHtml(altText ?? ''),\n category,\n sectionId: id,\n sectionType: 'image',\n source: imageUrl,\n width: widthPercentForImageSize(imageSize),\n });\n\n if (!description) return imageSection;\n\n const textSection = CABTextSection.parse({\n content: {\n en: {\n attrs: { blockSpacing: 'base' },\n content: [\n convertTextToTiptapParagraph({\n color: 'base',\n fontSize: textSize ?? 'base',\n text: description,\n textAlign: textAlignment ? V1_TO_CAB_ALIGN[textAlignment] : 'start',\n }),\n ],\n type: 'doc',\n },\n },\n sectionType: 'text',\n });\n\n return CABLayoutSection.parse({\n alignment: { horizontal: 'center', vertical: 'middle' },\n direction: placement === 'left' || placement === 'right' ? 'columns' : 'rows',\n sections:\n placement === 'left' || placement === 'top' ? [imageSection, textSection] : [textSection, imageSection],\n sectionType: 'layout',\n spacing: 'tight',\n });\n};\n", "import { TiptapDocument } from '~/schema/widgets/checkout-and-beyond/text';\nimport { convertTextToTiptapParagraph } from '~/transforms/contentBlockV1/convertTextToTiptapParagraph';\nimport { type V1Language } from '~/transforms/contentBlockV1/types';\n\nexport const convertContentBlockTextToV2 = (language: V1Language | undefined): TiptapDocument => {\n const description = language?.description;\n const superTitle = language?.superTitle;\n const title = language?.title;\n\n return TiptapDocument.parse({\n attrs: { blockSpacing: 'tight' },\n content: [\n superTitle\n ? convertTextToTiptapParagraph({\n color: 'base',\n fontSize: 'extraLarge',\n marks: [{ type: 'bold' }],\n text: superTitle,\n textAlign: 'center',\n })\n : null,\n title\n ? convertTextToTiptapParagraph({\n color: 'base',\n fontSize: 'medium',\n marks: [{ type: 'bold' }],\n text: title,\n textAlign: 'center',\n })\n : null,\n description\n ? convertTextToTiptapParagraph({\n color: 'base',\n fontSize: 'base',\n text: description,\n textAlign: 'center',\n })\n : null,\n ].filter((p): p is NonNullable<typeof p> => p !== null),\n type: 'doc',\n });\n};\n", "import { z } from 'zod';\n\nimport { EditorMode, editorModes } from './common';\nimport { targetAreas, WidgetType, widgetTypes } from './constants';\nimport { CABLayoutSection } from './layout';\nimport { UI_LABELS } from './uiLabels';\n\n/**\n * A per-slot `Record<locale, string>` defaulted from {@link UI_LABELS}: a missing slot gets the fallback,\n * and a present-but-empty slot (`{}`) is guarded back to the fallback too \u2014 otherwise the per-slot default\n * (which only fires for `undefined`) is bypassed and the client renders a blank aria label.\n */\nconst localized = (fallback: Record<string, string>) =>\n z\n .record(z.string(), z.string())\n .default(() => ({ ...fallback }))\n .transform((labels) => (Object.keys(labels).length > 0 ? labels : { ...fallback }));\n\n/**\n * Localized UI-chrome labels for the tree, defaulted from {@link UI_LABELS} at parse so every widget\n * carries them without converter or merchant work. Per-slot `Record<locale, string>`; the client indexes\n * the buyer language with `selectLanguage`. Lives on the root (not per section) because these strings \u2014\n * spinner/carousel/select-label/variant-state chrome \u2014 are shared across the whole tree.\n */\nexport const CABUILabels = z\n .object({\n currentPage: localized(UI_LABELS.currentPage),\n loadingOptions: localized(UI_LABELS.loadingOptions),\n nextPage: localized(UI_LABELS.nextPage),\n offerDialog: localized(UI_LABELS.offerDialog),\n page: localized(UI_LABELS.page),\n previousPage: localized(UI_LABELS.previousPage),\n selected: localized(UI_LABELS.selected),\n subscriptionOptions: localized(UI_LABELS.subscriptionOptions),\n updating: localized(UI_LABELS.updating),\n })\n .default(() => ({\n currentPage: { ...UI_LABELS.currentPage },\n loadingOptions: { ...UI_LABELS.loadingOptions },\n nextPage: { ...UI_LABELS.nextPage },\n offerDialog: { ...UI_LABELS.offerDialog },\n page: { ...UI_LABELS.page },\n previousPage: { ...UI_LABELS.previousPage },\n selected: { ...UI_LABELS.selected },\n subscriptionOptions: { ...UI_LABELS.subscriptionOptions },\n updating: { ...UI_LABELS.updating },\n }));\n\nexport type CABUILabels = Record<keyof typeof UI_LABELS, Record<string, string>>;\n\nconst TargetArea = z\n .object({\n fill: z.boolean().optional(),\n flip: z.enum(['both', 'horizontal', 'vertical']).optional(),\n icon: z.string(),\n label: z.string(),\n width: z.string(),\n })\n .default(targetAreas[EditorMode.checkoutExtension][1]);\n\nexport type TargetArea = {\n fill?: boolean;\n flip?: 'horizontal' | 'vertical' | 'both';\n icon: string;\n label: string;\n width: string;\n};\n\nexport const CABTracking = z\n .object({\n enableAttribution: z.boolean().default(true),\n enableSource: z.boolean().default(true),\n enableWidget: z.boolean().default(true),\n })\n .default({ enableAttribution: true, enableSource: true, enableWidget: true });\n\nexport type CABTracking = z.infer<typeof CABTracking>;\n\n/**\n * The A/B experiment this tree was selected for, attached server-side when the placeholder widget is an\n * experiment target (else absent). The client renders the chosen variant's tree as usual and emits the\n * `ab-test-viewed` / `ABN.TEST` analytics from these fields \u2014 replicating React's `useAnalyticsEvent`.\n */\nexport const CABExperiment = z.object({\n elementId: z.number(),\n experimentId: z.number(),\n experimentType: z.string(),\n selectedId: z.number(),\n});\n\nexport type CABExperiment = z.infer<typeof CABExperiment>;\n\nexport const CABRootSection = CABLayoutSection.extend({\n editorMode: z.enum(editorModes).default(EditorMode.checkoutExtension),\n experiment: CABExperiment.optional(),\n previewMode: z.boolean().default(false),\n storeId: z.number().nullable().default(null),\n targetArea: TargetArea.nullable(),\n tracking: CABTracking,\n type: z.enum(widgetTypes).default(WidgetType.ui_extension_content_block),\n uiLabels: CABUILabels,\n version: z.literal(2).default(2),\n widgetId: z.number().nullable().default(null),\n});\n\nexport type CABRootSection = CABLayoutSection & {\n editorMode: EditorMode;\n experiment?: CABExperiment;\n previewMode: boolean;\n storeId: number | null;\n targetArea: TargetArea | null;\n tracking: CABTracking;\n type: WidgetType;\n uiLabels: CABUILabels;\n version: number;\n widgetId: number | null;\n};\n", "/**\n * Default UI-chrome labels \u2014 the buyer-visible and screen-reader strings that have no per-section\n * merchant slot: the subscription-frequency select's group label, spinner busy text, carousel control\n * names + current-page semantics, the variant selected-state suffix, and the Monetize offer dialog\n * name. Keyed by slot then locale, shipped in the payload so the client never bundles a dictionary\n * (Peter, 2026-07-06: visible customer strings must be localized). English defaults only \u2014 unlike the\n * merchant-authored `SWITCH_LABELS`/`GIFT_LABELS`, these mirror strings legacy hardcoded in English, so\n * the fix is making them payload-sourced (localizable, zero bundle) rather than inventing 25 unreviewed\n * translations; a merchant or a later localization pass can populate other locales. `{{page}}` in the\n * pagination slots is interpolated per control at render.\n */\nexport const UI_LABELS = {\n currentPage: { en: 'Page {{page}}, current' },\n loadingOptions: { en: 'Loading subscription options' },\n nextPage: { en: 'Next' },\n offerDialog: { en: 'Offer' },\n page: { en: 'Page {{page}}' },\n previousPage: { en: 'Previous' },\n selected: { en: 'selected' },\n subscriptionOptions: { en: 'Subscription Options' },\n updating: { en: 'Updating' },\n} satisfies Record<string, Record<string, string>>;\n", "import { CABRootSection } from '~/schema/widgets/checkout-and-beyond/root';\nimport { convertContentBlockImageToV2 } from '~/transforms/contentBlockV1/convertContentBlockImageToV2';\nimport { convertContentBlockTextToV2 } from '~/transforms/contentBlockV1/convertContentBlockTextToV2';\nimport {\n SHOPIFY_CHECKOUT_EXTENSION_CONTENT_BLOCK,\n type V1ConvertInput,\n type V1Language,\n} from '~/transforms/contentBlockV1/types';\n\nconst LOCATION_TO_EDITOR_MODE = {\n checkout: 'checkoutExtension',\n 'order-status': 'orderStatusPage',\n 'thank-you': 'thankYouPage',\n} as const;\n\nconst hasText = (language: V1Language | undefined): boolean =>\n !!language && !!(language.description || language.superTitle || language.title);\n\n/** Translates a v1 content-block widget into a fully-formed `CABRootSection`. */\nexport const convertContentBlockToV2 = ({ id, settings }: V1ConvertInput): CABRootSection => {\n const imageBlocks = settings.imageBlocks ?? [];\n\n return CABRootSection.parse({\n alignment: { horizontal: 'center', vertical: 'top' },\n direction: 'rows',\n editorMode: LOCATION_TO_EDITOR_MODE[settings.location ?? 'checkout'],\n previewMode: settings.previewMode,\n sections: [\n hasText(settings.language)\n ? {\n content: { en: convertContentBlockTextToV2(settings.language) },\n sectionType: 'text',\n }\n : null,\n imageBlocks.length > 0\n ? {\n // Legacy centers every image block (`InlineLayout inlineAlignment=\"center\"`).\n alignment: { horizontal: 'center', vertical: 'middle' },\n // Legacy: `image_layout === 'row' ? BlockStack : InlineStack` \u2014 an UNSET layout is\n // horizontal (columns), so only an explicit 'row' may stack vertically.\n direction: settings.imageLayout === 'row' ? 'rows' : 'columns',\n sections: imageBlocks.map(convertContentBlockImageToV2),\n sectionType: 'layout',\n spacing: settings.blockSpacing ?? 'extraTight',\n }\n : null,\n ].filter((section): section is NonNullable<typeof section> => section !== null),\n sectionType: 'layout',\n type: SHOPIFY_CHECKOUT_EXTENSION_CONTENT_BLOCK,\n version: 2,\n widgetId: id,\n });\n};\n", "const ARRAY_INDEX_STRING = /^(?:0|[1-9]\\d*)$/;\n\nconst isPlainObject = (input: unknown): input is Record<string, unknown> => {\n if (input === null || typeof input !== 'object') return false;\n\n const proto = Object.getPrototypeOf(input) as object | null;\n\n return proto === Object.prototype || proto === null;\n};\n\nconst hasOnlyNumericKeys = (input: Record<string, unknown>): boolean => {\n const keys = Object.keys(input);\n\n if (keys.length === 0) return false;\n\n if (!keys.every((key) => ARRAY_INDEX_STRING.test(key) && Number.isSafeInteger(Number(key)))) return false;\n\n // Require the indices to form a complete `0..n-1` sequence \u2014 `{ \"10\": \"a\", \"20\": \"b\" }`\n // would otherwise silently collapse into `[\"a\", \"b\"]` and lose its original positions.\n const sorted = keys.map(Number).sort((a, b) => a - b);\n\n return sorted.every((n, i) => n === i);\n};\n\nconst numericObjectToArray = (input: Record<string, unknown>): unknown[] =>\n Object.entries(input)\n .sort(([a], [b]) => Number(a) - Number(b))\n .map(([, value]) => value);\n\n/**\n * Recursively converts objects whose keys are a complete `0..n-1` sequence\n * (PHP-serialized \"sparse\" arrays) into real arrays. Everything else passes\n * through unchanged.\n */\nexport const convertNumericObjects = (input: unknown): unknown => {\n if (Array.isArray(input)) return input.map(convertNumericObjects);\n\n if (isPlainObject(input)) {\n if (hasOnlyNumericKeys(input)) return numericObjectToArray(input).map(convertNumericObjects);\n\n const out: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(input)) out[key] = convertNumericObjects(value);\n\n return out;\n }\n\n return input;\n};\n", "const isPlainObject = (input: unknown): input is Record<string, unknown> => {\n if (input === null || typeof input !== 'object') return false;\n\n const proto = Object.getPrototypeOf(input) as object | null;\n\n return proto === Object.prototype || proto === null;\n};\n\nconst camelCase = (key: string): string =>\n key.replace(/[-_\\s]+(.)?/g, (_, char: string | undefined) => (char ? char.toUpperCase() : ''));\n\nexport type ToCamelCase<S extends string> = S extends `${infer Head}_${infer Tail}` | `${infer Head}-${infer Tail}`\n ? `${Head}${Capitalize<ToCamelCase<Tail>>}`\n : S;\n\nexport type DeepCamelCase<T> = T extends (infer U)[]\n ? DeepCamelCase<U>[]\n : T extends object\n ? { [K in keyof T as ToCamelCase<K & string>]: DeepCamelCase<T[K]> }\n : T;\n\n/**\n * Recursively converts object keys to camelCase. Snake_case and kebab-case\n * are both handled; numeric array indices and primitives pass through\n * unchanged.\n *\n * Language keys used by the CAB schema (`text.content[<lang>]`, etc.) are\n * authored as plain lowercase tags (`en`, `de`, `fr`) by us \u2014 they have no\n * `_` or `-` to convert and survive camelCase as-is.\n */\nexport const deepCamelCase = <T>(input: T): DeepCamelCase<T> => {\n if (Array.isArray(input)) return input.map((item) => deepCamelCase(item)) as DeepCamelCase<T>;\n\n if (isPlainObject(input)) {\n const out: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(input)) {\n out[camelCase(key)] = deepCamelCase(value);\n }\n\n return out as DeepCamelCase<T>;\n }\n\n return input as DeepCamelCase<T>;\n};\n", "import { type TextColorName, type TextSizeName } from '~/schema/widgets/checkout-and-beyond/common';\nimport { type Mark } from '~/transforms/htmlToTiptap/types';\n\nexport const buildDefaultTextStyleMark = (\n style: { color?: TextColorName; fontSize?: TextSizeName } | undefined\n): Mark | null => {\n if (!style || (style.color === undefined && style.fontSize === undefined)) return null;\n\n return {\n attrs: {\n color: style.color ?? 'base',\n fontSize: style.fontSize ?? 'base',\n },\n type: 'textStyle',\n };\n};\n", "import { type StackEntry } from '~/transforms/htmlToTiptap/types';\n\nexport const closeTag = (stack: StackEntry[], name: string): void => {\n for (let index = stack.length - 1; index >= 0; index--) {\n if (stack[index].tag === name) {\n stack.length = index;\n break;\n }\n }\n};\n", "export const TAG_RE = /<(\\/)?([a-zA-Z][a-zA-Z0-9]*)((?:\\s+[^>]*?)?)\\s*(\\/)?>/g;\n\n/**\n * Tags that introduce a paragraph break on both open and close. Container tags\n * like `ul`/`ol`/`dl` are intentionally NOT here \u2014 their child `li`/`dt`/`dd`\n * elements already break, and including the containers would double-flush.\n */\nexport const BLOCK_TAGS = new Set([\n 'article',\n 'aside',\n 'blockquote',\n 'dd',\n 'div',\n 'dt',\n 'figcaption',\n 'figure',\n 'footer',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'header',\n 'hr',\n 'li',\n 'main',\n 'nav',\n 'p',\n 'pre',\n 'section',\n]);\n", "import { TiptapParagraph, type TiptapText } from '~/schema/widgets/checkout-and-beyond/text';\n\nexport const makeParagraph = (content: TiptapText[]): TiptapParagraph => TiptapParagraph.parse({ content });\n", "import { makeParagraph } from '~/transforms/htmlToTiptap/makeParagraph';\nimport { type State } from '~/transforms/htmlToTiptap/types';\n\nexport const flushParagraph = (state: State): void => {\n state.paragraphs.push(makeParagraph(state.currentRuns));\n state.currentRuns = [];\n};\n", "import { type StackEntry } from '~/transforms/htmlToTiptap/types';\n\nexport const isSkipping = (stack: StackEntry[] = []): boolean => stack.some(({ skip }) => skip);\n", "import { type Spacing } from '~/schema/widgets/checkout-and-beyond/common';\nimport { TiptapDocument, type TiptapParagraph } from '~/schema/widgets/checkout-and-beyond/text';\n\nexport const makeDoc = (content: TiptapParagraph[], blockSpacing: Spacing): TiptapDocument =>\n TiptapDocument.parse({ attrs: { blockSpacing }, content });\n", "const DYNAMIC_TOKEN_REGEX = /^\\{\\{\\s*[A-Za-z]+\\s*\\}\\}$/;\n\n/**\n * Protocols we'll preserve on `<a href>` when converting HTML to Tiptap. Any URL\n * whose `URL.protocol` falls outside this set (e.g. `javascript:`, `data:`,\n * `file:`, `vbscript:`) is dropped from the link mark \u2014 the text content is\n * kept but the click target is not. Renderers downstream still get to do their\n * own validation, but the package shouldn't be the one preserving an XSS\n * payload through the conversion.\n */\nconst ALLOWED_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'tel:']);\n\n/**\n * Decides whether an `<a href>` value should survive HTML \u2192 Tiptap conversion\n * as a link mark. Allows `#`, dynamic `{{token}}` placeholders, root-relative\n * same-origin paths (e.g. Shopify's `/policies/privacy-policy`), and a fixed\n * allowlist of URL schemes; everything else (including `javascript:`, `data:`,\n * protocol-relative `//host` paths, other relative paths, and malformed URLs)\n * drops the link mark while keeping the surrounding text.\n *\n * @param href - Raw `href` attribute from the source HTML.\n *\n * @returns `true` if the URL should be preserved as a link mark.\n */\nexport const isValidHref = (href: string): boolean => {\n if (!href) return false;\n\n if (href === '#') return true;\n\n if (DYNAMIC_TOKEN_REGEX.test(href)) return true;\n\n /** Root-relative same-origin path (single leading slash); `//host` is protocol-relative, not same-origin. */\n if (href.startsWith('/') && !href.startsWith('//')) return true;\n\n try {\n const url = new URL(href);\n\n return ALLOWED_PROTOCOLS.has(url.protocol);\n } catch {\n return false;\n }\n};\n", "import { isValidHref } from '~/transforms/htmlToTiptap/isValidHref';\nimport { type Mark } from '~/transforms/htmlToTiptap/types';\n\n/**\n * The schema defaults for an `<a>` mark when the source HTML omits them. Match\n * `TiptapText` in `~/schema/widgets/checkout-and-beyond/text` so the sanitizer\n * resolves the same effective values the downstream parse would have used.\n */\nconst DEFAULT_TARGET = '_blank';\nconst DEFAULT_REL = 'noopener noreferrer nofollow';\n\n/**\n * Forces `noopener noreferrer` on every `_blank` link to defend against\n * reverse-tabnabbing (window.opener attacks). When the source omits `rel`\n * entirely, fall back to the schema default (`noopener noreferrer nofollow`).\n * When source `rel` is non-empty, preserve the existing tokens, drop `opener`,\n * and ensure the safe pair is present.\n *\n * Non-`_blank` targets pass through unchanged \u2014 they can't be tabnabbed.\n */\nconst ensureSafeRel = (rel: string, target: string): string => {\n if (target !== '_blank') return rel;\n\n const sourceTokens = (rel ?? '').split(/\\s+/).filter(Boolean);\n\n if (sourceTokens.length === 0) return DEFAULT_REL;\n\n const tokens = new Set(sourceTokens.filter((token) => token.toLowerCase() !== 'opener'));\n\n tokens.add('noopener');\n tokens.add('noreferrer');\n\n return Array.from(tokens).join(' ');\n};\n\nexport const buildLinkMark = (attrs: Record<string, string> = {}): Mark | null => {\n const { href } = attrs;\n\n if (!href || !isValidHref(href)) return null;\n\n // Resolve target BEFORE sanitizing rel so the safety guard sees the same\n // value the downstream schema parse will use.\n const target = attrs.target ?? DEFAULT_TARGET;\n\n return {\n attrs: {\n class: null,\n href,\n rel: ensureSafeRel(attrs.rel, target),\n target,\n },\n type: 'link',\n };\n};\n", "const NAMED_ENTITIES: Record<string, string> = {\n amp: '&',\n apos: \"'\",\n copy: '\u00A9',\n gt: '>',\n hellip: '\u2026',\n ldquo: '\u201C',\n lsquo: '\u2018',\n lt: '<',\n mdash: '\u2014',\n nbsp: ' ',\n ndash: '\u2013',\n quot: '\"',\n rdquo: '\u201D',\n reg: '\u00AE',\n rsquo: '\u2019',\n trade: '\u2122',\n} as const;\n\nexport const decodeEntities = (input: string = ''): string =>\n input.replace(/&(#x[\\da-f]+|#\\d+|[a-z][a-z\\d]*);/gi, (match, code: string) => {\n if (code[0] !== '#') return NAMED_ENTITIES[code.toLowerCase()] ?? match;\n\n const isHex = /^#x/i.test(code);\n const cp = parseInt(code.slice(isHex ? 2 : 1), isHex ? 16 : 10);\n\n return Number.isInteger(cp) && cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : match;\n });\n", "import { decodeEntities } from '~/transforms/htmlToTiptap/decodeEntities';\n\nconst ATTRIB_RE = /([a-zA-Z_:][\\w:.-]*)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'`=<>]+)))?/g;\n\nexport const parseAttribs = (attrString: string): Record<string, string> => {\n const result: Record<string, string> = {};\n let match: RegExpExecArray | null;\n\n ATTRIB_RE.lastIndex = 0;\n\n while ((match = ATTRIB_RE.exec(attrString)) !== null) {\n result[match[1].toLowerCase()] = decodeEntities(match[2] ?? match[3] ?? match[4] ?? '');\n }\n\n return result;\n};\n", "import { type TextSizeName } from '~/schema/widgets/checkout-and-beyond/common';\nimport { buildLinkMark } from '~/transforms/htmlToTiptap/buildLinkMark';\nimport { parseAttribs } from '~/transforms/htmlToTiptap/parseAttribs';\nimport { type Mark, type StackEntry } from '~/transforms/htmlToTiptap/types';\n\nconst INLINE_MARK_TAGS: Record<string, 'bold' | 'italic' | 'strike'> = {\n b: 'bold',\n del: 'strike',\n em: 'italic',\n i: 'italic',\n s: 'strike',\n strike: 'strike',\n strong: 'bold',\n};\n\nconst HEADING_FONT_SIZE: Record<string, TextSizeName> = {\n h1: 'extraLarge',\n h2: 'large',\n h3: 'medium',\n h4: 'base',\n h5: 'small',\n h6: 'small',\n};\n\nconst STRIPPED_TAGS = ['embed', 'iframe', 'noscript', 'object', 'script', 'style', 'template'];\n\nconst marksForTag = (name: string, attrs: string): Mark[] => {\n if (INLINE_MARK_TAGS[name]) return [{ type: INLINE_MARK_TAGS[name] }];\n\n if (HEADING_FONT_SIZE[name]) {\n return [{ type: 'bold' }, { attrs: { color: 'base', fontSize: HEADING_FONT_SIZE[name] }, type: 'textStyle' }];\n }\n\n if (name === 'a') {\n const link = buildLinkMark(parseAttribs(attrs));\n\n return link ? [link] : [];\n }\n\n return [];\n};\n\nexport const openTag = (stack: StackEntry[], name: string, attrs: string): void => {\n stack.push({\n marks: marksForTag(name, attrs),\n skip: STRIPPED_TAGS.includes(name),\n tag: name,\n });\n};\n", "import { TiptapText } from '~/schema/widgets/checkout-and-beyond/text';\n\nimport { decodeEntities } from '~/transforms/htmlToTiptap/decodeEntities';\nimport { flushParagraph } from '~/transforms/htmlToTiptap/flushParagraph';\nimport { isSkipping } from '~/transforms/htmlToTiptap/isSkipping';\nimport { type Mark, type State } from '~/transforms/htmlToTiptap/types';\n\nexport const pushText = (state: State, rawText: string): void => {\n if (!rawText || isSkipping(state.stack)) return;\n\n decodeEntities(rawText)\n .split('\\n')\n .forEach((segment, index) => {\n if (index > 0) flushParagraph(state);\n\n if (!segment) return;\n\n const marks: Mark[] = state.stack.flatMap((entry) => entry.marks);\n\n if (state.defaultTextStyleMark && !marks.some((mark) => mark.type === 'textStyle')) {\n marks.push(state.defaultTextStyleMark);\n }\n\n state.currentRuns.push(TiptapText.parse(marks.length > 0 ? { marks, text: segment } : { text: segment }));\n });\n};\n", "const HTML_COMMENT_RE = /<!--[\\s\\S]*?-->/g;\n\nexport const stripHtmlComments = (html: string = ''): string => html.replace(HTML_COMMENT_RE, '');\n", "import { type Spacing, type TextColorName, type TextSizeName } from '~/schema/widgets/checkout-and-beyond/common';\nimport { type TiptapDocument } from '~/schema/widgets/checkout-and-beyond/text';\nimport { buildDefaultTextStyleMark } from '~/transforms/htmlToTiptap/buildDefaultTextStyleMark';\nimport { closeTag } from '~/transforms/htmlToTiptap/closeTag';\nimport { BLOCK_TAGS, TAG_RE } from '~/transforms/htmlToTiptap/constants';\nimport { flushParagraph } from '~/transforms/htmlToTiptap/flushParagraph';\nimport { isSkipping } from '~/transforms/htmlToTiptap/isSkipping';\nimport { makeDoc } from '~/transforms/htmlToTiptap/makeDoc';\nimport { makeParagraph } from '~/transforms/htmlToTiptap/makeParagraph';\nimport { openTag } from '~/transforms/htmlToTiptap/openTag';\nimport { pushText } from '~/transforms/htmlToTiptap/pushText';\nimport { stripHtmlComments } from '~/transforms/htmlToTiptap/stripHtmlComments';\nimport { type State } from '~/transforms/htmlToTiptap/types';\n\nexport type HtmlToTiptapOptions = {\n blockSpacing?: Spacing;\n defaultTextStyle?: { color?: TextColorName; fontSize?: TextSizeName };\n};\n\nconst maybeFlushParagraph = (state: State): void => {\n if (state.currentRuns.length > 0) flushParagraph(state);\n};\n\nexport const htmlToTiptap = (html: string, options: HtmlToTiptapOptions = {}): TiptapDocument => {\n const state: State = {\n currentRuns: [],\n defaultTextStyleMark: buildDefaultTextStyleMark(options.defaultTextStyle),\n listStack: [],\n paragraphs: [],\n stack: [],\n };\n const blockSpacing = options.blockSpacing ?? 'base';\n\n if (typeof html !== 'string' || !html) return makeDoc([makeParagraph([])], blockSpacing);\n\n const htmlWithoutComments = stripHtmlComments(html);\n let lastIndex = 0;\n let match: RegExpExecArray | null;\n\n TAG_RE.lastIndex = 0;\n\n while ((match = TAG_RE.exec(htmlWithoutComments)) !== null) {\n const [full, slash, rawName, attrs, selfClose] = match;\n\n if (match.index > lastIndex) pushText(state, htmlWithoutComments.slice(lastIndex, match.index));\n\n lastIndex = match.index + full.length;\n\n const name = rawName.toLowerCase();\n\n if (slash) {\n closeTag(state.stack, name);\n\n if (name === 'ul' || name === 'ol') state.listStack.pop();\n\n if (BLOCK_TAGS.has(name) && !isSkipping(state.stack)) maybeFlushParagraph(state);\n } else if (name === 'br') {\n if (!isSkipping(state.stack)) flushParagraph(state);\n } else if (name === 'hr') {\n if (!isSkipping(state.stack)) {\n maybeFlushParagraph(state);\n pushText(state, '\u2014\u2014\u2014');\n flushParagraph(state);\n }\n } else if (!selfClose) {\n if (BLOCK_TAGS.has(name) && !isSkipping(state.stack)) maybeFlushParagraph(state);\n\n if (name === 'ul' || name === 'ol') state.listStack.push({ counter: 0, ordered: name === 'ol' });\n\n openTag(state.stack, name, attrs);\n\n if (name === 'li' && state.listStack.length > 0) {\n const top = state.listStack[state.listStack.length - 1]!;\n\n if (top.ordered) top.counter += 1;\n\n pushText(state, top.ordered ? `${top.counter}. ` : '\u2022 ');\n }\n }\n }\n\n if (lastIndex < htmlWithoutComments.length) pushText(state, htmlWithoutComments.slice(lastIndex));\n\n maybeFlushParagraph(state);\n\n if (state.paragraphs.length === 0) flushParagraph(state);\n\n return makeDoc(state.paragraphs, blockSpacing);\n};\n", "/**\n * True when the input has `version === 2` \u2014 the marker for a current-generation\n * Checkout-and-Beyond root section. The transformer for CAB (`CABRootSection.parse`)\n * should ONLY run on values that pass this check; v1 widget shapes either get\n * converted (e.g. via `convertContentBlockToV2`) or pass through unchanged.\n *\n * @param input - The post-camelCase, post-numeric-fix upstream payload.\n *\n * @returns `true` if `input.version === 2`, otherwise `false`.\n */\nexport const isCABRootSection = (input: unknown): boolean => {\n if (!input || typeof input !== 'object') return false;\n\n return (input as { version?: unknown }).version === 2;\n};\n", "/**\n * Default localized labels for the switch-to-subscription button content, keyed by `buttonField` then locale.\n * The single source of truth shared by the admin editor and the read-time `convertLineItemEditorToV2` transform\n * so a widget renders identically whether migrated in admin or converted on the fly. `{{subscriptionDiscount}}`\n * is substituted per-plan at render \u2014 CAB tokens are camelCase by default; a legacy snake_case token in a v1\n * merchant override still resolves (the client camelCases unknown token keys against its camelCase variables).\n * `subscriptionOption` is the frequency-select option template (legacy\n * `SwitchToSubscriptionLanguageDefaults.subscription_option_label`); the client resolves `{{interval}}`\n * through `Intl.NumberFormat` unit style, so the noun arrives in the buyer's language, pluralized per count\n * from the runtime's CLDR data (English CLDR nouns are lowercase \u2014 an accepted divergence from legacy).\n */\nexport const SWITCH_LABELS = {\n subscriptionOption: {\n ar: '\u064A\u062A\u0645 \u0627\u0644\u062A\u0648\u0635\u064A\u0644 \u0643\u0644 {{frequency}} {{interval}}',\n cs: 'Doru\u010Den\u00ED ka\u017Ed\u00FDch {{frequency}} {{interval}}',\n da: 'Leveres hver {{frequency}} {{interval}}',\n de: 'Lieferung alle {{frequency}} {{interval}}',\n en: 'Delivers every {{frequency}} {{interval}}',\n es: 'Entrega cada {{frequency}} {{interval}}',\n fi: 'Toimitus {{frequency}} {{interval}} v\u00E4lein',\n fr: 'Livraison tous les {{frequency}} {{interval}}',\n ga: 'Seachadtar gach {{frequency}} {{interval}}',\n he: '\u05DE\u05E9\u05DC\u05D5\u05D7 \u05DB\u05DC {{frequency}} {{interval}}',\n hi: '\u0939\u0930 {{frequency}} {{interval}} \u092E\u0947\u0902 \u0921\u093F\u0932\u0940\u0935\u0930\u0940',\n id: 'Dikirim setiap {{frequency}} {{interval}}',\n it: 'Consegna ogni {{frequency}} {{interval}}',\n ja: '{{frequency}} {{interval}}\u3054\u3068\u306B\u304A\u5C4A\u3051',\n ko: '{{frequency}} {{interval}}\uB9C8\uB2E4 \uBC30\uC1A1',\n nl: 'Wordt elke {{frequency}} {{interval}} geleverd',\n no: 'Leveres hver {{frequency}} {{interval}}',\n pl: 'Dostawa co {{frequency}} {{interval}}',\n pt: 'Entrega a cada {{frequency}} {{interval}}',\n ru: '\u0414\u043E\u0441\u0442\u0430\u0432\u043A\u0430 \u043A\u0430\u0436\u0434\u044B\u0435 {{frequency}} {{interval}}',\n sv: 'Levereras var {{frequency}} {{interval}}',\n th: '\u0E08\u0E31\u0E14\u0E2A\u0E48\u0E07\u0E17\u0E38\u0E01 {{frequency}} {{interval}}',\n tr: 'Her {{frequency}} {{interval}} aral\u0131\u011F\u0131nda teslimat',\n uk: '\u0414\u043E\u0441\u0442\u0430\u0432\u043A\u0430 \u043A\u043E\u0436\u043D\u0456 {{frequency}} {{interval}}',\n vi: 'Giao h\u00E0ng m\u1ED7i {{frequency}} {{interval}}',\n zh: '\u6BCF {{frequency}} {{interval}} \u914D\u9001\u4E00\u6B21',\n },\n switchToOneTimePurchase: {\n ar: '\u0627\u0644\u062A\u0628\u062F\u064A\u0644 \u0625\u0644\u0649 \u0634\u0631\u0627\u0621 \u0644\u0645\u0631\u0629 \u0648\u0627\u062D\u062F\u0629',\n cs: 'P\u0159epnout na jednor\u00E1zov\u00FD n\u00E1kup',\n da: 'Skift til engangsk\u00F8b',\n de: 'Zu einmaligem Kauf wechseln',\n en: 'Switch to One-time Purchase',\n es: 'Cambiar a compra \u00FAnica',\n fi: 'Vaihda kertaluonteiseen ostoon',\n fr: 'Passer \u00E0 un achat unique',\n ga: 'Athraigh go ceannach aonuaire',\n he: '\u05E2\u05D1\u05D5\u05E8 \u05DC\u05E8\u05DB\u05D9\u05E9\u05D4 \u05D7\u05D3-\u05E4\u05E2\u05DE\u05D9\u05EA',\n hi: '\u090F\u0915 \u092C\u093E\u0930 \u0915\u0940 \u0916\u0930\u0940\u0926 \u092A\u0930 \u0938\u094D\u0935\u093F\u091A \u0915\u0930\u0947\u0902',\n id: 'Beralih ke pembelian satu kali',\n it: 'Passa all\u2019acquisto una tantum',\n ja: '1\u56DE\u9650\u308A\u306E\u8CFC\u5165\u306B\u5207\u308A\u66FF\u3048\u308B',\n ko: '\uC77C\uD68C\uC131 \uAD6C\uB9E4\uB85C \uC804\uD658',\n nl: 'Overschakelen naar eenmalige aankoop',\n no: 'Bytt til engangskj\u00F8p',\n pl: 'Prze\u0142\u0105cz na jednorazowy zakup',\n pt: 'Mudar para compra \u00FAnica',\n ru: '\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043D\u0430 \u0440\u0430\u0437\u043E\u0432\u0443\u044E \u043F\u043E\u043A\u0443\u043F\u043A\u0443',\n sv: 'Byt till eng\u00E5ngsk\u00F6p',\n th: '\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E40\u0E1B\u0E47\u0E19\u0E01\u0E32\u0E23\u0E0B\u0E37\u0E49\u0E2D\u0E04\u0E23\u0E31\u0E49\u0E07\u0E40\u0E14\u0E35\u0E22\u0E27',\n tr: 'Tek seferlik sat\u0131n almaya ge\u00E7',\n uk: '\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u0438\u0441\u044F \u043D\u0430 \u043E\u0434\u043D\u043E\u0440\u0430\u0437\u043E\u0432\u0443 \u043F\u043E\u043A\u0443\u043F\u043A\u0443',\n vi: 'Chuy\u1EC3n sang mua m\u1ED9t l\u1EA7n',\n zh: '\u5207\u6362\u4E3A\u4E00\u6B21\u6027\u8D2D\u4E70',\n },\n switchToSubscriptionNoDiscount: {\n ar: '\u0627\u0644\u062A\u0628\u062F\u064A\u0644 \u0625\u0644\u0649 \u0627\u0634\u062A\u0631\u0627\u0643',\n cs: 'P\u0159epnout na p\u0159edplatn\u00E9',\n da: 'Skift til abonnement',\n de: 'Zu einem Abonnement wechseln',\n en: 'Switch to Subscription',\n es: 'Cambiar a suscripci\u00F3n',\n fi: 'Vaihda tilaukseen',\n fr: 'Passer \u00E0 un abonnement',\n ga: 'Athraigh go s\u00EDnti\u00FAs',\n he: '\u05E2\u05D1\u05D5\u05E8 \u05DC\u05DE\u05E0\u05D5\u05D9',\n hi: '\u0938\u0926\u0938\u094D\u092F\u0924\u093E \u092A\u0930 \u0938\u094D\u0935\u093F\u091A \u0915\u0930\u0947\u0902',\n id: 'Beralih ke langganan',\n it: 'Passa all\u2019abbonamento',\n ja: '\u5B9A\u671F\u8CFC\u5165\u306B\u5207\u308A\u66FF\u3048\u308B',\n ko: '\uAD6C\uB3C5\uC73C\uB85C \uC804\uD658',\n nl: 'Overschakelen naar abonnement',\n no: 'Bytt til abonnement',\n pl: 'Prze\u0142\u0105cz na subskrypcj\u0119',\n pt: 'Mudar para assinatura',\n ru: '\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043D\u0430 \u043F\u043E\u0434\u043F\u0438\u0441\u043A\u0443',\n sv: 'Byt till prenumeration',\n th: '\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E40\u0E1B\u0E47\u0E19\u0E01\u0E32\u0E23\u0E2A\u0E21\u0E31\u0E04\u0E23\u0E2A\u0E21\u0E32\u0E0A\u0E34\u0E01',\n tr: 'Aboneli\u011Fe ge\u00E7',\n uk: '\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u0438\u0441\u044F \u043D\u0430 \u043F\u0456\u0434\u043F\u0438\u0441\u043A\u0443',\n vi: 'Chuy\u1EC3n sang \u0111\u0103ng k\u00FD',\n zh: '\u5207\u6362\u4E3A\u8BA2\u9605',\n },\n switchToSubscriptionWithDiscount: {\n ar: '\u0627\u0644\u062A\u0628\u062F\u064A\u0644 \u0625\u0644\u0649 \u0627\u0634\u062A\u0631\u0627\u0643 \u0648\u062A\u0648\u0641\u064A\u0631 {{subscriptionDiscount}}%',\n cs: 'P\u0159epnout na p\u0159edplatn\u00E9 a u\u0161et\u0159it {{subscriptionDiscount}} %',\n da: 'Skift til abonnement og spar {{subscriptionDiscount}}%',\n de: 'Zu einem Abonnement wechseln und {{subscriptionDiscount}} % sparen',\n en: 'Switch to Subscription & Save {{subscriptionDiscount}}%',\n es: 'Cambiar a suscripci\u00F3n y ahorrar {{subscriptionDiscount}}%',\n fi: 'Vaihda tilaukseen ja s\u00E4\u00E4st\u00E4 {{subscriptionDiscount}} %',\n fr: 'Passer \u00E0 un abonnement et \u00E9conomiser {{subscriptionDiscount}} %',\n ga: 'Athraigh go s\u00EDnti\u00FAs agus s\u00E1bh\u00E1il {{subscriptionDiscount}}%',\n he: '\u05E2\u05D1\u05D5\u05E8 \u05DC\u05DE\u05E0\u05D5\u05D9 \u05D5\u05D7\u05E1\u05D5\u05DA {{subscriptionDiscount}}%',\n hi: '\u0938\u0926\u0938\u094D\u092F\u0924\u093E \u092A\u0930 \u0938\u094D\u0935\u093F\u091A \u0915\u0930\u0947\u0902 \u0914\u0930 {{subscriptionDiscount}}% \u092C\u091A\u093E\u090F\u0902',\n id: 'Beralih ke langganan dan hemat {{subscriptionDiscount}}%',\n it: 'Passa all\u2019abbonamento e risparmia {{subscriptionDiscount}}%',\n ja: '\u5B9A\u671F\u8CFC\u5165\u306B\u5207\u308A\u66FF\u3048\u3066{{subscriptionDiscount}}%\u304A\u5F97',\n ko: '\uAD6C\uB3C5\uC73C\uB85C \uC804\uD658\uD558\uACE0 {{subscriptionDiscount}}% \uC808\uC57D',\n nl: 'Overschakelen naar abonnement en {{subscriptionDiscount}}% besparen',\n no: 'Bytt til abonnement og spar {{subscriptionDiscount}}%',\n pl: 'Prze\u0142\u0105cz na subskrypcj\u0119 i oszcz\u0119d\u017A {{subscriptionDiscount}}%',\n pt: 'Mudar para assinatura e economizar {{subscriptionDiscount}}%',\n ru: '\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u044C\u0441\u044F \u043D\u0430 \u043F\u043E\u0434\u043F\u0438\u0441\u043A\u0443 \u0438 \u0441\u044D\u043A\u043E\u043D\u043E\u043C\u0438\u0442\u044C {{subscriptionDiscount}}%',\n sv: 'Byt till prenumeration och spara {{subscriptionDiscount}}%',\n th: '\u0E40\u0E1B\u0E25\u0E35\u0E48\u0E22\u0E19\u0E40\u0E1B\u0E47\u0E19\u0E01\u0E32\u0E23\u0E2A\u0E21\u0E31\u0E04\u0E23\u0E2A\u0E21\u0E32\u0E0A\u0E34\u0E01\u0E41\u0E25\u0E30\u0E1B\u0E23\u0E30\u0E2B\u0E22\u0E31\u0E14 {{subscriptionDiscount}}%',\n tr: 'Aboneli\u011Fe ge\u00E7 ve {{subscriptionDiscount}}% tasarruf et',\n uk: '\u041F\u0435\u0440\u0435\u043A\u043B\u044E\u0447\u0438\u0442\u0438\u0441\u044F \u043D\u0430 \u043F\u0456\u0434\u043F\u0438\u0441\u043A\u0443 \u0442\u0430 \u0437\u0430\u043E\u0449\u0430\u0434\u0438\u0442\u0438 {{subscriptionDiscount}}%',\n vi: 'Chuy\u1EC3n sang \u0111\u0103ng k\u00FD v\u00E0 ti\u1EBFt ki\u1EC7m {{subscriptionDiscount}}%',\n zh: '\u5207\u6362\u4E3A\u8BA2\u9605\u5E76\u8282\u7701 {{subscriptionDiscount}}%',\n },\n} as const satisfies Record<string, Record<string, string>>;\n", "import { stripContentBlockHtml } from '~/transforms/contentBlockV1/stripContentBlockHtml';\n\n/**\n * The v1 label-override policy shared by the offer-card and line-item-editor converters: a defined v1\n * label ALWAYS passes through verbatim as the `en` entry over the localized defaults \u2014 existing widget\n * language is never rewritten (product owner, 2026-07-02); blank/whitespace falls back to the full\n * default locale set (legacy `getLabelWithFallback` parity). HTML the merchant typed into a label is\n * stripped first \u2014 `CABTextSection.content` rejects tag-shaped strings at parse, so a raw `<b>`-style\n * label would otherwise 500 the whole widget.\n */\nexport const localizedContent = (defaults: Record<string, string>, override: string | undefined) => {\n const trimmed = stripContentBlockHtml(override ?? '').trim();\n\n return trimmed ? { ...defaults, en: trimmed } : defaults;\n};\n", "import { WidgetType } from '~/schema/widgets/checkout-and-beyond/constants';\nimport { CABRootSection } from '~/schema/widgets/checkout-and-beyond/root';\nimport { SWITCH_LABELS } from '~/schema/widgets/checkout-and-beyond/switchLabels';\nimport { type LineItemEditorSwitchLanguageV1 } from '~/schema/widgets/lineItemEditor';\nimport { type V1LineItemEditorConvertInput } from '~/transforms/lineItemEditorV1/types';\nimport { localizedContent } from '~/transforms/localizedContent';\n\n/** The v1 `switchToSubscription.language` key that overrides each `buttonField`'s English label. */\nconst OVERRIDE_KEY = {\n subscriptionOption: 'subscriptionOptionLabel',\n switchToOneTimePurchase: 'downgradeToOneTimeLabel',\n switchToSubscriptionNoDiscount: 'upgradeToSubscriptionWithoutDiscountLabel',\n switchToSubscriptionWithDiscount: 'upgradeToSubscriptionLabel',\n} as const satisfies Record<keyof typeof SWITCH_LABELS, keyof LineItemEditorSwitchLanguageV1>;\n\n/**\n * Translate a v1 line-item-editor widget into a `CABRootSection`: a `cartLine` section holding a\n * switch-to-subscription button, whose `buttonField`-tagged text labels use the shared localized\n * `SWITCH_LABELS` defaults with the v1 `switchToSubscription.language` value overriding `en` (same output the\n * admin editor produces, so runtime-converted and admin-migrated widgets render identically). The button is\n * omitted when the widget's switch is disabled.\n */\nconst BUTTON_KINDS = ['plain', 'primary', 'secondary'] as const;\n\nexport const convertLineItemEditorToV2 = ({ id, settings }: V1LineItemEditorConvertInput): CABRootSection => {\n const { switchToSubscription, switchToSubscriptionEnabled, tracking } = settings;\n const kind = settings.button?.kind;\n const buttonStyle = BUTTON_KINDS.includes(kind as (typeof BUTTON_KINDS)[number]) ? kind : 'plain';\n\n const labelSections = (Object.keys(SWITCH_LABELS) as (keyof typeof SWITCH_LABELS)[]).map((buttonField) => ({\n buttonField,\n content: localizedContent(\n SWITCH_LABELS[buttonField],\n switchToSubscription?.language?.[OVERRIDE_KEY[buttonField]]\n ),\n sectionType: 'text',\n }));\n\n return CABRootSection.parse({\n previewMode: settings.previewMode,\n sections: [\n {\n sections: switchToSubscriptionEnabled\n ? [\n {\n action: 'switchToSubscription',\n buttonStyle,\n disableDowngrade: switchToSubscription?.disableDowngrade ?? false,\n sections: labelSections,\n sectionType: 'button',\n },\n ]\n : [],\n sectionType: 'cartLine',\n },\n ],\n sectionType: 'layout',\n tracking: {\n enableAttribution: tracking?.enableAttribution ?? true,\n enableSource: tracking?.enableSource ?? true,\n enableWidget: tracking?.enableWidget ?? true,\n },\n type: WidgetType.ui_extension_line_item_editor,\n version: 2,\n widgetId: id,\n });\n};\n", "import { WidgetType } from '~/schema/widgets/checkout-and-beyond/constants';\nimport { type LineItemEditorV1 } from '~/schema/widgets/lineItemEditor';\n\n/**\n * The legacy `/widgets/settings` endpoint returns the widget's settings object directly (no envelope), so\n * the converter input is just `{ id, settings }` \u2014 the settings shape lives in the schema\n * (`LineItemEditorV1`) and is derived here, never re-declared.\n */\nexport type V1LineItemEditorConvertInput = {\n id: number;\n settings: LineItemEditorV1;\n};\n\n/** Identifies a v1 line-item-editor payload by version + type (mirrors `isContentBlockV1`). */\nexport const isLineItemEditorV1 = (data: unknown): data is LineItemEditorV1 => {\n if (!data || typeof data !== 'object') return false;\n\n const obj = data as Record<string, unknown>;\n\n return obj.version === 1 && obj.type === WidgetType.ui_extension_line_item_editor;\n};\n", "const DEFAULT_KNOWN_TOKENS = ['firstName', 'lastName', 'email'] as const;\n\nconst escapeForRegex = (literal: string): string => literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n\n/**\n * Rewrites legacy personalization tokens into the CAB-canonical `{{tokenName}}`\n * form expected by the client's `replaceVariables`. Specifically:\n *\n * - `{firstName}` (single brace) \u2192 `{{firstName}}`\n * - `{FirstName}` / `{FIRSTNAME}` (case variants) \u2192 `{{firstName}}`\n * - `{ firstName }` (internal whitespace) \u2192 `{{firstName}}`\n * - `{{firstName}}` (already canonical) \u2192 unchanged\n *\n * Pass `knownTokens` to control which names are normalized; anything not in the\n * list (e.g., an unrelated `{{foo}}` token) passes through untouched.\n */\nexport const normalizeTokens = (text: string, knownTokens: readonly string[] = DEFAULT_KNOWN_TOKENS): string => {\n if (typeof text !== 'string') return text;\n\n return knownTokens.reduce((acc, token) => {\n /**\n * Tokens standardize on camelCase; `_?` before each capital also matches the legacy snake_case\n * spelling ({remaining_amount} \u2192 {{remainingAmount}}).\n */\n const snakeTolerant = escapeForRegex(token).replace(/([A-Z])/g, '_?$1');\n const pattern = new RegExp(`\\\\{{1,2}\\\\s*${snakeTolerant}\\\\s*\\\\}{1,2}`, 'gi');\n\n return acc.replace(pattern, `{{${token}}}`);\n }, text);\n};\n", "import { htmlToTiptap } from '~/transforms/htmlToTiptap/htmlToTiptap';\nimport { normalizeTokens } from '~/transforms/normalizeTokens';\n\nconst HTML_TAG_RE = /<[a-zA-Z]/;\n\nconst containsHtml = (text: string): boolean => HTML_TAG_RE.test(text);\n\nconst isObject = (x: unknown): x is Record<string, unknown> => x !== null && typeof x === 'object' && !Array.isArray(x);\n\nconst normalizeLangValue = (value: unknown): unknown => {\n if (typeof value !== 'string') return value;\n\n const tokenized = normalizeTokens(value);\n\n return containsHtml(tokenized) ? htmlToTiptap(tokenized) : tokenized;\n};\n\n/**\n * Walks an untyped CABRootSection-shaped object (post deepCamelCase, pre schema\n * parse) and rewrites `text` sections' `content[lang]` strings so that:\n *\n * - `{firstName}` (single brace) becomes `{{firstName}}` (canonical), and\n * - HTML-laden strings become a fully-formed `TiptapDocument`.\n *\n * Plain strings pass through unchanged. Non-text sections only recurse into\n * their `sections` array; Tiptap docs and other nested objects are not walked.\n */\nexport const normalizeTextContent = (node: unknown): unknown => {\n if (Array.isArray(node)) return node.map(normalizeTextContent);\n\n if (!isObject(node)) return node;\n\n if (node.sectionType === 'text' && isObject(node.content)) {\n const nextContent: Record<string, unknown> = {};\n\n for (const [lang, value] of Object.entries(node.content)) {\n nextContent[lang] = normalizeLangValue(value);\n }\n\n return { ...node, content: nextContent };\n }\n\n if (Array.isArray(node.sections)) {\n return { ...node, sections: node.sections.map(normalizeTextContent) };\n }\n\n return node;\n};\n", "import { type CabShopConfig } from '~/schema/cabShopConfig';\n\nexport type ActiveExperiment = CabShopConfig['activeExperiments'][number];\n\n/** What the client needs to render the chosen variant and emit the A/B analytics. */\nexport type ResolvedExperiment = {\n /** The widget whose settings actually render \u2014 the chosen variant (not the placeholder). */\n elementId: number;\n experimentId: number;\n /** The experiment's raw engine type (e.g. `CheckoutOffer`); the analytics layer snake-cases it. */\n experimentType: string;\n /** The variant's experiment-element id \u2014 `abTestViewed`'s `defined_noun_id` half. */\n selectedId: number;\n};\n\n/**\n * Deterministic [0, 100) bucket from a seed string (FNV-1a \u2192 two-decimal percent). Replaces React's\n * `Math.random() * 100`: hashing `visitorId:experimentId` keeps a visitor in the SAME variant across\n * requests WITHOUT a client-stored selection \u2014 the server can't read the client's storage, so\n * stickiness has to come from a stable input it is handed (the visitor id).\n */\nconst rollPercent = (seed: string): number => {\n let hash = 0x811c9dc5;\n\n for (let index = 0; index < seed.length; index++) {\n hash ^= seed.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n\n return ((hash >>> 0) % 10000) / 100;\n};\n\n/**\n * Picks the A/B variant for the placeholder widget `placeholderId`, or `undefined` when no experiment\n * targets it (the common case \u2014 render the placeholder itself). Walks the variants by cumulative\n * `traffic` weight against a visitor-stable roll, mirroring React's `useABTesting` selection but\n * server-side and deterministic. Falls back to the first variant when the weights under-cover the roll.\n */\nexport const resolveExperiment = (\n experiments: ActiveExperiment[],\n placeholderId: number,\n visitorId: string\n): ResolvedExperiment | undefined => {\n const experiment = experiments.find((candidate) => candidate.placeholderId === placeholderId);\n\n if (!experiment || experiment.data.length === 0) return undefined;\n\n const roll = rollPercent(`${visitorId}:${experiment.id}`);\n let cumulative = 0;\n\n const variant =\n experiment.data.find((candidate) => {\n cumulative += candidate.traffic;\n\n // Half-open roll [0, 100) with `<` (not `<=`): a 0-traffic bucket is never entered (so a paused\n // head can't capture the roll-0 visitor), and boundaries split evenly (50/50 \u2192 5000/5000).\n return roll < cumulative;\n }) ?? experiment.data[0];\n\n return {\n elementId: variant.elementId,\n experimentId: experiment.id,\n experimentType: experiment.type,\n selectedId: variant.id,\n };\n};\n", "/**\n * Default localized labels for the offer card's add-to-order button states and the opt-in undo banner,\n * keyed by slot then locale (same 26 locales as `SWITCH_LABELS`). The converter overlays a defined v1\n * merchant value as the `en` entry (verbatim) and falls back to these for blank/absent values, so a\n * migrated widget keeps its copy while new/unset widgets localize. `addedToCartMessage` tokens are\n * camelCase (CAB default); legacy snake_case tokens in merchant overrides still resolve client-side.\n */\nexport const OFFER_LABELS = {\n addedToCart: {\n ar: '\u062A\u0645\u062A \u0627\u0644\u0625\u0636\u0627\u0641\u0629!',\n cs: 'P\u0159id\u00E1no!',\n da: 'Tilf\u00F8jet!',\n de: 'Hinzugef\u00FCgt!',\n en: 'Added!',\n es: '\u00A1A\u00F1adido!',\n fi: 'Lis\u00E4tty!',\n fr: 'Ajout\u00E9 !',\n ga: 'Curtha leis!',\n he: '\u05E0\u05D5\u05E1\u05E3!',\n hi: '\u091C\u094B\u0921\u093C\u093E \u0917\u092F\u093E!',\n id: 'Ditambahkan!',\n it: 'Aggiunto!',\n ja: '\u8FFD\u52A0\u3057\u307E\u3057\u305F\uFF01',\n ko: '\uCD94\uAC00\uB428!',\n nl: 'Toegevoegd!',\n no: 'Lagt til!',\n pl: 'Dodano!',\n pt: 'Adicionado!',\n ru: '\u0414\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u043E!',\n sv: 'Tillagd!',\n th: '\u0E40\u0E1E\u0E34\u0E48\u0E21\u0E41\u0E25\u0E49\u0E27!',\n tr: 'Eklendi!',\n uk: '\u0414\u043E\u0434\u0430\u043D\u043E!',\n vi: '\u0110\u00E3 th\u00EAm!',\n zh: '\u5DF2\u6DFB\u52A0\uFF01',\n },\n addedToCartMessage: {\n ar: '\u062A\u0645\u062A \u0625\u0636\u0627\u0641\u0629 {{quantity}} {{productTitle}} \u0625\u0644\u0649 \u0627\u0644\u0633\u0644\u0629.',\n cs: '{{quantity}} {{productTitle}} p\u0159id\u00E1no do ko\u0161\u00EDku.',\n da: '{{quantity}} {{productTitle}} lagt i kurven.',\n de: '{{quantity}} {{productTitle}} zum Warenkorb hinzugef\u00FCgt.',\n en: '{{quantity}} {{productTitle}} successfully added to cart.',\n es: '{{quantity}} {{productTitle}} a\u00F1adido al carrito.',\n fi: '{{quantity}} {{productTitle}} lis\u00E4tty ostoskoriin.',\n fr: '{{quantity}} {{productTitle}} ajout\u00E9 au panier.',\n ga: 'Cuireadh {{quantity}} {{productTitle}} sa chairt.',\n he: '{{quantity}} {{productTitle}} \u05E0\u05D5\u05E1\u05E3 \u05DC\u05E2\u05D2\u05DC\u05D4.',\n hi: '{{quantity}} {{productTitle}} \u0915\u093E\u0930\u094D\u091F \u092E\u0947\u0902 \u091C\u094B\u0921\u093C\u093E \u0917\u092F\u093E\u0964',\n id: '{{quantity}} {{productTitle}} ditambahkan ke keranjang.',\n it: '{{quantity}} {{productTitle}} aggiunto al carrello.',\n ja: '{{quantity}} {{productTitle}}\u3092\u30AB\u30FC\u30C8\u306B\u8FFD\u52A0\u3057\u307E\u3057\u305F\u3002',\n ko: '{{quantity}} {{productTitle}}\uC774(\uAC00) \uC7A5\uBC14\uAD6C\uB2C8\uC5D0 \uCD94\uAC00\uB418\uC5C8\uC2B5\uB2C8\uB2E4.',\n nl: '{{quantity}} {{productTitle}} toegevoegd aan winkelwagen.',\n no: '{{quantity}} {{productTitle}} lagt i handlekurven.',\n pl: '{{quantity}} {{productTitle}} dodano do koszyka.',\n pt: '{{quantity}} {{productTitle}} adicionado ao carrinho.',\n ru: '{{quantity}} {{productTitle}} \u0434\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u043E \u0432 \u043A\u043E\u0440\u0437\u0438\u043D\u0443.',\n sv: '{{quantity}} {{productTitle}} har lagts i varukorgen.',\n th: '\u0E40\u0E1E\u0E34\u0E48\u0E21 {{quantity}} {{productTitle}} \u0E25\u0E07\u0E15\u0E30\u0E01\u0E23\u0E49\u0E32\u0E41\u0E25\u0E49\u0E27',\n tr: '{{quantity}} {{productTitle}} sepete eklendi.',\n uk: '{{quantity}} {{productTitle}} \u0434\u043E\u0434\u0430\u043D\u043E \u0434\u043E \u043A\u043E\u0448\u0438\u043A\u0430.',\n vi: '\u0110\u00E3 th\u00EAm {{quantity}} {{productTitle}} v\u00E0o gi\u1ECF h\u00E0ng.',\n zh: '{{quantity}} {{productTitle}} \u5DF2\u52A0\u5165\u8D2D\u7269\u8F66\u3002',\n },\n addingToCart: {\n ar: '\u062C\u0627\u0631\u064D \u0627\u0644\u0625\u0636\u0627\u0641\u0629...',\n cs: 'P\u0159id\u00E1v\u00E1n\u00ED...',\n da: 'Tilf\u00F8jer...',\n de: 'Wird hinzugef\u00FCgt...',\n en: 'Adding...',\n es: 'A\u00F1adiendo...',\n fi: 'Lis\u00E4t\u00E4\u00E4n...',\n fr: 'Ajout en cours...',\n ga: '\u00C1 chur leis...',\n he: '\u05DE\u05D5\u05E1\u05D9\u05E3...',\n hi: '\u091C\u094B\u0921\u093C\u093E \u091C\u093E \u0930\u0939\u093E \u0939\u0948...',\n id: 'Menambahkan...',\n it: 'Aggiunta in corso...',\n ja: '\u8FFD\u52A0\u4E2D...',\n ko: '\uCD94\uAC00 \uC911...',\n nl: 'Toevoegen...',\n no: 'Legger til...',\n pl: 'Dodawanie...',\n pt: 'Adicionando...',\n ru: '\u0414\u043E\u0431\u0430\u0432\u043B\u0435\u043D\u0438\u0435...',\n sv: 'L\u00E4gger till...',\n th: '\u0E01\u0E33\u0E25\u0E31\u0E07\u0E40\u0E1E\u0E34\u0E48\u0E21...',\n tr: 'Ekleniyor...',\n uk: '\u0414\u043E\u0434\u0430\u0432\u0430\u043D\u043D\u044F...',\n vi: '\u0110ang th\u00EAm...',\n zh: '\u6B63\u5728\u6DFB\u52A0...',\n },\n addToCart: {\n ar: '\u0623\u0636\u0641 \u0625\u0644\u0649 \u0627\u0644\u0633\u0644\u0629',\n cs: 'P\u0159idat do ko\u0161\u00EDku',\n da: 'L\u00E6g i kurv',\n de: 'In den Warenkorb',\n en: 'Add to cart',\n es: 'A\u00F1adir al carrito',\n fi: 'Lis\u00E4\u00E4 ostoskoriin',\n fr: 'Ajouter au panier',\n ga: 'Cuir sa chairt',\n he: '\u05D4\u05D5\u05E1\u05E3 \u05DC\u05E2\u05D2\u05DC\u05D4',\n hi: '\u0915\u093E\u0930\u094D\u091F \u092E\u0947\u0902 \u091C\u094B\u0921\u093C\u0947\u0902',\n id: 'Tambahkan ke keranjang',\n it: 'Aggiungi al carrello',\n ja: '\u30AB\u30FC\u30C8\u306B\u8FFD\u52A0',\n ko: '\uC7A5\uBC14\uAD6C\uB2C8\uC5D0 \uCD94\uAC00',\n nl: 'In winkelwagen',\n no: 'Legg i handlekurven',\n pl: 'Dodaj do koszyka',\n pt: 'Adicionar ao carrinho',\n ru: '\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0432 \u043A\u043E\u0440\u0437\u0438\u043D\u0443',\n sv: 'L\u00E4gg i varukorgen',\n th: '\u0E40\u0E1E\u0E34\u0E48\u0E21\u0E25\u0E07\u0E15\u0E30\u0E01\u0E23\u0E49\u0E32',\n tr: 'Sepete ekle',\n uk: '\u0414\u043E\u0434\u0430\u0442\u0438 \u0432 \u043A\u043E\u0448\u0438\u043A',\n vi: 'Th\u00EAm v\u00E0o gi\u1ECF h\u00E0ng',\n zh: '\u52A0\u5165\u8D2D\u7269\u8F66',\n },\n redirectToCheckout: {\n ar: '\u0627\u0644\u062F\u0641\u0639',\n cs: 'Pokladna',\n da: 'Til kassen',\n de: 'Zur Kasse',\n en: 'Checkout',\n es: 'Finalizar compra',\n fi: 'Kassalle',\n fr: 'Paiement',\n ga: 'Seice\u00E1il amach',\n he: '\u05DC\u05EA\u05E9\u05DC\u05D5\u05DD',\n hi: '\u091A\u0947\u0915\u0906\u0909\u091F',\n id: 'Checkout',\n it: 'Cassa',\n ja: '\u30C1\u30A7\u30C3\u30AF\u30A2\u30A6\u30C8',\n ko: '\uACB0\uC81C\uD558\uAE30',\n nl: 'Afrekenen',\n no: 'Til kassen',\n pl: 'Do kasy',\n pt: 'Finalizar compra',\n ru: '\u041E\u0444\u043E\u0440\u043C\u0438\u0442\u044C \u0437\u0430\u043A\u0430\u0437',\n sv: 'Till kassan',\n th: '\u0E0A\u0E33\u0E23\u0E30\u0E40\u0E07\u0E34\u0E19',\n tr: '\u00D6deme',\n uk: '\u041E\u0444\u043E\u0440\u043C\u0438\u0442\u0438 \u0437\u0430\u043C\u043E\u0432\u043B\u0435\u043D\u043D\u044F',\n vi: 'Thanh to\u00E1n',\n zh: '\u7ED3\u8D26',\n },\n soldOut: {\n ar: '\u0646\u0641\u062F\u062A \u0627\u0644\u0643\u0645\u064A\u0629',\n cs: 'Vyprod\u00E1no',\n da: 'Udsolgt',\n de: 'Ausverkauft',\n en: 'Sold out',\n es: 'Agotado',\n fi: 'Loppuunmyyty',\n fr: '\u00C9puis\u00E9',\n ga: 'D\u00EDolta amach',\n he: '\u05D0\u05D6\u05DC \u05DE\u05D4\u05DE\u05DC\u05D0\u05D9',\n hi: '\u0938\u094D\u091F\u0949\u0915 \u0916\u093C\u0924\u094D\u092E',\n id: 'Habis terjual',\n it: 'Esaurito',\n ja: '\u58F2\u308A\u5207\u308C',\n ko: '\uD488\uC808',\n nl: 'Uitverkocht',\n no: 'Utsolgt',\n pl: 'Wyprzedane',\n pt: 'Esgotado',\n ru: '\u0420\u0430\u0441\u043F\u0440\u043E\u0434\u0430\u043D\u043E',\n sv: 'Sluts\u00E5ld',\n th: '\u0E2A\u0E34\u0E19\u0E04\u0E49\u0E32\u0E2B\u0E21\u0E14',\n tr: 'T\u00FCkendi',\n uk: '\u0420\u043E\u0437\u043F\u0440\u043E\u0434\u0430\u043D\u043E',\n vi: 'H\u1EBFt h\u00E0ng',\n zh: '\u5DF2\u552E\u7F44',\n },\n undo: {\n ar: '\u062A\u0631\u0627\u062C\u0639',\n cs: 'Zp\u011Bt',\n da: 'Fortryd',\n de: 'R\u00FCckg\u00E4ngig',\n en: 'Undo',\n es: 'Deshacer',\n fi: 'Kumoa',\n fr: 'Annuler',\n ga: 'Cealaigh',\n he: '\u05D1\u05D8\u05DC',\n hi: '\u092A\u0942\u0930\u094D\u0935\u0935\u0924 \u0915\u0930\u0947\u0902',\n id: 'Urungkan',\n it: 'Annulla',\n ja: '\u5143\u306B\u623B\u3059',\n ko: '\uC2E4\uD589 \uCDE8\uC18C',\n nl: 'Ongedaan maken',\n no: 'Angre',\n pl: 'Cofnij',\n pt: 'Desfazer',\n ru: '\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C',\n sv: '\u00C5ngra',\n th: '\u0E40\u0E25\u0E34\u0E01\u0E17\u0E33',\n tr: 'Geri al',\n uk: '\u0421\u043A\u0430\u0441\u0443\u0432\u0430\u0442\u0438',\n vi: 'Ho\u00E0n t\u00E1c',\n zh: '\u64A4\u9500',\n },\n} as const satisfies Record<string, Record<string, string>>;\n", "/**\n * Minimal v1 Offer (Checkout Offers / product recommendations) input types.\n * The legacy widget's settings `type` is the generic `shopify_checkout_extension`\n * (the offer is the \"base\" checkout-extension type; other widgets carry\n * `ui_extension_*`), which uniquely identifies it at the settings level.\n */\nimport { type TiptapDocument } from '~/schema/widgets/checkout-and-beyond/text';\n\nexport const SHOPIFY_CHECKOUT_EXTENSION = 'shopify_checkout_extension' as const;\n\nexport type V1OfferLanguage = {\n addedToCart?: string;\n addingToCart?: string;\n addToCart?: string;\n /** Subscribe \u2192 one-time label for the offers `switchToSubscription` button. */\n cartSwitchToOnetime?: string;\n /** One-time \u2192 subscribe label (carries `{{subscription_discount}}`) for the `switchToSubscription` button. */\n cartSwitchToSubscription?: string;\n description?: string;\n /** Buy Now link label on off-checkout surfaces (thank-you / order-status), real key `redirect_to_checkout`. */\n redirectToCheckout?: string;\n /** Real payload key is `sold_out_label` \u2192 `soldOutLabel` (NOT `soldOut`). */\n soldOutLabel?: string;\n /** Opt-in undo banner shown after a buyer adds a recommended product. */\n successBannerEnabled?: boolean;\n successBannerMessageRte?: TiptapDocument | string;\n superTitle?: string;\n title?: string;\n /** Legacy \"Upgrade to Subscription and Save {{subscription_discount}}%\" upsell label. */\n upgradeToSubscription?: string;\n};\n\n/** v1 per-product text styling; `textSize` is the CAB `textSizeNames` enum verbatim. */\nexport type V1TextStyle = {\n textEmphasis?: 'base' | 'bold' | 'italic';\n textSize?: 'extraSmall' | 'small' | 'base' | 'medium' | 'large' | 'extraLarge';\n};\n\n/** v1 `displaySettings` \u2014 the controls behind product/variant/image/review presentation. */\nexport type V1OfferDisplaySettings = {\n image?: { imageFit?: 'contain' | 'cover' };\n product?: V1TextStyle;\n reviews?: { color?: string; size?: 'small' | 'default' | 'large' };\n variant?: V1TextStyle;\n};\n\n/**\n * v1 layout is per-breakpoint; CAB has no breakpoints, so the converter collapses them.\n * `style` drives orientation: list \u2192 rows, line \u2192 columns, grid \u2192 grid (none \u2192 rows).\n */\nexport type V1OfferBreakpointLayout = {\n carousel?: boolean;\n columns?: number;\n showPaginations?: boolean;\n style?: 'grid' | 'line' | 'list' | 'none';\n};\n\nexport type V1OfferSettings = {\n /** Free-form in real payloads; the converter safelists to the CAB enum (junk \u2192 'primary'). */\n button?: { kind?: string };\n /** `showSavingAmount` false hides the compare-at (sale) price; `amount`/`type`/`discountedFrom`/`discountedBy` drive the discount-setting price computation (emitted onto the offers section for the client's pricing pass). */\n discount?: {\n amount?: number | string;\n discountedBy?: string;\n discountedFrom?: string;\n /** Merchant-facing promo label (e.g. \"Enjoy 10% off!\") \u2192 carried onto the data-source discount. */\n message?: string;\n /** How many items the discount applies to (defaults to 1) \u2192 carried onto the discount section. */\n quantity?: number;\n showSavingAmount?: boolean;\n type?: string;\n };\n /** Per-product/variant/image/review presentation controls. */\n displaySettings?: V1OfferDisplaySettings;\n /** Engine path appended to `/api/v1` (e.g. '/products/recommended'). */\n endpoint?: string | null;\n images?: { source?: 'product' | 'variant' };\n /**\n * Nominally boolean, but legacy data carries \"yes\"/\"no\" strings (reviewsio, in prod) and numeric\n * 1/0 (PHP serialization) \u2014 the converter coerces both so neither throws at the schema boolean.\n */\n integrations?: Record<string, boolean | number | string>;\n language?: V1OfferLanguage;\n layout?: { large?: V1OfferBreakpointLayout; medium?: V1OfferBreakpointLayout; small?: V1OfferBreakpointLayout };\n limit?: number;\n location?: 'checkout' | 'order-status' | 'thank-you';\n /** The legacy widget's name, present in the settings payload; carried to the converted root. */\n name?: string;\n previewMode?: boolean;\n productOptions?: {\n hideOutOfStockVariants?: boolean;\n matchVariant?: boolean;\n matchVariantOutOfStock?: boolean;\n /** 'hide' (or absent) hides the per-card product description; any other value shows it. */\n showProductDescription?: string;\n showVariantOptions?: 'always' | 'default' | 'never';\n showVariantsAsProducts?: boolean;\n /** 'hide' (or absent) hides the selected-variant title line; any other value shows it. */\n showVariantTitle?: string;\n };\n productType?: 'both' | 'one-time' | 'subscription';\n quantityInputs?: {\n enabled?: boolean;\n /** Custom over-max error copy \u2192 CAB `errorMessages.en.max`. */\n maxError?: string;\n maxValue?: number;\n /** Custom under-min error copy \u2192 CAB `errorMessages.en.min`. */\n minError?: string;\n minValue?: number;\n /** Custom negative-value error copy \u2192 CAB `errorMessages.en.neg`. */\n negativeError?: string;\n /** Stepper kind ('dropdown-select' | 'buttons-manual-input') \u2192 CAB `inputType` (select | number). */\n type?: string;\n };\n /** Default subscribe-vs-one-time when `productType` is `both`. */\n subscriptionIsDefault?: boolean;\n tracking?: { enableAttribution?: boolean; enableSource?: boolean; enableWidget?: boolean };\n treatAsGwp?: boolean;\n type: typeof SHOPIFY_CHECKOUT_EXTENSION;\n /** Absent on real checkout-offers payloads; only `type` is the reliable discriminator. */\n version?: 1;\n /** v1 `viewOptions`: `displayActions === false` hides the variant selector (legacy `getVariantSelect`). */\n viewOptions?: { displayActions?: boolean; variantSelector?: 'select' | 'radio' | 'button' };\n};\n\nexport type V1OfferConvertInput = {\n id: number;\n /** The legacy widget's name; set on the converted root (the admin save schema requires it). */\n name?: string;\n settings: V1OfferSettings;\n};\n\n/**\n * The offer's settings `type` uniquely identifies it. Unlike the `ui_extension_*` widgets, the legacy\n * checkout-offers payload carries NO top-level `version` \u2014 so we must NOT gate on it (doing so silently\n * dropped real offers to the passthrough branch). `version: 2` payloads are already claimed upstream by\n * `isCABRootSection`, so they never reach here.\n */\nexport const isOfferV1 = (data: unknown): data is V1OfferSettings => {\n if (!data || typeof data !== 'object') return false;\n\n return (data as Record<string, unknown>).type === SHOPIFY_CHECKOUT_EXTENSION;\n};\n", "import { OFFER_LABELS } from '~/schema/widgets/checkout-and-beyond/offerLabels';\nimport { SWITCH_LABELS } from '~/schema/widgets/checkout-and-beyond/switchLabels';\nimport { localizedContent } from '~/transforms/localizedContent';\nimport { type V1OfferSettings, type V1TextStyle } from '~/transforms/offerV1/types';\n\n/** v1 `viewOptions.variantSelector` \u2192 CAB `variants.selector` ('select' is the v1 name for a dropdown menu). */\nconst VARIANT_SELECTOR = { button: 'button', radio: 'radio', select: 'menu' } as const;\n\n/**\n * A single-token Tiptap doc carrying a v1 text style: `textSize` is the CAB `fontSize`\n * verbatim (identical enums); `textEmphasis` adds a bold/italic mark ('base' adds none).\n */\nconst buildStyledText = (token: string, style: V1TextStyle | undefined, color = 'base') => {\n const marks: Record<string, unknown>[] = [\n { attrs: { color, fontSize: style?.textSize ?? 'base' }, type: 'textStyle' },\n ];\n\n if (style?.textEmphasis === 'bold') marks.push({ type: 'bold' });\n\n if (style?.textEmphasis === 'italic') marks.push({ type: 'italic' });\n\n return { content: [{ content: [{ marks, text: token, type: 'text' }], type: 'paragraph' }], type: 'doc' };\n};\n\n/**\n * The price line: the variant price, optionally followed by a strikethrough,\n * subdued compare-at price. The extension resolves `{{variantCompareAtPrice}}`\n * to '' off-sale, so the strikethrough disappears unless the variant is genuinely\n * discounted. `discount.showSavingAmount` false drops the compare-at node entirely.\n */\nconst buildPriceContent = (settings: V1OfferSettings) => {\n const content: Record<string, unknown>[] = [{ text: '{{variantPrice}}', type: 'text' }];\n\n if (settings.discount?.showSavingAmount !== false) {\n content.push(\n { text: ' ', type: 'text' },\n {\n marks: [{ type: 'strike' }, { attrs: { color: 'subdued' }, type: 'textStyle' }],\n text: '{{variantCompareAtPrice}}',\n type: 'text',\n }\n );\n }\n\n return { content: [{ content, type: 'paragraph' }], type: 'doc' };\n};\n\n/** A `reviews` star section, emitted only when the merchant has a review integration enabled. */\nconst buildReviews = (settings: V1OfferSettings): Record<string, unknown>[] => {\n if (!settings.integrations || !Object.values(settings.integrations).some(Boolean)) return [];\n\n const reviews = settings.displaySettings?.reviews;\n\n return [\n {\n ...(reviews?.color && { color: reviews.color }),\n sectionType: 'reviews',\n ...(reviews?.size && { size: reviews.size }),\n },\n ];\n};\n\n/** The recommended product's image; objectFit comes from v1 `displaySettings.image.imageFit`. */\nconst buildImage = (settings: V1OfferSettings): Record<string, unknown> => ({\n ...(settings.displaySettings?.image?.imageFit && {\n objectFit: settings.displaySettings.image.imageFit,\n }),\n /** Accessible name for the product image (legacy `OfferImage` used `accessibilityDescription={variantTitle}`); the renderer interpolates it, so an empty default would announce the image as decorative. */\n altText: '{{variantTitle}}',\n sectionType: 'image',\n source: settings.images?.source === 'product' ? '{{productImage}}' : '{{variantImage}}',\n width: 100,\n});\n\n/** The product title text, styled from v1 `displaySettings.product`. */\nconst buildTitle = (settings: V1OfferSettings): Record<string, unknown> => ({\n content: { en: buildStyledText('{{productTitle}}', settings.displaySettings?.product) },\n sectionType: 'text',\n});\n\n/** The price line (variant price + on-sale compare-at strikethrough). */\nconst buildPrice = (settings: V1OfferSettings): Record<string, unknown> => ({\n content: { en: buildPriceContent(settings) },\n sectionType: 'text',\n});\n\n/** The selected-variant title line, gated by `productOptions.showVariantTitle` ('hide'/absent = off). */\nconst buildVariantTitle = (settings: V1OfferSettings): Record<string, unknown>[] => {\n const show = settings.productOptions?.showVariantTitle;\n\n if (!show || show === 'hide') return [];\n\n return [\n {\n content: { en: buildStyledText('{{variantTitle}}', settings.displaySettings?.variant) },\n sectionType: 'text',\n },\n ];\n};\n\n/** The per-card product description, gated by `productOptions.showProductDescription` ('hide'/absent = off). */\nconst buildDescription = (settings: V1OfferSettings): Record<string, unknown>[] => {\n const show = settings.productOptions?.showProductDescription;\n\n if (!show || show === 'hide') return [];\n\n return [{ content: { en: buildStyledText('{{productDescription}}', undefined) }, sectionType: 'text' }];\n};\n\n/** The variant selector, unless the merchant hid variant options or turned actions off entirely. */\nconst buildVariants = (settings: V1OfferSettings): Record<string, unknown>[] => {\n /** Legacy `getVariantSelect`: `view_options.display_actions === false` suppresses the selector. */\n if (settings.viewOptions?.displayActions === false) return [];\n\n if (settings.productOptions?.showVariantOptions === 'never') return [];\n\n const selector = settings.viewOptions?.variantSelector;\n\n return [\n {\n hideOutOfStockVariants: !!settings.productOptions?.hideOutOfStockVariants,\n ...(selector && { selector: VARIANT_SELECTOR[selector] }),\n sectionType: 'variants',\n },\n ];\n};\n\n/** v1 stepper kind \u2192 CAB `inputType`. Unknown/absent \u2192 omitted so the schema default ('select') applies. */\nconst QUANTITY_INPUT_TYPE: Record<string, 'number' | 'select'> = {\n 'buttons-manual-input': 'number',\n 'dropdown-select': 'select',\n};\n\n/** Custom quantity error copy \u2192 CAB `errorMessages.en.{min,max,neg}`; omitted entirely when none is set. */\nconst buildQuantityErrors = (quantity: NonNullable<V1OfferSettings['quantityInputs']>) => {\n const en = {\n ...(quantity.maxError && { max: quantity.maxError }),\n ...(quantity.minError && { min: quantity.minError }),\n ...(quantity.negativeError && { neg: quantity.negativeError }),\n };\n\n return Object.keys(en).length ? { errorMessages: { en } } : {};\n};\n\n/** The quantity stepper, when the merchant enabled quantity input. */\nconst buildQuantity = (settings: V1OfferSettings): Record<string, unknown>[] => {\n const quantity = settings.quantityInputs;\n\n if (!quantity?.enabled) return [];\n\n const inputType = quantity.type ? QUANTITY_INPUT_TYPE[quantity.type] : undefined;\n\n // Legacy quantity had no upper bound (DefaultQuantityRule.MAX = null) and allowed 0; the CAB\n // schema pins `max` to [1, 100] and `min` to >= 1. Clamp instead of passing through so a legacy\n // `maxValue: 250` (or a 0) degrades to a valid widget rather than throwing at parse.\n const max = Math.min(Math.max(quantity.maxValue ?? 10, 1), 100);\n // Also cap `min` at `max` \u2014 the schema has no cross-field refine, so a legacy `min > max` (e.g.\n // {maxValue: 5, minValue: 8}) would parse but render a degenerate stepper (REB #766).\n const min = Math.min(Math.max(quantity.minValue ?? 1, 1), max);\n\n return [\n {\n ...buildQuantityErrors(quantity),\n ...(inputType && { inputType }),\n max,\n min,\n sectionType: 'quantity',\n },\n ];\n};\n\n/**\n * The in-card subscribe / one-time toggle: a `switchToSubscription` button with its four label slots\n * (the same `SWITCH_LABELS` slot set as the line-item editor, including the `subscriptionOption`\n * frequency template, so the frequency select localizes). Emitted when the merchant offers\n * subscriptions (`productType` both/subscription); the extension shows it per-product by selling-plan\n * availability. v1 carries the with-discount upsell (`upgradeToSubscription`) plus the cart switch\n * labels; anything blank/absent falls back to the shared localized defaults.\n */\nconst buildSubscriptionButton = (settings: V1OfferSettings): Record<string, unknown>[] => {\n if (settings.productType !== 'both' && settings.productType !== 'subscription') return [];\n\n const language = settings.language;\n\n const slot = (buttonField: keyof typeof SWITCH_LABELS, override: string | undefined) => ({\n buttonField,\n content: localizedContent(SWITCH_LABELS[buttonField], override),\n sectionType: 'text',\n });\n\n return [\n {\n action: 'switchToSubscription',\n buttonStyle: 'plain',\n /** A `subscription` widget offers no one-time purchase (legacy's offers checkbox renders only when `isProductTypeBoth`); suppress the downgrade so the buyer can't switch to one-time on a subscription-only offer. */\n ...(settings.productType === 'subscription' && { disableDowngrade: true }),\n sections: [\n slot('subscriptionOption', undefined),\n slot('switchToOneTimePurchase', language?.cartSwitchToOnetime),\n slot('switchToSubscriptionNoDiscount', language?.cartSwitchToSubscription),\n slot('switchToSubscriptionWithDiscount', language?.upgradeToSubscription),\n ],\n sectionType: 'button',\n },\n ];\n};\n\n/** v1 stores free-form `button.kind`; anything outside the CAB enum falls back to the legacy 'primary'. */\nconst BUTTON_KINDS = ['plain', 'primary', 'secondary'] as const;\n\n/** The add-to-order button with its four label slots (add / adding / added / sold-out). */\nconst buildAddButton = (settings: V1OfferSettings): Record<string, unknown> => {\n const kind = settings.button?.kind;\n\n const slot = (\n buttonField: 'addedToCart' | 'addingToCart' | 'addToCart' | 'redirectToCheckout' | 'soldOut',\n override?: string\n ) => ({\n buttonField,\n content: localizedContent(OFFER_LABELS[buttonField], override),\n sectionType: 'text',\n });\n\n return {\n action: 'addToOrder',\n buttonStyle: BUTTON_KINDS.includes(kind as (typeof BUTTON_KINDS)[number]) ? kind : 'primary',\n sections: [\n slot('addToCart', settings.language?.addToCart),\n slot('addingToCart', settings.language?.addingToCart),\n slot('addedToCart', settings.language?.addedToCart),\n slot('soldOut', settings.language?.soldOutLabel),\n // Off-checkout Buy Now: the label the button shows once it links to the created checkout.\n slot('redirectToCheckout', settings.language?.redirectToCheckout),\n ],\n sectionType: 'button',\n };\n};\n\n/** A `rows` layout wrapping sections into one grid cell (so they stack within a column of the card). */\nconst rowsLayout = (sections: Record<string, unknown>[]): Record<string, unknown> => ({\n direction: 'rows',\n sections,\n sectionType: 'layout',\n});\n\n/**\n * The per-offer product card: the sections rendered once per recommended product (the\n * offers renderer mounts a product context, so the `{{...}}` tokens resolve per product).\n *\n * `horizontal` mirrors the v1 layout orientation (see `convertOfferToV2`):\n * - horizontal (v1 `list`/default, vertical-stacked products): a 3-column grid card \u2014\n * image | title/price/reviews/variants | actions \u2014 matching the compact V1 row.\n * - vertical (v1 `grid`/`line`, side-by-side products): a flat top-to-bottom stack\n * (image \u2192 title \u2192 price \u2192 \u2026 \u2192 button), the narrow column card.\n *\n * Quantity is a full-width row beneath the card in the horizontal layout; in the vertical\n * layout it sits inline in the stack. NOT carried: the savings-amount badge (no live v1\n * control) and variant text styling (no CAB field).\n */\nexport const buildOfferCard = (settings: V1OfferSettings, horizontal: boolean): Record<string, unknown>[] => {\n const image = buildImage(settings);\n const title = buildTitle(settings);\n const variantTitle = buildVariantTitle(settings);\n const price = buildPrice(settings);\n const description = buildDescription(settings);\n const reviews = buildReviews(settings);\n const variants = buildVariants(settings);\n const quantity = buildQuantity(settings);\n const subscription = buildSubscriptionButton(settings);\n const addButton = buildAddButton(settings);\n\n if (!horizontal) {\n return [\n image,\n title,\n ...variantTitle,\n price,\n ...description,\n ...reviews,\n ...variants,\n ...quantity,\n ...subscription,\n addButton,\n ];\n }\n\n const info = rowsLayout([title, ...variantTitle, price, ...description, ...reviews, ...variants]);\n const actions = [...subscription, addButton];\n const actionsCell = actions.length === 1 ? actions[0] : rowsLayout(actions);\n\n const card = {\n direction: 'grid',\n grid: { columns: ['15%', 'fill', 'auto'], rows: ['auto'] },\n sections: [image, info, actionsCell],\n sectionType: 'layout',\n };\n\n return [card, ...quantity];\n};\n", "import { OFFER_LABELS } from '~/schema/widgets/checkout-and-beyond/offerLabels';\nimport { CABRootSection } from '~/schema/widgets/checkout-and-beyond/root';\nimport { convertContentBlockTextToV2 } from '~/transforms/contentBlockV1/convertContentBlockTextToV2';\nimport { stripContentBlockHtml } from '~/transforms/contentBlockV1/stripContentBlockHtml';\nimport { buildOfferCard } from '~/transforms/offerV1/offerCard';\nimport {\n SHOPIFY_CHECKOUT_EXTENSION,\n type V1OfferBreakpointLayout,\n type V1OfferConvertInput,\n type V1OfferSettings,\n} from '~/transforms/offerV1/types';\n\nconst LOCATION_TO_EDITOR_MODE = {\n checkout: 'checkoutExtension',\n 'order-status': 'orderStatusPage',\n 'thank-you': 'thankYouPage',\n} as const;\n\n/**\n * v1 per-breakpoint `layout.style` \u2192 CAB product-list `direction`. This is the product-TO-product\n * orientation and the card orientation flips with it (see `convertOfferToV2`):\n * - `grid`/`line` \u2192 products sit side-by-side (`grid`/`columns`); each card is a vertical stack.\n * - `list`/`none`/absent \u2192 products stack vertically (`rows`); each card is a horizontal row.\n * The v1 carousel toggle writes exactly these two: VERTICAL \u2192 `list`, HORIZONTAL \u2192 `grid`.\n */\nconst STYLE_TO_DIRECTION = {\n grid: 'grid',\n line: 'columns',\n list: 'rows',\n none: 'rows',\n} as const;\n\nconst directionForStyle = (style: V1OfferBreakpointLayout['style']) => (style ? STYLE_TO_DIRECTION[style] : 'rows');\n\n/**\n * The product-to-product layout \u2014 it belongs on the CONTAINER that holds the offers (the carousel\n * wrapper), NOT on the offers section. The renderer repeats the offers layout per product into its\n * parent's stack/grid, so a `grid` direction with N `'fill'` columns lays the products out N-across;\n * `list`/`none` stay a vertical stack.\n *\n * `'fill'` (equal share) \u2014 NOT `'auto'` (sizes to content), which yields unequal columns and so\n * unequal `objectFit: contain` image heights across products.\n */\nconst buildProductListLayout = (direction: string, columns: number) =>\n direction === 'grid'\n ? { direction, grid: { columns: Array.from({ length: Math.max(columns, 1) }, () => 'fill'), rows: ['auto'] } }\n : { direction };\n\nconst hasHeaderText = (language: V1OfferSettings['language']): boolean =>\n !!(language?.title || language?.superTitle || language?.description);\n\n/**\n * v1 `discountedFrom` \u2192 CAB `discountSources`. v1's \"Discounted From\" / \"Compare Price With\" select\n * stores `price` / `compare_at_price` directly; the legacy `original_price` (written in Shopify-Functions\n * mode) is the regular price, i.e. `price`. Unknown values are omitted (the CAB enum would reject them).\n */\nconst DISCOUNTED_FROM: Record<string, 'compare_at_price' | 'price'> = {\n compare_at_price: 'compare_at_price',\n original_price: 'price',\n price: 'price',\n};\n\n/**\n * The active widget-level discount as the `CABDiscount` carried on the DATA-SOURCE section \u2014 the field\n * the extension's price forecast actually reads (`dataSource.discount` \u2192 `priceVariant`); a discount\n * emitted anywhere else never reaches the card price. Undefined when there's no active discount;\n * `showSavingAmount` is a card-display concern handled in `buildOfferCard`.\n */\nconst dataSourceDiscount = (discount: V1OfferSettings['discount']): Record<string, unknown> | undefined => {\n if (!discount?.type || discount.type === 'none') return undefined;\n\n const discountedFrom = discount.discountedFrom ? DISCOUNTED_FROM[discount.discountedFrom] : undefined;\n\n return {\n amount: discount.amount ?? 0,\n ...(discount.discountedBy && { discountedBy: discount.discountedBy }),\n ...(discountedFrom && { discountedFrom }),\n type: discount.type,\n };\n};\n\n/**\n * The same discount as the config-only `discount` section just above the undo banner \u2014 the editor-facing\n * home of the FULL v1 shape (`message`/`quantity` have no `CABDiscount` counterpart). Both projections\n * come from the one v1 input in the same pass, so they cannot drift apart.\n */\nconst buildDiscountSection = (discount: V1OfferSettings['discount']): Record<string, unknown>[] => {\n const base = dataSourceDiscount(discount);\n\n if (!base) return [];\n\n return [\n {\n ...base,\n ...(discount?.message && { message: discount.message }),\n ...(discount?.quantity != null && { quantity: discount.quantity }),\n sectionType: 'discount',\n },\n ];\n};\n\n/**\n * The banner's success message content: a defined v1 message overrides `en`, absent falls back to the\n * localized defaults (P4 language policy). A string message is sanitized (a raw-HTML label would fail\n * `CABTextSection.content` and 500 the widget); an RTE doc passes through as authored. A string that\n * sanitizes to empty falls back to the defaults, same as absent.\n */\nconst bannerMessageContent = (message: NonNullable<V1OfferSettings['language']>['successBannerMessageRte']) => {\n const sanitized = typeof message === 'string' ? stripContentBlockHtml(message) : message;\n\n return sanitized ? { ...OFFER_LABELS.addedToCartMessage, en: sanitized } : OFFER_LABELS.addedToCartMessage;\n};\n\n/**\n * Legacy integrations values are nominally boolean but prod data carries \"yes\"/\"no\" strings\n * (React special-cased exactly this for reviewsio: only 'true'/'yes' count as enabled) and numeric\n * 1/0 (legacy PHP serialization). Coerce every value so neither a string nor a number can throw at\n * the schema's `z.boolean()` and kill the widget: only 'true'/'yes' and 1 count as enabled.\n */\nconst coerceIntegrations = (integrations: Record<string, boolean | number | string>): Record<string, boolean> =>\n Object.fromEntries(\n Object.entries(integrations).map(([key, value]) => {\n if (typeof value === 'string') return [key, ['true', 'yes'].includes(value.toLowerCase())];\n\n if (typeof value === 'number') return [key, value === 1];\n\n return [key, value];\n })\n );\n\n/** The opt-in undo banner: a success `banner` of the message + a plain undo button. */\nconst buildBanner = (language: V1OfferSettings['language']): Record<string, unknown>[] =>\n language?.successBannerEnabled\n ? [\n {\n /**\n * The banner-level tag is the extraction/routing key on BOTH renderers (React CAB's\n * `isBannerType` + marker check; the Preact extension's `isUndoBanner`) \u2014 without it\n * the banner renders per card as an always-visible plain success banner and the\n * cart-scoped undo rail never runs. The schema's default offers tree carries it too.\n */\n buttonField: 'undoAddToOrder',\n color: 'success',\n dismissible: true,\n sections: [\n {\n content: bannerMessageContent(language.successBannerMessageRte),\n sectionType: 'text',\n },\n {\n action: 'undoAddToOrder',\n buttonStyle: 'plain',\n /**\n * Tagged `undoAddToOrder`, never `buttonLabel` \u2014 the renderers (React CAB and\n * the Preact extension) and the schema's default offers tree resolve that slot.\n */\n sections: [\n { buttonField: 'undoAddToOrder', content: OFFER_LABELS.undo, sectionType: 'text' },\n ],\n sectionType: 'button',\n },\n ],\n sectionType: 'banner',\n },\n ]\n : [];\n\n/**\n * Translates a v1 Offer (Checkout Offers / product recommendations) widget into\n * a `CABRootSection`: an optional header (title/superTitle/description, reusing\n * the content-block text converter) over a `carousel` wrapper that ALWAYS contains\n * the `offers` section (the carousel is the required structural parent; it only\n * paginates when the v1 layout has carousel on). The offers section's `dataSource`\n * child carries the engine fetch config; its remaining children are the\n * per-offer card (see `buildOfferCard`).\n *\n * v1 `layout` is per-breakpoint; CAB has none, so the converter collapses to\n * the largest provided breakpoint. A widget-level discount lands on the data\n * source's `discount` field (what the extension prices cards from) plus a\n * config-only `discount` section, and an opt-in undo `banner` is appended after\n * the data source (discount above, banner pinned last) when each is configured.\n */\nexport const convertOfferToV2 = ({ id, name, settings }: V1OfferConvertInput): CABRootSection => {\n const layout = settings.layout?.large ?? settings.layout?.medium ?? settings.layout?.small;\n const columns = layout?.columns ?? 1;\n const direction = directionForStyle(layout?.style);\n const listLayout = buildProductListLayout(direction, columns);\n\n // The card orientation is the inverse of the product-list orientation: vertically-stacked\n // products (`rows`) carry a compact horizontal card (image | info | add); side-by-side products\n // (`grid`/`columns`) carry a narrow vertical card (image \u2192 info \u2192 add).\n const horizontalCard = direction === 'rows';\n\n const discount = dataSourceDiscount(settings.discount);\n\n const dataSource = {\n ...(settings.endpoint && { dataSourcePath: settings.endpoint }),\n ...(discount && { discount }),\n ...(settings.integrations && { integrations: coerceIntegrations(settings.integrations) }),\n ...(settings.limit !== undefined && { limit: settings.limit }),\n matchVariant: !!settings.productOptions?.matchVariant,\n matchVariantOutOfStock: !!settings.productOptions?.matchVariantOutOfStock,\n ...(settings.productType && { productType: settings.productType }),\n sectionType: 'dataSource',\n ...(settings.subscriptionIsDefault && { subscriptionIsDefault: true }),\n ...(settings.treatAsGwp && { treatAsGwp: true }),\n };\n\n // The visible card sections come first so their indices stay contiguous from\n // the top (the admin UI prepends newly-added visible sections). The trailing\n // config-only sections are never rendered per-card: data source (engine fetch\n // config), then the optional discount, then the undo banner pinned to the very\n // bottom. `offers` keeps the default `rows` direction; the card's own\n // orientation is baked into the sections `buildOfferCard` returns.\n const offers = {\n sections: [\n ...buildOfferCard(settings, horizontalCard),\n dataSource,\n ...buildDiscountSection(settings.discount),\n ...buildBanner(settings.language),\n ],\n sectionType: 'offers',\n };\n\n // Offers ALWAYS live inside a `carousel` section \u2014 it's the structural wrapper the CAB offers\n // architecture requires, regardless of whether the widget actually paginates (the name is\n // historical). It only shows pagination when there are more products than `itemsAtOnce`, so a\n // non-carousel v1 widget sets `itemsAtOnce` to the full limit and shows everything at once. The\n // product-list layout (direction/grid from the v1 style + columns) rides on this wrapper.\n const display = {\n autoAdvanceInterval: 0,\n // `itemsAtOnce` feeds the carousel schema's `.min(1)`; a legacy `columns`/`limit` of 0 would\n // otherwise throw at parse, so floor it at 1 (the carousel still shows a product per page).\n itemsAtOnce: Math.max(layout?.carousel ? columns : (settings.limit ?? columns), 1),\n ...listLayout,\n sections: [offers],\n sectionType: 'carousel',\n };\n\n return CABRootSection.parse({\n direction: 'rows',\n editorMode: LOCATION_TO_EDITOR_MODE[settings.location ?? 'checkout'],\n // The widget name is required by the admin save schema; carry the legacy widget's name through.\n ...(name && { name }),\n previewMode: settings.previewMode,\n sections: [\n ...(hasHeaderText(settings.language)\n ? [{ content: { en: convertContentBlockTextToV2(settings.language) }, sectionType: 'text' }]\n : []),\n display,\n ],\n tracking: {\n enableAttribution: settings.tracking?.enableAttribution ?? true,\n enableSource: settings.tracking?.enableSource ?? true,\n enableWidget: settings.tracking?.enableWidget ?? true,\n },\n type: SHOPIFY_CHECKOUT_EXTENSION,\n version: 2,\n widgetId: id,\n });\n};\n", "import { type z } from 'zod';\n\nimport { convertNumericObjects } from '~/transforms/convertNumericObjects';\nimport { deepCamelCase } from '~/transforms/deepCamelCase';\n\n/**\n * Runs the shielded-CDN response through the canonical pipeline:\n *\n * raw \u2192 deepCamelCase \u2192 convertNumericObjects \u2192 transform? \u2192 schema.parse\n *\n * `schema.parse` hydrates `.default(...)` values and surfaces any drift as a\n * ZodError. The optional `transform` step is for normalization that must run\n * before* validation \u2014 e.g. converting HTML-laden text content into Tiptap\n * documents (since the canonical CAB schema rejects HTML strings outright).\n *\n * @param schema - The canonical Zod schema to validate against.\n * @param raw - Untrusted upstream JSON.\n * @param transform - Optional pre-parse transform (defaults to identity).\n *\n * @returns The parsed-and-default-hydrated `z.infer<S>`.\n */\nexport const parseShielded = <S extends z.ZodType>(\n schema: S,\n raw: unknown,\n transform: (input: unknown) => unknown = (input) => input\n): z.infer<S> => schema.parse(transform(convertNumericObjects(deepCamelCase(raw))));\n", "export const UI_EXTENSION_PROGRESS_BAR = 'ui_extension_progress_bar' as const;\n\n/**\n * Per-currency free-shipping thresholds as production actually writes them: each amount is a FLAT sibling\n * key (CENTS, ISO code any casing) alongside `enabled`, while `currencies` is the admin's array of enabled\n * code strings \u2014 NOT a code\u2192amount map. The onsite reader indexes it flat (`presentment[code]`), same as the\n * smart-cart tier shape.\n */\nexport type V1PresentmentCurrencies = {\n [code: string]: number | string | string[] | boolean | undefined;\n currencies?: string[];\n enabled?: boolean;\n};\n\nexport type V1ProgressBarSettings = {\n barSettings: {\n barType: 'shipping' | 'smart-cart';\n configLabelsAndText?: {\n /** v1 field name carries this typo. Supports `{{remaining_amount}}`. */\n amoundRemaining?: string;\n amountReached?: string;\n };\n countryCodes?: string[];\n freeShippingOptions?: {\n freeShippingOnAll?: boolean;\n freeShippingOnSubscriptions?: boolean;\n presentmentCurrencies?: V1PresentmentCurrencies;\n };\n limitCountries?: boolean;\n /** Shop-currency DOLLARS (e.g. 75 for $75). */\n unlockPrice?: number;\n };\n location?: 'checkout' | 'order-status' | 'thank-you';\n previewMode?: boolean;\n type: typeof UI_EXTENSION_PROGRESS_BAR;\n version: 1;\n};\n\nexport type V1ProgressBarConvertInput = {\n id: number;\n /** The shop theme's `buttonBackground` (bar fill), resolved by the caller; stays absent when unresolved. */\n progressColor?: string;\n settings: V1ProgressBarSettings;\n};\n\nexport const isProgressBarV1 = (data: unknown): data is V1ProgressBarSettings => {\n if (!data || typeof data !== 'object') return false;\n\n const obj = data as Record<string, unknown>;\n\n return (\n obj.version === 1 &&\n obj.type === UI_EXTENSION_PROGRESS_BAR &&\n !!obj.barSettings &&\n typeof obj.barSettings === 'object'\n );\n};\n\n/**\n * Only `barType: 'shipping'` carries its full config in the widget settings.\n * Smart-cart bars reference settings that live in the smart-cart config (a\n * separate fetch in the old runtime) \u2014 they pass through unconverted until a\n * server-side source for that config exists.\n */\nexport const isConvertibleProgressBarV1 = (data: unknown): data is V1ProgressBarSettings =>\n isProgressBarV1(data) && data.barSettings.barType === 'shipping';\n", "import { CABRootSection } from '~/schema/widgets/checkout-and-beyond/root';\nimport { normalizeTextContent } from '~/transforms/normalizeTextContent';\nimport { normalizeTokens } from '~/transforms/normalizeTokens';\nimport {\n UI_EXTENSION_PROGRESS_BAR,\n type V1PresentmentCurrencies,\n type V1ProgressBarConvertInput,\n} from '~/transforms/progressBarV1/types';\n\nconst LOCATION_TO_EDITOR_MODE = {\n checkout: 'checkoutExtension',\n 'order-status': 'orderStatusPage',\n 'thank-you': 'thankYouPage',\n} as const;\n\nconst DEFAULT_REMAINING = 'Spend {{remainingAmount}} more to unlock free shipping!';\nconst DEFAULT_REACHED = \"Congratulations! You've unlocked free shipping!\";\n\n/**\n * Lowercased per-currency thresholds (cents) harvested from the FLAT presentment keys as production writes\n * them (`{ enabled, currencies: ['cad'], cad: 9900 }`) \u2014 `currencies` is the admin's enabled-code ARRAY, not\n * a code\u2192amount map, so amounts sit as flat siblings. Drops `enabled`, `currencies`, and malformed values.\n * Mirrors the onsite reader (`presentment[code]`) and the smart-cart tier converter.\n */\nconst toThresholds = (presentment?: V1PresentmentCurrencies): Record<string, number> => {\n if (!presentment?.enabled) return {};\n\n const thresholds: Record<string, number> = {};\n\n for (const [code, cents] of Object.entries(presentment)) {\n if (code === 'enabled' || code === 'currencies') continue;\n\n const value = Math.round(Number(cents));\n\n if (Number.isFinite(value) && value >= 0) thresholds[code.toLowerCase()] = value;\n }\n\n return thresholds;\n};\n\ntype TextSectionInput = Record<string, unknown>;\n\n/**\n * The progress-bar widget layout blueprint (decided 2026-06-12): a `rows`\n * layout with the progress bar in the first row, a `columns` layout of the\n * tiers' labels in the second row (omitted when no tier has a label), and any\n * other labels as further rows. The v1 SHIPPING bar has a single unlabeled\n * tier, so it emits just the bar row \u2014 the multi-tier smart-cart conversion\n * reuses this builder when its settings source exists.\n */\nexport const buildProgressBarLayout = (\n progressBar: Record<string, unknown>,\n tierLabels: TextSectionInput[],\n extraRows: TextSectionInput[] = []\n) => ({\n direction: 'rows',\n sections: [\n progressBar,\n ...(tierLabels.length > 0 ? [{ direction: 'columns', sections: tierLabels, sectionType: 'layout' }] : []),\n ...extraRows,\n ],\n sectionType: 'layout',\n});\n\n/**\n * `freeShippingOnAll` maps to a zero threshold (always reached). `freeShippingOnSubscriptions` rides on the\n * section so the client treats the bar as reached when the cart holds a subscription item (a live-cart\n * condition the server can't precompute).\n */\nexport const convertProgressBarToV2 = ({ id, progressColor, settings }: V1ProgressBarConvertInput): CABRootSection => {\n const { barSettings } = settings;\n const labels = barSettings.configLabelsAndText;\n const alwaysReached = barSettings.freeShippingOptions?.freeShippingOnAll === true;\n\n const progressBar = {\n /**\n * `limit_countries` enabled with an EMPTY list hid the bar everywhere in React (country \u2208 []\n * is never true), but the schema reads an empty countryCodes as UNRESTRICTED \u2014 that\n * misconfiguration would flip the bar visible. 'XX' (ISO 3166 user-assigned, never a real\n * buyer country) preserves the hide-everywhere reading without a schema change.\n */\n countryCodes: barSettings.limitCountries\n ? barSettings.countryCodes?.length\n ? barSettings.countryCodes\n : ['XX']\n : [],\n freeShippingOnSubscription: barSettings.freeShippingOptions?.freeShippingOnSubscriptions === true,\n ...(progressColor && { progressColor }),\n sections: [\n {\n buttonField: 'progressRemaining',\n content: { en: normalizeTokens(labels?.amoundRemaining || DEFAULT_REMAINING, ['remainingAmount']) },\n sectionType: 'text',\n },\n {\n buttonField: 'progressReached',\n content: { en: labels?.amountReached || DEFAULT_REACHED },\n sectionType: 'text',\n },\n ],\n sectionType: 'progressBar',\n tiers: [\n {\n threshold: alwaysReached ? 0 : Math.round((Number(barSettings.unlockPrice) || 0) * 100),\n thresholds: alwaysReached ? {} : toThresholds(barSettings.freeShippingOptions?.presentmentCurrencies),\n tierType: 'shipping',\n },\n ],\n };\n\n /** Merchant copy can carry HTML \u2014 the canonical pipeline converts it to Tiptap BEFORE the parse. */\n return CABRootSection.parse(\n normalizeTextContent({\n ...buildProgressBarLayout(progressBar, []),\n editorMode: LOCATION_TO_EDITOR_MODE[settings.location ?? 'checkout'],\n previewMode: settings.previewMode,\n type: UI_EXTENSION_PROGRESS_BAR,\n version: 2,\n widgetId: id,\n })\n );\n};\n", "import { type SmartCartBar, type SmartCartTier } from '~/schema/smartCart';\nimport { CABProgressTier } from '~/schema/widgets/checkout-and-beyond/progressBar';\nimport { CABRootSection } from '~/schema/widgets/checkout-and-beyond/root';\nimport { normalizeTextContent } from '~/transforms/normalizeTextContent';\nimport { normalizeTokens } from '~/transforms/normalizeTokens';\nimport { UI_EXTENSION_PROGRESS_BAR, type V1ProgressBarSettings } from '~/transforms/progressBarV1/types';\n\nconst LOCATION_TO_EDITOR_MODE = {\n checkout: 'checkoutExtension',\n 'order-status': 'orderStatusPage',\n 'thank-you': 'thankYouPage',\n} as const;\n\nconst DEFAULT_REMAINING = 'Spend {{remainingAmount}} more to unlock your reward!';\nconst DEFAULT_REACHED = \"Congratulations! You've unlocked your reward!\";\n\n/** All four onsite tier types render at checkout (discount/decorative migrated per the P12 re-scope). */\nconst IN_SCOPE_TIER_TYPES = new Set(['decorative', 'discount', 'product', 'shipping']);\n\nconst inScope = (tier: SmartCartTier): boolean => IN_SCOPE_TIER_TYPES.has(tier.type ?? '');\n\ntype TierType = 'decorative' | 'discount' | 'product' | 'shipping';\n\n/** The tier's `CABProgressTier` type \u2014 its config `type` when one of the four, else `product`. */\nconst tierTypeOf = (tier: SmartCartTier): TierType =>\n tier.type === 'shipping' || tier.type === 'discount' || tier.type === 'decorative' ? tier.type : 'product';\n\n/** The tier's threshold in its own unit: a raw item count for `item_quantity` tiers, shop-currency cents otherwise. */\nconst thresholdOf = (tier: SmartCartTier): number =>\n tier.unlockConditionType === 'item_quantity'\n ? Math.round(tier.minimum ?? 0)\n : Math.round((tier.minimum ?? 0) * 100);\n\n/**\n * Smart-cart tiers key per-currency thresholds as FLAT siblings on `presentmentCurrencies`\n * (`{ enabled, usd: 5000, \u2026 }`) \u2014 the same flat shape the shipping bar's `toThresholds` reads (that one\n * also carries a `currencies` code array). Returns lowercased ISO \u2192 cents, dropping `enabled` and malformed values.\n */\nconst tierThresholds = (tier: SmartCartTier): Record<string, number> => {\n const presentment = tier.presentmentCurrencies;\n\n if (!presentment?.enabled) return {};\n\n const thresholds: Record<string, number> = {};\n\n for (const [code, cents] of Object.entries(presentment)) {\n if (code === 'enabled') continue;\n\n const value = Math.round(Number(cents));\n\n if (Number.isFinite(value) && value >= 0) thresholds[code.toLowerCase()] = value;\n }\n\n return thresholds;\n};\n\n/**\n * The onsite `getTierLabel` step-row label (blank \u2192 no label under the icon): the merchant custom label\n * (always used for `decorative`), else the type default \u2014 'Free Shipping', the discount amount\n * (`{n}% Discount`, or `{{discountAmount}} Off` whose fixed amount the client resolves FX-aware per tier),\n * or the gift product title / 'Free Product'. Plain text \u2014 the compact step label is not rich copy.\n */\nconst tierLabel = (tier: SmartCartTier): string => {\n const type = tierTypeOf(tier);\n\n if ((tier.customTierLabel || type === 'decorative') && tier.customTierLabelText) return tier.customTierLabelText;\n\n if (type === 'decorative') return tier.customTierLabelText ?? '';\n\n if (type === 'shipping') return 'Free Shipping';\n\n if (type === 'discount')\n return tier.discountType === 'fixedAmount'\n ? '{{discountAmount}} Off'\n : `${tier.discountAmountFromTotal ?? 0}% Discount`;\n\n return tier.products?.[0]?.title ?? tier.allProducts?.[0]?.title ?? 'Free Product';\n};\n\n/**\n * The order-discount reward on a `discount` tier, carried so the client resolves `{{discountAmount}}`:\n * `fixedAmount` in shop-currency CENTS (FX-scaled client-side like the threshold), else the raw percent.\n */\nconst discountOf = (tier: SmartCartTier) => {\n if (tier.type !== 'discount') return undefined;\n\n const amount = tier.discountAmountFromTotal ?? 0;\n\n return tier.discountType === 'fixedAmount'\n ? { amount: Math.round(amount * 100), type: 'fixedAmount' as const }\n : { amount, type: 'percentage' as const };\n};\n\n/** The gift reward for a product tier (the first configured product), or undefined for shipping / unset. */\nconst giftOf = (tier: SmartCartTier) => {\n if (tier.type !== 'product') return undefined;\n\n const product = tier.products?.[0] ?? tier.allProducts?.[0];\n\n if (!product) return undefined;\n\n const productId = product.productId ?? product.id;\n\n if (productId === undefined) return undefined;\n\n return {\n productId,\n title: product.title,\n // One junk (non-positive) variant id must not fail the whole tier's schema \u2014 drop only the bad ids.\n variantIds: (product.variantIds ?? []).filter((id) => Number.isInteger(id) && id > 0),\n };\n};\n\n/**\n * A tier \u2192 its `CABProgressTier` metadata on the bar (threshold/gift/tierType/unit \u2014 NOT visual\n * content). Units resolve PER TIER (onsite `getTierMinimum`): an `item_quantity` tier's minimum is a\n * raw item count checked BEFORE any money handling \u2014 no \u00D7100, no presentment overrides (rounded only\n * because the schema pins counts to integers; onsite compares the raw value, so an integer count is\n * identical and junk fractional data degrades to the nearest count instead of a parse failure).\n */\nconst toTierMeta = (tier: SmartCartTier) => {\n const discount = discountOf(tier);\n const gift = giftOf(tier);\n const isItemCount = tier.unlockConditionType === 'item_quantity';\n const label = tierLabel(tier);\n const type = tierTypeOf(tier);\n\n return {\n ...(discount && { discount }),\n ...(gift && { gift }),\n ...(label && { label: { en: label } }),\n threshold: thresholdOf(tier),\n thresholds: !isItemCount && type === 'shipping' ? tierThresholds(tier) : {},\n ...(tier.id && { tierId: tier.id }),\n tierType: type,\n ...(isItemCount && { unit: 'item' }),\n };\n};\n\n/**\n * The renderable tiers of a bar: in scope (one of the four types) AND whose built `CABProgressTier` meta\n * passes the strict schema. A tier whose meta would fail (negative threshold, non-positive gift id, \u2026) is\n * dropped here rather than thrown by the final `CABRootSection.parse` \u2014 keeping the widget fail-safe against\n * numerically-valid-but-out-of-domain values that the loose `SmartCartTier` schema lets through.\n */\nconst renderableTiers = (bar: SmartCartBar): SmartCartTier[] =>\n (bar.tiers ?? []).filter((tier) => inScope(tier) && CABProgressTier.safeParse(toTierMeta(tier)).success);\n\nconst PRODUCT_TOKENS = ['productTitle', 'remainingAmount'];\nconst DISCOUNT_TOKENS = ['discountAmount', 'remainingAmount'];\nconst DECORATIVE_TOKENS = ['remainingAmount'];\n\ntype TierCopy = {\n reached?: boolean;\n reachedText?: string;\n remaining?: boolean;\n remainingText?: string;\n tokens: string[];\n};\n\n/** onsite's per-tier feedback copy for a non-shipping tier (shipping uses the bar-level free-shipping pair). */\nconst tierCopy = (tier: SmartCartTier): TierCopy => {\n switch (tierTypeOf(tier)) {\n case 'discount':\n return {\n reached: tier.discountAmountReachedLabel,\n reachedText: tier.discountAmountReachedLabelText,\n remaining: tier.discountAmountRemainingLabel,\n remainingText: tier.discountAmountRemainingLabelText,\n tokens: DISCOUNT_TOKENS,\n };\n case 'decorative':\n return {\n reached: tier.decorativeAmountReachedLabel,\n reachedText: tier.decorativeAmountReachedLabelText,\n remaining: tier.decorativeAmountRemainingLabel,\n remainingText: tier.decorativeAmountRemainingLabelText,\n tokens: DECORATIVE_TOKENS,\n };\n default:\n return {\n reached: tier.productAmountReachedLabel,\n reachedText: tier.productAmountReachedLabelText,\n remaining: tier.productAmountRemainingLabel,\n remainingText: tier.productAmountRemainingLabelText,\n tokens: PRODUCT_TOKENS,\n };\n }\n};\n\n/**\n * Per-tier feedback `text` sections (onsite `getTierFeedbackText`/`getTierCompletedText`): one for the\n * remaining prompt, one for the reached prompt, each tagged with the tier's id so the renderer shows it\n * only while that tier is the active one \u2014 falling back to the bar-level pair when a tier's copy is\n * blank/disabled (F-05). O-B3 is NOT replicated: the remaining prompt uses the remaining field, never the\n * reached one. Shipping tiers (and tiers with no id) emit nothing; the bar-level pair speaks for them.\n */\nconst toTierFeedback = (tier: SmartCartTier) => {\n if (tierTypeOf(tier) === 'shipping' || !tier.id) return [];\n\n const copy = tierCopy(tier);\n const meta = { threshold: thresholdOf(tier), tierId: tier.id, tierType: tierTypeOf(tier) };\n const sections: Record<string, unknown>[] = [];\n\n if (copy.remaining && copy.remainingText)\n sections.push({\n buttonField: 'progressRemaining',\n content: { en: normalizeTokens(copy.remainingText, copy.tokens) },\n sectionType: 'text',\n tier: meta,\n });\n\n if (copy.reached && copy.reachedText)\n sections.push({\n buttonField: 'progressReached',\n content: { en: normalizeTokens(copy.reachedText, copy.tokens) },\n sectionType: 'text',\n tier: meta,\n });\n\n return sections;\n};\n\n/**\n * A bar + its in-scope tiers \u2192 a self-contained `progressBar` container (a `rows` layout): the tier display\n * (if any) and the reached/remaining copy as children, the milestones on `tiers`. The renderer adds the bar\n * fill + active message; the country/FX gate covers the whole thing since it's one section. The caller\n * (`dedupeBars`) decides `countryCodes`/`excludeCountryCodes` so the rendered set matches React `getbar`.\n */\nconst toProgressBarSection = (\n bar: SmartCartBar,\n tiers: SmartCartTier[],\n countryCodes: string[],\n excludeCountryCodes: string[],\n progressColor?: string\n) => ({\n countryCodes,\n direction: 'rows',\n excludeCountryCodes,\n /** Discount tiers force the pre-discount subtotal so the tier's own reward can't un-reach it (F-08). */\n excludeDiscountInSubtotal:\n (bar.excludeDiscountInSubtotal ?? false) || tiers.some((tier) => tier.type === 'discount'),\n // Bar-level ids (not covered by the per-tier safeParse): drop non-positive ones so one junk id can't\n // fail `excludedVariantIds`' strict `.int().positive()` schema and 500 the whole widget.\n excludedVariantIds: (bar.excludedProducts ?? [])\n .flatMap((product) => product.variantIds ?? [])\n .filter((id) => Number.isInteger(id) && id > 0),\n freeShippingOnSubscription: bar.freeShippingOnSubscription ?? false,\n /** Absent \u21D2 omit so the section schema's `.default({ en: 'FREE GIFTS' })` is the single source of the fallback. */\n ...(bar.language?.giftAreaTitle && { giftAreaTitle: { en: bar.language.giftAreaTitle } }),\n ...(progressColor && { progressColor }),\n sections: [\n ...tiers.flatMap(toTierFeedback),\n {\n buttonField: 'progressRemaining',\n // Token-normalized here; any HTML in the copy is coerced to Tiptap by the text schema on parse.\n // `productTitle` resolves client-side to the active tier's gift (`{{product_title}}` parity).\n content: {\n en: normalizeTokens(bar.language?.freeShippingRemaining || DEFAULT_REMAINING, [\n 'productTitle',\n 'remainingAmount',\n ]),\n },\n sectionType: 'text',\n },\n {\n buttonField: 'progressReached',\n // `remainingAmount` normalized too (F24) \u2014 onsite reached copy can carry `{{remaining_amount}}`.\n content: {\n en: normalizeTokens(bar.language?.freeShippingReached || DEFAULT_REACHED, [\n 'productTitle',\n 'remainingAmount',\n ]),\n },\n sectionType: 'text',\n },\n ],\n sectionType: 'progressBar',\n tiers: tiers.map(toTierMeta),\n});\n\ntype BarEntry = { bar: SmartCartBar; tiers: SmartCartTier[] };\ntype RenderedBar = { countryCodes: string[]; entry: BarEntry; excludeCountryCodes: string[] };\n\n/** A bar's country codes, uppercased + de-duplicated (empty when unset). */\nconst barCountries = (bar: SmartCartBar): string[] => [\n ...new Set((bar.countryCodes ?? []).map((code) => code.trim().toUpperCase()).filter(Boolean)),\n];\n\n/**\n * Decide each bar's country gate to mirror React `getbar`, which renders exactly ONE bar per country: a geo\n * bar owns only the countries no EARLIER geo bar already claimed \u2014 and drops when it has none left (including\n * a geo bar that lists no countries, which `getbar` never matches); only the FIRST default (non-geo) bar\n * renders, gated to hide wherever any geo bar applies. Returns the bars that render, in order, with gates.\n *\n * A geo bar CLAIMS (shadows) its countries even when it has no renderable tiers \u2014 so an unrenderable geo bar\n * still hides the default (and any later geo bar) there, matching `getbar` one-bar-per-country precedence \u2014\n * but such a shadowing-only bar is not itself pushed (it renders nothing). Likewise an empty default never\n * consumes the default slot: the first default WITH tiers wins.\n */\nconst dedupeBars = (entries: BarEntry[]): RenderedBar[] => {\n const geoCountries = [\n ...new Set(entries.filter((entry) => entry.bar.geolocationEnabled).flatMap((entry) => barCountries(entry.bar))),\n ];\n const claimed = new Set<string>();\n const rendered: RenderedBar[] = [];\n let defaultUsed = false;\n\n for (const entry of entries) {\n if (entry.bar.geolocationEnabled) {\n const own = barCountries(entry.bar).filter((code) => !claimed.has(code));\n\n if (own.length === 0) continue;\n\n own.forEach((code) => claimed.add(code));\n\n if (entry.tiers.length > 0) rendered.push({ countryCodes: own, entry, excludeCountryCodes: [] });\n } else if (!defaultUsed && entry.tiers.length > 0) {\n defaultUsed = true;\n rendered.push({ countryCodes: [], entry, excludeCountryCodes: geoCountries });\n }\n }\n\n return rendered;\n};\n\n/**\n * Converts a smart-cart progress-bar widget into a CAB tree: a `rows` layout holding one self-contained\n * `progressBar` container per configured bar (tiers come from the shop's smart-cart config \u2014 see\n * `extractSmartCartBars`). Each container holds its tier display (composable `columns \u2192 rows \u2192 text/image`)\n * + copy as children, with milestones on `tiers` (server-precomputed per tier: cents \u2014 base +\n * per-presentment-currency for shipping tiers \u2014 or a raw item count for `item_quantity` tiers) so the\n * client only compares each tier against its own unit's progress, mirroring the shipping bar. DISPLAY\n * ONLY \u2014 gift add/remove is a later stage. Tiers whose meta fails the strict schema are dropped (never\n * thrown); a bar left with no renderable tier renders nothing \u2014 but a geo bar still shadows its countries\n * (so the default can't leak into them) even when it renders nothing.\n */\nexport const convertSmartCartProgressBarToV2 = (input: {\n bars: SmartCartBar[];\n id: number;\n /** The shop theme's `buttonBackground` (bar fill), resolved by the caller; schema-defaulted when absent. */\n progressColor?: string;\n settings: V1ProgressBarSettings;\n}): CABRootSection => {\n // NOT pre-filtered by renderable tiers: `dedupeBars` must see every geo bar so an unrenderable one\n // still claims (shadows) its countries; it only pushes bars that actually have tiers to render.\n const entries = input.bars.map((bar) => ({ bar, tiers: renderableTiers(bar) }));\n\n const sections = dedupeBars(entries).map(({ countryCodes, entry, excludeCountryCodes }) =>\n toProgressBarSection(entry.bar, entry.tiers, countryCodes, excludeCountryCodes, input.progressColor)\n );\n\n /** Merchant copy/labels can carry HTML \u2014 the canonical pipeline converts it to Tiptap BEFORE the parse. */\n return CABRootSection.parse(\n normalizeTextContent({\n direction: 'rows',\n editorMode: LOCATION_TO_EDITOR_MODE[input.settings.location ?? 'checkout'],\n previewMode: input.settings.previewMode,\n sections,\n sectionType: 'layout',\n type: UI_EXTENSION_PROGRESS_BAR,\n version: 2,\n widgetId: input.id,\n })\n );\n};\n", "import { type SmartCartBar, type SmartCartConfig } from '~/schema/smartCart';\n\n/** Component `type` value that carries the checkout smart-cart progress-bar tiers. */\nexport const SMART_CART_TIERED_PROGRESS_BAR = 'tiered_progress_bar' as const;\n\n/**\n * Pulls the progress-bar bars out of a shop's smart-cart config: the first\n * `tiered_progress_bar` component's `settings.bars`. Returns `[]` when smart cart is\n * absent / disabled / has no such component \u2014 the caller then renders nothing, matching\n * the legacy runtime (which only shows a smart-cart bar when one is configured).\n *\n * One bar per geo segment is returned as-is; country selection happens downstream via\n * each bar's `countryCodes` gate (parity with the shipping bar \u2014 no buyer country is\n * known at conversion time).\n */\nexport const extractSmartCartBars = (smartCart: SmartCartConfig | null | undefined): SmartCartBar[] => {\n const component = smartCart?.components?.find((entry) => entry.type === SMART_CART_TIERED_PROGRESS_BAR);\n\n return component?.settings?.bars ?? [];\n};\n", "import { CabUserConfig } from '~/schema/cabShopConfig';\nimport { NotFoundError, type ServerContext, UpstreamError, type UserConfigInput } from '~/server/shared';\nimport { parseShielded } from '~/transforms';\n\nconst unwrapData = (body: unknown): unknown =>\n body && typeof body === 'object' && 'data' in body ? (body as { data: unknown }).data : body;\n\nconst isEmptyObject = (x: unknown): boolean =>\n x == null || (typeof x === 'object' && !Array.isArray(x) && Object.keys(x as object).length === 0);\n\n/** Inactive/missing shops come back as `{ data: { shop: null } }` or `{ data: {} }`. */\nconst isMissingShopPayload = (data: unknown): boolean => {\n if (data == null || typeof data !== 'object' || Array.isArray(data)) return true;\n\n return isEmptyObject((data as { shop?: unknown }).shop);\n};\n\n/**\n * Resolves the shop's normalized config (publishable key, currency, integrations, \u2026) from the engine's\n * `/api/v1/user/config`. Throws {@link NotFoundError} for inactive/unknown shops.\n */\nexport const fetchUserConfig = async (input: UserConfigInput, ctx: ServerContext): Promise<CabUserConfig> => {\n let upstream: unknown;\n\n try {\n upstream = await ctx.fetchUpstream('/api/v1/user/config', { shop: input.shop }, { host: ctx.host });\n } catch (err) {\n /** Legacy `/api/v1/user/config` returns 404 for \"Shop is not active\"; treat 410 the same. */\n if (err instanceof UpstreamError && (err.status === 404 || err.status === 410)) {\n throw new NotFoundError(`Shop config not found: ${input.shop}`);\n }\n\n throw err;\n }\n\n const data = unwrapData(upstream);\n\n if (isMissingShopPayload(data)) throw new NotFoundError(`Shop config not found: ${input.shop}`);\n\n return parseShielded(CabUserConfig, data);\n};\n", "/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Returns true if the string is a valid base64 encoded string.\n *\n * @param {string} str - The string to check.\n *\n * @returns {boolean} True if the string is a valid base64 encoded string.\n */\nexport function isBase64Encoded(str: string): boolean {\n const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n\n return base64Regex.test(str) ? true : false;\n}\n\n/**\n * Returns a string as a JSON object.\n *\n * @param {string} data - The string to convert to a JSON object.\n * @param {boolean} decode - Whether to decode the string. *\n *\n * @returns {any} The JSON object.\n */\nexport function stringToData(data: string, decode: boolean): any {\n let response = data;\n\n // Base64 decode\n if (decode === true) {\n response = atob(response);\n }\n\n try {\n response = JSON.parse(response);\n } catch (e) {\n // failure to parse cookie\n response = data;\n }\n\n return response;\n}\n\n/**\n * Returns a JSON object as a string.\n *\n * @param {any} data - The JSON object to convert to a string.\n * @param {boolean} encode - Whether to encode the string. *\n *\n * @returns {string} The string.\n */\nexport function dataToString(data: any, encode: boolean): string {\n let response = data;\n\n if (typeof response != 'string') {\n response = JSON.stringify(response);\n }\n\n // Base64 encode\n if (encode === true) {\n response = btoa(response);\n }\n\n return response;\n}\n\n/**\n * Returns a string with HTML tags removed.\n *\n * @param {string} str - The string to strip HTML tags from.\n *\n * @returns {string} The string with HTML tags removed.\n */\nexport function stripHtml(str: string): string {\n return str?.replace(/<(.|\\n)*?>/g, '') ?? '';\n}\n\n/**\n * Returns the ID from a GraphQL URL.\n *\n * @param {string} graphId - The GraphQL URL.\n * @param {string} objectType - The object type.\n *\n * @returns {number | null} The ID.\n */\nexport function getIdFromGraphUrl(graphId: string, objectType: string): number | null {\n let id: number | null = null;\n\n const regex = new RegExp(`gid://shopify/${objectType}/(.*)`);\n const matches = graphId.match(regex);\n\n if (matches != null) {\n const matchedId = matches[1];\n\n if (!isNaN(Number(matchedId))) {\n id = Number(matchedId);\n }\n }\n\n return id;\n}\n\n/**\n * Returns true if the variant is available.\n *\n * @param {any} variant - The variant.\n *\n * @returns {boolean} True if the variant is available.\n */\nexport function variantAvailable(variant: any): boolean {\n return !(variant.inventory_management && variant.inventory_policy === 'deny' && variant.inventory_quantity <= 0);\n}\n\n/**\n * Returns the first available variant.\n *\n * @param {any} product - The product.\n *\n * @returns {any} The first available variant.\n */\nexport function firstAvailableVariant(product: any): any {\n // Select first variant\n let selectedVariant = product.variants[0];\n\n // Upgrade to first available\n for (let i = 0; i < product.variants.length; i++) {\n if (variantAvailable(product.variants[i])) {\n selectedVariant = product.variants[i];\n break;\n }\n }\n\n return selectedVariant;\n}\n\n/**\n * Returns a UUID.\n *\n * @returns {string} The UUID.\n */\nexport function uuid(): string {\n let d = new Date().getTime();\n let d2 = (performance && performance.now && performance.now() * 1000) || 0;\n\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n let r = Math.random() * 16;\n\n if (d > 0) {\n r = ((d + r) % 16) | 0;\n d = Math.floor(d / 16);\n } else {\n r = ((d2 + r) % 16) | 0;\n d2 = Math.floor(d2 / 16);\n }\n\n return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\n/**\n * Returns a session ID.\n *\n * @returns {string} The session ID.\n */\nexport function sessionId(): string {\n const config = {\n chars: '0123456789',\n length: 12,\n };\n\n let sessionId = '';\n const sessionStart = new Date().getTime();\n\n for (let i = config.length; i > 0; i--) {\n sessionId += config.chars[Math.floor(Math.random() * config.chars.length)];\n }\n\n return `REBUY.${sessionStart}.${sessionId}`;\n}\n\n/**\n * Converts a product to the storefront format.\n *\n * @param {any} product - The product.\n *\n * @returns {any} The product in the storefront format.\n */\nexport function convertProductToStorefrontFormat(product: any): any {\n const defaultVariant = firstAvailableVariant(product);\n const minVariantPrice = variantMinMaxPriceObject(product, 'price', 'min');\n const maxVariantPrice = variantMinMaxPriceObject(product, 'price', 'max');\n const minVariantCompareAtPrice = variantMinMaxPriceObject(product, 'compare_at_price', 'min');\n const maxVariantCompareAtPrice = variantMinMaxPriceObject(product, 'compare_at_price', 'max');\n const selectedOptions = selectedVariantOptions(product, defaultVariant);\n\n const variants = product.variants.map((variant: any) => convertVariantToStorefrontFormat(product, variant));\n\n return {\n collections: null,\n compareAtPriceRange: {\n maxVariantCompareAtPrice,\n minVariantCompareAtPrice,\n },\n description: stripHtml(product.body_html),\n descriptionHtml: product.body_html,\n featuredImage: productImageObject(product, null),\n handle: product.handle,\n id: `gid://shopify/Product/${product.id}`,\n images: null,\n media: [],\n metafields: [],\n options: [\n ...product.options.map((option: any) => {\n return { name: option.name, values: option.values };\n }),\n ],\n priceRange: {\n maxVariantPrice,\n minVariantPrice,\n },\n selectedOptions,\n selectedSellingPlan: null,\n selectedSellingPlanAllocation: null,\n sellingPlanGroups: [],\n seo: { description: null, title: null },\n title: product.title,\n variants: convertToNodes(variants),\n vendor: product.vendor,\n };\n}\n\n/**\n * Converts an array to a nodes object.\n *\n * @param {any} arr - The array to convert to a nodes object.\n *\n * @returns {any} The nodes object.\n */\nexport function convertToNodes(arr: any): any {\n return {\n edges: [\n ...arr.map((node: any) => {\n return { node };\n }),\n ],\n };\n}\n\n/**\n * Converts a variant to the storefront format.\n *\n * @param {any} product - The product.\n * @param {any} variant - The variant.\n *\n * @returns {any} The variant in the storefront format.\n */\nexport function convertVariantToStorefrontFormat(product: any, variant: any): any {\n const selectedOptions = selectedVariantOptions(product, variant);\n const image = productImageObject(product, variant.image_id);\n\n return {\n availableForSale: variantAvailable(variant),\n compareAtPriceV2: variantPriceObject(variant, 'compare_at_price'),\n id: `gid://shopify/ProductVariant/${variant.id}`,\n image: image,\n priceV2: variantPriceObject(variant, 'price'),\n product: {\n handle: product.handle,\n id: product.id,\n title: product.title,\n vendor: product.vendor,\n },\n selectedOptions: [selectedOptions],\n sku: variant.sku,\n title: variant.title,\n };\n}\n\n/**\n * Returns the minimum or maximum price object for a variant.\n *\n * @param {any} product - The product.\n * @param {string} key - The key to get the price object for.\n * @param {string} operator - The operator to use. *\n *\n * @returns {any} The price object.\n */\nexport function variantMinMaxPriceObject(product: any, key: string = 'price', operator: string = 'min'): any {\n let priceObject = variantPriceObject(product.variants[0], key);\n\n for (let i = 0; i < product.variants.length; i++) {\n const variantPrice = variantPriceObject(product.variants[i], key);\n\n if (variantPrice != null) {\n const variantPriceAmount = Number(variantPrice.amount);\n const currentPriceAmount = priceObject != null ? Number(priceObject.amount) : null;\n\n if (\n currentPriceAmount == null ||\n (operator === 'min' && variantPriceAmount < currentPriceAmount) ||\n (operator === 'max' && variantPriceAmount > currentPriceAmount)\n ) {\n priceObject = variantPrice;\n }\n }\n }\n\n return priceObject;\n}\n\n/**\n * Returns the price object for a variant.\n *\n * @param {any} variant - The variant.\n * @param {string} key - The key to get the price object for.\n *\n * @returns {any} The price object.\n */\nexport function variantPriceObject(variant: any, key: string = 'price'): any {\n if (variant[key] != null) {\n return {\n amount: variant[key],\n currencyCode: 'USD',\n };\n }\n\n return null;\n}\n\n/**\n * Returns the selected variant options.\n *\n * @param {any} product - The product.\n * @param {any} variant - The variant.\n *\n * @returns {any} The selected variant options.\n */\nexport function selectedVariantOptions(product: any, variant: any): any {\n const selectedOptions: Record<string, any> = {};\n\n if (variant.option1 != null) {\n selectedOptions[product.options[0].name] = variant.option1;\n }\n\n if (variant.option2 != null) {\n selectedOptions[product.options[1].name] = variant.option2;\n }\n\n if (variant.option3 != null) {\n selectedOptions[product.options[2].name] = variant.option3;\n }\n\n return selectedOptions;\n}\n\n/**\n * Returns the product image object.\n *\n * @param {any} product - The product.\n * @param {number | null} id - The ID of the image. *\n *\n * @returns {any} The product image object.\n */\nexport function productImageObject(product: any, id: number | null): any {\n let image = null;\n\n if (product.image) {\n image = {\n altText: product.image.alt,\n height: product.image.height,\n id: `gid://shopify/ProductImage/${product.image.id}`,\n url: product.image.src,\n width: product.image.width,\n };\n }\n\n if (product.images && product.images.length > 0 && id != null) {\n const matchingImage = product.images.find((i: any) => i.id === id);\n\n if (matchingImage) {\n image = {\n altText: matchingImage.alt,\n height: matchingImage.height,\n id: `gid://shopify/ProductImage/${matchingImage.id}`,\n url: matchingImage.src,\n width: matchingImage.width,\n };\n }\n }\n\n return image;\n}\n\n/**\n * Returns a query string as an object.\n *\n * @param {string} str - The query string to convert to an object.\n *\n * @returns {any} The object.\n */\nexport function queryStringToObject(str: string): any {\n const params = new URLSearchParams(str);\n\n return Object.fromEntries(params.entries());\n}\n\n/**\n * Returns a UTM object from a string.\n *\n * @param {string} str - The string to convert to a UTM object.\n *\n * @returns {any} The UTM object.\n */\nexport function utmObjectFromString(str: string): any {\n const utmKeys = ['utm_campaign', 'utm_medium', 'utm_source', 'utm_term', 'utm_content'];\n\n const matches: Record<string, any> = {};\n\n const url = new URL(str);\n const queryObject = queryStringToObject(url.search);\n\n for (const [key, value] of Object.entries(queryObject)) {\n if (utmKeys.includes(key)) {\n matches[key] = value;\n }\n }\n\n return Object.keys(matches).length > 0 ? matches : null;\n}\n\n/**\n * Returns the amount in cents.\n *\n * @param {number} amount - The amount to convert to cents.\n *\n * @returns {number} The amount in cents.\n */\nexport function amountToCents(amount: number | string): number {\n let normalizedAmount: number = 0;\n\n if (typeof amount === 'string') {\n if (amount.indexOf('.') !== -1) {\n normalizedAmount = Math.round(parseFloat(amount) * 100);\n } else {\n normalizedAmount = parseInt(amount, 10);\n }\n } else if (typeof amount === 'number') {\n normalizedAmount = Math.round(amount * 100);\n }\n\n if (isNaN(normalizedAmount)) {\n normalizedAmount = 0;\n }\n\n return normalizedAmount;\n}\n\n/**\n * Serializes an object.\n *\n * @param {Record<string, unknown>} obj - The object to serialize.\n *\n * @returns {string} The serialized object.\n */\nexport function serialize(obj: Record<string, unknown>): string {\n const serialized: string[] = [];\n\n const add = (key: string, value: any) => {\n value = typeof value === 'function' ? value() : value;\n value = value === null ? '' : value === undefined ? '' : value;\n serialized[serialized.length] = encodeURIComponent(key) + '=' + encodeURIComponent(value);\n };\n\n const buildParameters = (prefix: string, obj: any) => {\n let i, key, len;\n\n if (prefix) {\n if (Array.isArray(obj)) {\n for (i = 0, len = obj.length; i < len; i++) {\n buildParameters(prefix + '[' + (typeof obj[i] === 'object' && obj[i] ? i : '') + ']', obj[i]);\n }\n } else if (Object.prototype.toString.call(obj) === '[object Object]') {\n for (key in obj) {\n buildParameters(prefix + '[' + key + ']', obj[key]);\n }\n } else {\n add(prefix, obj);\n }\n } else if (Array.isArray(obj)) {\n for (i = 0, len = obj.length; i < len; i++) {\n add(obj[i].name, obj[i].value);\n }\n } else {\n for (key in obj) {\n buildParameters(key, obj[key]);\n }\n }\n\n return serialized;\n };\n\n return buildParameters('', obj).join('&');\n}\n", "import { RuleVerdict } from '~/schema/metadata';\nimport { OfferProduct } from '~/schema/offerProduct';\n\nimport {\n type DataSourceInput,\n NotFoundError,\n type ServerContext,\n type ServerDrift,\n UpstreamError,\n} from '~/server/shared';\nimport { fetchUserConfig } from '~/server/userConfig';\nimport { deepCamelCase } from '~/transforms';\nimport { serialize } from '~/utilities';\n\ntype Reporter = (event: ServerDrift) => void;\n\nexport type DataSourceResults = {\n metadata: unknown;\n products: unknown[];\n /**\n * The shop's base-currency ISO code (from the already-resolved shop config), so the client can derive\n * the shop minor-unit exponent and forecast a Functions fixed discount exactly in a cross-decimal market.\n * Undefined when the engine omits it \u2014 the client then falls back to the buyer currency's decimals.\n */\n shopCurrency?: string;\n};\n\n/**\n * Encode a key/value list the way the engine expects (React `getEncodedAttributes`): a `{key: value}` object,\n * JSON-stringified, then URL-encoded ONCE here. `serialize()` URL-encodes the whole value again when it builds\n * the query string, so the wire is double-encoded \u2014 matching what the SmartCart SDK sends (`cart[attributes]=%257B%257D`).\n */\nconst encodeAttributes = (pairs: { key: string; value?: string }[] = []): string =>\n encodeURIComponent(JSON.stringify(Object.fromEntries(pairs.map(({ key, value }) => [key, value ?? '']))));\n\n/**\n * Translate the camelCase input into the legacy engine's contract: snake_case keys, PHP-bracket query\n * serialization, derived aggregates (item/line counts, id CSVs), and the shop's publishable key. The\n * extension never carries any of this.\n */\nexport const buildEngineParams = (input: DataSourceInput, key: string): Record<string, unknown> => {\n const { cart, customerId, filterInputs, integrations, limit, productType, shop, visitorId } = input;\n\n const items = cart.items.map(({ productId, properties, quantity, subscriptionId, variantId }) => ({\n product_id: productId,\n properties: encodeAttributes(properties),\n quantity,\n ...(subscriptionId && { subscription_id: subscriptionId }),\n variant_id: variantId,\n }));\n\n const itemCount = cart.items.reduce((total, { quantity }) => total + quantity, 0);\n\n /**\n * Rule thresholds are authored in SHOP currency and evaluate against actual spend: subtract\n * cart-level discounts (React `useSearchParams`), then divide out the presentment FX rate (onsite\n * `convertToShopCurrency`). A missing or degenerate rate means the cart is already shop-currency.\n *\n * `subtotal`/`discountTotal` arrive in the buyer's presentment currency as integer minor units\n * (the \u00D7100 Shopify-cents convention the client sends); `currencyRate` is a MAJOR-unit ratio\n * (presentment \u00F7 shop). Dividing minor-unit presentment by the major-unit rate yields shop minor\n * units \u2014 the \u00D7100 cancels dimensionally, for any currency (e.g. \u00A5735000 \u00F7 147 = 5000\u00A2). Getting the\n * unit of one side wrong is the #117 class; keep both sides minor-vs-major as documented here.\n */\n const currencyRate = cart.currencyRate ?? 1;\n const rate = Number.isFinite(currencyRate) && currencyRate > 0 ? currencyRate : 1;\n const subtotal = Math.round((cart.subtotal - (cart.discountTotal ?? 0)) / rate);\n\n return {\n cart: {\n attributes: encodeAttributes(cart.attributes),\n /** `discount_code` rules match against this; React sends raw `useDiscountCodes()` as `[{code}]`. */\n ...(cart.discountCodes?.length && { discount_codes: cart.discountCodes.map((code) => ({ code })) }),\n item_count: itemCount,\n items,\n line_count: items.length,\n subtotal,\n },\n cart_count: items.length,\n cart_item_count: itemCount,\n cart_line_count: items.length,\n cart_subtotal: subtotal,\n ...(filterInputs && { filter_inputs: filterInputs }),\n key,\n limit,\n metafields: Object.values(integrations ?? {}).some(Boolean) ? 'yes' : 'no',\n // Only subscription-bearing product types request selling-plan data; absent/one-time send 'no'\n // to match the legacy engine contract (an absent `productType` must not opt a widget into plans).\n selling_plans: productType === 'subscription' || productType === 'both' ? 'yes' : 'no',\n shop,\n ...(customerId && { shopify_customer_id: customerId }),\n shopify_product_ids: items.map(({ product_id: id }) => id).join(','),\n shopify_variant_ids: items.map(({ variant_id: id }) => id).join(','),\n ...(visitorId && { uuid: visitorId }),\n };\n};\n\n/**\n * Keep an engine product only when it has the shape `toProduct` needs (options/variants present, prices\n * readable). One product missing them would throw and take the whole offers rail down; dropping it with a\n * drift signal costs one card instead. The valid product passes through as-is (extra engine fields intact).\n */\nconst keepValidProduct = (product: unknown, report?: Reporter): boolean => {\n const parse = OfferProduct.safeParse(product);\n\n if (parse.success) return true;\n\n /**\n * Name the first drifted field (e.g. `variants`) so ops can tell a missing-options product from an\n * unreadable-price one. Built by joining the first issue path in \u2014 an empty issues list (never emitted\n * by a failed zod parse) degrades to the bare message rather than throwing.\n */\n const detail = [\n 'offer product failed validation',\n ...parse.error.issues.slice(0, 1).map((issue) => issue.path.join('.')),\n ].join(': ');\n\n report?.({ detail, kind: 'product' });\n\n return false;\n};\n\n/** A definitive GWP rule answer (`matchedRules`/`unmatchedRules`) \u2014 the OTHER `limit: 0` metadata shape. */\nconst isRuleAnswer = (metadata: Record<string, unknown>): boolean =>\n metadata.matchedRules != null || metadata.unmatchedRules != null;\n\n/**\n * At `limit: 0` the metadata is either a rule-gating verdict (`custom.shouldShow`) or a GWP rule answer.\n * A non-null verdict-shaped payload that carries NEITHER a readable `shouldShow` NOR rule arrays means the\n * engine's verdict contract drifted \u2014 which would otherwise hide every gated section fleet-wide with no\n * signal. Emit a distinguishable drift so ops can tell it from a rule legitimately evaluating false.\n */\nconst reportUnreadableVerdict = (metadata: unknown, report?: Reporter): void => {\n if (metadata == null || typeof metadata !== 'object' || Array.isArray(metadata)) return;\n\n if (RuleVerdict.safeParse(metadata).success || isRuleAnswer(metadata as Record<string, unknown>)) return;\n\n report?.({ detail: 'rule verdict lacks readable custom.shouldShow', kind: 'ruleVerdict' });\n};\n\n/** Engine responses can repeat a product across rule outputs; first one wins. */\nconst dedupeById = (products: unknown[]): unknown[] => {\n const seen = new Set<unknown>();\n\n return products.filter((product) => {\n const id = (product as { id?: unknown }).id;\n\n if (seen.has(id)) return false;\n\n seen.add(id);\n\n return true;\n });\n};\n\n/**\n * Evaluates a data source against the live cart: resolves the shop's publishable key, GETs the engine\n * endpoint with the translated params, and returns camelCased, id-deduplicated products plus rule\n * metadata. `limit: 0` returns metadata only.\n */\nexport const fetchDataSourceResults = async (\n input: DataSourceInput,\n ctx: ServerContext\n): Promise<DataSourceResults> => {\n const { shop } = await fetchUserConfig({ shop: input.shop }, ctx);\n\n let upstream: unknown;\n\n try {\n upstream = await ctx.fetchUpstream(\n `/api/v1${input.dataSourcePath}`,\n {},\n { host: ctx.host, search: serialize(buildEngineParams(input, shop.apiKey)) }\n );\n } catch (err) {\n if (err instanceof UpstreamError && (err.status === 404 || err.status === 410)) {\n throw new NotFoundError(`Data source not found: ${input.dataSourcePath}`);\n }\n\n throw err;\n }\n\n const raw = upstream && typeof upstream === 'object' ? (upstream as { data?: unknown; metadata?: unknown }) : {};\n const rawProducts = Array.isArray(raw.data) ? (deepCamelCase(raw.data) as unknown[]) : [];\n const metadata = raw.metadata == null ? null : deepCamelCase(raw.metadata);\n\n if (input.limit === 0) reportUnreadableVerdict(metadata, ctx.reportDrift);\n\n return {\n metadata,\n products: dedupeById(rawProducts.filter((product) => keepValidProduct(product, ctx.reportDrift))),\n shopCurrency: shop.currency,\n };\n};\n", "import { v7 as uuidv7 } from 'uuid';\n\nimport { sectionTypes } from '~/schema/widgets/checkout-and-beyond/common';\nimport { CABRootSection } from '~/schema/widgets/checkout-and-beyond/root';\nimport { CABSection } from '~/schema/widgets/checkout-and-beyond/shared';\nimport { type ServerDrift } from '~/server/shared';\n\n/**\n * Parse orchestration, deliberately independent of the schema shapes it calls (so R3's zod-v4 getter\n * migration leaves it untouched): a whole-tree `CABRootSection.parse` makes ONE unknown/invalid section\n * fatal to the entire widget, and the client's graceful `UnknownSection` rail \u2014 which renders an\n * unrecognized `sectionType` as `null` \u2014 never gets the chance to run because the server 500s first.\n * Salvaging per section instead lets one bad section cost one section.\n */\n\ntype Reporter = (event: ServerDrift) => void;\n\n/** A section this build won't recognize, so the client dispatches it to `null` (maintainer choice over drop). */\nconst STUB_SECTION_TYPE = 'unknown';\n\nconst knownSectionTypes = new Set<string>(sectionTypes);\n\nconst hasSectionsArray = (raw: unknown): raw is { sections: unknown[] } =>\n typeof raw === 'object' && raw !== null && Array.isArray((raw as { sections?: unknown }).sections);\n\n/**\n * The non-renderable replacement for an unsalvageable section. A genuinely unknown `sectionType` is\n * preserved so the client's `unknown-section` analytics report the real drift; a known-but-invalid one\n * (bad data under a recognized type) is masked behind the sentinel so the client can't try to render it.\n */\nconst stubSection = (raw: unknown, report?: Reporter): { sectionId: string; sectionType: string } => {\n const record = typeof raw === 'object' && raw !== null ? (raw as Record<string, unknown>) : {};\n const original = record.sectionType;\n const rawId = record.sectionId;\n\n report?.({\n detail: `invalid section (${typeof original === 'string' ? original : 'no sectionType'})`,\n kind: 'section',\n });\n\n return {\n sectionId: typeof rawId === 'string' && rawId ? rawId : uuidv7(),\n sectionType: typeof original === 'string' && !knownSectionTypes.has(original) ? original : STUB_SECTION_TYPE,\n };\n};\n\n/**\n * Salvage one section: a section that parses whole is kept (defaults hydrated); a container whose own\n * fields are valid is rebuilt from its parsed shell with each child salvaged individually (so a bad\n * grandchild costs the grandchild, not the whole container); anything else becomes a stub. The shell is\n * recovered against the discriminated union \u2014 dispatched by the section's OWN `sectionType` to the matching\n * member (`offers`/`carousel`/`products`/\u2026 not always `layout`), so a drifted grandchild in a non-layout\n * rail no longer sinks the whole rail to a null-rendering stub.\n */\nconst salvageSection = (raw: unknown, report?: Reporter): unknown => {\n const parsed = CABSection.safeParse(raw);\n\n if (parsed.success) return parsed.data;\n\n if (hasSectionsArray(raw)) {\n const shell = CABSection.safeParse({ ...raw, sections: [] });\n\n if (shell.success)\n return { ...shell.data, sections: raw.sections.map((child) => salvageSection(child, report)) };\n }\n\n return stubSection(raw, report);\n};\n\n/**\n * Salvage-parse a v2-authored CAB tree: hydrate the root's own fields, then salvage each section. A root\n * whose OWN fields are invalid (not just its children) still throws \u2014 a fundamentally broken widget is a\n * real error, whereas section-level drift degrades gracefully.\n */\nexport const salvageRootSection = (raw: unknown, report?: Reporter): unknown => {\n const shell = CABRootSection.safeParse(hasSectionsArray(raw) ? { ...raw, sections: [] } : raw);\n\n if (!shell.success) return CABRootSection.parse(raw);\n\n const sections = hasSectionsArray(raw) ? raw.sections.map((child) => salvageSection(child, report)) : [];\n\n return { ...shell.data, sections };\n};\n", "import { type SmartCartBar } from '~/schema/smartCart';\nimport { SectionType } from '~/schema/widgets/checkout-and-beyond/common';\n\nimport { salvageRootSection } from '~/server/salvageSections';\nimport {\n NotFoundError,\n type ServerContext,\n type ServerDrift,\n UpstreamError,\n type WidgetSettingsInput,\n} from '~/server/shared';\nimport { fetchUserConfig } from '~/server/userConfig';\nimport {\n convertContentBlockToV2,\n convertLineItemEditorToV2,\n convertNumericObjects,\n convertOfferToV2,\n convertProgressBarToV2,\n convertSmartCartProgressBarToV2,\n deepCamelCase,\n extractSmartCartBars,\n isCABRootSection,\n isContentBlockV1,\n isConvertibleProgressBarV1,\n isLineItemEditorV1,\n isOfferV1,\n isProgressBarV1,\n normalizeTextContent,\n} from '~/transforms';\nimport { resolveExperiment, type ResolvedExperiment } from '~/transforms/experiments/resolveExperiment';\n\nconst unwrapData = (body: unknown): unknown =>\n body && typeof body === 'object' && 'data' in body ? (body as { data: unknown }).data : body;\n\n/**\n * The legacy shielded CDN returns `200 { data: null }` (or `{ data: {} }`) for deleted/missing widgets \u2014\n * it doesn't emit `404`. Treat both shapes as \"widget not found\".\n */\nconst isMissingUpstreamPayload = (data: unknown): boolean =>\n data == null || (typeof data === 'object' && !Array.isArray(data) && Object.keys(data as object).length === 0);\n\n/**\n * Routes a normalized (camelCased + numeric-fixed) upstream payload to the right transform by shape:\n * `version: 2` \u2192 CAB parse; a v1 content block \u2192 `convertContentBlockToV2`; a v1 line-item editor \u2192\n * `convertLineItemEditorToV2`; a v1 offer (`type: shopify_checkout_extension`, checked LAST \u2014 it has no\n * `version` discriminator) \u2192 `convertOfferToV2`. Progress bars route in {@link convertWidgetSettings}\n * (their conversion needs an async theme fetch). Every other widget type passes through unchanged \u2014 its\n * converter slots in here in the phase that introduces it.\n */\nconst dispatchWidgetTransform = (id: number, normalized: unknown, report?: (event: ServerDrift) => void): unknown => {\n if (isCABRootSection(normalized)) return salvageRootSection(normalizeTextContent(normalized), report);\n\n if (isContentBlockV1(normalized)) return convertContentBlockToV2({ id, settings: normalized });\n\n if (isLineItemEditorV1(normalized)) return convertLineItemEditorToV2({ id, settings: normalized });\n\n if (isOfferV1(normalized)) return convertOfferToV2({ id, name: normalized.name, settings: normalized });\n\n return normalized;\n};\n\n/**\n * The shop config + theme-derived bar fill color, degraded independently: a config-fetch failure \u21D2 `{}`\n * (no config \u21D2 no bars), guarded on its own; the theme color is best-effort ({@link fetchThemeColor}\n * self-catches to `undefined`) so a theme failure yields a colorless-but-present bar and can NEVER drop\n * the bars. A progress bar must never 404 the widget or break checkout.\n */\nconst fetchProgressBarContext = async (\n shop: string,\n ctx: ServerContext\n): Promise<{ bars?: SmartCartBar[]; progressColor?: string }> => {\n const config = await fetchUserConfig({ shop }, ctx).catch(() => undefined);\n\n if (!config) return {};\n\n return {\n bars: extractSmartCartBars(config.smartCart),\n progressColor: await fetchThemeColor(config.shop.shopId, ctx),\n };\n};\n\n/** The shop theme's `buttonBackground` \u2014 the bar fill React reads (`useRebuyTheme`); undefined on any failure. */\nconst fetchThemeColor = async (shopId: number | undefined, ctx: ServerContext): Promise<string | undefined> => {\n if (!shopId) return undefined;\n\n try {\n const theme = await ctx.fetchUpstream(`/admin/api/v1/shop/theme/${shopId}`, {}, { host: ctx.host });\n const color = (theme as { theme?: { settings?: { buttonBackground?: unknown } } }).theme?.settings\n ?.buttonBackground;\n\n return typeof color === 'string' && color ? color : undefined;\n } catch {\n return undefined;\n }\n};\n\ntype WalkableSection = { progressColor?: string; sections?: unknown[]; sectionType?: string };\n\n/**\n * Depth-first: the progress-bar sections of a parsed tree that lack an explicit fill color \u2014 the ones\n * whose color falls back to the live shop theme.\n */\nconst colorlessProgressBars = (section: WalkableSection): WalkableSection[] => {\n const own = section.sectionType === SectionType.progressBar && section.progressColor === undefined;\n const nested = (section.sections ?? []).flatMap((child) => colorlessProgressBars(child as WalkableSection));\n\n return own ? [section, ...nested] : nested;\n};\n\n/**\n * Fetch ONE widget's raw settings from the engine and convert them to a CAB section tree (or pass a\n * non-CAB widget through). Throws {@link NotFoundError} for deleted/missing widgets. `id` may be the\n * requested widget or an A/B-selected variant element; the rest of the params are shop-scoped.\n */\nconst fetchAndConvert = async (id: number, input: WidgetSettingsInput, ctx: ServerContext): Promise<unknown> => {\n const params: Record<string, string> = { id: String(id), shop: input.shop };\n\n if (input.cacheKey != null) params.cache_key = String(input.cacheKey);\n\n if (input.key) params.key = input.key;\n\n let upstream: unknown;\n\n try {\n upstream = await ctx.fetchUpstream('/api/v1/widgets/settings', params, { host: ctx.host });\n } catch (err) {\n // The legacy controller returns 4xx (e.g. 400 \"Invalid widget ID (probably deleted)\") for missing\n // widgets; treat any 4xx as \"not found\" \u2014 malformed input is already blocked upstream by Zod.\n if (err instanceof UpstreamError && err.status >= 400 && err.status < 500) {\n throw new NotFoundError(`Widget not found: ${id}`);\n }\n\n throw err;\n }\n\n const data = unwrapData(upstream);\n\n if (isMissingUpstreamPayload(data)) throw new NotFoundError(`Widget not found: ${id}`);\n\n const normalized = convertNumericObjects(deepCamelCase(data));\n\n /**\n * Smart-cart bars carry only `barType` in their widget settings \u2014 the tiers live in the shop's\n * smart-cart config (a second fetch through the same injected upstream). Both bar types also pull\n * the theme's bar fill color. Degrade on any config/theme failure: a non-critical progress bar must\n * never 404 the widget or break checkout.\n */\n if (isProgressBarV1(normalized) && normalized.barSettings.barType === 'smart-cart') {\n const { bars, progressColor } = await fetchProgressBarContext(input.shop, ctx);\n\n return convertSmartCartProgressBarToV2({ bars: bars ?? [], id, progressColor, settings: normalized });\n }\n\n /** Shipping bars carry their full config in the widget settings; only the fill color needs the shop. */\n if (isConvertibleProgressBarV1(normalized)) {\n const { progressColor } = await fetchProgressBarContext(input.shop, ctx);\n\n return convertProgressBarToV2({ id, progressColor, settings: normalized });\n }\n\n const converted = dispatchWidgetTransform(id, normalized, ctx.reportDrift);\n\n /**\n * v2-authored trees: an explicit `progressColor` is used verbatim; a bar without one gets the live\n * theme color (the same fallback the v1 conversion above applies), fetched once per widget.\n */\n const colorless = isCABRootSection(normalized) ? colorlessProgressBars(converted as WalkableSection) : [];\n\n if (colorless.length > 0) {\n const { progressColor: color } = await fetchProgressBarContext(input.shop, ctx);\n\n if (color) for (const bar of colorless) bar.progressColor = color;\n }\n\n return converted;\n};\n\n/**\n * The sticky A/B variant for the requested widget, or `undefined` when none targets it / no visitor id.\n * Experiments are non-critical: any failure resolving the shop config degrades to \"no experiment\" rather\n * than breaking the widget.\n */\nconst resolveWidgetExperiment = async (\n input: WidgetSettingsInput,\n ctx: ServerContext\n): Promise<ResolvedExperiment | undefined> => {\n if (!input.visitorId) return undefined;\n\n try {\n const { shop } = await fetchUserConfig({ shop: input.shop }, ctx);\n\n return resolveExperiment(shop.activeExperiments, input.id, input.visitorId);\n } catch {\n return undefined;\n }\n};\n\n/**\n * A converted result is a CAB tree (vs a passed-through non-CAB widget) when it carries `version: 2`.\n * `fetchAndConvert` always returns a non-null object (or throws), so reading `.version` is safe here.\n */\nconst isCABTree = (result: unknown): result is { version: number } => (result as { version?: unknown }).version === 2;\n\n/**\n * Resolve a widget's CAB section tree, applying server-side A/B selection: when the requested widget is\n * an experiment placeholder and a `visitorId` is supplied, the sticky-chosen variant's tree is fetched\n * instead and the experiment metadata is attached for the client's analytics. Without an experiment this\n * is a plain fetch-and-convert. Throws {@link NotFoundError} for deleted/missing widgets.\n */\nexport const convertWidgetSettings = async (input: WidgetSettingsInput, ctx: ServerContext): Promise<unknown> => {\n const experiment = await resolveWidgetExperiment(input, ctx);\n const result = await fetchAndConvert(experiment?.elementId ?? input.id, input, ctx);\n\n /** Only CAB trees can carry the experiment; a passed-through variant renders without A/B analytics. */\n return experiment && isCABTree(result) ? { ...result, experiment } : result;\n};\n", "import { type MatchedRule } from '~/gwp/types';\n\n/**\n * The product ids a widget's matched rules currently qualify \u2014 ported from the React\n * extension's `getValidGwpProductIds` (camelCased engine shape). A gift whose product is\n * not in this set no longer qualifies and should be removed.\n */\nexport const getValidGwpProductIds = (matchedRules: MatchedRule[] = []): Set<number> =>\n new Set(\n matchedRules\n .flatMap((rule) => rule.output ?? [])\n .flatMap((output) => output.products ?? [])\n .map((product) => Number(product.productId))\n .filter((id) => Number.isFinite(id))\n );\n", "import { type GwpMetadata, type MatchedRule } from '~/gwp/types';\n\n/**\n * Rule types the engine can't evaluate correctly in the cart/data-source context (no page URL,\n * no order) \u2014 ported from the React extension. When a widget's rules use these, the matched output\n * is unreliable, so the validator must NOT remove the gift.\n */\nconst UNSUPPORTED_RULE_TYPES = ['url', 'order_tag'];\n\nconst ruleHasUnsupportedType = (rule: MatchedRule): boolean =>\n (rule.logic ?? []).some((group) =>\n (group.rules ?? []).some((item) => UNSUPPORTED_RULE_TYPES.includes(item.type ?? ''))\n );\n\n/**\n * Whether any matched OR unmatched rule uses an unsupported type \u2014 the bail signal: the gift's\n * qualification can't be trusted, so keep it (never remove on uncertainty).\n */\nexport const hasUnsupportedRuleTypes = (metadata?: GwpMetadata | null): boolean =>\n [...(metadata?.matchedRules ?? []), ...(metadata?.unmatchedRules ?? [])].some(ruleHasUnsupportedType);\n", "import { type GwpMetadata } from '~/gwp/types';\n\n/**\n * Whether the engine metadata is a definitive rule answer the validator may act on. Removal is only\n * safe downstream of a parsed 2xx that actually evaluated rules (onsite-js standard: every degraded\n * path is a no-op): metadata missing entirely \u2014 the tolerated-empty-2xx path \u2014 or carrying NEITHER\n * `matchedRules` NOR `unmatchedRules` is uncertainty, so keep the gifts. `matchedRules: []` alongside\n * `unmatchedRules` IS definitive \u2014 the engine answered and nothing qualifies.\n */\nexport const isDefinitiveRuleAnswer = (metadata?: GwpMetadata | null): metadata is GwpMetadata =>\n metadata != null && (metadata.matchedRules != null || metadata.unmatchedRules != null);\n", "import { type GwpGift } from '~/gwp/types';\n\n/**\n * Whether a gift line should be removed: either its product no longer qualifies (\u2209 `validIds`),\n * OR it lost its Shopify Function discount (`!discounted && cost > 0`). The Function can't remove\n * a line it failed to discount, so the client must \u2014 this is the complete removal decision the\n * server returns as a receipt (see the rebuy-discount-architecture / GWP E2 notes).\n */\nexport const shouldRemoveGift = (\n gift: Pick<GwpGift, 'cost' | 'discounted' | 'productId'>,\n validIds: Set<number>\n): boolean => !validIds.has(gift.productId) || (!gift.discounted && gift.cost > 0);\n", "import {\n getValidGwpProductIds,\n type GwpMetadata,\n hasUnsupportedRuleTypes,\n isDefinitiveRuleAnswer,\n shouldRemoveGift,\n} from '~/gwp';\n\nimport { fetchDataSourceResults } from '~/server/dataSourceResults';\nimport { type GiftInput, type GiftValidationInput, type ServerContext } from '~/server/shared';\nimport { deepCamelCase } from '~/transforms';\n\n/** A widget's data-source path from its RAW settings `endpoint` (uniform across widget types). */\nconst resolveDataSourcePath = async (\n widgetId: number,\n shop: string,\n ctx: ServerContext\n): Promise<string | undefined> => {\n const raw = await ctx.fetchUpstream('/api/v1/widgets/settings', { id: String(widgetId), shop }, { host: ctx.host });\n const data = raw && typeof raw === 'object' && 'data' in raw ? (raw as { data: unknown }).data : raw;\n /** A deleted widget returns `{ data: null }`; `deepCamelCase(null)` is null, so guard the read (fail-open by design, not by a lucky TypeError). */\n const endpoint = (deepCamelCase(data) as { endpoint?: unknown } | null)?.endpoint;\n\n return typeof endpoint === 'string' && endpoint ? endpoint : undefined;\n};\n\nconst groupByWidget = (gifts: GiftInput[]): Map<number, GiftInput[]> => {\n const byWidget = new Map<number, GiftInput[]>();\n\n for (const gift of gifts) {\n byWidget.set(gift.widgetId, [...(byWidget.get(gift.widgetId) ?? []), gift]);\n }\n\n return byWidget;\n};\n\n/**\n * Validates gift lines per widget and returns the cart-line ids to remove (the complete receipt).\n * Per widget: resolve its data-source path, evaluate its rules against the cart (`limit: 0`), then\n * drop gifts that no longer qualify OR lost their discount. **Fail-safe**: any error, a missing\n * endpoint, a non-definitive rule answer (no metadata, or metadata with neither rule array \u2014 the\n * tolerated-empty-2xx path), or unsupported rule types (`url`/`order_tag`) \u2192 skip that widget (never\n * remove on uncertainty). A definitive answer that omits a gift \u2014 even `matchedRules: []` \u2014 removes it.\n *\n * **Every degraded path is a no-op by design** \u2014 this includes the discount-lost case (a gift whose\n * Function discount lapsed, so the buyer is being charged). React removed that on any successful fetch;\n * here it too is gated behind a definitive rule answer, so under a degraded response the gift stays and the\n * buyer may keep paying. Deliberate: falsely removing a genuinely-qualified gift is judged worse than\n * briefly leaving a lapsed-discount gift, and the client re-validates on the next cart change.\n */\nexport const validateGifts = async (input: GiftValidationInput, ctx: ServerContext): Promise<{ remove: string[] }> => {\n const perWidget = await Promise.all(\n [...groupByWidget(input.gifts)].map(async ([widgetId, gifts]) => {\n try {\n const dataSourcePath = await resolveDataSourcePath(widgetId, input.shop, ctx);\n\n if (!dataSourcePath) return [];\n\n const { metadata } = await fetchDataSourceResults(\n {\n cart: input.cart,\n customerId: input.customerId,\n dataSourcePath,\n /** The gift being validated is in the cart \u2014 input filtering would erase it from the answer. */\n filterInputs: 'no',\n /**\n * `limit: 0` fetches NO products \u2014 only the rule verdict is needed. Safe because the engine\n * derives `matchedRules` from rule-config evaluation, not from fetched results (traced through\n * `api.php`), so the metadata is complete at limit 0. Don't raise it to \"fix\" a non-bug.\n */\n limit: 0,\n shop: input.shop,\n visitorId: input.visitorId,\n },\n ctx\n );\n\n const meta = (metadata ?? undefined) as GwpMetadata | undefined;\n\n if (!isDefinitiveRuleAnswer(meta) || hasUnsupportedRuleTypes(meta)) return [];\n\n const validIds = getValidGwpProductIds(meta.matchedRules);\n\n return gifts.filter((gift) => shouldRemoveGift(gift, validIds)).map((gift) => gift.lineId);\n } catch {\n return [];\n }\n })\n );\n\n return { remove: perWidget.flat() };\n};\n", "import { z } from 'zod';\n\nimport { type MonetizeInput, REBUY_ENGINE_HOST, type ServerContext } from '~/server/shared';\nimport { fetchUserConfig } from '~/server/userConfig';\n\n/** Ads-engine supply (SSP) keys \u2014 public identifiers picked by environment, not credentials. */\nconst SUPPLY_KEY = { production: 'AQF5RKLR', staging: 'Z56LQ7PS' } as const;\n\n/** The ads engine sizes for a handful of offers; the carousel + modal chain expect the same. */\nconst OFFER_LIMIT = 4;\n\n/**\n * Countries the public ad network is allowed to serve. The ad server's `AdRequest.Validate()` 400s any\n * `country_code` outside this set, so we hard-gate here (mirroring the extension's `isSupportedCountry`).\n */\nconst SUPPORTED_COUNTRIES = new Set(['US', 'CA']);\n\n/** Max `transaction_items` the engine accepts before it truncates; we cap first (React parity). */\nconst MAX_TRANSACTION_ITEMS = 50;\n\n/**\n * Rebuy QA's customer email \u2014 a checkout with it is flagged `testing` so the engine excludes it from\n * billing/reporting (mirrors admin-api's `RebuyMonetizeService::TEST_EMAIL`). Compared lower-cased.\n */\nconst TEST_CUSTOMER_EMAIL = 'test@rebuyengine.com';\n\n/** The ads `transaction_items` \u2014 rich per-line detail when the client sent it, else `{id, quantity}` from the cart. */\nconst transactionItems = (input: MonetizeInput): Record<string, number | string>[] =>\n (\n input.transactionItems?.map(({ id, priceCents, quantity, title, type }) => ({\n id,\n price_cents: priceCents,\n quantity,\n title,\n type,\n })) ?? input.cart.items.map(({ productId, quantity }) => ({ id: productId, quantity }))\n ).slice(0, MAX_TRANSACTION_ITEMS);\n\n/**\n * A single ads-engine offer. The `*_url` fields are tracking endpoints the engine returns fully\n * built (impression/decline/click) \u2014 the composer wires them onto the card verbatim.\n */\nexport const AdsEngineOffer = z.object({\n click_url: z.string(),\n cta: z.string(),\n /** `omitempty` on the ad server \u2014 a bid without it must not fail the parse and drop the whole batch (composeOffer falls back to 'No Thanks'). */\n decline_cta: z.string().catch(''),\n decline_url: z.string(),\n description: z.string(),\n headline: z.string(),\n id: z.string(),\n image_url: z.string().optional(),\n view_url: z.string(),\n});\n\nexport type AdsEngineOffer = z.infer<typeof AdsEngineOffer>;\n\n/**\n * Per-offer resilient: parse the batch as `unknown[]` then keep only the offers that validate, so one\n * offer missing a required field (e.g. `click_url`) drops itself rather than throwing away the whole batch.\n */\nconst AdsEngineResponse = z.object({\n offers: z\n .array(z.unknown())\n .default([])\n .transform((offers) =>\n offers.flatMap((offer) => {\n const result = AdsEngineOffer.safeParse(offer);\n\n return result.success ? [result.data] : [];\n })\n ),\n});\n\n/** The ads engine lives on the `offers.` subdomain of the resolved engine host. */\nconst adsHost = (host: string): string => `offers.${host}`;\n\n/**\n * True when the request should be flagged `testing` (kept out of billing/reporting): a non-prod\n * upstream, the client's editor/QA indicator, or Rebuy's QA customer email \u2014 React's staging-OR-editor-\n * OR-test-email fold, split so the environment half stays host-derived and the rest travel on the input.\n */\nexport const isTestingRequest = (input: MonetizeInput, isProduction: boolean): boolean =>\n !isProduction || !!input.testing || input.customerEmail?.toLowerCase() === TEST_CUSTOMER_EMAIL;\n\n/**\n * Translate the extension's context into the ads-engine query contract. Publisher/supply keys and the\n * testing flag are server-decided; `session_id` prefers the rolling session id (React parity), falling\n * back to the visitor id (truthy `||`, so an empty-string `sessionId` still yields the visitor id rather\n * than an empty `session_id` the ad server 400s on); cart lines become `transaction_items`/`transaction_total`\n * (total preferred over subtotal). Empty values are omitted.\n */\nexport const buildAdsParams = (\n input: MonetizeInput,\n publisherKey: string,\n supplyKey: string,\n testing: boolean,\n userAgent?: string,\n ipAddress?: string\n): Record<string, string> => {\n const items = transactionItems(input);\n\n return {\n limit: String(OFFER_LIMIT),\n placement: input.placement,\n publisher_key: publisherKey,\n supply_key: supplyKey,\n testing: String(testing),\n transaction_total: String(input.transactionTotal ?? input.cart.subtotal),\n ...(items.length > 0 && { transaction_items: JSON.stringify(items) }),\n ...(input.country && { country_code: input.country }),\n ...(input.currency && { currency_code: input.currency }),\n ...(input.customerEmail && { customer_email: input.customerEmail }),\n ...(input.customerId && { customer_id: input.customerId }),\n ...(input.customerFirstName && { first_name: input.customerFirstName }),\n ...(input.customerLastName && { last_name: input.customerLastName }),\n ...(input.language && { language: input.language }),\n ...(input.timezone && { timezone: input.timezone }),\n ...(input.transactionId && { transaction_id: input.transactionId }),\n ...(input.zipCode && { zip_code: input.zipCode }),\n ...(ipAddress && { ip_address: ipAddress }),\n ...((input.sessionId || input.visitorId) && { session_id: input.sessionId || input.visitorId! }),\n ...(userAgent && { user_agent: userAgent }),\n };\n};\n\n/**\n * Fetch live ad offers from the Rebuy ads engine. Resolves the shop's publisher key server-side (and\n * returns `[]` when the shop isn't enrolled \u2014 no ads, not an error). A non-prod upstream sends the\n * staging supply key; a non-prod/editor/QA-email request is flagged `testing` (excluded from billing).\n */\nexport const fetchAdsEngineOffers = async (input: MonetizeInput, ctx: ServerContext): Promise<AdsEngineOffer[]> => {\n /**\n * The ad server 400s an unsupported `country_code` or a request with no session id, so short-circuit\n * BEFORE `fetchUserConfig` (saving that upstream call too). `[]` means \"no offers\", never an error \u2014\n * the same hard gate the extension applies with `isSupportedCountry`.\n */\n if (!input.country || !SUPPORTED_COUNTRIES.has(input.country.toUpperCase())) return [];\n\n if (!(input.sessionId || input.visitorId)) return [];\n\n const { shop } = await fetchUserConfig({ shop: input.shop }, ctx);\n const publisherKey = shop.monetize?.publisherKey;\n\n if (!publisherKey) return [];\n\n const isProduction = ctx.host === REBUY_ENGINE_HOST;\n const supplyKey = isProduction ? SUPPLY_KEY.production : SUPPLY_KEY.staging;\n\n const upstream = await ctx.fetchUpstream(\n '/api/v1/offers',\n buildAdsParams(\n input,\n publisherKey,\n supplyKey,\n isTestingRequest(input, isProduction),\n ctx.userAgent,\n ctx.ipAddress\n ),\n { host: adsHost(ctx.host) }\n );\n\n return AdsEngineResponse.parse(upstream).offers;\n};\n", "import {\n ButtonAction,\n ButtonField,\n ButtonStyle,\n CABLayoutSection,\n type CABSection,\n SectionType,\n} from '~/schema/widgets/checkout-and-beyond';\n\nimport { type AdsEngineOffer } from '~/server/adsEngine';\nimport { type MonetizeInput } from '~/server/shared';\nimport { normalizeTextContent } from '~/transforms/normalizeTextContent';\n\n/** Empty engine CTA/decline labels fall back to these (React `normalizeAdsEngineOffer` parity). */\nconst ACCEPT_FALLBACK = 'Accept';\nconst DECLINE_FALLBACK = 'No Thanks';\n\n/** A button's visible label is a nested `text` slot tagged `buttonLabel`. */\nconst label = (text: string) => ({\n buttonField: ButtonField.buttonLabel,\n content: { en: text },\n sectionType: SectionType.text,\n});\n\n/** A plain-text content section (English ad copy \u2014 the engine speaks one language per placement). */\nconst text = (content: string) => ({ content: { en: content }, sectionType: SectionType.text });\n\n/** The Monetize header shop name: the shop's config carries none here, so derive it from the domain (React fallback). */\nconst shopName = (shop: string): string => shop.replace(/\\.myshopify\\.com$/, '') || 'store';\n\n/**\n * Compose one ads-engine offer into a renderable CAB card: a `layout` whose `viewUrl` is the\n * impression pixel, holding the (optional) image, the headline, the HTML body (coerced to Tiptap by\n * the text-content schema on parse), and the two CTA buttons. `acceptOffer` links out to the advertiser (`destinationUrl` = `click_url`,\n * which self-tracks); `declineOffer` fires the decline pixel (`trackingUrl`) and advances. Parsing\n * through the schema fills defaults (section ids, layout direction) and validates the shape.\n */\nexport const composeOfferCard = (offer: AdsEngineOffer, privacyPolicyUrl?: string): CABSection | undefined => {\n /** Ad copy can carry HTML \u2014 the canonical pipeline converts it to Tiptap BEFORE the parse. */\n const result = CABLayoutSection.safeParse(\n normalizeTextContent({\n sections: [\n ...(offer.image_url\n ? [\n {\n /** Image alt must be PLAIN \u2014 a DSP headline like `Get <b>50%</b> off` would trip the image NO_HTML refine and bleed fill; the visible `text(offer.headline)` still gets the HTML\u2192Tiptap pipeline. */\n altText: offer.headline.replace(/<[^>]*>/g, ''),\n sectionType: SectionType.image,\n source: offer.image_url,\n },\n ]\n : []),\n text(offer.headline),\n text(offer.description),\n {\n action: ButtonAction.acceptOffer,\n buttonStyle: ButtonStyle.primary,\n sections: [\n label(offer.cta || ACCEPT_FALLBACK),\n {\n buttonField: ButtonField.destinationUrl,\n content: { en: offer.click_url },\n sectionType: SectionType.text,\n },\n ],\n sectionType: SectionType.button,\n },\n {\n action: ButtonAction.declineOffer,\n buttonStyle: ButtonStyle.secondary,\n sections: [label(offer.decline_cta || DECLINE_FALLBACK)],\n sectionType: SectionType.button,\n trackingUrl: offer.decline_url,\n },\n /** Ad-unit Privacy Policy footer (compliance); a valid href is required for the Tiptap link mark. */\n ...(privacyPolicyUrl ? [text(`<a href=\"${privacyPolicyUrl}\">Privacy Policy</a>`)] : []),\n ],\n viewUrl: offer.view_url,\n })\n );\n\n /** A single un-composable offer (e.g. a malformed `image_url`) drops just itself, not the whole batch. */\n return result.success ? result.data : undefined;\n};\n\n/**\n * The Monetize header shown ABOVE the inline offer only (never inside the accept modal \u2014 same reason\n * React keeps it out of `RebuyMonetizeModal`): the concluded experiment's winning copy (\"Congratulations!\n * / Your {shop} purchase unlocked a bonus:\") plus the \"Order \u2026 Confirmed\" line. Composed server-side so\n * the extension renders it as ordinary localized content.\n */\nexport const composeMonetizeHeader = (input: MonetizeInput): CABSection =>\n CABLayoutSection.parse(\n normalizeTextContent({\n sections: [\n text('Congratulations!'),\n text(`Your ${shopName(input.shop)} purchase unlocked a bonus:`),\n text(input.orderName ? `Order ${input.orderName} Confirmed` : 'Order Confirmed'),\n ],\n })\n );\n", "import { type CABSection } from '~/schema/widgets/checkout-and-beyond';\n\nimport { fetchAdsEngineOffers } from '~/server/adsEngine';\nimport { composeMonetizeHeader, composeOfferCard } from '~/server/composeOffer';\nimport { type MonetizeInput, type ServerContext } from '~/server/shared';\n\n/** `header` is the inline chrome (experiment copy + order-confirmed line); present only when there's an offer. */\nexport type MonetizeOffers = { header?: CABSection; offers: CABSection[] };\n\n/**\n * The monetize-offers orchestrator: fetch live ad offers from the engine and compose each into a CAB\n * offer card the extension renders directly, plus the inline header chrome. Empty (no card, no header)\n * when the shop isn't ad-enrolled.\n */\nexport const fetchMonetizeOffers = async (input: MonetizeInput, ctx: ServerContext): Promise<MonetizeOffers> => {\n const offers = (await fetchAdsEngineOffers(input, ctx))\n .map((offer) => composeOfferCard(offer, input.privacyPolicyUrl))\n /** Drop any offer that failed to compose (safeParse \u2192 undefined) so one bad bid can't lose the batch. */\n .filter((card): card is CABSection => card !== undefined);\n\n return { offers, ...(offers.length > 0 && { header: composeMonetizeHeader(input) }) };\n};\n", "import { type AnalyticsEventInput, type AnalyticsInput, type ServerContext } from '~/server/shared';\nimport { fetchUserConfig } from '~/server/userConfig';\n\n/** The legacy engine's analytics event shape (`POST /api/v2/analytics/event/bulk`). */\ntype EngineEvent = {\n aggregator?: string;\n cart_token?: string;\n defined_noun_id?: string;\n event_time?: string;\n meta?: Record<string, boolean | string>;\n noun: 'cart' | 'checkout-extension' | 'widget';\n shopify_checkout_token?: string;\n subject: 'abtest' | 'user';\n tags?: string[];\n uuid: string;\n verb: 'added-from' | 'tracking' | 'viewed';\n widget_id?: string;\n};\n\ntype Taxonomy = {\n buildDefinedNounId?: (properties: Record<string, unknown>) => string | undefined;\n buildMeta?: (properties: Record<string, unknown>) => Record<string, boolean | string>;\n buildTags?: (properties: Record<string, unknown>) => string[] | undefined;\n /** Overrides which id lands in `widget_id` (default: the request's `widgetId`). */\n buildWidgetId?: (properties: Record<string, unknown>, input: AnalyticsInput) => string | undefined;\n noun: EngineEvent['noun'];\n subject: EngineEvent['subject'];\n usesWidgetId: boolean;\n verb: EngineEvent['verb'];\n};\n\n/** Raw engine experiment type \u2192 the snake_case form the engine expects in A/B meta (React parity). */\nconst EXPERIMENT_TYPE_MAP: Record<string, string> = {\n CheckoutOffer: 'checkout_offer',\n Generic: 'generic',\n GlobalSmartFlow: 'smart_flow',\n SmartCart: 'smart_cart',\n Widget: 'widget',\n};\n\n/** The `ABN.TEST.<experimentId>` tag React attaches to every experiment-attributed event, or none. */\nconst experimentTags = ({ experimentId }: Record<string, unknown>): string[] | undefined =>\n experimentId != null ? [`ABN.TEST.${experimentId}`] : undefined;\n\n/**\n * Maps a generic client event `name` \u2192 the engine's (noun, verb, subject) taxonomy, verbatim from the\n * React extension. Names with no entry are dropped (analytics is fire-and-forget; never error a buyer).\n */\nconst TAXONOMY = {\n 'ab-test-viewed': {\n // Only when BOTH ids are present \u2014 otherwise the template literal would emit \"undefined.undefined\".\n buildDefinedNounId: ({ experimentId, selectedId }) =>\n experimentId != null && selectedId != null ? `${experimentId}.${selectedId}` : undefined,\n buildMeta: ({ elementId, experimentType }) => ({\n element_id: String(elementId ?? ''),\n experiment_type: EXPERIMENT_TYPE_MAP[String(experimentType ?? '')] ?? '',\n }),\n buildTags: experimentTags,\n noun: 'cart',\n subject: 'abtest',\n usesWidgetId: false,\n verb: 'tracking',\n },\n 'added-to-cart': {\n /** React credits the add to the A/B-selected variant (`defined_noun_id: selectedId`). */\n buildDefinedNounId: ({ selectedId }) => (selectedId != null ? String(selectedId) : undefined),\n buildMeta: ({ productId, variantId }) => ({\n ...(productId != null && { [`product_id:${productId}`]: true }),\n ...(variantId != null && { [`variant_id:${variantId}`]: true }),\n }),\n buildTags: experimentTags,\n /** Under an experiment the add belongs to the VARIANT element, not the placeholder (React parity). */\n buildWidgetId: ({ elementId }, input) => (elementId != null ? String(elementId) : input.widgetId),\n noun: 'widget',\n subject: 'user',\n usesWidgetId: true,\n verb: 'added-from',\n },\n 'checkout-viewed': {\n /** React's random hex shard key (\"used instead of widget_id for aggregation\"). */\n buildDefinedNounId: () => Math.floor(Math.random() * 16).toString(16),\n buildMeta: () => ({ has_widget: true }),\n noun: 'checkout-extension',\n subject: 'user',\n usesWidgetId: false,\n verb: 'viewed',\n },\n // Forward-compat diagnostic (no React precedent): a deployed extension rendered a sectionType it\n // didn't recognize. Generic `tracking` verb; the unknown type rides in meta so we can spot schema drift.\n 'unknown-section': {\n buildMeta: ({ sectionType }) => ({ [`section_type:${String(sectionType ?? 'unknown')}`]: true }),\n noun: 'widget',\n subject: 'user',\n usesWidgetId: true,\n verb: 'tracking',\n },\n 'widget-viewed': {\n buildTags: experimentTags,\n /** Under an experiment the view belongs to the VARIANT element, not the placeholder (React parity, same as added-to-cart) \u2014 else views credit the placeholder while adds credit the variant and per-widget conversion is meaningless. */\n buildWidgetId: ({ elementId }, input) => (elementId != null ? String(elementId) : input.widgetId),\n noun: 'widget',\n subject: 'user',\n usesWidgetId: true,\n verb: 'viewed',\n },\n} satisfies Record<string, Taxonomy>;\n\n/**\n * The client analytics event names the server knows how to translate \u2014 the typed contract R5's analytics\n * work targets instead of the stringly-typed one. Derived from the taxonomy so the two never drift.\n */\nexport type CabAnalyticsEventName = keyof typeof TAXONOMY;\n\nconst isKnownEvent = (name: string): name is CabAnalyticsEventName => name in TAXONOMY;\n\n/** Translate one client event into an engine event, or `null` if its `name` isn't in the taxonomy. */\nexport const translateAnalyticsEvent = (event: AnalyticsEventInput, input: AnalyticsInput): EngineEvent | null => {\n if (!isKnownEvent(event.name)) return null;\n\n /** `satisfies` narrows each entry to its own literal shape; widen back to the optional-method contract. */\n const taxonomy: Taxonomy = TAXONOMY[event.name];\n\n const properties = event.properties ?? {};\n const meta = taxonomy.buildMeta?.(properties);\n const tags = taxonomy.buildTags?.(properties);\n const definedNounId = taxonomy.buildDefinedNounId?.(properties);\n const widgetId = taxonomy.buildWidgetId?.(properties, input) ?? input.widgetId;\n\n return {\n noun: taxonomy.noun,\n subject: taxonomy.subject,\n uuid: input.visitorId,\n verb: taxonomy.verb,\n // Aggregate by checkout identity (Rebuy cart token + Shopify checkout token); else the visitor id (React parity).\n ...(event.sentAt && { event_time: event.sentAt }),\n ...(input.cartToken && { cart_token: input.cartToken }),\n ...(input.checkoutToken && { shopify_checkout_token: input.checkoutToken }),\n ...(!input.cartToken && !input.checkoutToken && { aggregator: input.visitorId }),\n ...(taxonomy.usesWidgetId && widgetId && { widget_id: widgetId }),\n ...(definedNounId && { defined_noun_id: definedNounId }),\n ...(meta && Object.keys(meta).length > 0 && { meta }),\n ...(tags && tags.length > 0 && { tags }),\n };\n};\n\n/** The engine's bulk endpoint 400s (dropping the WHOLE batch) above this size, so we POST in slices of it. */\nconst MAX_ANALYTICS_EVENTS = 100;\n\n/**\n * Translate a batch of client events to the engine contract and POST them to the analytics bulk\n * endpoint with the shop's publishable key (resolved server-side, never sent by the client). No-ops\n * when nothing maps. Chunks into POSTs of at most {@link MAX_ANALYTICS_EVENTS} so an oversized batch\n * isn't rejected wholesale. Returns the total count forwarded.\n */\nexport const postAnalyticsEvents = async (input: AnalyticsInput, ctx: ServerContext): Promise<{ accepted: number }> => {\n const events = input.events\n .map((event) => translateAnalyticsEvent(event, input))\n .filter((event): event is EngineEvent => event !== null);\n\n if (events.length === 0) return { accepted: 0 };\n\n const { shop } = await fetchUserConfig({ shop: input.shop }, ctx);\n\n for (let index = 0; index < events.length; index += MAX_ANALYTICS_EVENTS) {\n await ctx.fetchUpstream(\n '/api/v2/analytics/event/bulk',\n {},\n {\n body: events.slice(index, index + MAX_ANALYTICS_EVENTS),\n headers: { 'X-Rebuy-User-Token': shop.apiKey },\n host: ctx.host,\n method: 'POST',\n }\n );\n }\n\n return { accepted: events.length };\n};\n", "/**\n * Zod schemas for the `/cab/*` REQUEST bodies the orchestrators accept. Centralized here so rebuy-api can\n * validate incoming requests against the same contract the orchestrators are typed on \u2014 the hand-written\n * `*Input` twins in `./shared` are now `z.infer` of these schemas (single source of truth, no drift).\n *\n * These model the wire shape only: no `.default()`s (a request field is either sent or omitted \u2014 defaulting\n * would diverge `z.infer` from the twin it replaces and hide a missing field), and unknown keys are stripped\n * by the plain `z.object`, which is the intended lenient request-parse behavior.\n */\nimport { z } from 'zod';\n\n/** A raw key/value pair (line-item / cart attribute); the engine receives these JSON-encoded. */\nconst KeyValue = z.object({ key: z.string(), value: z.string().optional() });\n\n/** A cart line in the live-cart context the engine evaluates against. */\nexport const CartLineInputSchema = z.object({\n productId: z.string(),\n properties: z.array(KeyValue).optional(),\n quantity: z.number(),\n subscriptionId: z.string().optional(),\n variantId: z.string(),\n});\n\n/** The live cart context shared by the data-source, gift-validation, and monetize inputs. */\nexport const CartInputSchema = z.object({\n attributes: z.array(KeyValue).optional(),\n /**\n * Presentment-per-shop-currency FX rate (buyer price \u00F7 shop price, e.g. `1.35` for a USD shop\n * selling in CAD). Money rule thresholds are authored in SHOP currency, so the engine subtotal is\n * divided by this before evaluation. Omit (or send 1) when the cart is already in the shop's currency.\n */\n currencyRate: z.number().optional(),\n /** Applied discount codes; the engine evaluates `discount_code` rules against them (sent as `[{code}]`). */\n discountCodes: z.array(z.string()).optional(),\n /** Presentment cents of cart-level discount allocations, subtracted from `subtotal` for the engine. */\n discountTotal: z.number().optional(),\n items: z.array(CartLineInputSchema),\n /** Presentment subtotal in cents. */\n subtotal: z.number(),\n});\n\n/** Input for `convertWidgetSettings`. */\nexport const WidgetSettingsInputSchema = z.object({\n cacheKey: z.number().optional(),\n id: z.number(),\n key: z.string().optional(),\n shop: z.string(),\n /** Stable per-buyer id; when present, enables sticky server-side A/B variant selection. */\n visitorId: z.string().optional(),\n});\n\n/** Input for `fetchUserConfig`. */\nexport const UserConfigInputSchema = z.object({ shop: z.string() });\n\n/** Input for `fetchDataSourceResults`. */\nexport const DataSourceInputSchema = z.object({\n cart: CartInputSchema,\n customerId: z.string().optional(),\n dataSourcePath: z.string(),\n /**\n * Engine `filter_inputs` override: `'no'` keeps in-cart (input) products in the results/rule\n * outputs \u2014 gift validation sends it so a gift's own product can appear in its answer. Omitted = the\n * engine's default filtering.\n */\n filterInputs: z.enum(['no', 'yes']).optional(),\n integrations: z.record(z.string(), z.boolean()).optional(),\n limit: z.number(),\n productType: z.enum(['both', 'one-time', 'subscription']).optional(),\n shop: z.string(),\n visitorId: z.string().optional(),\n});\n\n/** A gift line the gift-validation watcher asks the server to validate. */\nexport const GiftInputSchema = z.object({\n cost: z.number(),\n discounted: z.boolean(),\n lineId: z.string(),\n productId: z.number(),\n widgetId: z.number(),\n});\n\n/** Input for `validateGifts`. */\nexport const GiftValidationInputSchema = z.object({\n cart: CartInputSchema,\n customerId: z.string().optional(),\n gifts: z.array(GiftInputSchema),\n shop: z.string(),\n visitorId: z.string().optional(),\n});\n\n/**\n * A rich transaction line the ads engine prices/targets on \u2014 the full per-line detail React sends. Distinct\n * from a cart line: it carries the merchandise title/type/unit-price the rule-evaluation cart context omits.\n */\nexport const MonetizeTransactionItemSchema = z.object({\n id: z.string(),\n priceCents: z.number(),\n quantity: z.number(),\n title: z.string(),\n type: z.string(),\n});\n\n/** Input for `fetchMonetizeOffers`. */\nexport const MonetizeInputSchema = z.object({\n cart: CartInputSchema,\n country: z.string().optional(),\n currency: z.string().optional(),\n /** Ads-targeting identity/geo/locale fields (React parity); folded into the engine query verbatim. */\n customerEmail: z.string().optional(),\n customerFirstName: z.string().optional(),\n customerId: z.string().optional(),\n customerLastName: z.string().optional(),\n language: z.string().optional(),\n /** Buyer-facing order name (e.g. `#1001`) for the server-composed \"Order \u2026 Confirmed\" chrome line. */\n orderName: z.string().optional(),\n placement: z.enum(['order_status', 'thank_you_page']),\n /** Privacy Policy footer href \u2014 the Monetize widget's `privacy_policy_url` setting (React parity). */\n privacyPolicyUrl: z.string().optional(),\n /** 30-min rolling session id (React parity); used for the ads `session_id`, else the visitor id. */\n sessionId: z.string().optional(),\n shop: z.string(),\n /** Editor/QA indicator; OR-ed into the ads-engine `testing` flag so it stays out of billing/reporting. */\n testing: z.boolean().optional(),\n timezone: z.string().optional(),\n /** Decorated (numeric) order id \u2192 the ads `transaction_id`. */\n transactionId: z.string().optional(),\n /** Rich per-line ads items; capped at 50 server-side (engine contract). Preferred over `cart.items`. */\n transactionItems: z.array(MonetizeTransactionItemSchema).optional(),\n /** Order total in presentment cents (React prefers total over subtotal); else `cart.subtotal`. */\n transactionTotal: z.number().optional(),\n visitorId: z.string().optional(),\n zipCode: z.string().optional(),\n});\n\n/** A generic analytics event from the extension; the server maps `name` \u2192 the engine's noun/verb/subject. */\nexport const AnalyticsEventInputSchema = z.object({\n name: z.string(),\n properties: z.record(z.string(), z.unknown()).optional(),\n sentAt: z.string().optional(),\n});\n\n/** Input for `postAnalyticsEvents`: a batch of events plus the request-scoped identity fields. */\nexport const AnalyticsInputSchema = z.object({\n /** Rebuy cart token (the `r_cart_token` cart attribute), when available \u2014 primary aggregation key. */\n cartToken: z.string().optional(),\n /** Shopify checkout token, when available \u2014 drives cart/checkout aggregation downstream. */\n checkoutToken: z.string().optional(),\n events: z.array(AnalyticsEventInputSchema),\n shop: z.string(),\n visitorId: z.string(),\n /** The widget id (smartBlockId) the events belong to. */\n widgetId: z.string().optional(),\n});\n\nexport type AnalyticsEventInput = z.infer<typeof AnalyticsEventInputSchema>;\nexport type AnalyticsInput = z.infer<typeof AnalyticsInputSchema>;\nexport type CartInput = z.infer<typeof CartInputSchema>;\nexport type CartLineInput = z.infer<typeof CartLineInputSchema>;\nexport type DataSourceInput = z.infer<typeof DataSourceInputSchema>;\nexport type GiftInput = z.infer<typeof GiftInputSchema>;\nexport type GiftValidationInput = z.infer<typeof GiftValidationInputSchema>;\nexport type MonetizeInput = z.infer<typeof MonetizeInputSchema>;\nexport type MonetizeTransactionItem = z.infer<typeof MonetizeTransactionItemSchema>;\nexport type UserConfigInput = z.infer<typeof UserConfigInputSchema>;\nexport type Wid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SAASA,IAAE,QAAQ,EAAE,SAAS;AAAA,EAC9B,UAAUA,IAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAE9B,eAAeA,IAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAEnC,kBAAkBA,IAAE,MAAM,6BAA6B,EAAE,SAAS;AAAA;AAAA,EAElE,kBAAkBA,IAAE,OAAO,EAAE,SAAS;AAAA,EACtC,WAAWA,IAAE,OAAO,EAAE,SAAS;AAAA,EAC/B,SAASA,IAAE,OAAO,EAAE,SAAS;AACjC,CAAC;AAGM,IAAM,4BAA4BA,IAAE,OAAO;AAAA,EAC9C,MAAMA,IAAE,OAAO;AAAA,EACf,YAAYA,IAAE,OAAOA,IAAE,OAAO,GAAGA,IAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACvD,QAAQA,IAAE,OAAO,EAAE,SAAS;AAChC,CAAC;AAGM,IAAM,uBAAuBA,IAAE,OAAO;AAAA;AAAA,EAEzC,WAAWA,IAAE,OAAO,EAAE,SAAS;AAAA;AAAA,EAE/B,eAAeA,IAAE,OAAO,EAAE,SAAS;AAAA,EACnC,QAAQA,IAAE,MAAM,yBAAyB;AAAA,EACzC,MAAMA,IAAE,OAAO;AAAA,EACf,WAAWA,IAAE,OAAO;AAAA;AAAA,EAEpB,UAAUA,IAAE,OAAO,EAAE,SAAS;AAClC,CAAC;",
|
|
6
6
|
"names": ["z", "z", "z", "z", "z", "z", "uuidv7", "z", "z", "z", "z", "z", "z", "z", "uuidv7", "z", "isString", "uuidv7", "z", "text", "z", "uuidv7", "isString", "z", "uuidv7", "z", "z", "uuidv7", "z", "z", "uuidv7", "uuidv7", "z", "uuidv7", "z", "z", "uuidv7", "z", "uuidv7", "z", "z", "z", "z", "uuidv7", "z", "z", "uuidv7", "uuidv7", "z", "z", "uuidv7", "z", "z", "uuidv7", "z", "z", "uuidv7", "uuidv7", "z", "z", "uuidv7", "uuidv7", "z", "z", "uuidv7", "z", "z", "uuidv7", "text", "text", "z", "z", "ARRAY_INDEX_STRING", "isPlainObject", "isPlainObject", "DYNAMIC_TOKEN_REGEX", "HTML_COMMENT_RE", "text", "HTML_TAG_RE", "text", "BUTTON_KINDS", "LOCATION_TO_EDITOR_MODE", "LOCATION_TO_EDITOR_MODE", "LOCATION_TO_EDITOR_MODE", "DEFAULT_REMAINING", "DEFAULT_REACHED", "label", "obj", "uuidv7", "uuidv7", "unwrapData", "z", "z", "text", "z"]
|
|
7
7
|
}
|