bitsnap-react 1.20.0 → 1.21.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/BitsnapCart-73ESTTTH.mjs +2 -0
- package/dist/BitsnapCart-TWT7LVGJ.js +2 -0
- package/dist/BitsnapCart-TWT7LVGJ.js.map +1 -0
- package/dist/{CartProvider-G7FQUPXL.mjs → CartProvider-4WXJPQJB.mjs} +2 -2
- package/dist/CartProvider-CPF2E7JA.js +2 -0
- package/dist/CartProvider-CPF2E7JA.js.map +1 -0
- package/dist/PanelModelFiles-EKQRLF46.js.map +1 -1
- package/dist/analytics.js +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/analytics.mjs +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/chat.d.mts +2 -2
- package/dist/chat.d.ts +2 -2
- package/dist/chat.js +1 -1
- package/dist/chat.js.map +1 -1
- package/dist/chat.mjs +1 -1
- package/dist/chat.mjs.map +1 -1
- package/dist/{chunk-IXQCN7MR.mjs → chunk-27JN2GIQ.mjs} +2 -2
- package/dist/{chunk-URQBHNJK.mjs → chunk-6ALA5M44.mjs} +2 -2
- package/dist/{chunk-4Y233NII.js → chunk-6DEKVABT.js} +2 -2
- package/dist/chunk-6DEKVABT.js.map +1 -0
- package/dist/chunk-6Q3VGPSF.js.map +1 -1
- package/dist/{chunk-AQYHQY2Y.js → chunk-E5MMKBC4.js} +2 -2
- package/dist/chunk-E5MMKBC4.js.map +1 -0
- package/dist/chunk-EFN4OW2C.js.map +1 -1
- package/dist/{chunk-IRZJIPUF.js → chunk-EK3D44XW.js} +2 -2
- package/dist/chunk-EK3D44XW.js.map +1 -0
- package/dist/{chunk-BTERIY6N.mjs → chunk-EXC5Z5VM.mjs} +2 -2
- package/dist/{chunk-RJPQMDIQ.js → chunk-EZGL6DPG.js} +2 -2
- package/dist/chunk-EZGL6DPG.js.map +1 -0
- package/dist/{chunk-HP3I6D2R.js → chunk-FORZ5AH4.js} +2 -2
- package/dist/chunk-FORZ5AH4.js.map +1 -0
- package/dist/{chunk-KO7ZERN5.mjs → chunk-HLULQA3B.mjs} +2 -2
- package/dist/{chunk-YPA6MMGJ.js → chunk-I2RHVELR.js} +2 -2
- package/dist/chunk-I2RHVELR.js.map +1 -0
- package/dist/{chunk-GHBRR665.js → chunk-IKKMSLKC.js} +2 -2
- package/dist/chunk-IKKMSLKC.js.map +1 -0
- package/dist/{chunk-TW25G7XX.mjs → chunk-J6WKSO33.mjs} +2 -2
- package/dist/{chunk-TW25G7XX.mjs.map → chunk-J6WKSO33.mjs.map} +1 -1
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/{chunk-IXX6SUMB.mjs → chunk-KO7Z3E23.mjs} +2 -2
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/chunk-KYSMT6ZK.js +2 -0
- package/dist/chunk-KYSMT6ZK.js.map +1 -0
- package/dist/{chunk-LHQEM3CU.mjs → chunk-LRUBBPTV.mjs} +2 -2
- package/dist/chunk-MDAFPGPA.js.map +1 -1
- package/dist/chunk-Q337IQNA.js.map +1 -1
- package/dist/{chunk-5M3OUOMU.mjs → chunk-T5JO4SP7.mjs} +2 -2
- package/dist/{chunk-C736F727.js → chunk-TM3E3L57.js} +2 -2
- package/dist/chunk-TM3E3L57.js.map +1 -0
- package/dist/{chunk-LHNTSQYO.mjs → chunk-TMEII7BM.mjs} +2 -2
- package/dist/chunk-W3RGQYPD.js.map +1 -1
- package/dist/{chunk-A2ZDFN3J.mjs → chunk-WOA6W5RM.mjs} +2 -2
- package/dist/{chunk-KZWCVKLU.js → chunk-XMRGA5AN.js} +3 -3
- package/dist/chunk-XMRGA5AN.js.map +1 -0
- package/dist/chunk-Z3YOJ6NZ.js.map +1 -1
- package/dist/consent.js.map +1 -1
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/embed/analytics.js +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/internal.js.map +1 -1
- package/dist/methods-43RQLLWD.mjs +2 -0
- package/dist/methods-SZVF3HMF.js +2 -0
- package/dist/methods-SZVF3HMF.js.map +1 -0
- package/dist/model-files-client-P4PORZJ6.js.map +1 -1
- package/dist/models.js.map +1 -1
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/dist/viewer3d.js.map +1 -1
- package/dist/viewer3d.mjs +1 -1
- package/dist/{widgets-Bsojw94g.d.ts → widgets-BL6pCMdc.d.ts} +34 -2
- package/dist/{widgets-u7xMJbsY.d.mts → widgets-DmHlIbp8.d.mts} +34 -2
- package/package.json +1 -1
- package/dist/BitsnapCart-V4S4EXYV.js +0 -2
- package/dist/BitsnapCart-V4S4EXYV.js.map +0 -1
- package/dist/BitsnapCart-Z6JFYNH2.mjs +0 -2
- package/dist/CartProvider-5NP4WACK.js +0 -2
- package/dist/CartProvider-5NP4WACK.js.map +0 -1
- package/dist/chunk-4Y233NII.js.map +0 -1
- package/dist/chunk-AQYHQY2Y.js.map +0 -1
- package/dist/chunk-C736F727.js.map +0 -1
- package/dist/chunk-GHBRR665.js.map +0 -1
- package/dist/chunk-HP3I6D2R.js.map +0 -1
- package/dist/chunk-IRZJIPUF.js.map +0 -1
- package/dist/chunk-KDL35KEI.js +0 -2
- package/dist/chunk-KDL35KEI.js.map +0 -1
- package/dist/chunk-KZWCVKLU.js.map +0 -1
- package/dist/chunk-RJPQMDIQ.js.map +0 -1
- package/dist/chunk-YPA6MMGJ.js.map +0 -1
- package/dist/methods-33CWGKNA.mjs +0 -2
- package/dist/methods-4GB652MQ.js +0 -2
- package/dist/methods-4GB652MQ.js.map +0 -1
- /package/dist/{BitsnapCart-Z6JFYNH2.mjs.map → BitsnapCart-73ESTTTH.mjs.map} +0 -0
- /package/dist/{CartProvider-G7FQUPXL.mjs.map → CartProvider-4WXJPQJB.mjs.map} +0 -0
- /package/dist/{chunk-IXQCN7MR.mjs.map → chunk-27JN2GIQ.mjs.map} +0 -0
- /package/dist/{chunk-URQBHNJK.mjs.map → chunk-6ALA5M44.mjs.map} +0 -0
- /package/dist/{chunk-BTERIY6N.mjs.map → chunk-EXC5Z5VM.mjs.map} +0 -0
- /package/dist/{chunk-KO7ZERN5.mjs.map → chunk-HLULQA3B.mjs.map} +0 -0
- /package/dist/{chunk-IXX6SUMB.mjs.map → chunk-KO7Z3E23.mjs.map} +0 -0
- /package/dist/{chunk-LHQEM3CU.mjs.map → chunk-LRUBBPTV.mjs.map} +0 -0
- /package/dist/{chunk-5M3OUOMU.mjs.map → chunk-T5JO4SP7.mjs.map} +0 -0
- /package/dist/{chunk-LHNTSQYO.mjs.map → chunk-TMEII7BM.mjs.map} +0 -0
- /package/dist/{chunk-A2ZDFN3J.mjs.map → chunk-WOA6W5RM.mjs.map} +0 -0
- /package/dist/{methods-33CWGKNA.mjs.map → methods-43RQLLWD.mjs.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-AQYHQY2Y.js","../src/components/returns/state-machine.ts","../src/components/returns/BitsnapReturns.tsx"],"names":["STEPS_WITH_SESSION","stepRequiresSession","step","initialReturnsStep","hasSession","reduceReturnsStep","event","STEP_NUMBERS","RETURNS_STEP_COUNT","returnsStepNumber","StepIndicator","current","text","useReturnsText","slot","useReturnsSlot","jsx","cn","ReturnsRouter","panelToken","logo","status","challenge","projectID","useReturnsContext","locale","useReturnsLocale","dispatch","useReducer","useEffect","restored","useRef","SkeletonRows","stepNumber","loginStep","jsxs","LoginBrandLogo","ReturnsEmailStep","ReturnsCodeStep","ReturnsOrderList","orderId","ReturnsOrderDetail","items","note","ReturnsConfirmation","returnId","ReturnsResult","ReturnsMyReturnsList","ReturnsMyReturnDetail","BitsnapReturns","showLogo","logoUrl","logoDarkUrl","props","ReturnsProvider"],"mappings":"AAAA,+HAAyI,sDAAwC,IC8C3KA,CAAAA,CAAiD,CACrD,QAAA,CACA,OAAA,CACA,cAAA,CACA,QAAA,CACA,WAAA,CACA,UACF,CAAA,CAGO,SAASC,CAAAA,CAAoBC,CAAAA,CAAgC,CAClE,OAAOF,CAAAA,CAAmB,QAAA,CAASE,CAAI,CACzC,CAGO,SAASC,CAAAA,CAAmBC,CAAAA,CAAkC,CACnE,OAAOA,CAAAA,CAAa,CAAE,IAAA,CAAM,QAAS,CAAA,CAAI,CAAE,IAAA,CAAM,OAAQ,CAC3D,CAMO,SAASC,CAAAA,CACdH,CAAAA,CACAI,CAAAA,CACa,CACb,MAAA,CAAQA,CAAAA,CAAM,IAAA,CAAM,CAClB,IAAK,iBAAA,CAEH,OAAOL,CAAAA,CAAoBC,CAAAA,CAAK,IAAI,CAAA,CAAI,CAAE,IAAA,CAAM,OAAQ,CAAA,CAAIA,CAAAA,CAC9D,IAAK,WAAA,CACH,OAAOA,CAAAA,CAAK,IAAA,GAAS,OAAA,CAAU,CAAE,IAAA,CAAM,MAAO,CAAA,CAAIA,CAAAA,CACpD,IAAK,eAAA,CACH,OAAOA,CAAAA,CAAK,IAAA,GAAS,OAAA,EAAWA,CAAAA,CAAK,IAAA,GAAS,MAAA,CAC1C,CAAE,IAAA,CAAM,QAAS,CAAA,CACjBA,CAAAA,CACN,IAAK,cAAA,CACH,OAAOA,CAAAA,CAAK,IAAA,GAAS,QAAA,CACjB,CAAE,IAAA,CAAM,OAAA,CAAS,OAAA,CAASI,CAAAA,CAAM,OAAQ,CAAA,CACxCJ,CAAAA,CACN,IAAK,QAAA,CACH,OAAOA,CAAAA,CAAK,IAAA,GAAS,OAAA,CACjB,CACE,IAAA,CAAM,cAAA,CACN,OAAA,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E,CAAA,CACC,UAAA,CAAYmC,CAAAA,CAAM,gBAAA,EAAoB,IAAA,EAAQA,CAAAA,CAAM,gBAAA,GAAqB,EAAA,CACzE,IAAA,CAAM,CAAE,QAAA,CAAAH,CAAAA,CAAU,OAAA,CAAAC,CAAAA,CAAS,WAAA,CAAAC,CAAY,CAAA,CACzC,CAAA,CACF,CAEJ,CAAA,eAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-AQYHQY2Y.js","sourcesContent":[null,"/** One line chosen for return. */\nexport type SelectedReturnLine = {\n lineId: string;\n quantity: number;\n};\n\n/** Where the default flow of `BitsnapReturns` currently is. */\nexport type ReturnsStep =\n | { name: \"email\" }\n | { name: \"code\" }\n | { name: \"orders\" }\n | {\n name: \"order\";\n orderId: string;\n /** Selection to restore when coming back from the confirmation. */\n items?: SelectedReturnLine[];\n note?: string;\n }\n | {\n name: \"confirmation\";\n orderId: string;\n items: SelectedReturnLine[];\n note: string;\n }\n | { name: \"result\"; returnId: string }\n | { name: \"myReturns\" }\n | { name: \"myReturn\"; returnId: string };\n\nexport type ReturnsStepName = ReturnsStep[\"name\"];\n\nexport type ReturnsStepEvent =\n /** A verification code was requested. */\n | { type: \"CODE_SENT\" }\n /** The session became valid: code verified, stored session or panel token. */\n | { type: \"AUTHENTICATED\" }\n /** The session was dropped by the backend, expiry or logout. */\n | { type: \"SESSION_EXPIRED\" }\n | { type: \"SELECT_ORDER\"; orderId: string }\n | { type: \"REVIEW\"; items: SelectedReturnLine[]; note: string }\n | { type: \"SUBMITTED\"; returnId: string }\n | { type: \"OPEN_MY_RETURNS\" }\n | { type: \"SELECT_RETURN\"; returnId: string }\n | { type: \"BACK\" }\n /** Leave the result screen for the order list. */\n | { type: \"CONTINUE\" };\n\nconst STEPS_WITH_SESSION: readonly ReturnsStepName[] = [\n \"orders\",\n \"order\",\n \"confirmation\",\n \"result\",\n \"myReturns\",\n \"myReturn\",\n];\n\n/** Steps that cannot be shown without a returns session. */\nexport function stepRequiresSession(step: ReturnsStepName): boolean {\n return STEPS_WITH_SESSION.includes(step);\n}\n\n/** Starts at the orders when a session exists, otherwise at the email. */\nexport function initialReturnsStep(hasSession: boolean): ReturnsStep {\n return hasSession ? { name: \"orders\" } : { name: \"email\" };\n}\n\n/**\n * Pure transition function of the default flow. Events that do not apply to\n * the current step leave it unchanged.\n */\nexport function reduceReturnsStep(\n step: ReturnsStep,\n event: ReturnsStepEvent,\n): ReturnsStep {\n switch (event.type) {\n case \"SESSION_EXPIRED\":\n // Email and code do not need a session; keep a pending verification.\n return stepRequiresSession(step.name) ? { name: \"email\" } : step;\n case \"CODE_SENT\":\n return step.name === \"email\" ? { name: \"code\" } : step;\n case \"AUTHENTICATED\":\n return step.name === \"email\" || step.name === \"code\"\n ? { name: \"orders\" }\n : step;\n case \"SELECT_ORDER\":\n return step.name === \"orders\"\n ? { name: \"order\", orderId: event.orderId }\n : step;\n case \"REVIEW\":\n return step.name === \"order\"\n ? {\n name: \"confirmation\",\n orderId: step.orderId,\n items: event.items,\n note: event.note,\n }\n : step;\n case \"SUBMITTED\":\n return step.name === \"confirmation\"\n ? { name: \"result\", returnId: event.returnId }\n : step;\n case \"OPEN_MY_RETURNS\":\n return step.name === \"orders\" || step.name === \"result\"\n ? { name: \"myReturns\" }\n : step;\n case \"SELECT_RETURN\":\n return step.name === \"myReturns\"\n ? { name: \"myReturn\", returnId: event.returnId }\n : step;\n case \"CONTINUE\":\n return step.name === \"result\" ? { name: \"orders\" } : step;\n case \"BACK\":\n switch (step.name) {\n case \"code\":\n return { name: \"email\" };\n case \"order\":\n case \"myReturns\":\n return { name: \"orders\" };\n case \"confirmation\":\n return {\n name: \"order\",\n orderId: step.orderId,\n items: step.items,\n note: step.note,\n };\n case \"myReturn\":\n return { name: \"myReturns\" };\n default:\n return step;\n }\n }\n}\n\nconst STEP_NUMBERS: Partial<Record<ReturnsStepName, number>> = {\n email: 1,\n code: 2,\n orders: 3,\n order: 4,\n confirmation: 5,\n result: 6,\n};\n\nexport const RETURNS_STEP_COUNT = 6;\n\n/** Position of a step in the return flow, `undefined` for the \"my returns\" views. */\nexport function returnsStepNumber(step: ReturnsStepName): number | undefined {\n return STEP_NUMBERS[step];\n}\n","import { useEffect, useReducer, useRef } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport {\n LoginBrandLogo,\n type LoginLogoOptions,\n} from \"@/src/ui/email-code-login/LoginBrandLogo\";\nimport { useReturnsSlot } from \"./appearance.context\";\nimport { ReturnsCodeStep, ReturnsEmailStep } from \"./AuthSteps\";\nimport { SkeletonRows } from \"./internal\";\nimport { ReturnsMyReturnDetail, ReturnsMyReturnsList } from \"./MyReturns\";\nimport {\n ReturnsConfirmation,\n ReturnsOrderDetail,\n ReturnsOrderList,\n ReturnsResult,\n} from \"./OrderSteps\";\nimport {\n ReturnsProvider,\n useReturnsContext,\n type ReturnsProviderProps,\n} from \"./ReturnsProvider\";\nimport {\n initialReturnsStep,\n reduceReturnsStep,\n RETURNS_STEP_COUNT,\n returnsStepNumber,\n} from \"./state-machine\";\nimport { useReturnsLocale, useReturnsText } from \"./texts.context\";\n\n/**\n * Props of {@link BitsnapReturns}. `showLogo`, `logoUrl` and `logoDarkUrl` set\n * the shop logo above the e-mail and code steps: by default the logo from the\n * shop settings, or Bitsnap's when the shop has none.\n */\nexport type BitsnapReturnsProps = Omit<ReturnsProviderProps, \"children\"> &\n LoginLogoOptions;\n\nfunction StepIndicator({ current }: { current: number }) {\n const text = useReturnsText();\n const slot = useReturnsSlot(\"stepIndicator\");\n\n return (\n <p\n data-bitsnap-returns-slot=\"stepIndicator\"\n className={cn(\"text-xs\", slot.className)}\n style={slot.style}\n >\n {text(\"stepIndicator\", { current, total: RETURNS_STEP_COUNT })}\n </p>\n );\n}\n\n/** Default step router. All transitions come from the pure state machine. */\nfunction ReturnsRouter({\n panelToken,\n logo,\n}: {\n panelToken: boolean;\n logo: LoginLogoOptions;\n}) {\n const { status, challenge, projectID } = useReturnsContext(\"BitsnapReturns\");\n const locale = useReturnsLocale();\n const [step, dispatch] = useReducer(\n reduceReturnsStep,\n initialReturnsStep(false),\n );\n\n // A valid session (verified code, stored session, exchanged panel token)\n // moves on to the orders; a dropped one returns to the start.\n useEffect(() => {\n if (status === \"authenticated\") {\n dispatch({ type: \"AUTHENTICATED\" });\n } else if (status === \"anonymous\") {\n dispatch({ type: \"SESSION_EXPIRED\" });\n }\n }, [status]);\n\n // A verification that was pending before a reload or an app switch returns\n // to the code step once, when the stored state has been read.\n const restored = useRef(false);\n useEffect(() => {\n if (restored.current || status === \"hydrating\") {\n return;\n }\n restored.current = true;\n if (status === \"anonymous\" && challenge != null) {\n dispatch({ type: \"CODE_SENT\" });\n }\n }, [status, challenge]);\n\n // Without a panel token the server render and the first client render show\n // the email step; a stored session switches to the orders after hydration.\n if (status === \"exchanging\" || (status === \"hydrating\" && panelToken)) {\n return <SkeletonRows />;\n }\n\n const stepNumber = returnsStepNumber(step.name);\n\n // The logo sits above the step indicator, and stays mounted between the\n // e-mail and the code step; the steps themselves then show none.\n const loginStep = step.name === \"email\" || step.name === \"code\";\n\n return (\n <div className=\"flex flex-col gap-4\">\n {loginStep && (\n <LoginBrandLogo projectId={projectID} locale={locale} {...logo} />\n )}\n {stepNumber != null && <StepIndicator current={stepNumber} />}\n {step.name === \"email\" && (\n <ReturnsEmailStep\n showLogo={false}\n onSubmitted={() => dispatch({ type: \"CODE_SENT\" })}\n />\n )}\n {step.name === \"code\" && (\n <ReturnsCodeStep\n showLogo={false}\n onVerified={() => dispatch({ type: \"AUTHENTICATED\" })}\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n {step.name === \"orders\" && (\n <ReturnsOrderList\n showLogout={!panelToken}\n onSelectOrder={(orderId) =>\n dispatch({ type: \"SELECT_ORDER\", orderId })\n }\n onOpenMyReturns={() => dispatch({ type: \"OPEN_MY_RETURNS\" })}\n />\n )}\n {step.name === \"order\" && (\n <ReturnsOrderDetail\n orderId={step.orderId}\n initialItems={step.items}\n initialNote={step.note}\n onBack={() => dispatch({ type: \"BACK\" })}\n onContinue={({ items, note }) =>\n dispatch({ type: \"REVIEW\", items, note })\n }\n />\n )}\n {step.name === \"confirmation\" && (\n <ReturnsConfirmation\n orderId={step.orderId}\n items={step.items}\n note={step.note}\n onBack={() => dispatch({ type: \"BACK\" })}\n onSubmitted={(returnId) =>\n dispatch({ type: \"SUBMITTED\", returnId })\n }\n />\n )}\n {step.name === \"result\" && (\n <ReturnsResult\n returnId={step.returnId}\n onContinue={() => dispatch({ type: \"CONTINUE\" })}\n onOpenMyReturns={() => dispatch({ type: \"OPEN_MY_RETURNS\" })}\n />\n )}\n {step.name === \"myReturns\" && (\n <ReturnsMyReturnsList\n onSelectReturn={(returnId) =>\n dispatch({ type: \"SELECT_RETURN\", returnId })\n }\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n {step.name === \"myReturn\" && (\n <ReturnsMyReturnDetail\n returnId={step.returnId}\n onBack={() => dispatch({ type: \"BACK\" })}\n />\n )}\n </div>\n );\n}\n\n/**\n * Customer return flow: email, code, orders, line selection, confirmation and\n * result, plus the list of earlier returns. It is `ReturnsProvider` with the\n * default step router; compose your own page from the step components to\n * change the layout.\n *\n * ```tsx\n * <BitsnapReturns projectID=\"…\" appearance={brand} texts={{ emailStepTitle: \"Return a product\" }} />\n * ```\n */\nexport function BitsnapReturns({\n showLogo,\n logoUrl,\n logoDarkUrl,\n ...props\n}: BitsnapReturnsProps) {\n return (\n <ReturnsProvider {...props}>\n <ReturnsRouter\n panelToken={props.panelAccessToken != null && props.panelAccessToken !== \"\"}\n logo={{ showLogo, logoUrl, logoDarkUrl }}\n />\n </ReturnsProvider>\n );\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-C736F727.js","../src/components/products/fetch.ts"],"names":["DEFAULT_PAGE_SIZE","MAX_PAGE_SIZE","ProductListError","message","status","clamp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AM,CAAA,CAEnC,IAAME,CAAAA,iBAASF,CAAAA,mBAAM,MAAA,6BAAQ,IAAA,mBAAK,GAAA,CAClC,OAAIE,CAAAA,EACFD,CAAAA,CAAO,GAAA,CAAI,QAAA,CAAUC,CAAM,CAAA,CAItB,CAAA,EAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-C736F727.js","sourcesContent":[null,"import { withClientParam } from \"@/src/lib/client-header\";\nimport type { BitsnapModels } from \"@/src/models\";\n\nexport type PublicListProduct = BitsnapModels.PublicListProduct;\nexport type ProductListData = BitsnapModels.ProductListResponse;\n\nexport const DEFAULT_PAGE_SIZE = 24;\nexport const MAX_PAGE_SIZE = 48;\n\nexport type ProductListQuery = {\n projectID: string;\n /** Origin of the Bitsnap backend (or of a custom domain), without a path. */\n host: string;\n locale?: string;\n search?: string;\n limit: number;\n offset: number;\n};\n\nexport class ProductListError extends Error {\n readonly status: number | undefined;\n\n constructor(message: string, status?: number) {\n super(message);\n this.name = \"ProductListError\";\n this.status = status;\n }\n}\n\n/** Page size within what the backend accepts (1 to 48, default 24). */\nexport function clampPageSize(pageSize?: number): number {\n if (pageSize == null || !Number.isFinite(pageSize)) {\n return DEFAULT_PAGE_SIZE;\n }\n return Math.min(MAX_PAGE_SIZE, Math.max(1, Math.floor(pageSize)));\n}\n\nexport function pageCountFor(totalCount: number, pageSize: number): number {\n return Math.max(1, Math.ceil(totalCount / pageSize));\n}\n\n/** Origin without trailing slashes, so equal hosts compare equal as strings. */\nexport function normalizeHost(host: string): string {\n return host.replace(/\\/+$/, \"\");\n}\n\nexport function buildProductListURL(query: ProductListQuery): string {\n const params = new URLSearchParams();\n params.set(\"limit\", String(query.limit));\n params.set(\"offset\", String(query.offset));\n if (query.locale) {\n params.set(\"locale\", query.locale);\n }\n const search = query.search?.trim();\n if (search) {\n params.set(\"search\", search);\n }\n\n const host = normalizeHost(query.host);\n return `${host}/api/integrations/${encodeURIComponent(\n query.projectID,\n )}/public-commerce/product-list?${params.toString()}`;\n}\n\nfunction isProductListData(value: unknown): value is ProductListData {\n return (\n typeof value === \"object\" &&\n value != null &&\n Array.isArray((value as ProductListData).items) &&\n typeof (value as ProductListData).totalCount === \"number\"\n );\n}\n\n/**\n * Loads one page of the catalog with a plain, credential-less `fetch`. It does\n * not touch the global project ID or host.\n */\nexport async function fetchProductList(\n query: ProductListQuery,\n signal?: AbortSignal,\n): Promise<ProductListData> {\n const response = await fetch(withClientParam(buildProductListURL(query)), {\n method: \"GET\",\n credentials: \"omit\",\n headers: { Accept: \"application/json\" },\n signal,\n });\n\n if (!response.ok) {\n throw new ProductListError(\n `Could not load products (${response.status})`,\n response.status,\n );\n }\n\n const payload: unknown = await response.json();\n if (!isProductListData(payload)) {\n throw new ProductListError(\"Unexpected product list response\");\n }\n\n return payload;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-GHBRR665.js","../src/components/products/appearance.ts","../src/components/products/format.ts"],"names":["PRODUCT_LIST_SLOT_NAMES","PRODUCT_LIST_TOKEN_VARIABLES","PRODUCT_LIST_THEME_PRESETS","PRODUCT_LIST_SHADCN_VARIABLES","resolveProductListAppearance","appearance","resolved","resolveAppearanceCore","getProductListSlotAppearance","slot","getSlotAppearance","createFormatter","locale","currency","formatProductPrice","amount","DEFAULT_LOCALE","value","formatter"],"mappings":"AAAA,uuBAAgD,sDAAwE,sDAAgD,sDAAqE,sDAAgD,IC6DhRA,EAAAA,CAA0B,CACrC,MAAA,CACA,MAAA,CACA,MAAA,CACA,UAAA,CACA,OAAA,CACA,kBAAA,CACA,MAAA,CACA,MAAA,CACA,aAAA,CACA,OAAA,CACA,cAAA,CACA,OAAA,CACA,cAAA,CACA,SAAA,CACA,iBAAA,CACA,cAAA,CACA,SAAA,CACA,YAAA,CACA,kBAAA,CACA,eAAA,CACA,YAAA,CACA,OAAA,CACA,aAAA,CACA,UACF,C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RR665.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 * Product list appearance API.\n *\n * It mirrors `CheckoutAppearance` and `ReturnsAppearance` (theme, tokens,\n * elements) so a shop can reuse one brand object for all of them. The resolver\n * is pure: it turns the caller input into a theme name, the tokens in effect,\n * the slot overrides and the inline style for the theme boundary.\n */\n\nexport type ProductListTheme = \"light\" | \"dark\";\n\nexport type ProductListAppearanceTokens = {\n /** Font family of the list. The library never loads fonts. */\n fontFamily?: string;\n /** Minimum grid track width. Use \"100%\" for one column. */\n gridMinWidth?: string;\n /** Base font size. */\n fontSize?: string;\n /** List background. */\n background?: string;\n /** Raised surfaces: cards, image placeholders, skeletons. */\n surface?: string;\n /** Main text color. */\n foreground?: string;\n /** Secondary text: descriptions, the struck-through price. */\n mutedForeground?: string;\n /** Borders of cards and buttons. */\n border?: string;\n /** \"Add to cart\" button background. */\n buttonBackground?: string;\n /** \"Add to cart\" button text. */\n buttonForeground?: string;\n /** \"Add to cart\" button background on hover. */\n buttonHoverBackground?: string;\n /** Hover surface of cards and secondary buttons. */\n hoverSurface?: string;\n /** Focus ring color. */\n focusRing?: string;\n /** Error and unavailable state color. */\n error?: string;\n /** Badge background (subscription, unavailable). */\n badgeBackground?: string;\n /** Badge text. */\n badgeForeground?: string;\n /** Corner radius of cards, images and buttons. */\n radius?: string;\n};\n\n/**\n * Stable slot names. They are exposed as `data-bitsnap-products-slot`\n * attributes so they can also be targeted from plain CSS.\n */\nexport const PRODUCT_LIST_SLOT_NAMES = [\n \"root\",\n \"grid\",\n \"card\",\n \"cardLink\",\n \"image\",\n \"imagePlaceholder\",\n \"body\",\n \"name\",\n \"description\",\n \"price\",\n \"comparePrice\",\n \"badge\",\n \"model3dBadge\",\n \"actions\",\n \"addToCartButton\",\n \"selectButton\",\n \"message\",\n \"pagination\",\n \"paginationButton\",\n \"pageIndicator\",\n \"emptyState\",\n \"error\",\n \"retryButton\",\n \"skeleton\",\n] as const;\n\nexport type ProductListSlotName = (typeof PRODUCT_LIST_SLOT_NAMES)[number];\n\nexport type ProductListSlotAppearance = SlotAppearance;\n\nexport type ProductListAppearanceElements =\n AppearanceElements<ProductListSlotName>;\n\nexport type ProductListAppearance = {\n /** `\"light\"` or `\"dark\"`. Omitted means `\"light\"`. */\n theme?: ProductListTheme;\n /** Partial overrides applied over the theme preset. */\n tokens?: ProductListAppearanceTokens;\n /** Per element `className`/`style` overrides. */\n elements?: ProductListAppearanceElements;\n};\n\nexport type ResolvedProductListAppearance = {\n theme: ProductListTheme;\n /** Tokens that are in effect (the theme preset plus caller overrides). */\n tokens: ProductListAppearanceTokens;\n elements: ProductListAppearanceElements;\n /** Theme marker class for the theme boundary. */\n boundaryClassName: string;\n /** Inline custom properties applied to the list root. */\n boundaryStyle: CSSProperties;\n};\n\n/** CSS custom property used for each token. */\nexport const PRODUCT_LIST_TOKEN_VARIABLES = {\n fontFamily: \"--bitsnap-products-font-family\",\n gridMinWidth: \"--bitsnap-products-grid-min-width\",\n fontSize: \"--bitsnap-products-font-size\",\n background: \"--bitsnap-products-background\",\n surface: \"--bitsnap-products-surface\",\n foreground: \"--bitsnap-products-foreground\",\n mutedForeground: \"--bitsnap-products-muted-foreground\",\n border: \"--bitsnap-products-border\",\n buttonBackground: \"--bitsnap-products-button-background\",\n buttonForeground: \"--bitsnap-products-button-foreground\",\n buttonHoverBackground: \"--bitsnap-products-button-hover-background\",\n hoverSurface: \"--bitsnap-products-hover-surface\",\n focusRing: \"--bitsnap-products-focus-ring\",\n error: \"--bitsnap-products-error\",\n badgeBackground: \"--bitsnap-products-badge-background\",\n badgeForeground: \"--bitsnap-products-badge-foreground\",\n radius: \"--bitsnap-products-radius\",\n} as const;\n\nexport type ProductListTokenName = keyof typeof PRODUCT_LIST_TOKEN_VARIABLES;\n\n/**\n * Complete palettes. They carry colors and radius only, so typography is never\n * reset implicitly. `products.css` falls back to the light values, which keeps\n * the list usable even when the boundary style is missing.\n */\nexport const PRODUCT_LIST_THEME_PRESETS: Record<\n ProductListTheme,\n ProductListAppearanceTokens\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 badgeBackground: \"#f4f4f5\",\n badgeForeground: \"#3f3f46\",\n radius: \"8px\",\n gridMinWidth: \"9rem\",\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 badgeBackground: \"#3f3f46\",\n badgeForeground: \"#e4e4e7\",\n radius: \"8px\",\n gridMinWidth: \"9rem\",\n },\n};\n\n/** The list renders its own elements, so no shared primitive needs remapping. */\nconst PRODUCT_LIST_SHADCN_VARIABLES: ShadcnVariableMapping<ProductListTokenName> =\n [];\n\nexport function resolveProductListAppearance(\n appearance?: ProductListAppearance,\n): ResolvedProductListAppearance {\n const resolved = resolveAppearanceCore<\n ProductListTokenName,\n ProductListTheme,\n ProductListSlotName\n >(appearance, {\n defaultTheme: \"light\",\n presets: PRODUCT_LIST_THEME_PRESETS,\n variables: PRODUCT_LIST_TOKEN_VARIABLES,\n shadcnVariables: PRODUCT_LIST_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 getProductListSlotAppearance(\n resolved: ResolvedProductListAppearance,\n slot: ProductListSlotName,\n): ProductListSlotAppearance | undefined {\n return getSlotAppearance(resolved.elements, slot);\n}\n","import { DEFAULT_LOCALE } from \"../checkout/locale\";\n\nfunction createFormatter(\n locale: string,\n currency: string,\n): Intl.NumberFormat | undefined {\n try {\n return new Intl.NumberFormat(locale, {\n style: \"currency\",\n currency,\n currencyDisplay: \"symbol\",\n });\n } catch {\n // RangeError: invalid locale or currency code.\n return undefined;\n }\n}\n\n/**\n * Formats a price in minor units (grosze, cents) for the locale, the same way\n * the cart does (`amount / 100`). An unknown locale falls back to Polish and an\n * invalid currency code to a plain number followed by the code.\n */\nexport function formatProductPrice(\n amount: number,\n currency: string,\n locale: string = DEFAULT_LOCALE,\n): string {\n const value = amount / 100;\n const formatter =\n createFormatter(locale, currency) ??\n createFormatter(DEFAULT_LOCALE, currency);\n\n return formatter != null\n ? formatter.format(value)\n : `${value.toFixed(2)} ${currency}`;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-HP3I6D2R.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/ui/email-code-login/pending.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","browserStorage","pendingLoginKey","surface","projectID","host"],"mappings":"AAAA,y/BAAgD,sDAAwH,sDAAwC,sDAAyD,sDAAyD,ICiErTA,EAAAA,CAAqB,CAEhC,MAAA,CACA,QAAA,CACA,OAAA,CACA,aAAA,CACA,YAAA,CACA,eAAA,CACA,OAAA,CACA,YAAA,CACA,UAAA,CAEA,WAAA,CACA,YAAA,CACA,UAAA,CACA,WAAA,CACA,cAAA,CACA,cAAA,CAEA,WAAA,CACA,WAAA,CACA,gBAAA,CACA,WAAA,CACA,YAAA,CACA,YAAA,CAEA,UAAA,CACA,MAAA,CACA,UAAA,CACA,WAAA,CACA,qBAAA,CACA,gBAAA,CACA,eAAA,CACA,sBAAA,CACA,WAAA,CAEA,SAAA,CACA,cAAA,CACA,iBAAA,CACA,cAAA,CACA,iBAAA,CACA,oBAAA,CAEA,YAAA,CACA,YAAA,CACA,aAAA,CACA,SAAA,CACA,cACF,CAAA,CA6BaC,EAAAA,CAA0B,CACrC,UAAA,CAAY,+BAAA,CACZ,QAAA,CAAU,6BAAA,CACV,UAAA,CAAY,8BAAA,CACZ,OAAA,CAAS,2BAAA,CACT,UAAA,CAAY,8BAAA,CACZ,eAAA,CAAiB,oCAAA,CACjB,MAAA,CAAQ,0BAAA,CACR,gBAAA,CAAkB,qCAAA,CAClB,gBAAA,CAAkB,qCAAA,CAClB,qBAAA,CAAuB,2CAAA,CACvB,YAAA,CAAc,iCAAA,CACd,SAAA,CAAW,8BAAA,CACX,KAAA,CAAO,yBAAA,CACP,OAAA,CAAS,2BAAA,CACT,OAAA,CAAS,2BAAA,CACT,eAAA,CAAiB,oCAAA,CACjB,eAAA,CAAiB,oCA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,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACQ,CACR,MAAO,CAAA,sBAAA,EAAyBF,CAAO,CAAA,CAAA,EAAI,kBAAA,kBAAmBE,CAAAA,SAAQ,IAAE,CAAC,CAAA,CAAA,EAAI,kBAAA,kBAAmBD,CAAAA,SAAa,IAAE,CAAC,CAAA,CAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-HP3I6D2R.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 = Omit<ResolvedReturnsTexts, OptionalReturnsTextKey> &\n Partial<Pick<ResolvedReturnsTexts, OptionalReturnsTextKey>>;\n\n/**\n * Keys added after 1.6: optional in {@link ReturnsTexts} so that code which\n * builds a complete texts object keeps compiling. The defaults fill them in.\n */\ntype OptionalReturnsTextKey =\n | \"resendSent\"\n | \"codeSpamHint\"\n | \"codeValidity\"\n | \"codeIncomplete\"\n | \"errorNetwork\";\n\n/** The texts after the defaults are applied: every key is present. */\nexport type ResolvedReturnsTexts = {\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 /** Confirmation after a new code was sent. */\n resendSent: string;\n /** Hint under the code field. */\n codeSpamHint: string;\n codeValidity: string;\n /** Shown when the form is submitted with fewer than 6 digits. */\n codeIncomplete: 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 errorNetwork: 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 ResolvedReturnsTexts;\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 resendSent: \"We sent a new code.\",\n codeSpamHint: \"Can't see the email? Check your spam folder.\",\n codeValidity: \"The code is valid for 10 minutes.\",\n codeIncomplete: \"Enter all 6 digits of the code.\",\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 errorNetwork: \"Cannot reach the server. Check your connection and 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 resendSent: \"Wysłaliśmy nowy kod.\",\n codeSpamHint: \"Nie widzisz e-maila? Sprawdź folder spam.\",\n codeValidity: \"Kod jest ważny 10 minut.\",\n codeIncomplete: \"Wpisz wszystkie 6 cyfr kodu.\",\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 errorNetwork: \"Brak połączenia z serwerem. Sprawdź internet i 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): ResolvedReturnsTexts {\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 ResolvedReturnsTexts,\n type ReturnsTexts,\n} from \"./texts\";\n\ntype ReturnsTextsContextValue = {\n /** Active locale (the `locale` prop or the library locale). */\n locale: string;\n texts: ResolvedReturnsTexts;\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 {\n clearPendingLogin,\n pendingLoginKey,\n readPendingLogin,\n savePendingLogin,\n} from \"@/src/ui/email-code-login/pending\";\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 /**\n * Stores (or, with `undefined`, drops) the pending verification. It is kept\n * in `sessionStorage` too, so a reload returns to the code step.\n */\n setChallenge: (challenge: ReturnsChallenge | undefined) => void;\n /** Email of the last verification, kept after the challenge is dropped. */\n lastEmail: string | undefined;\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, setChallengeState] = useState<ReturnsChallenge>();\n const [lastEmail, setLastEmail] = useState<string>();\n const pendingKey = pendingLoginKey(\"returns\", projectID);\n const previousPanelToken = useRef<string | undefined>(undefined);\n\n const setChallenge = useCallback(\n (next: ReturnsChallenge | undefined) => {\n setChallengeState(next);\n if (next == null) {\n clearPendingLogin(pendingKey);\n return;\n }\n setLastEmail(next.email);\n savePendingLogin(pendingKey, {\n email: next.email,\n challengeId: next.challengeId,\n resendAt: next.resendAvailableAt,\n sentAt: Date.now(),\n });\n },\n [pendingKey],\n );\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, setChallenge]);\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, setChallenge],\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 // A verification that was pending before a reload or an app switch.\n const pending = stored == null ? readPendingLogin(pendingKey) : undefined;\n if (pending?.challengeId != null) {\n setChallengeState({\n challengeId: pending.challengeId,\n email: pending.email,\n resendAvailableAt: pending.resendAt,\n });\n setLastEmail(pending.email);\n }\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 lastEmail,\n authenticate,\n clearSession,\n }),\n [\n projectID,\n environment,\n session.status,\n session.token,\n exchangeError,\n challenge,\n setChallenge,\n lastEmail,\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","/**\n * The pending step of an e-mail-code login, kept in `sessionStorage` so a\n * reload or an app switch (the code arrives in the mail app) returns to the\n * code step. One key per surface and project; never holds the code itself.\n */\n\n/** How long a sent code stays usable, in milliseconds (the copy says 10 min). */\nexport const CODE_VALID_MS = 10 * 60 * 1000;\n\nexport type PendingLogin = {\n email: string;\n challengeId?: string;\n /** Unix milliseconds when a new code may be requested. */\n resendAt: number;\n /** Unix milliseconds when the code was sent. */\n sentAt: number;\n};\n\ntype StorageLike = Pick<Storage, \"getItem\" | \"setItem\" | \"removeItem\">;\n\nfunction browserStorage(): StorageLike | undefined {\n try {\n return typeof window !== \"undefined\" ? window.sessionStorage : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** `bitsnap-login-pending:<surface>:<host>:<project>`. */\nexport function pendingLoginKey(\n surface: string,\n projectID?: string,\n host?: string,\n): string {\n return `bitsnap-login-pending:${surface}:${encodeURIComponent(host ?? \"\")}:${encodeURIComponent(projectID ?? \"\")}`;\n}\n\nexport function savePendingLogin(key: string, pending: PendingLogin): void {\n try {\n browserStorage()?.setItem(key, JSON.stringify(pending));\n } catch {\n // Storage full or blocked: the login still works, it just is not restored.\n }\n}\n\nexport function clearPendingLogin(key: string): void {\n try {\n browserStorage()?.removeItem(key);\n } catch {\n // ignore\n }\n}\n\n/**\n * The stored step. Malformed and expired entries are removed and reported as\n * none.\n */\nexport function readPendingLogin(\n key: string,\n now: number = Date.now(),\n): PendingLogin | undefined {\n const storage = browserStorage();\n if (storage == null) return undefined;\n try {\n const raw = storage.getItem(key);\n if (raw == null) return undefined;\n const parsed = JSON.parse(raw) as Partial<PendingLogin> | null;\n if (\n parsed != null &&\n typeof parsed.email === \"string\" &&\n parsed.email !== \"\" &&\n typeof parsed.sentAt === \"number\" &&\n typeof parsed.resendAt === \"number\" &&\n (parsed.challengeId == null || typeof parsed.challengeId === \"string\") &&\n now - parsed.sentAt < CODE_VALID_MS\n ) {\n return {\n email: parsed.email,\n challengeId: parsed.challengeId,\n resendAt: parsed.resendAt,\n sentAt: parsed.sentAt,\n };\n }\n storage.removeItem(key);\n } catch {\n try {\n storage.removeItem(key);\n } catch {\n // ignore\n }\n }\n return undefined;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-IRZJIPUF.js","../src/analytics/pageviews.ts","../src/version.ts","../src/analytics/random.ts","../src/analytics/visitor.ts"],"names":["REGISTRY","registry","win","holder","watchNavigation","onChange","check","name","original","args","result","startAutoPageViews","send","reg","starter","path","resetAutoPageViews","SDK_VERSION","randomBytes","n","bytes","c","i","VISITOR_HEADER","MAX_AGE_SECONDS","VISITOR_ID_RE","consentApi","readCookie","doc","part","index","isBitsnapHost","hostname","host","consentBelongsTo","projectKey","api","onBitsnap","analyticsGranted","newVisitorId","binary","byte","rawVisitorCookie","clientIdCookieName","readVisitorCookie","value","writeVisitorCookie","id","base"],"mappings":"AAAA,uuBAA2G,ICYrGA,EAAAA,CAAW,MAAA,CAAO,GAAA,CAAI,mBAAmB,CAAA,CAE/C,SAASC,EAAAA,CAASC,CAAAA,CAAuB,CACvC,IAAMC,CAAAA,CAASD,CAAAA,CACf,OAAQ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AaiC,CAAAA,CAAoBY,CAAAA,CAAkB,CACpF,GAAI,CACF,IAAMnB,CAAAA,CAAM1B,CAAAA,CAAI,QAAA,CACV8C,CAAAA,CACJ,CAAA,EAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-IRZJIPUF.js","sourcesContent":[null,"/**\n * Page-wide state of the automatic page views. It lives on `window`, so the\n * npm package, a second copy of it and the `analytics.js` script agree on who\n * reports a path and the history is patched once.\n */\ntype Registry = {\n /** Last path some starter reported. */\n path: string | null;\n starters: Set<() => void>;\n watching: boolean;\n};\n\nconst REGISTRY = Symbol.for(\"bitsnap.pageViews\");\n\nfunction registry(win: Window): Registry {\n const holder = win as unknown as Record<symbol, Registry | undefined>;\n return (holder[REGISTRY] ??= { path: null, starters: new Set(), watching: false });\n}\n\n/** Calls `onChange` when the path changes through `history.pushState`/`replaceState` or Back/Forward. */\nfunction watchNavigation(win: Window, onChange: () => void) {\n const check = () => {\n try {\n onChange();\n } catch {}\n };\n for (const name of [\"pushState\", \"replaceState\"] as const) {\n const original = win.history[name];\n win.history[name] = function (this: History, ...args: Parameters<History[typeof name]>) {\n const result = original.apply(this, args);\n check();\n return result;\n };\n }\n win.addEventListener(\"popstate\", check);\n}\n\n/**\n * Calls `send` for the current path and again on every path change, unless\n * another starter on the page already reported that path: the page gets one\n * `page_view` per path change however many providers, components and embeds\n * start it. Returns the function that stops this starter.\n */\nexport function startAutoPageViews(send: () => void, win: Window = window): () => void {\n try {\n const reg = registry(win);\n const starter = () => send();\n if (!reg.watching) {\n reg.watching = true;\n watchNavigation(win, () => {\n const path = win.location.pathname;\n // Nobody listening: leave the path unreported so the next starter sends it.\n if (path === reg.path || reg.starters.size === 0) return;\n reg.path = path;\n reg.starters.values().next().value?.();\n });\n }\n reg.starters.add(starter);\n const path = win.location.pathname;\n if (path !== reg.path) {\n reg.path = path;\n starter();\n }\n return () => void reg.starters.delete(starter);\n } catch {\n return () => {};\n }\n}\n\n/** Forgets the reported path and the starters (tests, hot reload). The history patch stays. */\nexport function resetAutoPageViews(win: Window = window) {\n const reg = registry(win);\n reg.path = null;\n reg.starters.clear();\n}\n","// Generated by scripts/write-version.mjs from package.json. Do not edit.\nexport const SDK_VERSION = \"1.20.0\";\n","export function randomBytes(n: number): Uint8Array {\n const bytes = new Uint8Array(n);\n const c = typeof crypto !== \"undefined\" ? crypto : undefined;\n if (c && typeof c.getRandomValues === \"function\") c.getRandomValues(bytes);\n else for (let i = 0; i < n; i++) bytes[i] = Math.floor(Math.random() * 256);\n return bytes;\n}\n","import { domainCandidates } from \"../consent/core/cookie\";\nimport { clientIdCookieName } from \"./contract\";\nimport { randomBytes } from \"./random\";\n\n/** The part of `window.BitsnapConsent` (`bitsnap-react/consent`) the tracker reads. */\nexport type ConsentLike = {\n /** Absent on a consent script older than 1.9.0, which never counts as the project's banner. */\n scope?: \"global\" | \"project\";\n projectKey?: string | null;\n get(): { c: { analytics?: boolean } } | null;\n /** Also true for a refusal made on an older banner version, which `get()` no longer returns. */\n denied?(category: \"analytics\"): boolean;\n ready?: Promise<unknown>;\n};\n\n/** Sent to the Bitsnap server on the requests that create a checkout or payment link. */\nexport const VISITOR_HEADER = \"X-Bitsnap-Visitor\";\n// 390 days, under the 13 months CNIL allows. Set once, never extended.\nconst MAX_AGE_SECONDS = 390 * 24 * 60 * 60;\nconst VISITOR_ID_RE = /^[A-Za-z0-9_-]{22}$/;\n\nexport function consentApi(win: Window): ConsentLike | undefined {\n return (win as unknown as { BitsnapConsent?: ConsentLike }).BitsnapConsent;\n}\n\nfunction readCookie(doc: Document, name: string): string | null {\n for (const part of doc.cookie.split(\";\")) {\n const index = part.indexOf(\"=\");\n if (index !== -1 && part.slice(0, index).trim() === name) return part.slice(index + 1).trim();\n }\n return null;\n}\n\n/** bitsnap.pl and its subdomains: many merchants share them, and the site-wide choice is bitsnap's own. */\nfunction isBitsnapHost(hostname: string): boolean {\n const host = hostname.toLowerCase();\n return host === \"bitsnap.pl\" || host.endsWith(\".bitsnap.pl\");\n}\n\n/**\n * Whether the page's consent banner speaks for `projectKey`: a project-scope banner of that\n * key, or a site-scope banner on a merchant's own site. On bitsnap.pl a site-scope choice is\n * bitsnap's own, so only a project-scope one counts.\n */\nexport function consentBelongsTo(win: Window, projectKey: string): boolean {\n try {\n const api = consentApi(win);\n if (!api) return false;\n if (api.scope === \"project\") return api.projectKey === projectKey;\n const onBitsnap = isBitsnapHost(win.location.hostname);\n if (api.scope === \"global\") return !onBitsnap;\n // A consent script from before the scope info: it cannot be told apart from another project's banner.\n return false;\n } catch {\n return false;\n }\n}\n\n/** `true` only while a banner that speaks for `projectKey` holds a valid choice that grants `analytics`. */\nexport function analyticsGranted(win: Window, projectKey: string): boolean {\n try {\n return consentApi(win)?.get()?.c.analytics === true && consentBelongsTo(win, projectKey);\n } catch {\n return false;\n }\n}\n\n/** 16 random bytes as 22 base64url characters. */\nexport function newVisitorId(): string {\n let binary = \"\";\n randomBytes(16).forEach((byte) => (binary += String.fromCharCode(byte)));\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** Value of the `bs_vid_<projectKey>` cookie, whatever it holds; `null` when it is absent. */\nfunction rawVisitorCookie(doc: Document, projectKey: string): string | null {\n try {\n return readCookie(doc, clientIdCookieName(projectKey));\n } catch {\n return null;\n }\n}\n\n/** The project's client id from its first-party cookie (`bs_vid_<projectKey>`), or `null` if absent or malformed. */\nexport function readVisitorCookie(doc: Document, projectKey: string): string | null {\n const value = rawVisitorCookie(doc, projectKey);\n return value !== null && VISITOR_ID_RE.test(value) ? value : null;\n}\n\n/**\n * Sets the cookie on the widest registrable domain the browser accepts\n * (shortest suffix with two labels first, so `shop.example.co.uk` skips the\n * refused `co.uk`), host-only where no domain sticks (localhost, IP hosts).\n */\nexport function writeVisitorCookie(win: Window, projectKey: string, id: string): void {\n try {\n const doc = win.document;\n const base =\n `${clientIdCookieName(projectKey)}=${id}; Max-Age=${MAX_AGE_SECONDS}; Path=/; SameSite=Lax` +\n (win.location.protocol === \"https:\" ? \"; Secure\" : \"\");\n for (const domain of domainCandidates(win.location.hostname).reverse()) {\n doc.cookie = `${base}; Domain=${domain}`;\n if (readVisitorCookie(doc, projectKey) === id) return;\n }\n doc.cookie = base;\n } catch {\n // cookies blocked (sandboxed frame)\n }\n}\n\n/** Expires the cookie on the host and on every parent domain it may have been set on. */\nexport function deleteVisitorCookie(win: Window, projectKey: string): void {\n try {\n const doc = win.document;\n // Present under any value: a malformed one must go too.\n if (rawVisitorCookie(doc, projectKey) === null) return;\n const base =\n `${clientIdCookieName(projectKey)}=; Max-Age=0; Path=/; SameSite=Lax` +\n (win.location.protocol === \"https:\" ? \"; Secure\" : \"\");\n doc.cookie = base;\n for (const domain of domainCandidates(win.location.hostname)) doc.cookie = `${base}; Domain=${domain}`;\n } catch {\n // best effort\n }\n}\n\n/**\n * The project's client id to send, or `null`: analytics consent is granted,\n * Global Privacy Control is off, the browser is not automated and the cookie exists.\n */\nexport function readVisitorId(win: Window, projectKey: string): string | null {\n try {\n const nav = win.navigator as { globalPrivacyControl?: boolean; webdriver?: boolean } | undefined;\n if (nav?.globalPrivacyControl === true || nav?.webdriver === true) return null;\n return analyticsGranted(win, projectKey) ? readVisitorCookie(win.document, projectKey) : null;\n } catch {\n return null;\n }\n}\n"]}
|
package/dist/chunk-KDL35KEI.js
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var _chunkYPA6MMGJjs = require('./chunk-YPA6MMGJ.js');var _chunkMDAFPGPAjs = require('./chunk-MDAFPGPA.js');var _chunkIRZJIPUFjs = require('./chunk-IRZJIPUF.js');var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var a=_react.createContext.call(void 0, _chunkMDAFPGPAjs.b.call(void 0, )),u= exports.a =({children:c,analytics:s})=>{let n=_chunkMDAFPGPAjs.b.call(void 0, ),l=_chunkIRZJIPUFjs.n.call(void 0, n.projectID,s,"panel");return _jsxruntime.jsx.call(void 0, _chunkYPA6MMGJjs.j,{children:_jsxruntime.jsx.call(void 0, a.Provider,{value:{...n},children:_jsxruntime.jsx.call(void 0, _chunkIRZJIPUFjs.l,{value:l,children:_jsxruntime.jsx.call(void 0, "div",{className:"bitsnap-react",children:c})})})})},C= exports.b =()=>_react.useContext.call(void 0, a);exports.a = u; exports.b = C;
|
|
2
|
-
//# sourceMappingURL=chunk-KDL35KEI.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-KDL35KEI.js","../src/panel/PanelProvider.tsx"],"names":["PanelContext","createContext","getPanelConfig","PanelProvider","children","analytics","config","instrument","useInstrument","jsx","RpcProvider","InstrumentProvider","usePanelConfig","useContext"],"mappings":"AAAA,+HAAuC,sDAAwC,sDAA+C,8BCApF,+CA2BhC,IAlBJA,CAAAA,CAAeC,kCAAAA,gCAA2BC,CAAgB,CAAA,CAEnDC,CAAAA,aASR,CAAC,CAAE,QAAA,CAAAC,CAAAA,CAAU,SAAA,CAAAC,CAAU,CAAA,CAAA,EAAM,CAChC,IAAMC,CAAAA,CAASJ,gCAAAA,CAAe,CACxBK,CAAAA,CAAaC,gCAAAA,CAAcF,CAAO,SAAA,CAAWD,CAAAA,CAAW,OAAO,CAAA,CACrE,OACEI,6BAAAA,kBAACC,CAAA,CACC,QAAA,CAAAD,6BAAAA,CAACT,CAAa,QAAA,CAAb,CAAsB,KAAA,CAAO,CAAE,GAAGM,CAAO,CAAA,CACxC,QAAA,CAAAG,6BAAAA,kBAACE,CAAA,CAAmB,KAAA,CAAOJ,CAAAA,CACzB,QAAA,CAAAE,6BAAAA,KAAC,CAAA,CAAI,SAAA,CAAU,eAAA,CAAiB,QAAA,CAAAL,CAAAA,CAAS,CAAA,CAC3C,CAAA,CACF,CAAA,CACF,CAEJ,CAAA,CAEaQ,CAAAA,aAAiB,CAAA,CAAA,EAAMC,+BAAAA,CAAuB,CAAA,CAAA,6BAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-KDL35KEI.js","sourcesContent":[null,"import { createContext, useContext } from \"react\";\nimport {\n InstrumentProvider,\n useInstrument,\n type AnalyticsOption,\n} from \"../analytics/instrument\";\nimport { RpcProvider } from \"../rpc-provider\";\nimport { getPanelConfig, type PanelConfig } from \"./config\";\n\nconst PanelContext = createContext<PanelConfig>(getPanelConfig());\n\nexport const PanelProvider: React.FC<{\n children: React.ReactNode;\n /**\n * Usage statistics for your Bitsnap dashboard (panel logins, orders viewed,\n * downloads, course progress). On by default; `false` turns it off. An\n * object lets you forward every event: `{ onEvent }`. Nothing is stored on\n * the visitor's device.\n */\n analytics?: AnalyticsOption;\n}> = ({ children, analytics }) => {\n const config = getPanelConfig();\n const instrument = useInstrument(config.projectID, analytics, \"panel\");\n return (\n <RpcProvider>\n <PanelContext.Provider value={{ ...config }}>\n <InstrumentProvider value={instrument}>\n <div className=\"bitsnap-react\">{children}</div>\n </InstrumentProvider>\n </PanelContext.Provider>\n </RpcProvider>\n );\n};\n\nexport const usePanelConfig = () => useContext(PanelContext);\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-KZWCVKLU.js","../src/panel/components/PanelLogin.tsx","../src/ui/card.tsx","../src/ui/email-code-login/EmailCodeLoginForm.tsx","../src/lib/render.text.tsx","../src/panel/audio-player/media.session.coordinator.ts","../src/panel/audio-player/AudioPlayer.tsx"],"names":["Card","className","props","jsx","cn","CardHeader","CardTitle","CardDescription","CardContent","MUTED","DARK_FIELD","EMAIL_FAILURES","LINK","EmailCodeLoginForm","login","texts","allowHaveCode","emailPlaceholder","emailInputId","codeInputId","buttonClassName","children","uid","useId","emailId"],"mappings":"AAAA,ylCAAgN,sDAAyC,sDAA+F,sDAAyC,sDAAyF,sDAAiF,sDAA+E,sDAAyE,sDA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AA,CAAiB,IAAI,GAAA,CAAI,CAAC,cAAA,CAAgB,eAAA,CAAiB,qBAAqB,CAAC,CAAA,CACjFC,EAAAA,CACJ,sNAAA,CAOK,SAASC,EAAAA,CAAmB,CACjC,KAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,aAAA,CAAAC,CAAAA,CAAgB,CAAA,CAAA,CAChB,gBAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,SAAA,CAAAlB,CAAAA,CACA,eAAA,CAAAmB,CAAAA,CACA,QAAA,CAAAC,CACF,CAAA,CAA4B,CAC1B,IAAMC,CAAAA,CAAMC,2BAAAA,CAAM,CACZC,CAAAA,kBAAUN,CAAAA,SAAgB,CAAA,EAAA;ACGlB,QAAA;ACMZ,YAAA;ACwzBQ","file":"/home/emems/.t3/worktrees/bitsnap-react/chat-free-pwyw/dist/chunk-KZWCVKLU.js","sourcesContent":[null,"import { useAutoAnimate } from \"@formkit/auto-animate/react\";\nimport { useEffect, useMemo, useRef, useState, type CSSProperties } from \"react\";\nimport { TurnstileChallenge } from \"../../captcha/TurnstileChallenge\";\nimport {\n InstrumentProvider,\n useInstrument,\n useInstrumentContext,\n type AnalyticsOption,\n} from \"../../analytics/instrument\";\nimport { getLocale } from \"../../components/checkout/locale\";\nimport { rpcProvider, useMutation } from \"../../rpc-provider\";\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from \"../../ui/card\";\nimport { kindFromRpcError } from \"../../ui/email-code-login/errors\";\nimport {\n LoginBrandLogo,\n type LoginLogoOptions,\n} from \"../../ui/email-code-login/LoginBrandLogo\";\nimport { EmailCodeLoginForm } from \"../../ui/email-code-login/EmailCodeLoginForm\";\nimport { pendingLoginKey } from \"../../ui/email-code-login/pending\";\nimport {\n useEmailCodeLogin,\n type EmailCodeAdapter,\n} from \"../../ui/email-code-login/useEmailCodeLogin\";\nimport {\n getAllowedReturnOrigins,\n setAllowedReturnOrigins,\n} from \"../config\";\nimport { panelFailureKind } from \"../login-adapter\";\nimport { resolvePanelLoginTexts, type PanelLoginTexts } from \"../login-texts\";\nimport { usePanelConfig } from \"../PanelProvider\";\nimport type { PanelLoginProps } from \"../types\";\nimport {\n buildAccessTokenRedirect,\n getReturnURLFromSearch,\n persistReturnURL,\n readPersistedReturnURL,\n} from \"../return-url\";\nimport { getPanelSession, savePanelSession } from \"../session-storage\";\n\nif (typeof window !== \"undefined\") {\n const currentOrigin = window.location.origin;\n const knownSiblings = [\n currentOrigin,\n \"https://bitsnap.pl\",\n \"https://kursy.bitsnap.pl\",\n ];\n if (getAllowedReturnOrigins().length === 0) {\n setAllowedReturnOrigins(Array.from(new Set(knownSiblings)));\n }\n}\n\n\n/** Props of {@link PanelLogin}; `PanelLoginProps` of the package is a superset. */\nexport type PanelLoginComponentProps = Pick<\n PanelLoginProps,\n \"analytics\" | \"texts\" | \"locale\" | \"showLogo\" | \"logoUrl\" | \"logoDarkUrl\"\n>;\n\ntype PanelLoginResult = { accessToken: string };\n\nconst PanelLoginForm = ({\n texts,\n projectID,\n host,\n locale,\n logo,\n}: {\n texts: PanelLoginTexts;\n projectID?: string;\n host?: string;\n locale?: string;\n logo: LoginLogoOptions;\n}) => {\n const [challengeVisible, setChallengeVisible] = useState(false);\n const challengeWaiter = useRef<((token: string | null) => void) | undefined>(undefined);\n const captchaToken = useRef(\"\");\n const beforeSend = useMemo(() => () => new Promise<boolean>((resolve) => {\n setChallengeVisible(true);\n const timer = window.setTimeout(() => { challengeWaiter.current = undefined; setChallengeVisible(false); resolve(false); }, 5 * 60 * 1000);\n challengeWaiter.current = (token) => { window.clearTimeout(timer); challengeWaiter.current = undefined; setChallengeVisible(false); captchaToken.current = token ?? \"\"; resolve(token !== null); };\n }), []);\n const instrument = useInstrumentContext();\n const { mutateAsync: loginUserAsync } = useMutation(\n rpcProvider.publicApi.userPanelLogin,\n );\n const { mutateAsync: verifyCodeAsync } = useMutation(\n rpcProvider.publicApi.userPanelLoginWithCode,\n );\n\n const adapter = useMemo<EmailCodeAdapter<PanelLoginResult>>(\n () => ({\n async send(email) {\n try {\n const response = await loginUserAsync({ email, turnstileToken: captchaToken.current });\n captchaToken.current = \"\";\n if (response.result.case === \"success\") {\n return {\n ok: true,\n retryIn: response.result.value.retryIn || undefined,\n challengeId: response.result.value.challengeId || undefined,\n };\n }\n return {\n ok: false,\n kind: panelFailureKind(\n response.result.case === \"failure\" ? response.result.value : 0,\n ),\n };\n } catch (cause) {\n return { ok: false, kind: kindFromRpcError(cause), cause };\n }\n },\n async verify({ email, code, challengeId }) {\n try {\n const response = await verifyCodeAsync({\n code: parseInt(code, 10),\n email,\n challengeId,\n });\n if (response.result.case === \"accessToken\" && response.result.value) {\n return { ok: true, value: { accessToken: response.result.value } };\n }\n return {\n ok: false,\n kind: panelFailureKind(\n response.result.case === \"failure\" ? response.result.value : 0,\n ),\n };\n } catch (cause) {\n return { ok: false, kind: kindFromRpcError(cause), cause };\n }\n },\n }),\n [loginUserAsync, verifyCodeAsync],\n );\n\n const login = useEmailCodeLogin<PanelLoginResult>({\n adapter,\n texts,\n beforeSend,\n storageKey: pendingLoginKey(\"panel\", projectID, host),\n onVerified: ({ accessToken }, email) => {\n instrument.track(\"panel_login\", {});\n savePanelSession(projectID, accessToken, email, host);\n const returnURL =\n typeof window !== \"undefined\" ? readPersistedReturnURL() : null;\n setTimeout(() => {\n if (returnURL) {\n window.location.href = buildAccessTokenRedirect(returnURL, accessToken);\n return;\n }\n window.location.reload();\n }, 100);\n },\n });\n\n const onCodeStep = login.step === \"code\";\n const title = onCodeStep && !login.needsEmail ? texts.codeTitle : texts.title;\n const description =\n onCodeStep && !login.needsEmail ? texts.codeDescription : texts.description;\n\n return (\n // Top-aligned: a vertically centred card moved when the step changed height.\n <main className=\"mx-auto flex w-full max-w-sm flex-1 flex-col justify-start pt-4 sm:pt-[12vh]\">\n <Card>\n <LoginBrandLogo\n projectId={projectID}\n locale={locale}\n className=\"px-4 sm:px-6\"\n {...logo}\n />\n <CardHeader className=\"px-4 sm:px-6\">\n <CardTitle role=\"heading\" aria-level={1} className=\"text-2xl\">\n {title}\n </CardTitle>\n <CardDescription>{description}</CardDescription>\n </CardHeader>\n <CardContent className=\"px-4 sm:px-6\">\n <EmailCodeLoginForm\n login={login}\n texts={texts}\n emailInputId=\"email\"\n codeInputId=\"verify-code\"\n />\n {challengeVisible && <TurnstileChallenge action=\"panel_login\" locale={locale} onToken={(token) => challengeWaiter.current?.(token)} onFailure={() => challengeWaiter.current?.(null)} />}\n </CardContent>\n </Card>\n </main>\n );\n};\n\nconst PanelLoginComponentWrapper = ({\n analytics,\n texts: textOverrides,\n locale,\n showLogo,\n logoUrl,\n logoDarkUrl,\n}: PanelLoginComponentProps) => {\n const { theme, allowedReturnOrigins, projectID, host } = usePanelConfig();\n const instrument = useInstrument(projectID, analytics, \"panel\");\n const texts = useMemo(\n () => resolvePanelLoginTexts(locale ?? getLocale(), textOverrides),\n [locale, textOverrides],\n );\n\n const styles = {\n \"--button-background-color\": theme?.colors?.brand ?? \"#FFFFFF\",\n \"--button-background-color-dark\": theme?.colors?.brandDark ?? \"#000000\",\n \"--button-text-color\": theme?.colors?.brandDark ?? \"#000000\",\n \"--button-text-color-dark\": theme?.colors?.brand ?? \"#FFFFFF\",\n } as CSSProperties;\n\n const [parent] = useAutoAnimate({\n duration: 300,\n easing: \"ease-in-out\",\n disrespectUserMotionPreference: false,\n });\n\n // Already signed in: leave the login page. Declared before the return URL\n // effect below, so that one (a token redirect) wins when both apply.\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n if (getPanelSession(projectID, host) != null) {\n window.location.href = window.location.href.replaceAll(\"login\", \"\");\n }\n }, [projectID, host]);\n\n useEffect(() => {\n if (typeof window === \"undefined\") return;\n if (window.parent !== window) return;\n\n const queryReturnURL = getReturnURLFromSearch(window.location.search);\n if (queryReturnURL) {\n persistReturnURL(queryReturnURL);\n }\n\n const returnURL = queryReturnURL ?? readPersistedReturnURL();\n if (!returnURL) return;\n\n const existingToken = getPanelSession(projectID, host);\n if (!existingToken) return;\n\n window.location.href = buildAccessTokenRedirect(returnURL, existingToken);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [allowedReturnOrigins, projectID, host]);\n\n return (\n <InstrumentProvider value={instrument}>\n <div className=\"bg-white text-black dark:bg-black dark:text-white\">\n <div\n className=\"font-inter flex min-h-screen w-full flex-col p-4\"\n style={styles}\n ref={parent}\n >\n <PanelLoginForm\n texts={texts}\n projectID={projectID}\n host={host}\n locale={locale}\n logo={{\n showLogo,\n logoUrl: logoUrl ?? theme?.logoURL,\n logoDarkUrl: logoDarkUrl ?? theme?.logoDarkURL,\n }}\n />\n </div>\n </div>\n </InstrumentProvider>\n );\n};\n\nexport const PanelLogin = (props: PanelLoginComponentProps = {}) => {\n return <PanelLoginComponentWrapper {...props} />;\n};\n","import * as React from \"react\"\n\nimport { cn } from \"@/src/lib/utils\"\n\nfunction Card({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card\"\n className={cn(\n \"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\"leading-none font-semibold\", className)}\n {...props}\n />\n )\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-muted-foreground text-sm\", className)}\n {...props}\n />\n )\n}\n\nfunction CardAction({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-action\"\n className={cn(\n \"col-start-2 row-span-2 row-start-1 self-start justify-self-end\",\n className\n )}\n {...props}\n />\n )\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"px-6\", className)}\n {...props}\n />\n )\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\"flex items-center px-6 [.border-t]:pt-6\", className)}\n {...props}\n />\n )\n}\n\nexport {\n Card,\n CardHeader,\n CardFooter,\n CardTitle,\n CardAction,\n CardDescription,\n CardContent,\n}\n","import { CircleCheck } from \"lucide-react\";\nimport { useId, type FormEvent, type ReactNode } from \"react\";\nimport { cn } from \"@/src/lib/utils\";\nimport { Button } from \"../button\";\nimport { Input } from \"../input\";\nimport { Label } from \"../label\";\nimport { Spinner } from \"../spinner\";\nimport { OtpCodeField } from \"./OtpCodeField\";\nimport { fillText, type EmailCodeTexts } from \"./texts\";\nimport { type EmailCodeLogin } from \"./useEmailCodeLogin\";\n\nexport type EmailCodeLoginFormProps = {\n login: EmailCodeLogin;\n texts: EmailCodeTexts;\n /** Offers \"I already have a code\" under the e-mail step. */\n allowHaveCode?: boolean;\n /** Overrides the e-mail input placeholder. */\n emailPlaceholder?: string;\n /** `id` of the e-mail input; unique per instance by default. */\n emailInputId?: string;\n /** `id` of the code input; unique per instance by default. */\n codeInputId?: string;\n className?: string;\n /** Classes of the two primary buttons (brand colors). */\n buttonClassName?: string;\n /** Shown above the fields of the code step, after the \"sent to\" line. */\n children?: ReactNode;\n};\n\nconst MUTED = \"text-muted-foreground text-xs leading-5\";\n/** Borders of the dark theme: the `input` token is nearly the card colour. */\nconst DARK_FIELD =\n \"dark:border-foreground/30 dark:focus-visible:border-foreground/70 dark:focus-visible:ring-foreground/25 dark:aria-invalid:border-destructive-foreground dark:aria-invalid:ring-destructive-foreground/30\";\n/** Failures about the address itself; a throttled or failed send is not. */\nconst EMAIL_FAILURES = new Set([\"invalidEmail\", \"emailNotFound\", \"deliveryUnavailable\"]);\nconst LINK =\n \"inline-flex min-h-11 items-center px-1 text-sm underline underline-offset-4 hover:no-underline focus-visible:ring-[3px] focus-visible:ring-ring/50 rounded-sm outline-none disabled:opacity-50 disabled:no-underline\";\n\n/**\n * The two steps of the shared e-mail-code login. Markup only: all state comes\n * from {@link useEmailCodeLogin}. The surface wraps it in its own card or\n * dialog and renders the titles.\n */\nexport function EmailCodeLoginForm({\n login,\n texts,\n allowHaveCode = true,\n emailPlaceholder,\n emailInputId,\n codeInputId,\n className,\n buttonClassName,\n children,\n}: EmailCodeLoginFormProps) {\n const uid = useId();\n const emailId = emailInputId ?? `${uid}-email`;\n const codeId = codeInputId ?? `${uid}-code`;\n const noticeId = `${uid}-notice`;\n const hintId = `${uid}-hint`;\n\n const { notice } = login;\n const isError = notice?.kind === \"error\";\n const sending = login.busy === \"send\";\n const verifying = login.busy === \"verify\";\n const resending = login.busy === \"resend\";\n const buttonBase = cn(\"h-11 w-full\", buttonClassName);\n\n // Both live regions stay mounted (empty) so that a screen reader has\n // registered them before a message is put in; only their text changes.\n // The area reserves two lines, so a longer message does not push the buttons.\n const success = notice?.kind === \"success\";\n const noticeArea = (\n <div id={noticeId} className=\"min-h-10 text-sm leading-5\">\n <p\n role=\"alert\"\n className=\"font-medium text-red-700 dark:text-red-400\"\n >\n {isError ? notice.text : null}\n </p>\n <p\n role=\"status\"\n className={cn(\n \"flex items-start gap-1.5\",\n success\n ? \"font-medium text-emerald-700 dark:text-emerald-400\"\n : \"text-foreground\",\n )}\n >\n {success && <CircleCheck aria-hidden className=\"mt-0.5 size-4 shrink-0\" />}\n <span>{notice != null && !isError ? notice.text : null}</span>\n </p>\n </div>\n );\n const emailInvalid =\n isError &&\n login.step === \"email\" &&\n (notice.failure == null || EMAIL_FAILURES.has(notice.failure));\n\n const announcer = (\n <p className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n {login.announcement}\n </p>\n );\n\n const emailField = (\n <div className=\"grid gap-2\">\n <Label htmlFor={emailId}>{texts.emailLabel}</Label>\n <Input\n id={emailId}\n ref={login.emailRef}\n name=\"email\"\n type=\"email\"\n autoComplete=\"email\"\n inputMode=\"email\"\n autoCapitalize=\"none\"\n autoCorrect=\"off\"\n spellCheck={false}\n autoFocus\n required\n className={cn(\n \"h-11 text-base disabled:opacity-100 disabled:text-foreground/70\",\n DARK_FIELD,\n )}\n placeholder={emailPlaceholder ?? texts.emailPlaceholder}\n value={login.email}\n disabled={login.isBusy}\n aria-invalid={emailInvalid ? true : undefined}\n aria-describedby={noticeId}\n onChange={(event) => login.setEmail(event.target.value)}\n />\n </div>\n );\n\n if (login.step === \"email\") {\n return (\n <form\n noValidate\n className={cn(\"flex flex-col gap-4\", className)}\n onSubmit={(event: FormEvent) => {\n event.preventDefault();\n void login.sendCode();\n }}\n >\n {announcer}\n {emailField}\n {noticeArea}\n <Button\n type=\"submit\"\n disabled={login.isBusy}\n aria-busy={sending}\n className={buttonBase}\n >\n {sending && <Spinner aria-hidden />}\n {sending ? texts.sending : texts.sendCode}\n </Button>\n {allowHaveCode && (\n <p className=\"flex flex-wrap items-center justify-center text-center text-sm\">\n {texts.haveCodePrompt !== \"\" && <span>{texts.haveCodePrompt}</span>}\n <button\n type=\"button\"\n className={LINK}\n disabled={login.isBusy}\n onClick={login.haveCode}\n >\n {texts.haveCode}\n </button>\n </p>\n )}\n </form>\n );\n }\n\n const [before, after] = texts.codeSentTo.split(\"{email}\");\n const dead = login.dead != null;\n const resendLabel = dead\n ? texts.resendNew\n : login.secondsLeft > 0\n ? fillText(texts.resendIn, { seconds: login.secondsLeft })\n : texts.resend;\n\n return (\n <form\n noValidate\n className={cn(\"flex flex-col gap-4\", className)}\n onSubmit={(event: FormEvent) => {\n event.preventDefault();\n void login.submitCode();\n }}\n >\n {announcer}\n {login.needsEmail ? (\n emailField\n ) : (\n <div className=\"flex flex-wrap items-center justify-between gap-x-2\">\n {/* The address moves to its own line before it is cut; the word\n joiner keeps the full stop with it. */}\n <p className=\"min-w-0 flex-[1_1_14rem] text-sm leading-5 break-words\">\n {before}\n <strong className=\"font-semibold\">{login.email}</strong>\n {\"\\u2060\"}\n {after}\n </p>\n <button\n type=\"button\"\n className={cn(LINK, \"-ml-1 shrink-0\")}\n disabled={login.isBusy}\n onClick={login.changeEmail}\n >\n {texts.changeEmail}\n </button>\n </div>\n )}\n {children}\n <div className=\"grid gap-2\">\n <Label htmlFor={codeId}>{texts.codeLabel}</Label>\n <OtpCodeField\n id={codeId}\n name=\"code\"\n inputRef={login.codeRef}\n value={login.code}\n onChange={login.setCode}\n onComplete={(value) => void login.submitCode(value)}\n disabled={login.isBusy || dead}\n invalid={isError && !login.needsEmail}\n aria-describedby={`${noticeId} ${hintId}`}\n />\n <p id={hintId} className={MUTED}>\n {texts.validity} {texts.spamHint}\n </p>\n </div>\n {noticeArea}\n <Button\n type=\"submit\"\n disabled={login.isBusy || dead}\n aria-busy={verifying}\n className={buttonBase}\n >\n {verifying && <Spinner aria-hidden />}\n {verifying ? texts.verifying : texts.verify}\n </Button>\n {login.needsEmail ? (\n <div className=\"flex justify-center\">\n <button\n type=\"button\"\n className={LINK}\n disabled={login.isBusy}\n onClick={login.changeEmail}\n >\n {texts.noCode}\n </button>\n </div>\n ) : (\n <Button\n type=\"button\"\n variant={dead ? \"default\" : \"outline\"}\n disabled={login.isBusy || (!dead && login.secondsLeft > 0)}\n aria-busy={resending}\n className={dead ? buttonBase : \"h-11 w-full\"}\n onClick={() => void login.resend()}\n >\n {resending && <Spinner aria-hidden />}\n {resendLabel}\n </Button>\n )}\n </form>\n );\n}\n","const URL_REGEX =\n /https?:\\/\\/(www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&//=]*)/g;\n\ntype Replacements = {\n url: string;\n startIndex: number;\n endIndex: number;\n replacementText?: string;\n};\n\nconst findURLIndices = (text: string) => {\n const matches = [...text.matchAll(URL_REGEX)];\n return matches.map(\n (match) =>\n ({\n url: match[0],\n startIndex: match.index,\n endIndex: match.index + match[0].length - 1,\n }) as Replacements,\n );\n};\n\nconst replaceTextByIndices = (\n originalText: string,\n replacements: Replacements[],\n) => {\n let result = \"\";\n let lastIndex = 0;\n\n // Sort replacements by startIndex to handle them in order\n replacements.sort((a, b) => a.startIndex - b.startIndex);\n\n for (const { startIndex, endIndex, replacementText } of replacements) {\n // Append text before the current replacement\n result += originalText.slice(lastIndex, startIndex);\n // Append the replacement text\n result += replacementText;\n // Update lastIndex to after the replaced segment\n lastIndex = endIndex + 1;\n }\n\n // Append any remaining text after the last replacement\n result += originalText.slice(lastIndex);\n\n return result;\n};\n\nexport const renderText = (txt: string) => {\n const urlIndices = findURLIndices(txt);\n\n return (\n <p\n dangerouslySetInnerHTML={{\n __html: replaceTextByIndices(\n txt,\n urlIndices.map((el) => {\n el[\"replacementText\"] =\n `<a key=${el.url} href=${el.url} style=\"text-decoration: underline;\" target=\"_blank\">\n ${el.url}\n </a>`;\n return el;\n }),\n ),\n }}\n ></p>\n );\n};\n","/** Skip length of the player buttons and of the lock-screen skip handlers. */\nexport const SEEK_STEP_SECONDS = 10;\n\n/** Under this position \"previous track\" restarts the chapter instead of going back. */\nexport const PREVIOUS_TRACK_RESTART_SECONDS = 3;\n\nexport type MediaSessionArtwork = {\n src: string;\n sizes?: string;\n type?: string;\n};\n\nexport type MediaSessionMetadata = {\n title: string;\n album?: string;\n artist?: string;\n artwork?: string | MediaSessionArtwork | (string | MediaSessionArtwork)[];\n};\n\nconst MIME_BY_EXTENSION: Record<string, string> = {\n png: \"image/png\",\n jpg: \"image/jpeg\",\n jpeg: \"image/jpeg\",\n webp: \"image/webp\",\n gif: \"image/gif\",\n avif: \"image/avif\",\n svg: \"image/svg+xml\",\n};\n\n/** Lock-screen artwork size we declare; the player does not decode the image. */\nconst ARTWORK_SIZES = \"512x512\";\n\nfunction mediaSessionAvailable(): boolean {\n return (\n typeof navigator != \"undefined\" &&\n typeof navigator.mediaSession != \"undefined\"\n );\n}\n\n/**\n * Turns an image URL into a media-session artwork entry. The `type` comes from\n * the file extension and is omitted when the extension is unknown, so the\n * browser does not get a wrong MIME type.\n */\nexport function mediaSessionArtworkFromUrl(url: string): MediaSessionArtwork {\n if (typeof url != \"string\" || url.length === 0) {\n return { src: url, sizes: ARTWORK_SIZES };\n }\n const withoutQuery = url.split(/[?#]/)[0];\n const extension = withoutQuery.includes(\".\")\n ? withoutQuery.slice(withoutQuery.lastIndexOf(\".\") + 1).toLowerCase()\n : \"\";\n const type = MIME_BY_EXTENSION[extension];\n const artwork: MediaSessionArtwork = { src: url, sizes: ARTWORK_SIZES };\n if (type != null) {\n artwork.type = type;\n }\n return artwork;\n}\n\nfunction normalizeArtwork(\n artwork: MediaSessionMetadata[\"artwork\"],\n): MediaSessionArtwork[] | undefined {\n if (artwork == null) {\n return undefined;\n }\n const entries = Array.isArray(artwork) ? artwork : [artwork];\n const normalized: MediaSessionArtwork[] = [];\n for (const entry of entries) {\n if (typeof entry === \"string\") {\n if (entry.length > 0) {\n normalized.push(mediaSessionArtworkFromUrl(entry));\n }\n continue;\n }\n if (entry != null && entry.src.length > 0) {\n normalized.push({\n src: entry.src,\n sizes: entry.sizes ?? ARTWORK_SIZES,\n ...(entry.type != null ? { type: entry.type } : {}),\n });\n }\n }\n return normalized.length > 0 ? normalized : undefined;\n}\n\nexport function mediaSessionSetMetadata(metadata: MediaSessionMetadata) {\n if (\n !mediaSessionAvailable() ||\n typeof MediaMetadata == \"undefined\"\n ) {\n return;\n }\n navigator.mediaSession.metadata = new MediaMetadata({\n title: metadata.title,\n album: metadata.album,\n artist: metadata.artist,\n artwork: normalizeArtwork(metadata.artwork),\n });\n}\n\nexport function mediaSessionPlay() {\n if (!mediaSessionAvailable()) return;\n navigator.mediaSession.playbackState = \"playing\";\n}\n\nexport function mediaSessionPause() {\n if (!mediaSessionAvailable()) return;\n navigator.mediaSession.playbackState = \"paused\";\n}\n\n/**\n * Reports duration, position and the real playback rate to the lock screen.\n * `setPositionState` throws on values it does not accept (no duration yet,\n * position past the end), so those calls are skipped or clamped.\n */\nexport function mediaSessionUpdateDurationAndPosition(\n duration: number | undefined,\n currentTime: number | undefined,\n playbackRate = 1,\n) {\n if (!mediaSessionAvailable()) return;\n if (duration == null || !Number.isFinite(duration) || duration <= 0) {\n return;\n }\n if (currentTime != null && isNaN(currentTime)) {\n return;\n }\n const position = Math.min(Math.max(currentTime ?? 0, 0), duration);\n const rate =\n Number.isFinite(playbackRate) && playbackRate > 0 ? playbackRate : 1;\n try {\n navigator.mediaSession.setPositionState({\n playbackRate: rate,\n duration,\n position,\n });\n } catch (e) {\n // Older browsers reject some combinations; the lock screen just keeps the\n // previous state.\n }\n}\n\nconst MEDIA_SESSION_ACTIONS: MediaSessionAction[] = [\n \"play\",\n \"pause\",\n \"stop\",\n \"seekbackward\",\n \"seekforward\",\n \"seekto\",\n \"previoustrack\",\n \"nexttrack\",\n];\n\nexport function startMediaSessionCoordinator(args: {\n title: string;\n album?: string;\n artist?: string;\n artwork?: MediaSessionMetadata[\"artwork\"];\n\n action: (details: MediaSessionActionDetails) => void;\n}) {\n if (!mediaSessionAvailable()) return;\n\n mediaSessionSetMetadata({\n title: args.title,\n album: args.album,\n artist: args.artist,\n artwork: args.artwork,\n });\n\n for (const action of MEDIA_SESSION_ACTIONS) {\n try {\n navigator.mediaSession.setActionHandler(action, (details) => {\n args.action(details);\n });\n } catch (e) {\n // The browser does not support this action (e.g. nexttrack).\n }\n }\n}\n\nexport function stopMediaSessionCoordinator() {\n if (!mediaSessionAvailable()) return;\n navigator.mediaSession.metadata = null;\n for (const action of MEDIA_SESSION_ACTIONS) {\n try {\n navigator.mediaSession.setActionHandler(action, null);\n } catch (e) {\n // Unsupported action; nothing to clear.\n }\n }\n}\n","import Hls from \"hls.js\";\nimport { Pause, Play, SkipBack, SkipForward } from \"lucide-react\";\nimport {\n forwardRef,\n useEffect,\n useImperativeHandle,\n useRef,\n useState,\n type CSSProperties,\n} from \"react\";\nimport { cn } from \"../../lib/utils\";\nimport { Button } from \"../../ui/button\";\nimport LoadingIndicator from \"../LoadingIndicator\";\nimport {\n createHlsSource,\n playerErrorFromMediaError,\n prefersNativeHls,\n type HlsSource,\n type PlayerError,\n} from \"./hls-engine\";\nimport {\n PREVIOUS_TRACK_RESTART_SECONDS,\n SEEK_STEP_SECONDS,\n mediaSessionPause,\n mediaSessionPlay,\n mediaSessionSetMetadata,\n mediaSessionUpdateDurationAndPosition,\n startMediaSessionCoordinator,\n stopMediaSessionCoordinator,\n} from \"./media.session.coordinator\";\n\nimport \"./audio-player.css\";\nimport { useAudioTexts, formatTime } from \"./texts\";\nimport { playerStorage, SPEED_KEY, SPEEDS } from \"./storage\";\n\nexport type ChapterWithPublicUrl = {\n id: string;\n multimediaId?: string;\n name: string;\n description?: string;\n publicUrl: string;\n downloadableUrl?: string;\n duration?: number;\n};\n\n/** What the player could not play; `status` is the HTTP status when known. */\nexport type AudioPlayerError = PlayerError;\n\nexport type AudioPlayerMethods = {\n selectChapter: (chapter: ChapterWithPublicUrl) => void;\n /** Loads the current chapter again after an error, keeping the position. */\n retry: () => void;\n /** The error currently shown, if any. */\n getError: () => AudioPlayerError | null;\n};\n\ntype AudioPlayerProps = {\n locale?: string;\n chapters: ChapterWithPublicUrl[];\n styles: CSSProperties;\n updateCurrentTime?: (currentTime: number) => void;\n\n title?: string;\n imageURL?: string;\n /** Hide the repeated visual heading when the desktop details show the cover beside it. */\n coverShownBeside?: boolean;\n /** Book author, used as the lock-screen artist. */\n author?: string;\n\n setCurrentTimeHandler?: (seekTo: (second: number) => void) => void;\n uniqueProductID: string;\n\n onChapterChange?: (chapter: ChapterWithPublicUrl) => void;\n /** A fatal playback error the player could not recover from. */\n onError?: (error: AudioPlayerError) => void;\n /** The signed URL returned 401/403; the owner should refetch the chapters. */\n onExpiredUrl?: () => void;\n /** The last chapter ended. */\n onFinished?: () => void;\n};\n\nconst AudioPlayer = forwardRef<AudioPlayerMethods, AudioPlayerProps>(\n (\n {\n chapters,\n locale,\n styles,\n updateCurrentTime,\n setCurrentTimeHandler,\n title,\n imageURL,\n coverShownBeside,\n author,\n uniqueProductID,\n onChapterChange,\n onError,\n onExpiredUrl,\n onFinished,\n },\n ref,\n ) => {\n const t = useAudioTexts(locale);\n const [speed, setSpeed] = useState(1);\n const speedRef = useRef(1);\n const [chapterID, setChapterID] = useState<string>();\n const [sleepMode, setSleepMode] = useState(\"off\");\n const [sleepRemaining, setSleepRemaining] = useState(0);\n const sleepRef = useRef<{ mode: string; deadline: number }>({\n mode: \"off\",\n deadline: 0,\n });\n\n function cancelSleep() {\n sleepRef.current = { mode: \"off\", deadline: 0 };\n setSleepMode(\"off\");\n setSleepRemaining(0);\n }\n function changeSleep(mode: string) {\n const seconds = Number(mode) * 60;\n sleepRef.current = {\n mode,\n deadline: Number.isFinite(seconds) ? Date.now() + seconds * 1000 : 0,\n };\n setSleepMode(mode);\n setSleepRemaining(Number.isFinite(seconds) ? seconds : 0);\n }\n function changeSpeed(rate: number) {\n if (!SPEEDS.includes(rate)) return;\n setSpeed(rate);\n speedRef.current = rate;\n playerStorage.set(SPEED_KEY, String(rate));\n if (videoRef.current) videoRef.current.playbackRate = rate;\n updatePlayerDetails();\n }\n useEffect(() => {\n const saved = Number(playerStorage.get(SPEED_KEY));\n if (SPEEDS.includes(saved)) changeSpeed(saved);\n const timer = setInterval(() => {\n const { mode, deadline } = sleepRef.current;\n if (mode === \"off\" || mode === \"chapter\") return;\n const remaining = Math.max(\n 0,\n Math.ceil((deadline - Date.now()) / 1000),\n );\n setSleepRemaining(remaining);\n if (remaining === 0) {\n playWhenReadyRef.current = false;\n pause();\n cancelSleep();\n }\n }, 1000);\n return () => clearInterval(timer);\n }, []);\n\n enum PlayState {\n Playing,\n Paused,\n }\n\n const [playState, setPlayState] = useState<PlayState>(PlayState.Paused);\n const [currentTime, setCurrentTime] = useState<number | undefined>(\n undefined,\n );\n const [duration, setDuration] = useState<number | undefined>(undefined);\n const [isLoading, setIsLoading] = useState(false);\n const [playerError, setPlayerError] = useState<AudioPlayerError | null>(\n null,\n );\n\n const videoRef = useRef<HTMLVideoElement | null>(null);\n const hlsRef = useRef<HlsSource | null>(null);\n const timerRef = useRef<ReturnType<typeof setInterval> | undefined>(\n undefined,\n );\n\n const audioPlayerContainerRef = useRef<HTMLDivElement>(null!);\n\n const currentChapterRef = useRef<ChapterWithPublicUrl | null>(null);\n const playerErrorRef = useRef<AudioPlayerError | null>(null);\n\n /** Set by a user action; the next `loadeddata` starts playback once. */\n const playWhenReadyRef = useRef(false);\n /** Position restored for the chapter that is loading, once. */\n const resumedRef = useRef(false);\n /** Position to restore instead of the remembered one (URL refresh, retry). */\n const pendingSeekRef = useRef<number | null>(null);\n /** Chapter URL that already asked the owner for a fresh signed URL. */\n const expiredUrlRef = useRef<string | null>(null);\n const chaptersRef = useRef(chapters);\n const chaptersSignatureRef = useRef<string | null>(null);\n\n // The owner passes new callbacks on every render; the player must keep the\n // current ones without restarting playback.\n const callbacksRef = useRef({\n onChapterChange,\n onError,\n onExpiredUrl,\n onFinished,\n updateCurrentTime,\n title,\n imageURL,\n author,\n });\n callbacksRef.current = {\n onChapterChange,\n onError,\n onExpiredUrl,\n onFinished,\n updateCurrentTime,\n title,\n imageURL,\n author,\n };\n\n function saveLastPlayedTime(timeInSeconds: number) {\n if (\n !resumedRef.current ||\n !Number.isFinite(timeInSeconds) ||\n timeInSeconds < 0\n ) {\n return;\n }\n playerStorage.set(\n `__player__${uniqueProductID}_${currentChapterRef.current?.id}`,\n `${Math.floor(timeInSeconds)}`,\n );\n }\n\n function getLastPlayedTime(): number | undefined {\n const time = playerStorage.get(\n `__player__${uniqueProductID}_${currentChapterRef.current?.id}`,\n );\n\n if (time == null) {\n return undefined;\n }\n try {\n const result = parseInt(time);\n\n if (isNaN(result) || result < 0) {\n return undefined;\n }\n\n return result;\n } catch (e) {\n return undefined;\n }\n }\n\n function getLastSelectedChapterID(): string | undefined {\n const lastSelectedChapterID = playerStorage.get(\n `__player__${uniqueProductID}_last_chapter`,\n );\n if (lastSelectedChapterID == null) {\n return undefined;\n }\n return lastSelectedChapterID;\n }\n\n function setLastSelectedChapterID(chapterID: string) {\n playerStorage.set(`__player__${uniqueProductID}_last_chapter`, chapterID);\n }\n\n function deleteMemoryChapter(chapterID: string) {\n playerStorage.remove(`__player__${uniqueProductID}_${chapterID}`);\n }\n\n function syncMediaSessionMetadata(chapter: ChapterWithPublicUrl | null) {\n mediaSessionSetMetadata({\n title: chapter?.name ?? callbacksRef.current.title ?? \"\",\n album: callbacksRef.current.title,\n artist: callbacksRef.current.author,\n artwork: callbacksRef.current.imageURL,\n });\n }\n\n function reportError(error: AudioPlayerError) {\n playerErrorRef.current = error;\n setPlayerError(error);\n setIsLoading(false);\n callbacksRef.current.onError?.(error);\n }\n\n function clearError() {\n playerErrorRef.current = null;\n setPlayerError(null);\n }\n\n function attemptPlay() {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n const result = video.play() as Promise<void> | undefined;\n if (result != null && typeof result.catch == \"function\") {\n result.catch(() => {\n // The browser blocked playback; the user presses play.\n });\n }\n updatePlayerDetails();\n }\n\n function play() {\n attemptPlay();\n }\n\n function pause() {\n videoRef.current?.pause();\n updatePlayerDetails();\n }\n\n function togglePlayState() {\n if (playState === PlayState.Playing) {\n pause();\n return;\n }\n play();\n }\n\n function seekTo(toSecond: number) {\n const video = videoRef.current;\n if (video == null || !Number.isFinite(toSecond)) {\n return;\n }\n const knownDuration = Number.isFinite(video.duration)\n ? video.duration\n : 0;\n const target =\n knownDuration > 0\n ? Math.min(Math.max(toSecond, 0), knownDuration)\n : Math.max(toSecond, 0);\n setCurrentTime(target);\n video.currentTime = target;\n updatePlayerDetails();\n }\n\n function seekBy(seconds: number) {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n const knownDuration = Number.isFinite(video.duration)\n ? video.duration\n : undefined;\n let target = Math.max(video.currentTime + seconds, 0);\n if (knownDuration != null && target > knownDuration) {\n target = knownDuration;\n }\n seekTo(target);\n }\n\n function loadSource(src: string) {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n clearError();\n setIsLoading(true);\n\n if (prefersNativeHls(video)) {\n destroyHls();\n video.src = src;\n video.load();\n return;\n }\n\n if (Hls.isSupported()) {\n if (hlsRef.current == null) {\n hlsRef.current = createHlsSource({\n media: video,\n handlers: {\n onError: (error) => {\n reportError(error);\n },\n onExpiredUrl: () => {\n callbacksRef.current.onExpiredUrl?.();\n },\n },\n });\n }\n hlsRef.current.load(src);\n return;\n }\n\n // No Media Source and no native HLS: let the browser try the URL itself.\n destroyHls();\n video.src = src;\n video.load();\n }\n\n function destroyHls() {\n hlsRef.current?.destroy();\n hlsRef.current = null;\n }\n\n function playChapter(\n chapter: ChapterWithPublicUrl,\n options?: { play?: boolean },\n ) {\n const shouldPlay = options?.play === true;\n if (\n currentChapterRef.current &&\n videoRef.current &&\n !videoRef.current.ended\n ) {\n saveLastPlayedTime(videoRef.current.currentTime);\n }\n resumedRef.current = false;\n pendingSeekRef.current = null;\n playWhenReadyRef.current = shouldPlay;\n currentChapterRef.current = chapter;\n setChapterID(chapter.id);\n setCurrentTime(0);\n setDuration(chapter.duration);\n loadSource(chapter.publicUrl);\n syncMediaSessionMetadata(chapter);\n callbacksRef.current.onChapterChange?.(chapter);\n setLastSelectedChapterID(chapter.id);\n }\n\n function loadChapters(list: ChapterWithPublicUrl[]) {\n if (list.length === 0) {\n return;\n }\n\n const chapterID = getLastSelectedChapterID();\n const chapter =\n (chapterID != null\n ? list.find((candidate) => candidate.id === chapterID)\n : undefined) ?? list[0];\n\n // Mount and content changes never start playback on their own.\n playChapter(chapter, { play: false });\n }\n\n function playNextChapter() {\n const list = chaptersRef.current;\n const current = currentChapterRef.current;\n if (list == null || list.length === 0 || current == null) {\n return;\n }\n const currentChapterIndex = list.findIndex(\n (chapter) => chapter.id === current.id,\n );\n if (currentChapterIndex === -1) {\n return;\n }\n const nextChapterIndex = currentChapterIndex + 1;\n if (nextChapterIndex >= list.length) {\n finishPlayback(current);\n return;\n }\n playChapter(list[nextChapterIndex], { play: true });\n }\n\n function playPreviousChapter() {\n const list = chaptersRef.current;\n const current = currentChapterRef.current;\n if (current == null) {\n return;\n }\n const video = videoRef.current;\n if (video != null && video.currentTime > PREVIOUS_TRACK_RESTART_SECONDS) {\n seekTo(0);\n return;\n }\n const currentChapterIndex =\n list == null\n ? -1\n : list.findIndex((chapter) => chapter.id === current.id);\n if (currentChapterIndex > 0) {\n playChapter(list[currentChapterIndex - 1], { play: true });\n return;\n }\n seekTo(0);\n }\n\n function finishPlayback(chapter: ChapterWithPublicUrl) {\n // The chapter is done: no resume point, and the element stays at the end.\n deleteMemoryChapter(chapter.id);\n playWhenReadyRef.current = false;\n videoRef.current?.pause();\n setPlayState(PlayState.Paused);\n callbacksRef.current.onFinished?.();\n }\n\n function handleEnded() {\n const current = currentChapterRef.current;\n if (current == null) {\n return;\n }\n playerStorage.set(\n `__player__${uniqueProductID}_${current.id}_completed`,\n \"true\",\n );\n deleteMemoryChapter(current.id);\n if (sleepRef.current.mode === \"chapter\") {\n playWhenReadyRef.current = false;\n pause();\n cancelSleep();\n return;\n }\n playNextChapter();\n updatePlayerDetails();\n }\n\n function handleLoadedData() {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n setIsLoading(false);\n video.playbackRate = speedRef.current;\n expiredUrlRef.current = null;\n if (!resumedRef.current) {\n resumedRef.current = true;\n const pending = pendingSeekRef.current;\n pendingSeekRef.current = null;\n if (pending != null) {\n seekTo(pending);\n } else {\n const lastPlayedTime = getLastPlayedTime();\n if (lastPlayedTime != null) {\n seekTo(lastPlayedTime);\n }\n }\n }\n if (playWhenReadyRef.current) {\n playWhenReadyRef.current = false;\n attemptPlay();\n }\n }\n\n function handleMediaElementError() {\n const mediaError = videoRef.current?.error;\n const src = currentChapterRef.current?.publicUrl;\n // Safari plays HLS itself and reports an expired signed URL as a network\n // error (2) or an unsupported source (4). Ask for a fresh URL once per\n // URL; an error that repeats after that refresh is a real error.\n const refreshable = mediaError?.code === 2 || mediaError?.code === 4;\n if (\n refreshable &&\n hlsRef.current == null &&\n src != null &&\n expiredUrlRef.current !== src\n ) {\n expiredUrlRef.current = src;\n callbacksRef.current.onExpiredUrl?.();\n }\n reportError(playerErrorFromMediaError(mediaError));\n }\n\n function retry() {\n const chapter = currentChapterRef.current;\n const src = chapter?.publicUrl ?? hlsRef.current?.src;\n if (src == null) {\n return;\n }\n const video = videoRef.current;\n const position = video?.currentTime ?? 0;\n clearError();\n resumedRef.current = false;\n pendingSeekRef.current = position > 0 ? position : null;\n setCurrentTime(position);\n if (hlsRef.current != null) {\n hlsRef.current.retry();\n } else {\n loadSource(src);\n }\n }\n\n function handleMediaSessionAction(details: MediaSessionActionDetails) {\n switch (details.action) {\n case \"play\":\n play();\n break;\n case \"pause\":\n case \"stop\":\n pause();\n break;\n case \"seekbackward\":\n seekBy(-(details.seekOffset ?? SEEK_STEP_SECONDS));\n break;\n case \"seekforward\":\n seekBy(details.seekOffset ?? SEEK_STEP_SECONDS);\n break;\n case \"seekto\":\n // A seek to 0 is valid: only a missing time is ignored.\n if (details.seekTime != null) {\n seekTo(details.seekTime);\n }\n break;\n case \"previoustrack\":\n playPreviousChapter();\n break;\n case \"nexttrack\":\n playNextChapter();\n break;\n default:\n break;\n }\n }\n\n useImperativeHandle(ref, () => {\n return {\n selectChapter: (chapter: ChapterWithPublicUrl) => {\n playChapter(chapter, { play: true });\n },\n retry,\n getError: () => playerErrorRef.current,\n };\n });\n\n function updatePlayerDetails() {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n setPlayState(video.paused ? PlayState.Paused : PlayState.Playing);\n setDuration(video.duration);\n setCurrentTime(video.currentTime);\n if (!video.ended) {\n saveLastPlayedTime(video.currentTime);\n }\n mediaSessionUpdateDurationAndPosition(\n video.duration,\n video.currentTime,\n video.playbackRate,\n );\n if (\n video.networkState === video.NETWORK_LOADING &&\n video.readyState <= video.HAVE_FUTURE_DATA\n ) {\n setIsLoading(true);\n } else {\n setIsLoading(false);\n }\n callbacksRef.current.updateCurrentTime?.(video.currentTime);\n }\n\n // Lock-screen handlers are registered once; they read refs, so they always\n // see the current chapters and callbacks.\n useEffect(() => {\n startMediaSessionCoordinator({\n title: title ?? \"\",\n album: title,\n artist: author,\n artwork: imageURL,\n action: handleMediaSessionAction,\n });\n\n return () => {\n stopMediaSessionCoordinator();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // The book title, cover or author arrive after the details request.\n useEffect(() => {\n syncMediaSessionMetadata(currentChapterRef.current);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [title, author, imageURL]);\n\n useEffect(() => {\n const video = videoRef.current;\n if (video == null) {\n return;\n }\n video.addEventListener(\"loadeddata\", handleLoadedData);\n video.addEventListener(\"ended\", handleEnded);\n video.addEventListener(\"error\", handleMediaElementError);\n video.addEventListener(\"timeupdate\", updatePlayerDetails);\n video.addEventListener(\"play\", updatePlayerDetails);\n video.addEventListener(\"pause\", updatePlayerDetails);\n video.addEventListener(\"ratechange\", updatePlayerDetails);\n\n updatePlayerDetails();\n timerRef.current = setInterval(updatePlayerDetails, 500);\n\n return () => {\n video.removeEventListener(\"loadeddata\", handleLoadedData);\n video.removeEventListener(\"ended\", handleEnded);\n video.removeEventListener(\"error\", handleMediaElementError);\n video.removeEventListener(\"timeupdate\", updatePlayerDetails);\n video.removeEventListener(\"play\", updatePlayerDetails);\n video.removeEventListener(\"pause\", updatePlayerDetails);\n video.removeEventListener(\"ratechange\", updatePlayerDetails);\n if (timerRef.current != null) {\n clearInterval(timerRef.current);\n timerRef.current = undefined;\n }\n if (!video.ended) saveLastPlayedTime(video.currentTime);\n setCurrentTime(undefined);\n video.pause();\n destroyHls();\n video.removeAttribute(\"src\");\n video.load();\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n useEffect(() => {\n if (setCurrentTimeHandler != null) {\n setCurrentTimeHandler(seekTo);\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n // Compare by chapter ids and URLs: a new array with the same content must\n // not reload the stream or restart playback.\n const chaptersSignature = chapters\n .map((chapter) => `${chapter.id}|${chapter.publicUrl ?? \"\"}`)\n .join(\"\\n\");\n\n useEffect(() => {\n chaptersRef.current = chapters;\n const previousSignature = chaptersSignatureRef.current;\n if (previousSignature === chaptersSignature) {\n return;\n }\n chaptersSignatureRef.current = chaptersSignature;\n\n if (previousSignature == null) {\n loadChapters(chapters);\n return;\n }\n\n const current = currentChapterRef.current;\n if (current == null) {\n loadChapters(chapters);\n return;\n }\n const replacement = chapters.find((chapter) => chapter.id === current.id);\n if (replacement != null && replacement.publicUrl === current.publicUrl) {\n // Same stream, different array: keep playing.\n return;\n }\n if (replacement != null) {\n // A fresh signed URL for the chapter that is playing: keep the position\n // and whether it was playing.\n const video = videoRef.current;\n const position = video?.currentTime ?? 0;\n const wasPlaying = video != null && !video.paused;\n currentChapterRef.current = replacement;\n resumedRef.current = false;\n pendingSeekRef.current = position > 0 ? position : null;\n playWhenReadyRef.current = wasPlaying;\n loadSource(replacement.publicUrl);\n syncMediaSessionMetadata(replacement);\n callbacksRef.current.onChapterChange?.(replacement);\n setLastSelectedChapterID(replacement.id);\n return;\n }\n loadChapters(chapters);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [chaptersSignature]);\n\n useEffect(() => {\n switch (playState) {\n case PlayState.Playing:\n mediaSessionPlay();\n break;\n case PlayState.Paused:\n mediaSessionPause();\n break;\n }\n }, [playState]);\n\n const currentIndex = chapters.findIndex(\n (chapter) => chapter.id === chapterID,\n );\n const knownDuration =\n Number.isFinite(duration) && duration! > 0\n ? duration!\n : (chapters[currentIndex]?.duration ?? 0);\n const position = Math.min(\n Math.max(currentTime ?? 0, 0),\n knownDuration || Infinity,\n );\n const wholeBookKnown =\n chapters.length > 0 &&\n chapters.every(\n (chapter) => Number.isFinite(chapter.duration) && chapter.duration! > 0,\n );\n const remaining =\n Math.max(\n 0,\n knownDuration -\n position +\n (wholeBookKnown\n ? chapters\n .slice(currentIndex + 1)\n .reduce((sum, chapter) => sum + chapter.duration!, 0)\n : 0),\n ) / speed;\n const minutesLeft = Math.ceil(remaining / 60);\n const leftText = `${Math.floor(minutesLeft / 60) > 0 ? `${Math.floor(minutesLeft / 60)} h ` : \"\"}${minutesLeft % 60} min`;\n\n return (\n <div\n id=\"audio-player-container\"\n className=\"bitsnap-audio-player flex min-w-0 flex-col gap-3 text-neutral-900 dark:text-neutral-100\"\n style={\n {\n ...styles,\n \"--seek-before-width\": `${knownDuration > 0 ? (position / knownDuration) * 100 : 0}%`,\n } as CSSProperties\n }\n ref={audioPlayerContainerRef}\n data-player-error={playerError?.kind}\n >\n <video\n ref={videoRef}\n className=\"hidden\"\n poster={imageURL}\n title={title}\n />\n <div className={cn(\"flex min-w-0 items-center gap-3\", coverShownBeside && \"lg:hidden\")}>\n {imageURL && (\n <img\n src={imageURL}\n alt=\"\"\n className=\"h-16 w-16 shrink-0 rounded object-contain\"\n />\n )}\n <div className=\"min-w-0 break-words\">\n <p className=\"font-semibold\">\n {chapters[currentIndex]?.name ?? title}\n </p>\n {author && (\n <p className=\"text-sm text-neutral-600 dark:text-neutral-300\">\n {author}\n </p>\n )}\n </div>\n </div>\n {playerError && (\n <div\n role=\"alert\"\n className=\"rounded-lg bg-red-50 p-3 text-red-800 dark:bg-red-950 dark:text-red-200\"\n >\n <p>{t.error}</p>\n <Button variant=\"outline\" onClick={retry}>\n {t.retry}\n </Button>\n </div>\n )}\n <input\n type=\"range\"\n min=\"0\"\n max={knownDuration || 100}\n value={position}\n disabled={!knownDuration}\n aria-label={t.progress}\n aria-valuetext={`${formatTime(position)} ${t.of} ${formatTime(knownDuration)}`}\n onChange={(event) => seekTo(Number(event.target.value))}\n />\n <section className=\"flex w-full justify-between text-sm tabular-nums\">\n <span id=\"current-time\">{formatTime(position)}</span>\n <span id=\"duration\">{formatTime(knownDuration)}</span>\n </section>\n {knownDuration > 0 && (\n <p className=\"text-sm text-neutral-600 dark:text-neutral-300\">\n {t.left === \"left\"\n ? `${leftText} ${t.left}`\n : `${t.left} ${leftText}`}{\" \"}\n · {wholeBookKnown ? t.book : t.chapter} ({speed}×)\n </p>\n )}\n <div className=\"flex flex-wrap items-center justify-center gap-2\">\n <Button\n variant=\"outline\"\n onClick={playPreviousChapter}\n disabled={currentIndex < 0}\n aria-label={t.previous}\n >\n <SkipBack className=\"h-5 w-5\" />\n </Button>\n <Button\n variant=\"outline\"\n onClick={() => seekBy(-SEEK_STEP_SECONDS)}\n aria-label={t.rewind}\n >\n −{SEEK_STEP_SECONDS}\n </Button>\n <Button\n variant=\"outline\"\n onClick={togglePlayState}\n aria-label={playState === PlayState.Paused ? t.play : t.pause}\n >\n {playState === PlayState.Paused ? (\n <Play className=\"h-5 w-5\" />\n ) : (\n <Pause className=\"h-5 w-5\" />\n )}\n </Button>\n <Button\n variant=\"outline\"\n onClick={() => seekBy(SEEK_STEP_SECONDS)}\n aria-label={t.forward}\n >\n +{SEEK_STEP_SECONDS}\n </Button>\n <Button\n variant=\"outline\"\n onClick={playNextChapter}\n disabled={currentIndex < 0 || currentIndex >= chapters.length - 1}\n aria-label={t.next}\n >\n <SkipForward className=\"h-5 w-5\" />\n </Button>\n </div>\n <div className=\"flex flex-wrap gap-3 md:grid md:grid-cols-2\">\n <label className=\"flex flex-1 items-center gap-2 text-sm md:flex-col md:items-start md:whitespace-nowrap\">\n {t.speed}\n <select\n aria-label={t.speed}\n value={speed}\n onChange={(event) => changeSpeed(Number(event.target.value))}\n >\n {SPEEDS.map((rate) => (\n <option key={rate} value={rate}>\n {rate}×\n </option>\n ))}\n </select>\n </label>\n <label className=\"flex flex-1 items-center gap-2 text-sm md:flex-col md:items-start md:whitespace-nowrap\">\n {t.sleep}\n <select\n aria-label={t.sleep}\n value={sleepMode}\n onChange={(event) => changeSleep(event.target.value)}\n >\n <option value=\"off\">{t.off}</option>\n {[15, 30, 45, 60].map((minutes) => (\n <option key={minutes} value={minutes}>\n {minutes} min\n </option>\n ))}\n <option value=\"chapter\">{t.end}</option>\n </select>\n </label>\n </div>\n {sleepMode !== \"off\" && (\n <div className=\"flex items-center justify-between gap-2 text-sm\">\n <span role=\"timer\">\n {sleepMode === \"chapter\" ? t.end : formatTime(sleepRemaining)}\n </span>\n <Button variant=\"outline\" onClick={cancelSleep}>\n {t.cancel}\n </Button>\n </div>\n )}\n {isLoading && (\n <div role=\"status\" className=\"flex justify-center\">\n <LoadingIndicator />\n </div>\n )}\n </div>\n );\n },\n);\n\nexport default AudioPlayer;\n"]}
|