bitsnap-react 1.9.0 → 1.10.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/README.md +38 -6
- package/dist/CartProvider-HXLGQ4EX.mjs +2 -0
- package/dist/CartProvider-OHHYOMSG.js +2 -0
- package/dist/CartProvider-OHHYOMSG.js.map +1 -0
- package/dist/analytics.d.mts +22 -5
- package/dist/analytics.d.ts +22 -5
- package/dist/analytics.js +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/analytics.mjs +1 -1
- package/dist/catalog.d.mts +1 -1
- package/dist/catalog.d.ts +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/{chunk-VM6JEJFZ.js → chunk-3Z6VNXBP.js} +2 -2
- package/dist/chunk-3Z6VNXBP.js.map +1 -0
- package/dist/{chunk-RA452LXZ.mjs → chunk-43IIYJ6J.mjs} +2 -2
- package/dist/{chunk-SLLBTQTW.mjs → chunk-6D3OORMK.mjs} +2 -2
- package/dist/chunk-ADYVTMGH.mjs +2 -0
- package/dist/chunk-ADYVTMGH.mjs.map +1 -0
- package/dist/{chunk-FHDFLSPW.js → chunk-AJNULBC3.js} +2 -2
- package/dist/chunk-AJNULBC3.js.map +1 -0
- package/dist/chunk-B32ACCW2.js +2 -0
- package/dist/chunk-B32ACCW2.js.map +1 -0
- package/dist/{chunk-SZ256RCC.mjs → chunk-DDY7IBMG.mjs} +2 -2
- package/dist/{chunk-KG6RU37U.js → chunk-DPKT6ITB.js} +3 -3
- package/dist/chunk-DPKT6ITB.js.map +1 -0
- package/dist/{chunk-VXB7LA4E.js → chunk-F46RJVWC.js} +2 -2
- package/dist/chunk-F46RJVWC.js.map +1 -0
- package/dist/{chunk-3IMJALBX.js → chunk-F6GQLKA6.js} +2 -2
- package/dist/chunk-F6GQLKA6.js.map +1 -0
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/{chunk-LZE2E4TE.mjs → chunk-JXCHRSPW.mjs} +3 -3
- package/dist/{chunk-LZE2E4TE.mjs.map → chunk-JXCHRSPW.mjs.map} +1 -1
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/chunk-RLEC25JI.mjs +2 -0
- package/dist/chunk-RLEC25JI.mjs.map +1 -0
- package/dist/{chunk-V4U2PTKN.js → chunk-RVILRUW3.js} +2 -2
- package/dist/chunk-RVILRUW3.js.map +1 -0
- package/dist/{chunk-HKVMSMDF.mjs → chunk-T2OUOO4X.mjs} +2 -2
- package/dist/{chunk-CO2P4FR5.js → chunk-VIII45AC.js} +2 -2
- package/dist/chunk-VIII45AC.js.map +1 -0
- package/dist/chunk-XIHGWNTS.js +2 -0
- package/dist/chunk-XIHGWNTS.js.map +1 -0
- package/dist/{chunk-LJWS6ZRJ.mjs → chunk-YXFJG4MF.mjs} +2 -2
- package/dist/{chunk-GN63ITLA.mjs → chunk-ZPTHK4OX.mjs} +2 -2
- package/dist/consent.d.mts +7 -0
- package/dist/consent.d.ts +7 -0
- package/dist/consent.js +4 -4
- package/dist/consent.js.map +1 -1
- package/dist/consent.mjs +4 -4
- package/dist/consent.mjs.map +1 -1
- package/dist/course.d.mts +2 -2
- package/dist/course.d.ts +2 -2
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/course.mjs.map +1 -1
- package/dist/embed/analytics.js +1 -1
- package/dist/embed/consent.js +2 -2
- package/dist/errors.js.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/{instrument-C_abZLHk.d.ts → instrument-CmxK7S4T.d.mts} +22 -5
- package/dist/{instrument-C_abZLHk.d.mts → instrument-CmxK7S4T.d.ts} +22 -5
- package/dist/internal.js.map +1 -1
- package/dist/methods-A5KGZBAM.js +2 -0
- package/dist/methods-A5KGZBAM.js.map +1 -0
- package/dist/methods-AOHKV7IN.mjs +2 -0
- package/dist/models.js.map +1 -1
- package/dist/returns.d.mts +1 -1
- package/dist/returns.d.ts +1 -1
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/dist/{types-D_WnqwR_.d.mts → types-BnVWLcoB.d.mts} +1 -1
- package/dist/{types-BaqLJYuq.d.ts → types-i-IuN4Im.d.ts} +1 -1
- package/package.json +2 -2
- package/dist/CartProvider-XWTLBIZ5.js +0 -2
- package/dist/CartProvider-XWTLBIZ5.js.map +0 -1
- package/dist/CartProvider-ZURLJNBW.mjs +0 -2
- package/dist/chunk-3IMJALBX.js.map +0 -1
- package/dist/chunk-3UHPJ6NK.js +0 -2
- package/dist/chunk-3UHPJ6NK.js.map +0 -1
- package/dist/chunk-CO2P4FR5.js.map +0 -1
- package/dist/chunk-E6QVQEGZ.mjs +0 -2
- package/dist/chunk-E6QVQEGZ.mjs.map +0 -1
- package/dist/chunk-FHDFLSPW.js.map +0 -1
- package/dist/chunk-KG6RU37U.js.map +0 -1
- package/dist/chunk-QZJGNLCZ.js +0 -2
- package/dist/chunk-QZJGNLCZ.js.map +0 -1
- package/dist/chunk-V4U2PTKN.js.map +0 -1
- package/dist/chunk-VM6JEJFZ.js.map +0 -1
- package/dist/chunk-VXB7LA4E.js.map +0 -1
- package/dist/chunk-XVQKEGPO.mjs +0 -2
- package/dist/chunk-XVQKEGPO.mjs.map +0 -1
- package/dist/methods-CYARZTYL.mjs +0 -2
- package/dist/methods-DAPEWVI6.js +0 -2
- package/dist/methods-DAPEWVI6.js.map +0 -1
- /package/dist/{CartProvider-ZURLJNBW.mjs.map → CartProvider-HXLGQ4EX.mjs.map} +0 -0
- /package/dist/{chunk-RA452LXZ.mjs.map → chunk-43IIYJ6J.mjs.map} +0 -0
- /package/dist/{chunk-SLLBTQTW.mjs.map → chunk-6D3OORMK.mjs.map} +0 -0
- /package/dist/{chunk-SZ256RCC.mjs.map → chunk-DDY7IBMG.mjs.map} +0 -0
- /package/dist/{chunk-HKVMSMDF.mjs.map → chunk-T2OUOO4X.mjs.map} +0 -0
- /package/dist/{chunk-LJWS6ZRJ.mjs.map → chunk-YXFJG4MF.mjs.map} +0 -0
- /package/dist/{chunk-GN63ITLA.mjs.map → chunk-ZPTHK4OX.mjs.map} +0 -0
- /package/dist/{methods-CYARZTYL.mjs.map → methods-AOHKV7IN.mjs.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/visitor-cookie/dist/chunk-RVILRUW3.js","../src/components/returns/appearance.ts","../src/components/returns/appearance.context.tsx","../src/components/returns/legacy.ts","../src/components/returns/texts.ts","../src/components/returns/texts.context.tsx","../src/components/returns/ReturnsProvider.tsx","../src/components/returns/session-storage.ts"],"names":["RETURNS_SLOT_NAMES","RETURNS_TOKEN_VARIABLES","RETURNS_THEME_PRESETS","RETURNS_SHADCN_VARIABLES","resolveReturnsAppearance","appearance","resolved","resolveAppearanceCore","getReturnsSlotAppearance","slot","getSlotAppearance","ReturnsAppearanceContext","createContext","ReturnsAppearanceProvider","children","useMemo","jsx","useReturnsAppearance","useContext","useReturnsSlot","resolveReturnsEnvironment","environment","LEGACY_TEXT_KEYS","mapLegacyTexts","texts","result","legacyKey","targets","value","target","key","resolveBrandAppearance","theme","color","brandColorTokens","resolvePagedArguments","first","pageToken","RETURNS_TEXT_TABLES","resolveReturnsTexts","locale","overrides","resolveTexts","fillText","template","values","match","name","STATUS_TEXT_KEYS","REFUND_STATUS_TEXT_KEYS","statusTextKey","status","refundStatusTextKey","ReturnsTextsContext","ReturnsTextsProvider","activeLocale","getLocale","useReturnsText","useCallback","useReturnsLocale","KEY_PREFIX","sessionStorageKey","projectID"],"mappings":"AAAA,y/BAAgD,sDAAuG,sDAAwD,sDAAyD,ICiE3PA,EAAAA,CAAqB,CAEhC,MAAA,CACA,QAAA,CACA,OAAA,CACA,aAAA,CACA,YAAA,CACA,eAAA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,CAAAA,CAAAA,CAGJ,CACV,GAAM,CAAE,KAAA,CAAAjC,CAAM,CAAA,CAAIN,+BAAAA,EAA8B,CAAA,CAEhD,OAAOwC,gCAAAA,CACJ5B,CAAAA,CAAKe,CAAAA,CAAAA,EACJA,CAAAA,EAAU,IAAA,CAAOrB,CAAAA,CAAMM,CAAG,CAAA,CAAIa,EAAAA,CAASnB,CAAAA,CAAMM,CAAG,CAAA,CAAGe,CAAM,CAAA,CAC3D,CAACrB,CAAK,CACR,CACF,CAGO,SAASmC,CAAAA,CAAAA,CAA2B,CACzC,OAAOzC,+BAAAA,EAA8B,CAAA,CAAE,MACzC,CCtEA,8CAA6B,yDAItB,mDAMA,6CCVqC,IAetC0C,EAAAA,CAAa,0BAAA,CAGZ,SAASC,EAAAA,CAAkBC,CAAAA,CAA2B,CAC3D,MAAO,CAAA,EAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/visitor-cookie/dist/chunk-RVILRUW3.js","sourcesContent":[null,"import type { CSSProperties } from \"react\";\nimport {\n getSlotAppearance,\n resolveAppearanceCore,\n type AppearanceElements,\n type ShadcnVariableMapping,\n type SlotAppearance,\n} from \"@/src/lib/appearance-core\";\n\n/**\n * Returns appearance API.\n *\n * It mirrors `CheckoutAppearance` (theme, tokens, elements) so a shop can reuse\n * one brand object for both. The resolver is pure: it turns the caller input\n * into a theme name, the tokens in effect, the slot overrides and the inline\n * style for the theme boundary.\n */\n\nexport type ReturnsTheme = \"light\" | \"dark\";\n\nexport type ReturnsAppearanceTokens = {\n /** Font family of the returns views. The library never loads fonts. */\n fontFamily?: string;\n /** Base font size. */\n fontSize?: string;\n /** Page background. */\n background?: string;\n /** Raised surfaces: cards, skeletons, summaries. */\n surface?: string;\n /** Main text color. */\n foreground?: string;\n /** Secondary text: descriptions, dates, hints. */\n mutedForeground?: string;\n /** Borders of cards, inputs and separators. */\n border?: string;\n /** Primary button background. */\n buttonBackground?: string;\n /** Primary button text. */\n buttonForeground?: string;\n /** Primary button background on hover. */\n buttonHoverBackground?: string;\n /** Hover surface of secondary buttons and selectable cards. */\n hoverSurface?: string;\n /** Focus ring color. Also applied to shared UI primitives through `--ring`. */\n focusRing?: string;\n /** Error color. */\n error?: string;\n /** Success color: result screen, completed and refunded statuses. */\n success?: string;\n /** Warning color: statuses that need attention. */\n warning?: string;\n /** Status badge background. */\n badgeBackground?: string;\n /** Status badge text. */\n badgeForeground?: string;\n /** Background of text inputs and the note field. */\n inputBackground?: string;\n /** Corner radius, applied through `--radius`. */\n radius?: string;\n};\n\n/**\n * Stable slot names. They are exposed as `data-bitsnap-returns-slot`\n * attributes so they can also be targeted from plain CSS.\n */\nexport const RETURNS_SLOT_NAMES = [\n // Frame\n \"root\",\n \"header\",\n \"title\",\n \"description\",\n \"backButton\",\n \"stepIndicator\",\n \"error\",\n \"emptyState\",\n \"skeleton\",\n // Auth\n \"emailForm\",\n \"emailInput\",\n \"codeForm\",\n \"codeInput\",\n \"resendButton\",\n \"logoutButton\",\n // Orders\n \"orderList\",\n \"orderCard\",\n \"orderReference\",\n \"orderDate\",\n \"orderTotal\",\n \"pagination\",\n // Selection\n \"lineList\",\n \"line\",\n \"lineName\",\n \"linePrice\",\n \"lineQuantityControl\",\n \"quantityButton\",\n \"quantityInput\",\n \"lineIneligibleReason\",\n \"noteInput\",\n // Confirmation and result\n \"summary\",\n \"submitButton\",\n \"secondaryButton\",\n \"successState\",\n \"returnReference\",\n \"returnInstructions\",\n // My returns\n \"returnList\",\n \"returnCard\",\n \"statusBadge\",\n \"history\",\n \"historyEntry\",\n] as const;\n\nexport type ReturnsSlotName = (typeof RETURNS_SLOT_NAMES)[number];\n\nexport type ReturnsSlotAppearance = SlotAppearance;\n\nexport type ReturnsAppearanceElements = AppearanceElements<ReturnsSlotName>;\n\nexport type ReturnsAppearance = {\n /** `\"light\"` or `\"dark\"`. Omitted means `\"light\"`. */\n theme?: ReturnsTheme;\n /** Partial overrides applied over the theme preset. */\n tokens?: ReturnsAppearanceTokens;\n /** Per element `className`/`style` overrides. */\n elements?: ReturnsAppearanceElements;\n};\n\nexport type ResolvedReturnsAppearance = {\n theme: ReturnsTheme;\n /** Tokens that are in effect (the theme preset plus caller overrides). */\n tokens: ReturnsAppearanceTokens;\n elements: ReturnsAppearanceElements;\n /** Theme marker class for the theme boundary. */\n boundaryClassName: string;\n /** Inline custom properties applied to the returns root. */\n boundaryStyle: CSSProperties;\n};\n\n/** CSS custom property used for each token. */\nexport const RETURNS_TOKEN_VARIABLES = {\n fontFamily: \"--bitsnap-returns-font-family\",\n fontSize: \"--bitsnap-returns-font-size\",\n background: \"--bitsnap-returns-background\",\n surface: \"--bitsnap-returns-surface\",\n foreground: \"--bitsnap-returns-foreground\",\n mutedForeground: \"--bitsnap-returns-muted-foreground\",\n border: \"--bitsnap-returns-border\",\n buttonBackground: \"--bitsnap-returns-button-background\",\n buttonForeground: \"--bitsnap-returns-button-foreground\",\n buttonHoverBackground: \"--bitsnap-returns-button-hover-background\",\n hoverSurface: \"--bitsnap-returns-hover-surface\",\n focusRing: \"--bitsnap-returns-focus-ring\",\n error: \"--bitsnap-returns-error\",\n success: \"--bitsnap-returns-success\",\n warning: \"--bitsnap-returns-warning\",\n badgeBackground: \"--bitsnap-returns-badge-background\",\n badgeForeground: \"--bitsnap-returns-badge-foreground\",\n inputBackground: \"--bitsnap-returns-input-background\",\n radius: \"--bitsnap-returns-radius\",\n} as const;\n\nexport type ReturnsTokenName = keyof typeof RETURNS_TOKEN_VARIABLES;\n\n/**\n * Complete palettes. They carry colors and radius only, so typography is never\n * reset implicitly. `returns.css` falls back to the light values, which keeps\n * the views usable even when the boundary style is missing.\n */\nexport const RETURNS_THEME_PRESETS: Record<\n ReturnsTheme,\n ReturnsAppearanceTokens\n> = {\n light: {\n background: \"#ffffff\",\n surface: \"#f9fafb\",\n foreground: \"#18181b\",\n mutedForeground: \"#71717a\",\n border: \"#e4e4e7\",\n buttonBackground: \"#18181b\",\n buttonForeground: \"#fafafa\",\n buttonHoverBackground: \"#000000\",\n hoverSurface: \"#f4f4f5\",\n focusRing: \"#71717a\",\n error: \"#dc2626\",\n success: \"#16a34a\",\n warning: \"#d97706\",\n badgeBackground: \"#f4f4f5\",\n badgeForeground: \"#3f3f46\",\n inputBackground: \"#ffffff\",\n radius: \"8px\",\n },\n dark: {\n background: \"#18181b\",\n surface: \"#27272a\",\n foreground: \"#fafafa\",\n mutedForeground: \"#a1a1aa\",\n border: \"#3f3f46\",\n buttonBackground: \"#fafafa\",\n buttonForeground: \"#18181b\",\n buttonHoverBackground: \"#e4e4e7\",\n hoverSurface: \"#3f3f46\",\n focusRing: \"#a1a1aa\",\n error: \"#f87171\",\n success: \"#4ade80\",\n warning: \"#fbbf24\",\n badgeBackground: \"#3f3f46\",\n badgeForeground: \"#e4e4e7\",\n inputBackground: \"#27272a\",\n radius: \"8px\",\n },\n};\n\n/**\n * Shared UI primitives (`Button`, `Input`, `Label`, ...) read the shadcn theme\n * variables, so those follow the returns tokens inside the boundary.\n */\nconst RETURNS_SHADCN_VARIABLES: ShadcnVariableMapping<ReturnsTokenName> = [\n { token: \"background\", variable: \"--background\" },\n { token: \"foreground\", variable: \"--foreground\" },\n { token: \"surface\", variable: \"--card\" },\n { token: \"foreground\", variable: \"--card-foreground\" },\n { token: \"surface\", variable: \"--popover\" },\n { token: \"foreground\", variable: \"--popover-foreground\" },\n { token: \"buttonBackground\", variable: \"--primary\" },\n { token: \"buttonForeground\", variable: \"--primary-foreground\" },\n { token: \"surface\", variable: \"--secondary\" },\n { token: \"foreground\", variable: \"--secondary-foreground\" },\n { token: \"hoverSurface\", variable: \"--accent\" },\n { token: \"foreground\", variable: \"--accent-foreground\" },\n { token: \"mutedForeground\", variable: \"--muted-foreground\" },\n { token: \"border\", variable: \"--border\" },\n { token: \"border\", variable: \"--input\" },\n { token: \"focusRing\", variable: \"--ring\" },\n { token: \"error\", variable: \"--destructive\" },\n { token: \"radius\", variable: \"--radius\" },\n];\n\nexport function resolveReturnsAppearance(\n appearance?: ReturnsAppearance,\n): ResolvedReturnsAppearance {\n const resolved = resolveAppearanceCore<\n ReturnsTokenName,\n ReturnsTheme,\n ReturnsSlotName\n >(appearance, {\n defaultTheme: \"light\",\n presets: RETURNS_THEME_PRESETS,\n variables: RETURNS_TOKEN_VARIABLES,\n shadcnVariables: RETURNS_SHADCN_VARIABLES,\n });\n\n return {\n theme: resolved.theme,\n tokens: resolved.tokens,\n elements: resolved.elements,\n boundaryClassName: resolved.theme,\n boundaryStyle: resolved.boundaryStyle,\n };\n}\n\n/** Caller overrides for a single slot, if any were provided. */\nexport function getReturnsSlotAppearance(\n resolved: ResolvedReturnsAppearance,\n slot: ReturnsSlotName,\n): ReturnsSlotAppearance | undefined {\n return getSlotAppearance(resolved.elements, slot);\n}\n","import { createContext, useContext, useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n getReturnsSlotAppearance,\n resolveReturnsAppearance,\n type ResolvedReturnsAppearance,\n type ReturnsAppearance,\n type ReturnsSlotAppearance,\n type ReturnsSlotName,\n} from \"./appearance\";\n\nconst ReturnsAppearanceContext = createContext<ResolvedReturnsAppearance>(\n resolveReturnsAppearance(),\n);\n\n/**\n * Returns scoped appearance provider. It only wraps the returns views, so the\n * configuration never leaks into checkout, the panel or the host page.\n */\nexport function ReturnsAppearanceProvider({\n appearance,\n children,\n}: {\n appearance?: ReturnsAppearance;\n children: ReactNode;\n}) {\n const resolved = useMemo(\n () => resolveReturnsAppearance(appearance),\n [appearance],\n );\n\n return (\n <ReturnsAppearanceContext.Provider value={resolved}>\n {children}\n </ReturnsAppearanceContext.Provider>\n );\n}\n\nexport function useReturnsAppearance(): ResolvedReturnsAppearance {\n return useContext(ReturnsAppearanceContext);\n}\n\n/**\n * Returns the caller overrides for a slot, meant to be merged with the\n * built-in presentation:\n *\n * ```tsx\n * const slot = useReturnsSlot(\"title\");\n *\n * return <h2 className={cn(\"text-xl font-semibold\", slot.className)} style={slot.style} />;\n * ```\n */\nexport function useReturnsSlot(slot: ReturnsSlotName): ReturnsSlotAppearance {\n const resolved = useReturnsAppearance();\n\n return getReturnsSlotAppearance(resolved, slot) ?? {};\n}\n","import { Environment } from \"@/src/gen/proto/common/v1/environment_pb\";\nimport type { ReturnsAppearance } from \"./appearance\";\nimport { brandColorTokens } from \"./color\";\nimport type { ReturnsTexts } from \"./texts\";\n\n/**\n * Compatibility layer for the `bitsnap-react` 1.6.0 returns widget. Everything\n * here is pure; the components and hooks apply it at their boundary.\n */\n\n/** Environment as a string or as the proto enum used by 1.6.0. */\nexport type ReturnsEnvironmentInput = \"production\" | \"test\" | Environment;\n\n/** Text keys of the 1.6.0 widget. */\nexport type LegacyReturnsTexts = Partial<{\n title: string;\n email: string;\n sendCode: string;\n code: string;\n verify: string;\n orders: string;\n submit: string;\n note: string;\n loading: string;\n history: string;\n}>;\n\n/** Our text keys plus the 1.6.0 ones. Our keys win when both are given. */\nexport type ReturnsTextsInput = Partial<ReturnsTexts> & LegacyReturnsTexts;\n\n/** 1.6.0 `theme` prop. */\nexport type LegacyReturnsTheme = { brandColor?: string };\n\n/** Backend environment for a string or enum value. Defaults to production. */\nexport function resolveReturnsEnvironment(\n environment?: ReturnsEnvironmentInput,\n): Environment {\n return environment === \"test\" || environment === Environment.TEST\n ? Environment.TEST\n : Environment.PRODUCTION;\n}\n\nconst LEGACY_TEXT_KEYS: Record<\n Exclude<keyof LegacyReturnsTexts, \"loading\">,\n readonly (keyof ReturnsTexts)[]\n> = {\n title: [\"emailStepTitle\"],\n email: [\"emailLabel\"],\n sendCode: [\"emailSubmit\"],\n code: [\"codeLabel\"],\n verify: [\"codeSubmit\"],\n orders: [\"ordersTitle\"],\n submit: [\"confirmationSubmit\"],\n note: [\"noteLabel\"],\n history: [\"myReturnsTitle\", \"myReturnsLink\"],\n};\n\n/**\n * Maps 1.6.0 text keys onto ours. A key of the new API always wins over the\n * legacy key that maps to it. `loading` has the same name in both.\n */\nexport function mapLegacyTexts(\n texts: ReturnsTextsInput | undefined,\n): Partial<ReturnsTexts> | undefined {\n if (texts == null) {\n return undefined;\n }\n\n const result: Partial<ReturnsTexts> = {};\n for (const [legacyKey, targets] of Object.entries(LEGACY_TEXT_KEYS) as [\n keyof typeof LEGACY_TEXT_KEYS,\n readonly (keyof ReturnsTexts)[],\n ][]) {\n const value = texts[legacyKey];\n if (typeof value === \"string\") {\n for (const target of targets) {\n result[target] = value;\n }\n }\n }\n\n for (const key of Object.keys(texts) as (keyof ReturnsTextsInput)[]) {\n if (key in LEGACY_TEXT_KEYS) {\n continue;\n }\n const value = texts[key];\n if (typeof value === \"string\") {\n result[key as keyof ReturnsTexts] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Appearance with the 1.6.0 `brandColor` applied as button background, focus\n * ring and readable button foreground. Explicit `appearance.tokens` win.\n */\nexport function resolveBrandAppearance(\n appearance: ReturnsAppearance | undefined,\n theme: LegacyReturnsTheme | undefined,\n): ReturnsAppearance | undefined {\n const color = theme?.brandColor?.trim();\n if (color == null || color === \"\") {\n return appearance;\n }\n return {\n ...appearance,\n tokens: { ...brandColorTokens(color), ...appearance?.tokens },\n };\n}\n\n/** Arguments of the paged hooks in either call style. */\nexport type PagedArguments = {\n pageSize: number;\n /** Explicit page token of the positional (1.6.0) form. */\n explicitPageToken: string | undefined;\n};\n\n/**\n * Normalizes `(pageSize?, pageToken?)` (1.6.0) and `({ pageSize })` (ours).\n * Both forms default to 20 items, like 1.6.0.\n */\nexport function resolvePagedArguments(\n first: number | { pageSize?: number } | undefined,\n pageToken: string | undefined,\n): PagedArguments {\n if (typeof first === \"object\" && first != null) {\n return { pageSize: first.pageSize ?? 20, explicitPageToken: undefined };\n }\n if (typeof first === \"number\" || pageToken !== undefined) {\n return { pageSize: first ?? 20, explicitPageToken: pageToken ?? \"\" };\n }\n return { pageSize: 20, explicitPageToken: undefined };\n}\n","import { lookupText, resolveTexts, type LocaleTables } from \"@/src/lib/texts\";\n\n/**\n * Every string the returns views render. Pass a partial object through the\n * `texts` prop of `BitsnapReturns`/`ReturnsProvider` to override any of them,\n * whatever the locale. Strings with `{name}` placeholders keep them in\n * overrides; unknown placeholders are left untouched.\n */\nexport type ReturnsTexts = {\n // Frame\n /** Label of the back buttons. */\n back: string;\n /** Step indicator, placeholders `{current}` and `{total}`. */\n stepIndicator: string;\n /** Skeleton accessible label. */\n loading: string;\n /** Button that opens the list of previous returns. */\n myReturnsLink: string;\n\n // Email step\n emailStepTitle: string;\n emailStepDescription: string;\n emailLabel: string;\n emailPlaceholder: string;\n emailSubmit: string;\n\n // Code step\n codeStepTitle: string;\n /** Placeholder `{email}`. */\n codeStepDescription: string;\n codeLabel: string;\n codeSubmit: string;\n resend: string;\n /** Placeholder `{seconds}`. */\n resendIn: string;\n logout: string;\n\n // Orders\n ordersTitle: string;\n ordersDescription: string;\n ordersEmpty: string;\n /** Placeholder `{reference}`. */\n orderTitle: string;\n /** Placeholder `{count}`. */\n orderReturnableLines: string;\n orderSelect: string;\n paginationPrevious: string;\n paginationNext: string;\n /** Placeholders `{page}` and `{total}` (number of orders). */\n paginationInfo: string;\n\n // Order detail\n /** Placeholder `{reference}`. */\n orderDetailTitle: string;\n orderDetailDescription: string;\n /** Placeholder `{name}`. */\n quantityLabel: string;\n /** Placeholder `{name}`. */\n quantityDecrease: string;\n /** Placeholder `{name}`. */\n quantityIncrease: string;\n /** Placeholder `{available}`. */\n quantityOfAvailable: string;\n /** Shown for an ineligible line without a reason from the backend. */\n lineIneligibleFallback: string;\n noteLabel: string;\n notePlaceholder: string;\n selectionContinue: string;\n selectionEmpty: string;\n previousReturnsTitle: string;\n\n // Confirmation\n confirmationTitle: string;\n confirmationDescription: string;\n confirmationSummary: string;\n /** Placeholder `{quantity}`. */\n confirmationQuantity: string;\n confirmationNote: string;\n confirmationSubmit: string;\n\n // Result\n successTitle: string;\n successDescription: string;\n successReference: string;\n successInstructions: string;\n successDone: string;\n\n // My returns\n myReturnsTitle: string;\n myReturnsDescription: string;\n myReturnsEmpty: string;\n myReturnOpen: string;\n myReturnDetailTitle: string;\n /** Placeholder `{reference}`. */\n myReturnTitle: string;\n myReturnCreatedAt: string;\n myReturnRefund: string;\n myReturnLines: string;\n /** Placeholders `{requested}`, `{approved}`, `{received}`. */\n myReturnLineQuantities: string;\n myReturnNote: string;\n myReturnHistory: string;\n\n // Request status labels\n statusSubmitted: string;\n statusApproved: string;\n statusRejected: string;\n statusAwaitingReceipt: string;\n statusReceived: string;\n statusCompleted: string;\n statusCancelled: string;\n statusRefunded: string;\n /** Any status the backend adds later. */\n statusFallback: string;\n\n // Refund status labels\n refundStatusNotStarted: string;\n refundStatusPending: string;\n refundStatusSucceeded: string;\n refundStatusFailed: string;\n refundStatusFallback: string;\n\n // Error messages\n errorGeneric: string;\n errorInvalidEmail: string;\n errorInvalidCode: string;\n errorSessionExpired: string;\n errorOrderNotFound: string;\n errorReturnNotFound: string;\n errorQuantityUnavailable: string;\n errorItemNotReturnable: string;\n errorReturnsDisabled: string;\n errorRateLimited: string;\n errorIdempotencyConflict: string;\n errorDeliveryFailed: string;\n errorRetry: string;\n};\n\nexport type ReturnsTextKey = keyof ReturnsTexts;\n\nexport const RETURNS_TEXT_TABLES: LocaleTables<ReturnsTextKey> = {\n en: {\n back: \"Back\",\n stepIndicator: \"Step {current} of {total}\",\n loading: \"Loading\",\n myReturnsLink: \"My returns\",\n\n emailStepTitle: \"Return a product\",\n emailStepDescription:\n \"Enter the email address you used for the order. We will send you a verification code.\",\n emailLabel: \"Email address\",\n emailPlaceholder: \"name@example.com\",\n emailSubmit: \"Send code\",\n\n codeStepTitle: \"Enter the code\",\n codeStepDescription: \"We sent a verification code to {email}.\",\n codeLabel: \"Verification code\",\n codeSubmit: \"Verify\",\n resend: \"Send the code again\",\n resendIn: \"Send again in {seconds} s\",\n logout: \"Sign out\",\n\n ordersTitle: \"Your orders\",\n ordersDescription: \"Choose the order that contains the product to return.\",\n ordersEmpty: \"There are no orders eligible for return.\",\n orderTitle: \"Order {reference}\",\n orderReturnableLines: \"Products available to return: {count}\",\n orderSelect: \"Choose\",\n paginationPrevious: \"Previous\",\n paginationNext: \"Next\",\n paginationInfo: \"Page {page}, {total} orders\",\n\n orderDetailTitle: \"Order {reference}\",\n orderDetailDescription: \"Select the products and quantities to return.\",\n quantityLabel: \"Quantity to return: {name}\",\n quantityDecrease: \"Decrease quantity: {name}\",\n quantityIncrease: \"Increase quantity: {name}\",\n quantityOfAvailable: \"of {available}\",\n lineIneligibleFallback: \"This product cannot be returned.\",\n noteLabel: \"Note (optional)\",\n notePlaceholder: \"Tell us why you are returning the product\",\n selectionContinue: \"Continue\",\n selectionEmpty: \"Select at least one item to return.\",\n previousReturnsTitle: \"Earlier returns for this order\",\n\n confirmationTitle: \"Confirm the return\",\n confirmationDescription: \"Check the products before you submit the request.\",\n confirmationSummary: \"Products to return\",\n confirmationQuantity: \"Quantity: {quantity}\",\n confirmationNote: \"Your note\",\n confirmationSubmit: \"Submit return request\",\n\n successTitle: \"Return request submitted\",\n successDescription: \"We received your request and will keep you posted.\",\n successReference: \"Request number\",\n successInstructions: \"What to do next\",\n successDone: \"Back to orders\",\n\n myReturnsTitle: \"My returns\",\n myReturnsDescription: \"Track the status of your return requests.\",\n myReturnsEmpty: \"You have not submitted any return requests yet.\",\n myReturnOpen: \"Details\",\n myReturnDetailTitle: \"Return details\",\n myReturnTitle: \"Return {reference}\",\n myReturnCreatedAt: \"Submitted\",\n myReturnRefund: \"Refund\",\n myReturnLines: \"Products\",\n myReturnLineQuantities:\n \"Requested: {requested}, approved: {approved}, received: {received}\",\n myReturnNote: \"Your note\",\n myReturnHistory: \"History\",\n\n statusSubmitted: \"Submitted\",\n statusApproved: \"Approved\",\n statusRejected: \"Rejected\",\n statusAwaitingReceipt: \"Awaiting the package\",\n statusReceived: \"Package received\",\n statusCompleted: \"Completed\",\n statusCancelled: \"Cancelled\",\n statusRefunded: \"Refunded\",\n statusFallback: \"In progress\",\n\n refundStatusNotStarted: \"Not started\",\n refundStatusPending: \"Refund in progress\",\n refundStatusSucceeded: \"Refunded\",\n refundStatusFailed: \"Refund failed\",\n refundStatusFallback: \"Unknown\",\n\n errorGeneric: \"Something went wrong. Please try again.\",\n errorInvalidEmail: \"Enter a valid email address.\",\n errorInvalidCode: \"The code is invalid or has expired.\",\n errorSessionExpired: \"Your session has expired. Verify your email again.\",\n errorOrderNotFound: \"We could not find this order.\",\n errorReturnNotFound: \"We could not find this return request.\",\n errorQuantityUnavailable:\n \"The selected quantity is no longer available for return.\",\n errorItemNotReturnable: \"One of the selected products cannot be returned.\",\n errorReturnsDisabled: \"Returns are not available in this shop.\",\n errorRateLimited: \"Too many attempts. Please try again later.\",\n errorIdempotencyConflict:\n \"This request was already submitted with different contents. Reload and try again.\",\n errorDeliveryFailed: \"We could not send the code. Please try again.\",\n errorRetry: \"Try again\",\n },\n pl: {\n back: \"Wstecz\",\n stepIndicator: \"Krok {current} z {total}\",\n loading: \"Ładowanie\",\n myReturnsLink: \"Moje zwroty\",\n\n emailStepTitle: \"Zwróć produkt\",\n emailStepDescription:\n \"Podaj adres e-mail użyty w zamówieniu. Wyślemy na niego kod weryfikacyjny.\",\n emailLabel: \"Adres e-mail\",\n emailPlaceholder: \"jan@example.com\",\n emailSubmit: \"Wyślij kod\",\n\n codeStepTitle: \"Wpisz kod\",\n codeStepDescription: \"Wysłaliśmy kod weryfikacyjny na adres {email}.\",\n codeLabel: \"Kod weryfikacyjny\",\n codeSubmit: \"Zweryfikuj\",\n resend: \"Wyślij kod ponownie\",\n resendIn: \"Wyślij ponownie za {seconds} s\",\n logout: \"Wyloguj się\",\n\n ordersTitle: \"Twoje zamówienia\",\n ordersDescription: \"Wybierz zamówienie z produktem do zwrotu.\",\n ordersEmpty: \"Brak zamówień, które można zwrócić.\",\n orderTitle: \"Zamówienie {reference}\",\n orderReturnableLines: \"Produkty do zwrotu: {count}\",\n orderSelect: \"Wybierz\",\n paginationPrevious: \"Poprzednia\",\n paginationNext: \"Następna\",\n paginationInfo: \"Strona {page}, zamówień: {total}\",\n\n orderDetailTitle: \"Zamówienie {reference}\",\n orderDetailDescription: \"Wybierz produkty i ilości do zwrotu.\",\n quantityLabel: \"Ilość do zwrotu: {name}\",\n quantityDecrease: \"Zmniejsz ilość: {name}\",\n quantityIncrease: \"Zwiększ ilość: {name}\",\n quantityOfAvailable: \"z {available}\",\n lineIneligibleFallback: \"Ten produkt nie podlega zwrotowi.\",\n noteLabel: \"Uwagi (opcjonalnie)\",\n notePlaceholder: \"Napisz, dlaczego zwracasz produkt\",\n selectionContinue: \"Dalej\",\n selectionEmpty: \"Wybierz co najmniej jedną sztukę do zwrotu.\",\n previousReturnsTitle: \"Wcześniejsze zwroty tego zamówienia\",\n\n confirmationTitle: \"Potwierdź zwrot\",\n confirmationDescription: \"Sprawdź produkty przed wysłaniem zgłoszenia.\",\n confirmationSummary: \"Produkty do zwrotu\",\n confirmationQuantity: \"Ilość: {quantity}\",\n confirmationNote: \"Twoje uwagi\",\n confirmationSubmit: \"Wyślij zgłoszenie zwrotu\",\n\n successTitle: \"Zgłoszenie zwrotu zostało wysłane\",\n successDescription: \"Otrzymaliśmy zgłoszenie i będziemy informować o jego statusie.\",\n successReference: \"Numer zgłoszenia\",\n successInstructions: \"Co dalej\",\n successDone: \"Wróć do zamówień\",\n\n myReturnsTitle: \"Moje zwroty\",\n myReturnsDescription: \"Sprawdź status swoich zgłoszeń zwrotu.\",\n myReturnsEmpty: \"Nie masz jeszcze żadnych zgłoszeń zwrotu.\",\n myReturnOpen: \"Szczegóły\",\n myReturnDetailTitle: \"Szczegóły zwrotu\",\n myReturnTitle: \"Zwrot {reference}\",\n myReturnCreatedAt: \"Zgłoszono\",\n myReturnRefund: \"Zwrot środków\",\n myReturnLines: \"Produkty\",\n myReturnLineQuantities:\n \"Zgłoszono: {requested}, zaakceptowano: {approved}, odebrano: {received}\",\n myReturnNote: \"Twoje uwagi\",\n myReturnHistory: \"Historia\",\n\n statusSubmitted: \"Zgłoszony\",\n statusApproved: \"Zaakceptowany\",\n statusRejected: \"Odrzucony\",\n statusAwaitingReceipt: \"Oczekiwanie na paczkę\",\n statusReceived: \"Paczka odebrana\",\n statusCompleted: \"Zakończony\",\n statusCancelled: \"Anulowany\",\n statusRefunded: \"Środki zwrócone\",\n statusFallback: \"W trakcie\",\n\n refundStatusNotStarted: \"Nie rozpoczęto\",\n refundStatusPending: \"Zwrot środków w toku\",\n refundStatusSucceeded: \"Środki zwrócone\",\n refundStatusFailed: \"Zwrot środków nie powiódł się\",\n refundStatusFallback: \"Nieznany\",\n\n errorGeneric: \"Coś poszło nie tak. Spróbuj ponownie.\",\n errorInvalidEmail: \"Podaj poprawny adres e-mail.\",\n errorInvalidCode: \"Kod jest nieprawidłowy lub wygasł.\",\n errorSessionExpired: \"Sesja wygasła. Zweryfikuj adres e-mail ponownie.\",\n errorOrderNotFound: \"Nie znaleziono tego zamówienia.\",\n errorReturnNotFound: \"Nie znaleziono tego zgłoszenia zwrotu.\",\n errorQuantityUnavailable:\n \"Wybrana ilość nie jest już dostępna do zwrotu.\",\n errorItemNotReturnable: \"Jeden z wybranych produktów nie podlega zwrotowi.\",\n errorReturnsDisabled: \"Zwroty nie są dostępne w tym sklepie.\",\n errorRateLimited: \"Zbyt wiele prób. Spróbuj ponownie później.\",\n errorIdempotencyConflict:\n \"To zgłoszenie zostało już wysłane z inną zawartością. Odśwież stronę i spróbuj ponownie.\",\n errorDeliveryFailed: \"Nie udało się wysłać kodu. Spróbuj ponownie.\",\n errorRetry: \"Spróbuj ponownie\",\n },\n};\n\n/** Default texts for a locale merged with the caller overrides. */\nexport function resolveReturnsTexts(\n locale: string,\n overrides?: Partial<ReturnsTexts>,\n): ReturnsTexts {\n return resolveTexts(RETURNS_TEXT_TABLES, locale, overrides);\n}\n\nexport function getReturnsText(\n key: ReturnsTextKey,\n locale: string,\n overrides?: Partial<ReturnsTexts>,\n): string {\n return lookupText(resolveReturnsTexts(locale, overrides), key);\n}\n\n/** Replaces `{name}` placeholders. Unknown placeholders stay as they are. */\nexport function fillText(\n template: string,\n values: Record<string, string | number>,\n): string {\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n Object.prototype.hasOwnProperty.call(values, name)\n ? String(values[name])\n : match,\n );\n}\n\nconst STATUS_TEXT_KEYS: Record<string, ReturnsTextKey> = {\n submitted: \"statusSubmitted\",\n approved: \"statusApproved\",\n rejected: \"statusRejected\",\n awaiting_receipt: \"statusAwaitingReceipt\",\n received: \"statusReceived\",\n completed: \"statusCompleted\",\n cancelled: \"statusCancelled\",\n refunded: \"statusRefunded\",\n};\n\nconst REFUND_STATUS_TEXT_KEYS: Record<string, ReturnsTextKey> = {\n not_started: \"refundStatusNotStarted\",\n pending: \"refundStatusPending\",\n succeeded: \"refundStatusSucceeded\",\n failed: \"refundStatusFailed\",\n};\n\n/** Text key for a backend request status, with a fallback for unknown ones. */\nexport function statusTextKey(status: string): ReturnsTextKey {\n return STATUS_TEXT_KEYS[status] ?? \"statusFallback\";\n}\n\n/** Text key for a backend refund status, with a fallback for unknown ones. */\nexport function refundStatusTextKey(status: string): ReturnsTextKey {\n return REFUND_STATUS_TEXT_KEYS[status] ?? \"refundStatusFallback\";\n}\n","import { createContext, useCallback, useContext, useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { getLocale } from \"@/src/components/checkout/locale\";\nimport {\n fillText,\n resolveReturnsTexts,\n type ReturnsTextKey,\n type ReturnsTexts,\n} from \"./texts\";\n\ntype ReturnsTextsContextValue = {\n /** Active locale (the `locale` prop or the library locale). */\n locale: string;\n texts: ReturnsTexts;\n};\n\nconst ReturnsTextsContext = createContext<ReturnsTextsContextValue>({\n locale: \"pl-PL\",\n texts: resolveReturnsTexts(\"pl-PL\"),\n});\n\n/**\n * Returns scoped texts provider. Carries the `texts` overrides and the\n * `locale` prop down to the returns tree.\n */\nexport function ReturnsTextsProvider({\n texts,\n locale,\n children,\n}: {\n texts?: Partial<ReturnsTexts>;\n locale?: string;\n children: ReactNode;\n}) {\n const activeLocale = locale ?? getLocale();\n const value = useMemo(\n () => ({\n locale: activeLocale,\n texts: resolveReturnsTexts(activeLocale, texts),\n }),\n [activeLocale, texts],\n );\n\n return (\n <ReturnsTextsContext.Provider value={value}>\n {children}\n </ReturnsTextsContext.Provider>\n );\n}\n\n/**\n * Returns a lookup for the returns strings: the caller override when provided,\n * otherwise the default for the locale. Optional `values` fill `{placeholders}`.\n */\nexport function useReturnsText(): (\n key: ReturnsTextKey,\n values?: Record<string, string | number>,\n) => string {\n const { texts } = useContext(ReturnsTextsContext);\n\n return useCallback(\n (key, values) =>\n values == null ? texts[key] : fillText(texts[key], values),\n [texts],\n );\n}\n\n/** Active locale of the returns views, for date and money formatting. */\nexport function useReturnsLocale(): string {\n return useContext(ReturnsTextsContext).locale;\n}\n","import { createClient } from \"@connectrpc/connect\";\nimport {\n createConnectQueryKey,\n TransportProvider,\n} from \"@connectrpc/connect-query\";\nimport {\n QueryClient,\n QueryClientContext,\n QueryClientProvider,\n useQueryClient,\n} from \"@tanstack/react-query\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { Environment } from \"@/src/gen/proto/common/v1/environment_pb\";\nimport { ReturnsService } from \"@/src/gen/proto/public/v1/returns_pb\";\nimport {\n InstrumentProvider,\n useInstrument,\n type AnalyticsOption,\n} from \"@/src/analytics/instrument\";\nimport { cn } from \"@/src/lib/utils\";\nimport { getRpcTransport, getTransportHost } from \"@/src/rpc-provider\";\nimport type { Transport } from \"@connectrpc/connect\";\nimport type { ReturnsAppearance } from \"./appearance\";\nimport {\n ReturnsAppearanceProvider,\n useReturnsAppearance,\n useReturnsSlot,\n} from \"./appearance.context\";\nimport {\n clearStoredSession,\n expiryToMillis,\n getBrowserSessionStorage,\n readStoredSession,\n writeStoredSession,\n type StoredReturnsSession,\n} from \"./session-storage\";\nimport {\n mapLegacyTexts,\n resolveBrandAppearance,\n resolveReturnsEnvironment,\n type LegacyReturnsTheme,\n type ReturnsEnvironmentInput,\n type ReturnsTextsInput,\n} from \"./legacy\";\nimport { ReturnsTextsProvider } from \"./texts.context\";\n\n/**\n * Backend environment the returns calls run against. The library has no other\n * environment switch for public API calls, so this defaults to `\"production\"`.\n */\nexport type ReturnsEnvironment = \"production\" | \"test\";\n\nexport type ReturnsSessionStatus =\n /** Server render and first client render: storage has not been read yet. */\n | \"hydrating\"\n /** A `panelAccessToken` is being exchanged for a returns session. */\n | \"exchanging\"\n | \"anonymous\"\n | \"authenticated\";\n\n/** A pending email verification. */\nexport type ReturnsChallenge = {\n challengeId: string;\n email: string;\n /** Unix milliseconds when the next code may be requested. */\n resendAvailableAt: number;\n};\n\nexport type ReturnsContextValue = {\n projectID: string;\n environment: Environment;\n status: ReturnsSessionStatus;\n /** Session token. Never log it. */\n token: string | undefined;\n /** Failure of the last panel token exchange, if any. */\n exchangeError: unknown;\n challenge: ReturnsChallenge | undefined;\n setChallenge: (challenge: ReturnsChallenge | undefined) => void;\n /** Stores a freshly issued session in state and `sessionStorage`. */\n authenticate: (session: StoredReturnsSession) => void;\n /** Drops the session, the pending challenge and cached customer data. */\n clearSession: () => void;\n};\n\nconst ReturnsContext = createContext<ReturnsContextValue | undefined>(\n undefined,\n);\n\n/**\n * Context of the nearest `ReturnsProvider`. Throws a clear error outside of\n * it, naming the component or hook that was misplaced.\n */\nexport function useReturnsContext(name: string): ReturnsContextValue {\n const value = useContext(ReturnsContext);\n\n if (value == null) {\n throw new Error(`${name} must be rendered inside <ReturnsProvider>`);\n }\n\n return value;\n}\n\nexport type ReturnsProviderProps = {\n /** Bitsnap project ID. */\n projectID: string;\n /**\n * API host. Defaults to the host set with `setCustomHost`/`setHost`, then to\n * `https://bitsnap.pl`. Each provider keeps its own transport.\n */\n host?: string;\n /**\n * Backend environment, `\"production\"` unless set to `\"test\"`. The proto\n * `Environment` enum is accepted too.\n */\n environment?: ReturnsEnvironmentInput;\n /** Theme, tokens and per-element overrides. */\n appearance?: ReturnsAppearance;\n /**\n * Text overrides, applied whatever the locale. The keys of `bitsnap-react`\n * 1.6.0 (`title`, `email`, `sendCode`, ...) are accepted too; our own keys\n * win when both are given.\n */\n texts?: ReturnsTextsInput;\n /** `bitsnap-react` 1.6.0 brand color. Explicit `appearance.tokens` win. */\n theme?: LegacyReturnsTheme;\n /** Locale of texts, dates and money. Defaults to the library locale. */\n locale?: string;\n /**\n * Customer panel access token. When set, it is exchanged for a returns\n * session on mount, so the customer needs no second verification code.\n * Changing or removing it drops the session.\n */\n panelAccessToken?: string;\n /** Class of the themed root element. */\n className?: string;\n /**\n * Usage statistics for your Bitsnap dashboard (return started, return\n * submitted). On by default; `false` turns it off. An object lets you\n * forward every event: `{ onEvent }`. Inside `<Panel>` the panel's setting\n * applies unless this is given. Nothing is stored on the visitor's device.\n */\n analytics?: AnalyticsOption;\n children?: ReactNode;\n};\n\n/** Key prefix that matches every returns query, for invalidation and removal. */\nexport function returnsQueryKey(): readonly unknown[] {\n return createConnectQueryKey({\n schema: ReturnsService,\n cardinality: undefined,\n });\n}\n\n/** Longest delay `setTimeout` accepts. */\nconst MAX_TIMEOUT_MS = 2 ** 31 - 1;\n\nfunction SessionProvider({\n projectID,\n environment,\n transport,\n panelAccessToken,\n className,\n children,\n}: {\n projectID: string;\n environment: Environment;\n transport: Transport;\n panelAccessToken?: string;\n className?: string;\n children?: ReactNode;\n}) {\n const queryClient = useQueryClient();\n const { boundaryClassName, boundaryStyle } = useReturnsAppearance();\n const root = useReturnsSlot(\"root\");\n\n const [session, setSession] = useState<{\n status: ReturnsSessionStatus;\n token?: string;\n expiresAt?: number;\n }>({ status: \"hydrating\" });\n const [exchangeError, setExchangeError] = useState<unknown>();\n const [challenge, setChallenge] = useState<ReturnsChallenge>();\n const previousPanelToken = useRef<string | undefined>(undefined);\n\n const dropCachedData = useCallback(() => {\n // Query inputs carry the session token, so cached customer data must not\n // outlive the session. Only returns queries are touched.\n queryClient.removeQueries({ queryKey: returnsQueryKey() });\n }, [queryClient]);\n\n const clearSession = useCallback(() => {\n clearStoredSession(getBrowserSessionStorage(), projectID);\n setChallenge(undefined);\n setSession({ status: \"anonymous\" });\n dropCachedData();\n }, [projectID, dropCachedData]);\n\n const authenticate = useCallback(\n (next: StoredReturnsSession) => {\n writeStoredSession(getBrowserSessionStorage(), projectID, next);\n setExchangeError(undefined);\n setChallenge(undefined);\n setSession({\n status: \"authenticated\",\n token: next.token,\n expiresAt: next.expiresAt,\n });\n },\n [projectID],\n );\n\n // Hydrates from `sessionStorage`, or exchanges the panel token. Runs after\n // mount, so render never touches `window`.\n useEffect(() => {\n let cancelled = false;\n const storage = getBrowserSessionStorage();\n\n if (panelAccessToken == null || panelAccessToken === \"\") {\n const hadPanelToken = previousPanelToken.current != null;\n previousPanelToken.current = undefined;\n\n if (hadPanelToken) {\n clearSession();\n return;\n }\n\n const stored = readStoredSession(storage, projectID);\n setSession(\n stored != null\n ? {\n status: \"authenticated\",\n token: stored.token,\n expiresAt: stored.expiresAt,\n }\n : { status: \"anonymous\" },\n );\n return;\n }\n\n previousPanelToken.current = panelAccessToken;\n clearStoredSession(storage, projectID);\n dropCachedData();\n setExchangeError(undefined);\n setSession({ status: \"exchanging\" });\n\n createClient(ReturnsService, transport)\n .exchangePanelSession({\n projectId: projectID,\n accessToken: panelAccessToken,\n environment,\n })\n .then((response) => {\n if (cancelled) {\n return;\n }\n const expiresAt = expiryToMillis(response.expiresAt);\n if (response.sessionToken === \"\" || expiresAt == null) {\n throw new Error(\"EMPTY_SESSION\");\n }\n authenticate({ token: response.sessionToken, expiresAt });\n })\n .catch((error: unknown) => {\n if (cancelled) {\n return;\n }\n setExchangeError(error);\n setSession({ status: \"anonymous\" });\n });\n\n return () => {\n cancelled = true;\n };\n // `clearSession`, `authenticate` and `dropCachedData` only change with the\n // project or the query client, which are already covered.\n }, [panelAccessToken, projectID, environment, transport]);\n\n // Expired sessions are dropped even when the page stays open.\n useEffect(() => {\n if (session.status !== \"authenticated\" || session.expiresAt == null) {\n return;\n }\n const remaining = session.expiresAt - Date.now();\n if (remaining <= 0) {\n clearSession();\n return;\n }\n const timer = setTimeout(\n clearSession,\n Math.min(remaining, MAX_TIMEOUT_MS),\n );\n return () => clearTimeout(timer);\n }, [session.status, session.expiresAt, clearSession]);\n\n const value = useMemo<ReturnsContextValue>(\n () => ({\n projectID,\n environment,\n status: session.status,\n token: session.token,\n exchangeError,\n challenge,\n setChallenge,\n authenticate,\n clearSession,\n }),\n [\n projectID,\n environment,\n session.status,\n session.token,\n exchangeError,\n challenge,\n authenticate,\n clearSession,\n ],\n );\n\n return (\n <ReturnsContext.Provider value={value}>\n <div\n data-bitsnap-returns=\"root\"\n data-bitsnap-returns-slot=\"root\"\n className={cn(\"bitsnap-react\", boundaryClassName, className, root.className)}\n style={{ ...boundaryStyle, ...root.style } as CSSProperties}\n >\n {children}\n </div>\n </ReturnsContext.Provider>\n );\n}\n\n/**\n * Holds everything the returns views share: the per-instance transport, the\n * query client (when the app has none), appearance, texts and the returns\n * session. It renders the themed root element, so step components composed\n * under it are themed without extra markup.\n *\n * ```tsx\n * <ReturnsProvider projectID=\"…\" appearance={brand}>\n * <ReturnsOrderList onSelectOrder={setOrderId} />\n * </ReturnsProvider>\n * ```\n */\nexport function ReturnsProvider({\n projectID,\n host,\n environment,\n appearance,\n texts,\n theme,\n locale,\n panelAccessToken,\n className,\n analytics,\n children,\n}: ReturnsProviderProps) {\n const instrument = useInstrument(projectID, analytics, \"returns\");\n const existingQueryClient = useContext(QueryClientContext);\n const [ownQueryClient] = useState(() =>\n existingQueryClient == null\n ? new QueryClient({ defaultOptions: { queries: { staleTime: 5000 } } })\n : undefined,\n );\n\n const resolvedHost = host ?? getTransportHost();\n const transport = useMemo(\n () => getRpcTransport(resolvedHost),\n [resolvedHost],\n );\n\n const brandColor = theme?.brandColor;\n const resolvedAppearance = useMemo(\n () => resolveBrandAppearance(appearance, { brandColor }),\n [appearance, brandColor],\n );\n const resolvedTexts = useMemo(() => mapLegacyTexts(texts), [texts]);\n\n const content = (\n <InstrumentProvider value={instrument}>\n <TransportProvider transport={transport}>\n <ReturnsAppearanceProvider appearance={resolvedAppearance}>\n <ReturnsTextsProvider texts={resolvedTexts} locale={locale}>\n <SessionProvider\n projectID={projectID}\n environment={resolveReturnsEnvironment(environment)}\n transport={transport}\n panelAccessToken={panelAccessToken}\n className={className}\n >\n {children}\n </SessionProvider>\n </ReturnsTextsProvider>\n </ReturnsAppearanceProvider>\n </TransportProvider>\n </InstrumentProvider>\n );\n\n return existingQueryClient == null && ownQueryClient != null ? (\n <QueryClientProvider client={ownQueryClient}>{content}</QueryClientProvider>\n ) : (\n content\n );\n}\n\n/** Name of {@link ReturnsProvider} in `bitsnap-react` 1.6.0. */\nexport const BitsnapReturnsProvider = ReturnsProvider;\n\nexport type BitsnapReturnsProviderProps = ReturnsProviderProps;\n","import { timestampMs, type Timestamp } from \"@bufbuild/protobuf/wkt\";\n\n/** Returns session as kept in `sessionStorage`. */\nexport type StoredReturnsSession = {\n token: string;\n /** Expiry as unix milliseconds. */\n expiresAt: number;\n};\n\n/** The part of `Storage` the session code needs. */\nexport type SessionStorageLike = Pick<\n Storage,\n \"getItem\" | \"setItem\" | \"removeItem\"\n>;\n\nconst KEY_PREFIX = \"bitsnap-returns-session:\";\n\n/** One key per project, so projects on the same page never share a session. */\nexport function sessionStorageKey(projectID: string): string {\n return `${KEY_PREFIX}${projectID}`;\n}\n\n/**\n * `window.sessionStorage` when it is usable, otherwise `undefined`. Safe to\n * call on the server and where storage access throws (blocked cookies).\n */\nexport function getBrowserSessionStorage(): SessionStorageLike | undefined {\n try {\n return typeof window !== \"undefined\" ? window.sessionStorage : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Reads the stored session. Malformed and expired entries are removed and\n * reported as no session.\n */\nexport function readStoredSession(\n storage: SessionStorageLike | undefined,\n projectID: string,\n now: number = Date.now(),\n): StoredReturnsSession | undefined {\n if (storage == null) {\n return undefined;\n }\n\n const key = sessionStorageKey(projectID);\n\n try {\n const raw = storage.getItem(key);\n if (raw == null) {\n return undefined;\n }\n\n const parsed: unknown = JSON.parse(raw);\n if (\n parsed != null &&\n typeof parsed === \"object\" &&\n typeof (parsed as StoredReturnsSession).token === \"string\" &&\n (parsed as StoredReturnsSession).token.length > 0 &&\n typeof (parsed as StoredReturnsSession).expiresAt === \"number\" &&\n (parsed as StoredReturnsSession).expiresAt > now\n ) {\n const { token, expiresAt } = parsed as StoredReturnsSession;\n return { token, expiresAt };\n }\n\n storage.removeItem(key);\n } catch {\n try {\n storage.removeItem(key);\n } catch {\n // Storage is unusable; nothing else to clean up.\n }\n }\n\n return undefined;\n}\n\nexport function writeStoredSession(\n storage: SessionStorageLike | undefined,\n projectID: string,\n session: StoredReturnsSession,\n): void {\n try {\n storage?.setItem(sessionStorageKey(projectID), JSON.stringify(session));\n } catch {\n // The session still works in memory when storage is full or blocked.\n }\n}\n\nexport function clearStoredSession(\n storage: SessionStorageLike | undefined,\n projectID: string,\n): void {\n try {\n storage?.removeItem(sessionStorageKey(projectID));\n } catch {\n // Nothing to do when storage is blocked.\n }\n}\n\n/** Expiry of a backend session in unix milliseconds, `undefined` when missing. */\nexport function expiryToMillis(\n expiresAt: Timestamp | undefined,\n): number | undefined {\n return expiresAt == null ? undefined : timestampMs(expiresAt);\n}\n"]}
|