@viu/emporix-sdk-react 2.14.0 → 2.15.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/provider.tsx","../src/telemetry.ts","../src/company-context.tsx"],"sourcesContent":["import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { QueryClient, QueryClientProvider, useQueryClient } from \"@tanstack/react-query\";\nimport { auth, type EmporixClient } from \"@viu/emporix-sdk\";\nimport type { EmporixStorage } from \"./storage/index\";\nimport { createMemoryStorage } from \"./storage/memory\";\nimport { EmporixTelemetryContext, type EmporixTelemetryEvent } from \"./telemetry\";\nimport { CompanyContextProvider } from \"./company-context\";\n\ninterface EmporixContextValue {\n client: EmporixClient;\n storage: EmporixStorage;\n}\n\nexport interface SiteContextValue {\n siteCode: string | null;\n /** MS-4 populates this from the active site's DTO. */\n currency: string | null;\n /** MS-4 populates this from the active site's DTO. */\n targetLocation: string | null;\n /** Active language for localized reads (Accept-Language). `null` = site/tenant default. */\n language: string | null;\n /**\n * Asynchronous site switch. Updates local state + storage immediately\n * (optimistic), then PATCHes `/session-context/{tenant}/me/context` so\n * the server sees the same site on the next request. When no session\n * context exists yet (first visit, before any cart), the PATCH is\n * skipped — local state still flips.\n *\n * `isSwitching` is `true` while the PATCH is in flight. `switchError`\n * surfaces a PATCH failure; the optimistic state is NOT rolled back\n * (the cache was already invalidated, the UI already moved on).\n */\n setSite: (code: string | null) => Promise<void>;\n /**\n * Switch the active currency at runtime. Re-binds the anonymous price context\n * (so guest pricing changes even before a cart exists), clears the\n * currency-bound guest cart, and PATCHes an existing server session context.\n * The chosen currency must be in the active site's `availableCurrencies`.\n */\n setCurrency: (currency: string) => Promise<void>;\n /**\n * Switch the active language at runtime. Sets the `Accept-Language` request\n * header (via `setStorefrontContext`), invalidates the React-Query cache so\n * localized reads refetch, and PATCHes an existing server session context.\n * Does NOT clear the cart (language does not affect pricing).\n */\n setLanguage: (language: string) => Promise<void>;\n isSwitching: boolean;\n switchError: Error | null;\n}\n\nconst EmporixContext = createContext<EmporixContextValue | null>(null);\nexport const EmporixSiteContext = createContext<SiteContextValue | null>(null);\n\n/**\n * Balanced React-Query defaults scoped to the `[\"emporix\"]` key namespace of\n * whatever QueryClient is active (the fallback OR a consumer-supplied one).\n * Keeps the Emporix API-quota in check by suppressing window-focus refetches\n * and capping retries. Consumer-set emporix defaults and per-hook options win.\n */\nconst DEFAULT_QUERY_OPTIONS = {\n staleTime: 30_000,\n refetchOnWindowFocus: false,\n retry: 1,\n} as const;\n\n/** Props for {@link EmporixProvider}. */\nexport interface EmporixProviderProps {\n client: EmporixClient;\n queryClient?: QueryClient;\n storage?: EmporixStorage;\n initialCustomerToken?: string;\n /**\n * Initial site code. Resolution order: this prop → `storage.getSiteCode()` →\n * `client.config.credentials.storefront.context.siteCode` → `null`.\n */\n initialSiteCode?: string;\n /**\n * Initial active language. Resolution order: this prop → `storage.getLanguage()`\n * → `client.config.credentials.storefront.context.language` → `null` (then\n * seeded from the active site's `defaultLanguage` on mount).\n */\n initialLanguage?: string;\n /**\n * Initial active legal-entity id (B2B). When set, the CompanyContext\n * provider tries to match it against `companies.listMine()` once the\n * customer is loaded; mismatches are dropped silently.\n */\n initialActiveLegalEntityId?: string | null;\n /**\n * Opt-in telemetry callback. Receives a typed event stream covering cache\n * hit/miss, refetches, errors, mutations, auth refreshes, storage writes,\n * and consumer-emitted custom events. Wire this to Datadog/Sentry/custom\n * analytics. The handler is wrapped in try/catch — a throwing handler\n * never breaks the provider.\n */\n onTelemetry?: (event: EmporixTelemetryEvent) => void;\n /**\n * Opt in to reactive customer-token auto-refresh: on a `customer`-kind 401,\n * the SDK refreshes once (via the stored refresh token + anonymous auth) and\n * retries. Default: false (the customer token stays caller-owned).\n */\n autoRefreshCustomerToken?: boolean;\n /**\n * Called when a customer-token refresh is needed but fails (refresh token\n * expired/revoked) or no refresh token is stored. Use to drive logout /\n * redirect to login.\n */\n onCustomerSessionExpired?: () => void;\n children: ReactNode;\n}\n\n/** Provides the SDK client, token storage, react-query client, and site context to the tree. */\nexport function EmporixProvider({\n client,\n queryClient,\n storage,\n initialCustomerToken,\n initialSiteCode,\n initialLanguage,\n initialActiveLegalEntityId,\n onTelemetry,\n autoRefreshCustomerToken,\n onCustomerSessionExpired,\n children,\n}: EmporixProviderProps): React.JSX.Element {\n const value = useMemo<EmporixContextValue>(() => {\n const s =\n storage ??\n createMemoryStorage(\n initialCustomerToken !== undefined ? { initial: initialCustomerToken } : {},\n );\n return { client, storage: s };\n }, [client, storage, initialCustomerToken]);\n\n // Fallback QueryClient held in state, not useMemo: React may discard a\n // useMemo cache, which would silently drop the entire query cache mid-session.\n // Defaults are applied below via setQueryDefaults, scoped to [\"emporix\"].\n const [fallbackQc] = useState(() => new QueryClient());\n const qc = queryClient ?? fallbackQc;\n\n // Scope our balanced defaults to the [\"emporix\"] key namespace on WHATEVER\n // QueryClient is in use — a bare consumer client (e.g. the next-app-router\n // example) otherwise runs SDK queries with React-Query factory defaults\n // (staleTime 0, focus refetch, retry 3 → multiplied by the SDK's own HTTP\n // retry). We only FILL GAPS: a consumer's explicit choices win, whether set\n // globally (`defaultOptions.queries`) or emporix-scoped — both are spread\n // after ours. Host-app queries outside the namespace are untouched.\n // Ref-guarded: re-applies only for a new client.\n const defaultsRef = useRef<QueryClient | null>(null);\n if (defaultsRef.current !== qc) {\n qc.setQueryDefaults([\"emporix\"], {\n ...DEFAULT_QUERY_OPTIONS,\n ...qc.getDefaultOptions().queries,\n ...qc.getQueryDefaults([\"emporix\"]),\n });\n defaultsRef.current = qc;\n }\n\n // Idempotent wiring that must precede the children's first fetch effects:\n // (1) attach the storage-backed anonymous-session adapter to the SDK token\n // provider, (2) seed the SSR-provided customer token into external storage.\n // Ref-guarded so it re-runs when (client, storage) identity changes — a\n // useState lazy initializer runs once per component INSTANCE and silently\n // skips re-wiring on prop swaps; a useEffect runs AFTER children fetch.\n const wiredRef = useRef<{ client: EmporixClient; storage: EmporixStorage } | null>(null);\n if (wiredRef.current?.client !== client || wiredRef.current?.storage !== value.storage) {\n client.tokenProvider.attachAnonymousStore?.({\n read: () => value.storage.getAnonymousSession(),\n write: (s) => value.storage.setAnonymousSession(s),\n });\n if (initialCustomerToken && storage && storage.getCustomerToken() === null) {\n storage.setCustomerToken(initialCustomerToken);\n }\n wiredRef.current = { client, storage: value.storage };\n }\n\n // Telemetry: stable safeEmit + context value. emit is no-op when no\n // onTelemetry callback was provided (no overhead).\n const safeEmit = useCallback(\n (event: EmporixTelemetryEvent) => {\n if (!onTelemetry) return;\n try {\n onTelemetry(event);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"[emporix] telemetry handler threw:\", err);\n }\n },\n [onTelemetry],\n );\n const telemetryValue = useMemo(() => ({ emit: safeEmit }), [safeEmit]);\n\n // Source subscriptions: cache + mutation cache + token-provider + storage.\n // All only active when onTelemetry is provided.\n useEffect(() => {\n if (!onTelemetry) return;\n const startedAt = new Map<string, number>();\n\n const unsubQuery = qc.getQueryCache().subscribe((event) => {\n const key = event.query.queryKey;\n if (!Array.isArray(key) || key[0] !== \"emporix\") return;\n if (event.type === \"updated\") {\n const action = event.action as { type: string };\n if (action.type === \"fetch\") {\n const isRefetch = event.query.state.dataUpdateCount > 0;\n if (isRefetch) {\n safeEmit({\n type: \"query.refetch\",\n queryKey: key,\n tenant: client.tenant,\n reason: \"invalidate\",\n });\n }\n startedAt.set(event.query.queryHash, Date.now());\n } else if (action.type === \"success\") {\n const start = startedAt.get(event.query.queryHash);\n startedAt.delete(event.query.queryHash);\n safeEmit({\n type: \"cache.miss\",\n queryKey: key,\n tenant: client.tenant,\n durationMs: start ? Date.now() - start : 0,\n });\n } else if (action.type === \"error\") {\n startedAt.delete(event.query.queryHash);\n safeEmit({\n type: \"query.error\",\n queryKey: key,\n tenant: client.tenant,\n error: event.query.state.error,\n });\n }\n } else if (event.type === \"observerResultsUpdated\") {\n const s = event.query.state;\n if (s.status === \"success\" && s.fetchStatus === \"idle\" && s.dataUpdateCount > 0) {\n safeEmit({ type: \"cache.hit\", queryKey: key, tenant: client.tenant });\n }\n }\n });\n\n const unsubMut = qc.getMutationCache().subscribe((event) => {\n if (event.type !== \"updated\") return;\n const m = event.mutation;\n const dur = Date.now() - (m.state.submittedAt ?? Date.now());\n const mk = m.options.mutationKey;\n if (m.state.status === \"success\") {\n safeEmit({\n type: \"mutation.success\",\n ...(mk ? { mutationKey: mk as readonly unknown[] } : {}),\n tenant: client.tenant,\n durationMs: dur,\n });\n } else if (m.state.status === \"error\") {\n safeEmit({\n type: \"mutation.error\",\n ...(mk ? { mutationKey: mk as readonly unknown[] } : {}),\n tenant: client.tenant,\n error: m.state.error,\n durationMs: dur,\n });\n }\n });\n\n const unsubAuth = client.tokenProvider.onRefresh?.((evt) =>\n safeEmit({ type: \"auth.refresh\", ...evt, tenant: client.tenant }),\n );\n\n const unsubStorage = value.storage.subscribeAll?.((key) =>\n safeEmit({ type: \"storage.write\", key }),\n );\n\n return () => {\n unsubQuery();\n unsubMut();\n unsubAuth?.();\n unsubStorage?.();\n };\n }, [qc, onTelemetry, client, value.storage, safeEmit]);\n\n // Opt-in reactive customer-token auto-refresh. Registered on the client so\n // the core HttpClient can refresh-and-retry a customer 401. Single-flight is\n // handled in the core registry. Off unless `autoRefreshCustomerToken`.\n useEffect(() => {\n if (!autoRefreshCustomerToken) return;\n const storage = value.storage;\n client.setCustomerTokenRefresher({\n refresh: async () => {\n const refreshToken = storage.getRefreshToken();\n if (!refreshToken) {\n safeEmit({ type: \"auth.refresh\", kind: \"customer\", success: false, tenant: client.tenant });\n onCustomerSessionExpired?.();\n return null;\n }\n try {\n const legalEntityId = storage.getActiveLegalEntityId() ?? undefined;\n const s = await client.customers.refresh({\n refreshToken,\n ...(legalEntityId ? { legalEntityId } : {}),\n });\n storage.setCustomerToken(s.customerToken);\n if (s.refreshToken) storage.setRefreshToken(s.refreshToken);\n safeEmit({ type: \"auth.refresh\", kind: \"customer\", success: true, tenant: client.tenant });\n return s.customerToken;\n } catch {\n safeEmit({ type: \"auth.refresh\", kind: \"customer\", success: false, tenant: client.tenant });\n onCustomerSessionExpired?.();\n return null;\n }\n },\n });\n return () => client.setCustomerTokenRefresher(null);\n }, [autoRefreshCustomerToken, client, value.storage, safeEmit, onCustomerSessionExpired]);\n\n return (\n <EmporixContext.Provider value={value}>\n <EmporixTelemetryContext.Provider value={telemetryValue}>\n <QueryClientProvider client={qc}>\n <SiteContextProvider\n client={client}\n storage={value.storage}\n {...(initialSiteCode !== undefined ? { initialSiteCode } : {})}\n {...(initialLanguage !== undefined ? { initialLanguage } : {})}\n >\n <CompanyContextProvider\n client={client}\n storage={value.storage}\n {...(initialActiveLegalEntityId !== undefined\n ? { initialActiveLegalEntityId }\n : {})}\n >\n {children}\n </CompanyContextProvider>\n </SiteContextProvider>\n </QueryClientProvider>\n </EmporixTelemetryContext.Provider>\n </EmporixContext.Provider>\n );\n}\n\n/**\n * Manages the active-site state. Sits inside `QueryClientProvider` so\n * `setSite` can invalidate the React-Query cache on switch.\n */\nfunction SiteContextProvider({\n client,\n storage,\n initialSiteCode,\n initialLanguage,\n children,\n}: {\n client: EmporixClient;\n storage: EmporixStorage;\n initialSiteCode?: string;\n initialLanguage?: string;\n children: ReactNode;\n}): React.JSX.Element {\n const qc = useQueryClient();\n const [siteCode, setSiteCodeState] = useState<string | null>(() => {\n if (initialSiteCode !== undefined) return initialSiteCode;\n const fromStorage = storage.getSiteCode();\n if (fromStorage !== null) return fromStorage;\n return client.config?.credentials?.storefront?.context?.siteCode ?? null;\n });\n const [currency, setCurrencyState] = useState<string | null>(\n () => client.config?.credentials?.storefront?.context?.currency ?? null,\n );\n const [language, setLanguageState] = useState<string | null>(() => {\n if (initialLanguage !== undefined) return initialLanguage;\n const fromStorage = storage.getLanguage();\n if (fromStorage !== null) return fromStorage;\n return client.config?.credentials?.storefront?.context?.language ?? null;\n });\n const [targetLocation, setTargetLocation] = useState<string | null>(null);\n const [isSwitching, setIsSwitching] = useState(false);\n const [switchError, setSwitchError] = useState<Error | null>(null);\n\n // Mount-time derivation: if a siteCode is already resolved, fetch its DTO\n // once so currency + targetLocation populate without a user-driven switch.\n // A currency seeded from the client config is NOT overridden (the user's /\n // persisted choice wins); only fields still `null` are filled in.\n useEffect(() => {\n if (!siteCode || (currency !== null && targetLocation !== null && language !== null)) return;\n let cancelled = false;\n const token = storage.getCustomerToken();\n const authCtx = token ? auth.customer(token) : auth.anonymous();\n qc.fetchQuery({\n queryKey: [\n \"emporix\",\n \"site-by-code\",\n siteCode,\n { tenant: client.tenant, authKind: authCtx.kind },\n ],\n queryFn: () => client.sites.get(siteCode, authCtx),\n staleTime: 5 * 60_000,\n })\n .then((site) => {\n if (cancelled) return;\n if (currency === null) setCurrencyState(site.currency);\n setTargetLocation(site.homeBase?.address?.country ?? null);\n if (language === null && site.defaultLanguage) {\n setLanguageState(site.defaultLanguage);\n client.setStorefrontContext({ language: site.defaultLanguage });\n }\n })\n .catch(() => {\n // Best-effort — silent. setSite-driven derivation surfaces real errors.\n });\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [siteCode]);\n\n // Push the initially-resolved language (prop / storage / config) to the SDK so\n // the very first reads carry `Accept-Language` — React state alone does not\n // reach the client. Mount-only; later changes go through setLanguage / setSite.\n useEffect(() => {\n if (language) client.setStorefrontContext({ language });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const setSite = useCallback(\n async (code: string | null) => {\n // 1) Optimistic flip — UI moves immediately.\n storage.setSiteCode(code);\n storage.setCartId(null);\n setSiteCodeState(code);\n setSwitchError(null);\n void qc.invalidateQueries({ queryKey: [\"emporix\"] });\n\n if (code === null) {\n setCurrencyState(null);\n setTargetLocation(null);\n return;\n }\n\n setIsSwitching(true);\n try {\n const token = storage.getCustomerToken();\n const authCtx = token ? auth.customer(token) : auth.anonymous();\n // 2) Derive currency + targetLocation from the site DTO (cached 5min).\n const site = await qc.fetchQuery({\n queryKey: [\n \"emporix\",\n \"site-by-code\",\n code,\n { tenant: client.tenant, authKind: authCtx.kind },\n ],\n queryFn: () => client.sites.get(code, authCtx),\n staleTime: 5 * 60_000,\n });\n const nextCurrency = site.currency;\n const nextTarget = site.homeBase?.address?.country ?? null;\n setCurrencyState(nextCurrency);\n setTargetLocation(nextTarget);\n // Reset the language if the new site doesn't support the active one.\n if (site.languages && !site.languages.includes(language ?? \"\") && site.defaultLanguage) {\n setLanguageState(site.defaultLanguage);\n client.setStorefrontContext({ language: site.defaultLanguage });\n }\n // 3) Push everything into the session-context PATCH.\n await client.sessionContext.patch(\n {\n siteCode: code,\n ...(nextCurrency ? { currency: nextCurrency } : {}),\n ...(nextTarget ? { targetLocation: nextTarget } : {}),\n },\n authCtx,\n );\n } catch (e) {\n setSwitchError(e instanceof Error ? e : new Error(String(e)));\n } finally {\n setIsSwitching(false);\n }\n },\n [client, storage, qc, language],\n );\n\n const setCurrency = useCallback(\n async (next: string) => {\n // Carts are currency-bound — drop the guest cart so a fresh one is created.\n storage.setCartId(null);\n setCurrencyState(next);\n setSwitchError(null);\n // Re-bind the anonymous price context so guest pricing uses the new\n // currency even before a session/cart exists (sessionContext.patch can't).\n client.setStorefrontContext({ currency: next });\n void qc.invalidateQueries({ queryKey: [\"emporix\"] });\n setIsSwitching(true);\n try {\n const token = storage.getCustomerToken();\n const authCtx = token ? auth.customer(token) : auth.anonymous();\n // Update an existing server session context (no-op / returns false pre-cart).\n await client.sessionContext.patch(\n { currency: next, ...(siteCode ? { siteCode } : {}) },\n authCtx,\n );\n } catch (e) {\n setSwitchError(e instanceof Error ? e : new Error(String(e)));\n } finally {\n setIsSwitching(false);\n }\n },\n [client, storage, qc, siteCode],\n );\n\n const setLanguage = useCallback(\n async (next: string) => {\n storage.setLanguage(next);\n setLanguageState(next);\n setSwitchError(null);\n // Header source — applies to anonymous + pre-session reads too.\n client.setStorefrontContext({ language: next });\n void qc.invalidateQueries({ queryKey: [\"emporix\"] });\n setIsSwitching(true);\n try {\n const token = storage.getCustomerToken();\n const authCtx = token ? auth.customer(token) : auth.anonymous();\n // Update an existing server session context (no-op / returns false pre-cart).\n await client.sessionContext.patch(\n { language: next, ...(siteCode ? { siteCode } : {}) },\n authCtx,\n );\n } catch (e) {\n setSwitchError(e instanceof Error ? e : new Error(String(e)));\n } finally {\n setIsSwitching(false);\n }\n },\n [client, storage, qc, siteCode],\n );\n\n const value = useMemo<SiteContextValue>(\n () => ({\n siteCode,\n currency,\n targetLocation,\n language,\n setSite,\n setCurrency,\n setLanguage,\n isSwitching,\n switchError,\n }),\n [siteCode, currency, targetLocation, language, setSite, setCurrency, setLanguage, isSwitching, switchError],\n );\n\n return <EmporixSiteContext.Provider value={value}>{children}</EmporixSiteContext.Provider>;\n}\n\n/** Returns the SDK client and token storage. Throws outside an {@link EmporixProvider}. */\nexport function useEmporix(): EmporixContextValue {\n const ctx = useContext(EmporixContext);\n if (!ctx) throw new Error(\"useEmporix must be used within an EmporixProvider\");\n return ctx;\n}\n","import { createContext, useContext } from \"react\";\n\n/**\n * All telemetry events emitted through the EmporixProvider's `onTelemetry`\n * callback. Discriminated by `type` — exhaustive switch is type-safe.\n *\n * Consumers can emit their own `{ type: \"custom\" }` events via\n * {@link useEmporixTelemetry}. Namespace `name` with an app-specific\n * prefix (e.g. `\"app.checkout-cta-click\"`) to avoid collisions with\n * future SDK event types.\n */\nexport type EmporixTelemetryEvent =\n // Cache lifecycle (React-Query QueryCache)\n | { type: \"cache.hit\"; queryKey: readonly unknown[]; tenant: string }\n | {\n type: \"cache.miss\";\n queryKey: readonly unknown[];\n tenant: string;\n durationMs: number;\n }\n | {\n type: \"query.refetch\";\n queryKey: readonly unknown[];\n tenant: string;\n reason: \"invalidate\" | \"focus\" | \"stale\";\n }\n | {\n type: \"query.error\";\n queryKey: readonly unknown[];\n tenant: string;\n error: unknown;\n }\n // Mutation lifecycle\n | {\n type: \"mutation.success\";\n mutationKey?: readonly unknown[];\n tenant: string;\n durationMs: number;\n }\n | {\n type: \"mutation.error\";\n mutationKey?: readonly unknown[];\n tenant: string;\n error: unknown;\n durationMs: number;\n }\n // Auth refresh (SDK-side)\n | {\n type: \"auth.refresh\";\n kind: \"anonymous\" | \"customer\";\n tenant: string;\n success: boolean;\n }\n // Storage writes\n | {\n type: \"storage.write\";\n key: \"customerToken\" | \"cartId\" | \"siteCode\" | \"language\" | \"anonymousSession\" | \"activeLegalEntityId\" | \"refreshToken\";\n }\n // Active-company switch (B2B)\n | {\n type: \"company:switched\";\n from: string | null;\n to: string | null;\n durationMs: number;\n }\n // Consumer-emitted\n | { type: \"custom\"; name: string; props?: Record<string, unknown> };\n\n/** Internal: the React context carrying the emit function down the tree. */\nexport const EmporixTelemetryContext = createContext<{\n emit: (event: EmporixTelemetryEvent) => void;\n} | null>(null);\n\n/**\n * Hook to emit custom telemetry events through the same channel as SDK\n * events. Throws when used outside an {@link EmporixProvider}.\n *\n * When the provider has no `onTelemetry` callback configured, `emit` is a\n * no-op — calling it is safe and incurs no overhead.\n */\nexport function useEmporixTelemetry(): {\n emit: (event: EmporixTelemetryEvent) => void;\n} {\n const ctx = useContext(EmporixTelemetryContext);\n if (!ctx) {\n throw new Error(\"useEmporixTelemetry must be used within an EmporixProvider\");\n }\n return ctx;\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { auth, type EmporixClient, type LegalEntity } from \"@viu/emporix-sdk\";\nimport type { EmporixStorage } from \"./storage\";\nimport { useEmporixTelemetry } from \"./telemetry\";\n\nexport type CompanyMode = \"b2c\" | \"b2b\" | \"unresolved\";\n\nexport interface CompanyContextValue {\n /** Active legal entity. `null` = B2C mode. */\n activeCompany: LegalEntity | null;\n /** All legal entities the customer is assigned to. */\n myCompanies: LegalEntity[];\n /**\n * `b2b` = a company is active; `b2c` = none active (and ≤1 available);\n * `unresolved` = multiple companies available, none picked yet — the\n * storefront must render a picker.\n */\n mode: CompanyMode;\n status: \"idle\" | \"loading\" | \"switching\" | \"error\";\n error: unknown;\n /**\n * Switch the active company. Eagerly calls\n * `client.customers.refresh({ legalEntityId })` so the customer token is\n * rescoped server-side, drops the cart id, then invalidates company-scoped\n * queries. Falls back to a local-state-only update when no refresh token\n * is in storage (e.g. fresh page load with memory storage).\n */\n setActiveCompany: (legalEntityId: string | null) => Promise<void>;\n refetchMyCompanies: () => Promise<void>;\n}\n\nconst NULL_CTX: CompanyContextValue = {\n activeCompany: null,\n myCompanies: [],\n mode: \"b2c\",\n status: \"idle\",\n error: null,\n setActiveCompany: async () => {\n throw new Error(\"CompanyContextProvider not mounted\");\n },\n refetchMyCompanies: async () => {},\n};\n\nexport const EmporixCompanyContext = createContext<CompanyContextValue>(NULL_CTX);\n\n/** Returns the active-company context. Safe outside the provider — returns idle B2C defaults. */\nexport function useActiveCompany(): CompanyContextValue {\n return useContext(EmporixCompanyContext);\n}\n\nexport interface CompanyContextProviderProps {\n client: EmporixClient;\n storage: EmporixStorage;\n initialActiveLegalEntityId?: string | null;\n children: ReactNode;\n}\n\nexport function CompanyContextProvider({\n client,\n storage,\n initialActiveLegalEntityId,\n children,\n}: CompanyContextProviderProps): React.JSX.Element {\n const qc = useQueryClient();\n const { emit } = useEmporixTelemetry();\n const [myCompanies, setMyCompanies] = useState<LegalEntity[]>([]);\n const [activeCompany, setActive] = useState<LegalEntity | null>(null);\n const [status, setStatus] = useState<CompanyContextValue[\"status\"]>(\"idle\");\n const [error, setError] = useState<unknown>(null);\n // Ref so switchTo can capture the latest `activeCompany` for telemetry `from`.\n // Written in an effect: render-phase ref writes are illegal under concurrent\n // rendering (an abandoned render's value could leak into a committed pass).\n const activeRef = useRef<LegalEntity | null>(null);\n useEffect(() => {\n activeRef.current = activeCompany;\n }, [activeCompany]);\n\n // Serializes token-rotating switches: two concurrent switchTo calls would\n // both read the same refresh token; with server-side rotation the second\n // consumes a stale token (401, worst case session revocation).\n const switchChain = useRef<Promise<void>>(Promise.resolve());\n\n /** Internal: eager refresh + storage write + state update. */\n const switchTo = useCallback(\n (target: LegalEntity | null): Promise<void> => {\n const run = async (): Promise<void> => {\n const start = Date.now();\n const from = activeRef.current?.id ?? null;\n const refreshToken = storage.getRefreshToken();\n const token = storage.getCustomerToken();\n if (!refreshToken || !token) {\n // Local-state-only fallback — no rescope possible.\n setActive(target);\n storage.setActiveLegalEntityId(target?.id ?? null);\n } else {\n const next = await client.customers.refresh({\n refreshToken,\n ...(target ? { legalEntityId: target.id } : {}),\n });\n storage.setCustomerToken(next.customerToken);\n if (next.refreshToken) storage.setRefreshToken(next.refreshToken);\n storage.setCartId(null);\n storage.setActiveLegalEntityId(target?.id ?? null);\n setActive(target);\n qc.invalidateQueries({\n predicate: (q) =>\n Array.isArray(q.queryKey) &&\n q.queryKey.some(\n (k) =>\n k === \"cart\" ||\n k === \"companies\" ||\n k === \"customer\" ||\n k === from ||\n (target !== null && k === target.id),\n ),\n });\n }\n emit({\n type: \"company:switched\",\n from,\n to: target?.id ?? null,\n durationMs: Date.now() - start,\n });\n };\n // Chain on the previous switch so concurrent calls run in order and each\n // reads the refresh token the prior switch rotated to.\n const task = switchChain.current.then(run, run);\n switchChain.current = task.catch(() => {\n /* keep the chain alive after a failed switch */\n });\n return task;\n },\n [client, storage, qc, emit],\n );\n\n const load = useCallback(\n async (signal?: { cancelled: boolean }) => {\n const token = storage.getCustomerToken();\n if (!token) {\n if (signal?.cancelled) return;\n setMyCompanies([]);\n setActive(null);\n setStatus(\"idle\");\n return;\n }\n setStatus(\"loading\");\n try {\n const companies = await client.companies.listMine(auth.customer(token));\n if (signal?.cancelled) return; // unmounted (StrictMode probe) — no state, no auto-switch\n setMyCompanies(companies);\n const persisted = initialActiveLegalEntityId ?? storage.getActiveLegalEntityId();\n const matched = persisted ? companies.find((c) => c.id === persisted) ?? null : null;\n if (matched) {\n setActive(matched);\n if (storage.getActiveLegalEntityId() !== matched.id) {\n storage.setActiveLegalEntityId(matched.id ?? null);\n }\n } else if (companies.length === 1) {\n await switchTo(companies[0] ?? null);\n } else {\n setActive(null);\n if (persisted && !matched) storage.setActiveLegalEntityId(null);\n }\n if (signal?.cancelled) return;\n setStatus(\"idle\");\n } catch (e) {\n if (signal?.cancelled) return;\n setError(e);\n setStatus(\"error\");\n }\n },\n [client, storage, initialActiveLegalEntityId, switchTo],\n );\n\n useEffect(() => {\n const signal = { cancelled: false };\n void load(signal);\n return () => {\n signal.cancelled = true;\n };\n }, [load]);\n\n // Re-run bootstrap only on token-presence transitions (login/logout). A\n // mid-session token swap (e.g. switch-driven refresh) keeps prev/next both\n // truthy and is ignored — otherwise the auto-pick branch would clobber an\n // explicit B2C choice as soon as the new token is written.\n useEffect(() => {\n let prev = storage.getCustomerToken();\n return storage.subscribe?.((next) => {\n const becameAuth = !prev && next;\n const becameUnauth = prev && !next;\n prev = next;\n if (becameAuth || becameUnauth) void load();\n });\n }, [storage, load]);\n\n const setActiveCompany = useCallback(\n async (legalEntityId: string | null) => {\n setStatus(\"switching\");\n try {\n if (legalEntityId === null) {\n await switchTo(null);\n } else {\n const target = myCompanies.find((c) => c.id === legalEntityId) ?? null;\n if (!target) throw new Error(`setActiveCompany: unknown legalEntityId ${legalEntityId}`);\n await switchTo(target);\n }\n setStatus(\"idle\");\n } catch (e) {\n setError(e);\n setStatus(\"error\");\n throw e;\n }\n },\n [myCompanies, switchTo],\n );\n\n const value = useMemo<CompanyContextValue>(() => {\n const mode: CompanyMode = activeCompany\n ? \"b2b\"\n : myCompanies.length > 1\n ? \"unresolved\"\n : \"b2c\";\n return {\n activeCompany,\n myCompanies,\n mode,\n status,\n error,\n setActiveCompany,\n refetchMyCompanies: load,\n };\n }, [activeCompany, myCompanies, status, error, setActiveCompany, load]);\n\n return (\n <EmporixCompanyContext.Provider value={value}>{children}</EmporixCompanyContext.Provider>\n );\n}\n"],"mappings":";;;;;;AAAA,SAAS,iBAAAA,gBAAe,eAA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mBAAmB,UAAnB,EAA4B,OAAe,UAAS;AAC9D;AAGO,SAAS,aAAkC;AAChD,QAAM,MAAMU,YAAW,cAAc;AACrC,MAAI,CAAC,IAAK,OAAM,IAAI,MAAM,mDAAmD;AAC7E,SAAO;AACT;","names":["createContext","useCallback","useContext","useEffect","useMemo","useRef","useState","useQueryClient","auth","createContext","useContext","createContext","useContext","jsx","createContext","useMemo","useState","useRef","useCallback","useEffect","storage","useQueryClient","auth","useContext"]}
1
+ {"version":3,"sources":["../src/provider.tsx","../src/telemetry.ts","../src/company-context.tsx"],"sourcesContent":["import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { QueryClient, QueryClientProvider, useQueryClient } from \"@tanstack/react-query\";\nimport { auth, type EmporixClient } from \"@viu/emporix-sdk\";\nimport type { EmporixStorage } from \"./storage/index\";\nimport { createMemoryStorage } from \"./storage/memory\";\nimport { EmporixTelemetryContext, type EmporixTelemetryEvent } from \"./telemetry\";\nimport { CompanyContextProvider } from \"./company-context\";\n\ninterface EmporixContextValue {\n client: EmporixClient;\n storage: EmporixStorage;\n}\n\nexport interface SiteContextValue {\n siteCode: string | null;\n /** MS-4 populates this from the active site's DTO. */\n currency: string | null;\n /** MS-4 populates this from the active site's DTO. */\n targetLocation: string | null;\n /** Active language for localized reads (Accept-Language). `null` = site/tenant default. */\n language: string | null;\n /**\n * Asynchronous site switch. Updates local state + storage immediately\n * (optimistic), then PATCHes `/session-context/{tenant}/me/context` so\n * the server sees the same site on the next request. When no session\n * context exists yet (first visit, before any cart), the PATCH is\n * skipped — local state still flips.\n *\n * `isSwitching` is `true` while the PATCH is in flight. `switchError`\n * surfaces a PATCH failure; the optimistic state is NOT rolled back\n * (the cache was already invalidated, the UI already moved on).\n */\n setSite: (code: string | null) => Promise<void>;\n /**\n * Switch the active currency at runtime. Re-binds the anonymous price context\n * (so guest pricing changes even before a cart exists), clears the\n * currency-bound guest cart, and PATCHes an existing server session context.\n * The chosen currency must be in the active site's `availableCurrencies`.\n */\n setCurrency: (currency: string) => Promise<void>;\n /**\n * Switch the active language at runtime. Sets the `Accept-Language` request\n * header (via `setStorefrontContext`), invalidates the React-Query cache so\n * localized reads refetch, and PATCHes an existing server session context.\n * Does NOT clear the cart (language does not affect pricing).\n */\n setLanguage: (language: string) => Promise<void>;\n isSwitching: boolean;\n switchError: Error | null;\n}\n\nconst EmporixContext = createContext<EmporixContextValue | null>(null);\nexport const EmporixSiteContext = createContext<SiteContextValue | null>(null);\n\n/**\n * Balanced React-Query defaults scoped to the `[\"emporix\"]` key namespace of\n * whatever QueryClient is active (the fallback OR a consumer-supplied one).\n * Keeps the Emporix API-quota in check by suppressing window-focus refetches\n * and capping retries. Consumer-set emporix defaults and per-hook options win.\n */\nconst DEFAULT_QUERY_OPTIONS = {\n staleTime: 30_000,\n refetchOnWindowFocus: false,\n retry: 1,\n} as const;\n\n/** Props for {@link EmporixProvider}. */\nexport interface EmporixProviderProps {\n client: EmporixClient;\n queryClient?: QueryClient;\n storage?: EmporixStorage;\n initialCustomerToken?: string;\n /**\n * Initial site code. Resolution order: this prop → `storage.getSiteCode()` →\n * `client.config.credentials.storefront.context.siteCode` → `null`.\n */\n initialSiteCode?: string;\n /**\n * Initial active language. Resolution order: this prop → `storage.getLanguage()`\n * → `client.config.credentials.storefront.context.language` → `null` (then\n * seeded from the active site's `defaultLanguage` on mount).\n */\n initialLanguage?: string;\n /**\n * Initial active legal-entity id (B2B). When set, the CompanyContext\n * provider tries to match it against `companies.listMine()` once the\n * customer is loaded; mismatches are dropped silently.\n */\n initialActiveLegalEntityId?: string | null;\n /**\n * Opt-in telemetry callback. Receives a typed event stream covering cache\n * hit/miss, refetches, errors, mutations, auth refreshes, storage writes,\n * and consumer-emitted custom events. Wire this to Datadog/Sentry/custom\n * analytics. The handler is wrapped in try/catch — a throwing handler\n * never breaks the provider.\n */\n onTelemetry?: (event: EmporixTelemetryEvent) => void;\n /**\n * Opt in to reactive customer-token auto-refresh: on a `customer`-kind 401,\n * the SDK refreshes once (via the stored refresh token + anonymous auth) and\n * retries. Default: false (the customer token stays caller-owned).\n */\n autoRefreshCustomerToken?: boolean;\n /**\n * Called when a customer-token refresh is needed but fails (refresh token\n * expired/revoked) or no refresh token is stored. Use to drive logout /\n * redirect to login.\n */\n onCustomerSessionExpired?: () => void;\n children: ReactNode;\n}\n\n/** Provides the SDK client, token storage, react-query client, and site context to the tree. */\nexport function EmporixProvider({\n client,\n queryClient,\n storage,\n initialCustomerToken,\n initialSiteCode,\n initialLanguage,\n initialActiveLegalEntityId,\n onTelemetry,\n autoRefreshCustomerToken,\n onCustomerSessionExpired,\n children,\n}: EmporixProviderProps): React.JSX.Element {\n const value = useMemo<EmporixContextValue>(() => {\n const s =\n storage ??\n createMemoryStorage(\n initialCustomerToken !== undefined ? { initial: initialCustomerToken } : {},\n );\n return { client, storage: s };\n }, [client, storage, initialCustomerToken]);\n\n // Fallback QueryClient held in state, not useMemo: React may discard a\n // useMemo cache, which would silently drop the entire query cache mid-session.\n // Defaults are applied below via setQueryDefaults, scoped to [\"emporix\"].\n const [fallbackQc] = useState(() => new QueryClient());\n const qc = queryClient ?? fallbackQc;\n\n // Scope our balanced defaults to the [\"emporix\"] key namespace on WHATEVER\n // QueryClient is in use — a bare consumer client (e.g. the next-app-router\n // example) otherwise runs SDK queries with React-Query factory defaults\n // (staleTime 0, focus refetch, retry 3 → multiplied by the SDK's own HTTP\n // retry). We only FILL GAPS: a consumer's explicit choices win, whether set\n // globally (`defaultOptions.queries`) or emporix-scoped — both are spread\n // after ours. Host-app queries outside the namespace are untouched.\n // Ref-guarded: re-applies only for a new client.\n const defaultsRef = useRef<QueryClient | null>(null);\n if (defaultsRef.current !== qc) {\n qc.setQueryDefaults([\"emporix\"], {\n ...DEFAULT_QUERY_OPTIONS,\n ...qc.getDefaultOptions().queries,\n ...qc.getQueryDefaults([\"emporix\"]),\n });\n defaultsRef.current = qc;\n }\n\n // Idempotent wiring that must precede the children's first fetch effects:\n // (1) attach the storage-backed anonymous-session adapter to the SDK token\n // provider, (2) seed the SSR-provided customer token into external storage.\n // Ref-guarded so it re-runs when (client, storage) identity changes — a\n // useState lazy initializer runs once per component INSTANCE and silently\n // skips re-wiring on prop swaps; a useEffect runs AFTER children fetch.\n const wiredRef = useRef<{ client: EmporixClient; storage: EmporixStorage } | null>(null);\n if (wiredRef.current?.client !== client || wiredRef.current?.storage !== value.storage) {\n client.tokenProvider.attachAnonymousStore?.({\n read: () => value.storage.getAnonymousSession(),\n write: (s) => value.storage.setAnonymousSession(s),\n });\n if (initialCustomerToken && storage && storage.getCustomerToken() === null) {\n storage.setCustomerToken(initialCustomerToken);\n }\n wiredRef.current = { client, storage: value.storage };\n }\n\n // Telemetry: stable safeEmit + context value. emit is no-op when no\n // onTelemetry callback was provided (no overhead).\n const safeEmit = useCallback(\n (event: EmporixTelemetryEvent) => {\n if (!onTelemetry) return;\n try {\n onTelemetry(event);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"[emporix] telemetry handler threw:\", err);\n }\n },\n [onTelemetry],\n );\n const telemetryValue = useMemo(() => ({ emit: safeEmit }), [safeEmit]);\n\n // Source subscriptions: cache + mutation cache + token-provider + storage.\n // All only active when onTelemetry is provided.\n useEffect(() => {\n if (!onTelemetry) return;\n const startedAt = new Map<string, number>();\n\n const unsubQuery = qc.getQueryCache().subscribe((event) => {\n const key = event.query.queryKey;\n if (!Array.isArray(key) || key[0] !== \"emporix\") return;\n if (event.type === \"updated\") {\n const action = event.action as { type: string };\n if (action.type === \"fetch\") {\n const isRefetch = event.query.state.dataUpdateCount > 0;\n if (isRefetch) {\n safeEmit({\n type: \"query.refetch\",\n queryKey: key,\n tenant: client.tenant,\n reason: \"invalidate\",\n });\n }\n startedAt.set(event.query.queryHash, Date.now());\n } else if (action.type === \"success\") {\n const start = startedAt.get(event.query.queryHash);\n startedAt.delete(event.query.queryHash);\n safeEmit({\n type: \"cache.miss\",\n queryKey: key,\n tenant: client.tenant,\n durationMs: start ? Date.now() - start : 0,\n });\n } else if (action.type === \"error\") {\n startedAt.delete(event.query.queryHash);\n safeEmit({\n type: \"query.error\",\n queryKey: key,\n tenant: client.tenant,\n error: event.query.state.error,\n });\n }\n } else if (event.type === \"observerResultsUpdated\") {\n const s = event.query.state;\n if (s.status === \"success\" && s.fetchStatus === \"idle\" && s.dataUpdateCount > 0) {\n safeEmit({ type: \"cache.hit\", queryKey: key, tenant: client.tenant });\n }\n }\n });\n\n const unsubMut = qc.getMutationCache().subscribe((event) => {\n if (event.type !== \"updated\") return;\n const m = event.mutation;\n const dur = Date.now() - (m.state.submittedAt ?? Date.now());\n const mk = m.options.mutationKey;\n if (m.state.status === \"success\") {\n safeEmit({\n type: \"mutation.success\",\n ...(mk ? { mutationKey: mk as readonly unknown[] } : {}),\n tenant: client.tenant,\n durationMs: dur,\n });\n } else if (m.state.status === \"error\") {\n safeEmit({\n type: \"mutation.error\",\n ...(mk ? { mutationKey: mk as readonly unknown[] } : {}),\n tenant: client.tenant,\n error: m.state.error,\n durationMs: dur,\n });\n }\n });\n\n const unsubAuth = client.tokenProvider.onRefresh?.((evt) =>\n safeEmit({ type: \"auth.refresh\", ...evt, tenant: client.tenant }),\n );\n\n const unsubStorage = value.storage.subscribeAll?.((key) =>\n safeEmit({ type: \"storage.write\", key }),\n );\n\n return () => {\n unsubQuery();\n unsubMut();\n unsubAuth?.();\n unsubStorage?.();\n };\n }, [qc, onTelemetry, client, value.storage, safeEmit]);\n\n // Opt-in reactive customer-token auto-refresh. Registered on the client so\n // the core HttpClient can refresh-and-retry a customer 401. Single-flight is\n // handled in the core registry. Off unless `autoRefreshCustomerToken`.\n useEffect(() => {\n if (!autoRefreshCustomerToken) return;\n const storage = value.storage;\n client.setCustomerTokenRefresher({\n refresh: async () => {\n const refreshToken = storage.getRefreshToken();\n if (!refreshToken) {\n safeEmit({ type: \"auth.refresh\", kind: \"customer\", success: false, tenant: client.tenant });\n onCustomerSessionExpired?.();\n return null;\n }\n try {\n const legalEntityId = storage.getActiveLegalEntityId() ?? undefined;\n const s = await client.customers.refresh({\n refreshToken,\n ...(legalEntityId ? { legalEntityId } : {}),\n });\n storage.setCustomerToken(s.customerToken);\n if (s.refreshToken) storage.setRefreshToken(s.refreshToken);\n safeEmit({ type: \"auth.refresh\", kind: \"customer\", success: true, tenant: client.tenant });\n return s.customerToken;\n } catch {\n safeEmit({ type: \"auth.refresh\", kind: \"customer\", success: false, tenant: client.tenant });\n onCustomerSessionExpired?.();\n return null;\n }\n },\n });\n return () => client.setCustomerTokenRefresher(null);\n }, [autoRefreshCustomerToken, client, value.storage, safeEmit, onCustomerSessionExpired]);\n\n return (\n <EmporixContext.Provider value={value}>\n <EmporixTelemetryContext.Provider value={telemetryValue}>\n <QueryClientProvider client={qc}>\n <SiteContextProvider\n client={client}\n storage={value.storage}\n {...(initialSiteCode !== undefined ? { initialSiteCode } : {})}\n {...(initialLanguage !== undefined ? { initialLanguage } : {})}\n >\n <CompanyContextProvider\n client={client}\n storage={value.storage}\n {...(initialActiveLegalEntityId !== undefined\n ? { initialActiveLegalEntityId }\n : {})}\n >\n {children}\n </CompanyContextProvider>\n </SiteContextProvider>\n </QueryClientProvider>\n </EmporixTelemetryContext.Provider>\n </EmporixContext.Provider>\n );\n}\n\n/**\n * Manages the active-site state. Sits inside `QueryClientProvider` so\n * `setSite` can invalidate the React-Query cache on switch.\n */\nfunction SiteContextProvider({\n client,\n storage,\n initialSiteCode,\n initialLanguage,\n children,\n}: {\n client: EmporixClient;\n storage: EmporixStorage;\n initialSiteCode?: string;\n initialLanguage?: string;\n children: ReactNode;\n}): React.JSX.Element {\n const qc = useQueryClient();\n const [siteCode, setSiteCodeState] = useState<string | null>(() => {\n if (initialSiteCode !== undefined) return initialSiteCode;\n const fromStorage = storage.getSiteCode();\n if (fromStorage !== null) return fromStorage;\n return client.config?.credentials?.storefront?.context?.siteCode ?? null;\n });\n const [currency, setCurrencyState] = useState<string | null>(\n () => client.config?.credentials?.storefront?.context?.currency ?? null,\n );\n const [language, setLanguageState] = useState<string | null>(() => {\n if (initialLanguage !== undefined) return initialLanguage;\n const fromStorage = storage.getLanguage();\n if (fromStorage !== null) return fromStorage;\n return client.config?.credentials?.storefront?.context?.language ?? null;\n });\n const [targetLocation, setTargetLocation] = useState<string | null>(null);\n const [isSwitching, setIsSwitching] = useState(false);\n const [switchError, setSwitchError] = useState<Error | null>(null);\n\n // Mount-time derivation: if a siteCode is already resolved, fetch its DTO\n // once so currency + targetLocation populate without a user-driven switch.\n // A currency seeded from the client config is NOT overridden (the user's /\n // persisted choice wins); only fields still `null` are filled in.\n useEffect(() => {\n if (!siteCode || (currency !== null && targetLocation !== null && language !== null)) return;\n let cancelled = false;\n const token = storage.getCustomerToken();\n const authCtx = token ? auth.customer(token) : auth.anonymous();\n qc.fetchQuery({\n queryKey: [\n \"emporix\",\n \"site-by-code\",\n siteCode,\n { tenant: client.tenant, authKind: authCtx.kind },\n ],\n queryFn: () => client.sites.get(siteCode, authCtx),\n staleTime: 5 * 60_000,\n })\n .then((site) => {\n if (cancelled) return;\n if (currency === null) setCurrencyState(site.currency);\n setTargetLocation(site.homeBase?.address?.country ?? null);\n if (language === null && site.defaultLanguage) {\n setLanguageState(site.defaultLanguage);\n client.setStorefrontContext({ language: site.defaultLanguage });\n }\n })\n .catch(() => {\n // Best-effort — silent. setSite-driven derivation surfaces real errors.\n });\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [siteCode]);\n\n // Push the initially-resolved language (prop / storage / config) to the SDK so\n // the very first reads carry `Accept-Language` — React state alone does not\n // reach the client. Mount-only; later changes go through setLanguage / setSite.\n useEffect(() => {\n if (language) client.setStorefrontContext({ language });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const setSite = useCallback(\n async (code: string | null) => {\n // 1) Optimistic flip — UI moves immediately.\n storage.setSiteCode(code);\n storage.setCartId(null);\n setSiteCodeState(code);\n setSwitchError(null);\n void qc.invalidateQueries({ queryKey: [\"emporix\"] });\n\n if (code === null) {\n setCurrencyState(null);\n setTargetLocation(null);\n return;\n }\n\n setIsSwitching(true);\n try {\n const token = storage.getCustomerToken();\n const authCtx = token ? auth.customer(token) : auth.anonymous();\n // 2) Derive currency + targetLocation from the site DTO (cached 5min).\n const site = await qc.fetchQuery({\n queryKey: [\n \"emporix\",\n \"site-by-code\",\n code,\n { tenant: client.tenant, authKind: authCtx.kind },\n ],\n queryFn: () => client.sites.get(code, authCtx),\n staleTime: 5 * 60_000,\n });\n const nextCurrency = site.currency;\n const nextTarget = site.homeBase?.address?.country ?? null;\n setCurrencyState(nextCurrency);\n setTargetLocation(nextTarget);\n // Reset the language if the new site doesn't support the active one.\n if (site.languages && !site.languages.includes(language ?? \"\") && site.defaultLanguage) {\n setLanguageState(site.defaultLanguage);\n client.setStorefrontContext({ language: site.defaultLanguage });\n }\n // 3) Push everything into the session-context PATCH.\n await client.sessionContext.patch(\n {\n siteCode: code,\n ...(nextCurrency ? { currency: nextCurrency } : {}),\n ...(nextTarget ? { targetLocation: nextTarget } : {}),\n },\n authCtx,\n );\n } catch (e) {\n setSwitchError(e instanceof Error ? e : new Error(String(e)));\n } finally {\n setIsSwitching(false);\n }\n },\n [client, storage, qc, language],\n );\n\n const setCurrency = useCallback(\n async (next: string) => {\n // Carts are currency-bound — drop the guest cart so a fresh one is created.\n storage.setCartId(null);\n setCurrencyState(next);\n setSwitchError(null);\n // Re-bind the anonymous price context so guest pricing uses the new\n // currency even before a session/cart exists (sessionContext.patch can't).\n client.setStorefrontContext({ currency: next });\n void qc.invalidateQueries({ queryKey: [\"emporix\"] });\n setIsSwitching(true);\n try {\n const token = storage.getCustomerToken();\n const authCtx = token ? auth.customer(token) : auth.anonymous();\n // Update an existing server session context (no-op / returns false pre-cart).\n await client.sessionContext.patch(\n { currency: next, ...(siteCode ? { siteCode } : {}) },\n authCtx,\n );\n } catch (e) {\n setSwitchError(e instanceof Error ? e : new Error(String(e)));\n } finally {\n setIsSwitching(false);\n }\n },\n [client, storage, qc, siteCode],\n );\n\n const setLanguage = useCallback(\n async (next: string) => {\n storage.setLanguage(next);\n setLanguageState(next);\n setSwitchError(null);\n // Header source — applies to anonymous + pre-session reads too.\n client.setStorefrontContext({ language: next });\n void qc.invalidateQueries({ queryKey: [\"emporix\"] });\n setIsSwitching(true);\n try {\n const token = storage.getCustomerToken();\n const authCtx = token ? auth.customer(token) : auth.anonymous();\n // Update an existing server session context (no-op / returns false pre-cart).\n await client.sessionContext.patch(\n { language: next, ...(siteCode ? { siteCode } : {}) },\n authCtx,\n );\n } catch (e) {\n setSwitchError(e instanceof Error ? e : new Error(String(e)));\n } finally {\n setIsSwitching(false);\n }\n },\n [client, storage, qc, siteCode],\n );\n\n const value = useMemo<SiteContextValue>(\n () => ({\n siteCode,\n currency,\n targetLocation,\n language,\n setSite,\n setCurrency,\n setLanguage,\n isSwitching,\n switchError,\n }),\n [siteCode, currency, targetLocation, language, setSite, setCurrency, setLanguage, isSwitching, switchError],\n );\n\n return <EmporixSiteContext.Provider value={value}>{children}</EmporixSiteContext.Provider>;\n}\n\n/** Returns the SDK client and token storage. Throws outside an {@link EmporixProvider}. */\nexport function useEmporix(): EmporixContextValue {\n const ctx = useContext(EmporixContext);\n if (!ctx) throw new Error(\"useEmporix must be used within an EmporixProvider\");\n return ctx;\n}\n","import { createContext, useContext } from \"react\";\n\n/**\n * All telemetry events emitted through the EmporixProvider's `onTelemetry`\n * callback. Discriminated by `type` — exhaustive switch is type-safe.\n *\n * Consumers can emit their own `{ type: \"custom\" }` events via\n * {@link useEmporixTelemetry}. Namespace `name` with an app-specific\n * prefix (e.g. `\"app.checkout-cta-click\"`) to avoid collisions with\n * future SDK event types.\n */\nexport type EmporixTelemetryEvent =\n // Cache lifecycle (React-Query QueryCache)\n | { type: \"cache.hit\"; queryKey: readonly unknown[]; tenant: string }\n | {\n type: \"cache.miss\";\n queryKey: readonly unknown[];\n tenant: string;\n durationMs: number;\n }\n | {\n type: \"query.refetch\";\n queryKey: readonly unknown[];\n tenant: string;\n reason: \"invalidate\" | \"focus\" | \"stale\";\n }\n | {\n type: \"query.error\";\n queryKey: readonly unknown[];\n tenant: string;\n error: unknown;\n }\n // Mutation lifecycle\n | {\n type: \"mutation.success\";\n mutationKey?: readonly unknown[];\n tenant: string;\n durationMs: number;\n }\n | {\n type: \"mutation.error\";\n mutationKey?: readonly unknown[];\n tenant: string;\n error: unknown;\n durationMs: number;\n }\n // Auth refresh (SDK-side)\n | {\n type: \"auth.refresh\";\n kind: \"anonymous\" | \"customer\";\n tenant: string;\n success: boolean;\n }\n // Storage writes\n | {\n type: \"storage.write\";\n key: \"customerToken\" | \"cartId\" | \"siteCode\" | \"language\" | \"anonymousSession\" | \"activeLegalEntityId\" | \"refreshToken\" | \"saasToken\";\n }\n // Active-company switch (B2B)\n | {\n type: \"company:switched\";\n from: string | null;\n to: string | null;\n durationMs: number;\n }\n // Consumer-emitted\n | { type: \"custom\"; name: string; props?: Record<string, unknown> };\n\n/** Internal: the React context carrying the emit function down the tree. */\nexport const EmporixTelemetryContext = createContext<{\n emit: (event: EmporixTelemetryEvent) => void;\n} | null>(null);\n\n/**\n * Hook to emit custom telemetry events through the same channel as SDK\n * events. Throws when used outside an {@link EmporixProvider}.\n *\n * When the provider has no `onTelemetry` callback configured, `emit` is a\n * no-op — calling it is safe and incurs no overhead.\n */\nexport function useEmporixTelemetry(): {\n emit: (event: EmporixTelemetryEvent) => void;\n} {\n const ctx = useContext(EmporixTelemetryContext);\n if (!ctx) {\n throw new Error(\"useEmporixTelemetry must be used within an EmporixProvider\");\n }\n return ctx;\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { auth, type EmporixClient, type LegalEntity } from \"@viu/emporix-sdk\";\nimport type { EmporixStorage } from \"./storage\";\nimport { useEmporixTelemetry } from \"./telemetry\";\n\nexport type CompanyMode = \"b2c\" | \"b2b\" | \"unresolved\";\n\nexport interface CompanyContextValue {\n /** Active legal entity. `null` = B2C mode. */\n activeCompany: LegalEntity | null;\n /** All legal entities the customer is assigned to. */\n myCompanies: LegalEntity[];\n /**\n * `b2b` = a company is active; `b2c` = none active (and ≤1 available);\n * `unresolved` = multiple companies available, none picked yet — the\n * storefront must render a picker.\n */\n mode: CompanyMode;\n status: \"idle\" | \"loading\" | \"switching\" | \"error\";\n error: unknown;\n /**\n * Switch the active company. Eagerly calls\n * `client.customers.refresh({ legalEntityId })` so the customer token is\n * rescoped server-side, drops the cart id, then invalidates company-scoped\n * queries. Falls back to a local-state-only update when no refresh token\n * is in storage (e.g. fresh page load with memory storage).\n */\n setActiveCompany: (legalEntityId: string | null) => Promise<void>;\n refetchMyCompanies: () => Promise<void>;\n}\n\nconst NULL_CTX: CompanyContextValue = {\n activeCompany: null,\n myCompanies: [],\n mode: \"b2c\",\n status: \"idle\",\n error: null,\n setActiveCompany: async () => {\n throw new Error(\"CompanyContextProvider not mounted\");\n },\n refetchMyCompanies: async () => {},\n};\n\nexport const EmporixCompanyContext = createContext<CompanyContextValue>(NULL_CTX);\n\n/** Returns the active-company context. Safe outside the provider — returns idle B2C defaults. */\nexport function useActiveCompany(): CompanyContextValue {\n return useContext(EmporixCompanyContext);\n}\n\nexport interface CompanyContextProviderProps {\n client: EmporixClient;\n storage: EmporixStorage;\n initialActiveLegalEntityId?: string | null;\n children: ReactNode;\n}\n\nexport function CompanyContextProvider({\n client,\n storage,\n initialActiveLegalEntityId,\n children,\n}: CompanyContextProviderProps): React.JSX.Element {\n const qc = useQueryClient();\n const { emit } = useEmporixTelemetry();\n const [myCompanies, setMyCompanies] = useState<LegalEntity[]>([]);\n const [activeCompany, setActive] = useState<LegalEntity | null>(null);\n const [status, setStatus] = useState<CompanyContextValue[\"status\"]>(\"idle\");\n const [error, setError] = useState<unknown>(null);\n // Ref so switchTo can capture the latest `activeCompany` for telemetry `from`.\n // Written in an effect: render-phase ref writes are illegal under concurrent\n // rendering (an abandoned render's value could leak into a committed pass).\n const activeRef = useRef<LegalEntity | null>(null);\n useEffect(() => {\n activeRef.current = activeCompany;\n }, [activeCompany]);\n\n // Serializes token-rotating switches: two concurrent switchTo calls would\n // both read the same refresh token; with server-side rotation the second\n // consumes a stale token (401, worst case session revocation).\n const switchChain = useRef<Promise<void>>(Promise.resolve());\n\n /** Internal: eager refresh + storage write + state update. */\n const switchTo = useCallback(\n (target: LegalEntity | null): Promise<void> => {\n const run = async (): Promise<void> => {\n const start = Date.now();\n const from = activeRef.current?.id ?? null;\n const refreshToken = storage.getRefreshToken();\n const token = storage.getCustomerToken();\n if (!refreshToken || !token) {\n // Local-state-only fallback — no rescope possible.\n setActive(target);\n storage.setActiveLegalEntityId(target?.id ?? null);\n } else {\n const next = await client.customers.refresh({\n refreshToken,\n ...(target ? { legalEntityId: target.id } : {}),\n });\n storage.setCustomerToken(next.customerToken);\n if (next.refreshToken) storage.setRefreshToken(next.refreshToken);\n storage.setCartId(null);\n storage.setActiveLegalEntityId(target?.id ?? null);\n setActive(target);\n qc.invalidateQueries({\n predicate: (q) =>\n Array.isArray(q.queryKey) &&\n q.queryKey.some(\n (k) =>\n k === \"cart\" ||\n k === \"companies\" ||\n k === \"customer\" ||\n k === from ||\n (target !== null && k === target.id),\n ),\n });\n }\n emit({\n type: \"company:switched\",\n from,\n to: target?.id ?? null,\n durationMs: Date.now() - start,\n });\n };\n // Chain on the previous switch so concurrent calls run in order and each\n // reads the refresh token the prior switch rotated to.\n const task = switchChain.current.then(run, run);\n switchChain.current = task.catch(() => {\n /* keep the chain alive after a failed switch */\n });\n return task;\n },\n [client, storage, qc, emit],\n );\n\n const load = useCallback(\n async (signal?: { cancelled: boolean }) => {\n const token = storage.getCustomerToken();\n if (!token) {\n if (signal?.cancelled) return;\n setMyCompanies([]);\n setActive(null);\n setStatus(\"idle\");\n return;\n }\n setStatus(\"loading\");\n try {\n const companies = await client.companies.listMine(auth.customer(token));\n if (signal?.cancelled) return; // unmounted (StrictMode probe) — no state, no auto-switch\n setMyCompanies(companies);\n const persisted = initialActiveLegalEntityId ?? storage.getActiveLegalEntityId();\n const matched = persisted ? companies.find((c) => c.id === persisted) ?? null : null;\n if (matched) {\n setActive(matched);\n if (storage.getActiveLegalEntityId() !== matched.id) {\n storage.setActiveLegalEntityId(matched.id ?? null);\n }\n } else if (companies.length === 1) {\n await switchTo(companies[0] ?? null);\n } else {\n setActive(null);\n if (persisted && !matched) storage.setActiveLegalEntityId(null);\n }\n if (signal?.cancelled) return;\n setStatus(\"idle\");\n } catch (e) {\n if (signal?.cancelled) return;\n setError(e);\n setStatus(\"error\");\n }\n },\n [client, storage, initialActiveLegalEntityId, switchTo],\n );\n\n useEffect(() => {\n const signal = { cancelled: false };\n void load(signal);\n return () => {\n signal.cancelled = true;\n };\n }, [load]);\n\n // Re-run bootstrap only on token-presence transitions (login/logout). A\n // mid-session token swap (e.g. switch-driven refresh) keeps prev/next both\n // truthy and is ignored — otherwise the auto-pick branch would clobber an\n // explicit B2C choice as soon as the new token is written.\n useEffect(() => {\n let prev = storage.getCustomerToken();\n return storage.subscribe?.((next) => {\n const becameAuth = !prev && next;\n const becameUnauth = prev && !next;\n prev = next;\n if (becameAuth || becameUnauth) void load();\n });\n }, [storage, load]);\n\n const setActiveCompany = useCallback(\n async (legalEntityId: string | null) => {\n setStatus(\"switching\");\n try {\n if (legalEntityId === null) {\n await switchTo(null);\n } else {\n const target = myCompanies.find((c) => c.id === legalEntityId) ?? null;\n if (!target) throw new Error(`setActiveCompany: unknown legalEntityId ${legalEntityId}`);\n await switchTo(target);\n }\n setStatus(\"idle\");\n } catch (e) {\n setError(e);\n setStatus(\"error\");\n throw e;\n }\n },\n [myCompanies, switchTo],\n );\n\n const value = useMemo<CompanyContextValue>(() => {\n const mode: CompanyMode = activeCompany\n ? \"b2b\"\n : myCompanies.length > 1\n ? \"unresolved\"\n : \"b2c\";\n return {\n activeCompany,\n myCompanies,\n mode,\n status,\n error,\n setActiveCompany,\n refetchMyCompanies: load,\n };\n }, [activeCompany, myCompanies, status, error, setActiveCompany, load]);\n\n return (\n <EmporixCompanyContext.Provider value={value}>{children}</EmporixCompanyContext.Provider>\n );\n}\n"],"mappings":";;;;;;AAAA,SAAS,iBAAAA,gBAAe,eAAAC,cAAa,cAAAC,aAAY,aAAAC,YAAW,WAAAC,UAAS,UAAAC,SAAQ,YAAAC,iBAAgC;AAC7G,SAAS,aAAa,qBAAqB,kBAAAC,uBAAsB;AACjE,SAAS,QAAAC,aAAgC;;;ACFzC,SAAS,eAAe,kBAAkB;AAqEnC,IAAM,0BAA0B,cAE7B,IAAI;AASP,SAAS,sBAEd;AACA,QAAM,MAAM,WAAW,uBAAuB;AAC9C,MAAI,CAAC,KAAK;AACR,UAAM,IAAI,MAAM,4DAA4D;AAAA,EAC9E;AACA,SAAO;AACT;;;ACxFA;AAAA,EACE,iBAAAC;AAAA,EACA;AAAA,EACA,cAAAC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,sBAAsB;AAC/B,SAAS,YAAkD;AA0OvD;AA5MJ,IAAM,WAAgC;AAAA,EACpC,eAAe;AAAA,EACf,aAAa,CAAC;AAAA,EACd,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,kBAAkB,YAAY;AAC5B,UAAM,IAAI,MAAM,oCAAoC;AAAA,EACtD;AAAA,EACA,oBAAoB,YAAY;AAAA,EAAC;AACnC;AAEO,IAAM,wBAAwBC,eAAmC,QAAQ;AAGzE,SAAS,mBAAwC;AACtD,SAAOC,YAAW,qBAAqB;AACzC;AASO,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAmD;AACjD,QAAM,KAAK,eAAe;AAC1B,QAAM,EAAE,KAAK,IAAI,oBAAoB;AACrC,QAAM,CAAC,aAAa,cAAc,IAAI,SAAwB,CAAC,CAAC;AAChE,QAAM,CAAC,eAAe,SAAS,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A,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,CAAC,UAAU,UAAU,gBAAgB,UAAU,SAAS,aAAa,aAAa,aAAa,WAAW;AAAA,EAC5G;AAEA,SAAO,gBAAAF,KAAC,mBAAmB,UAAnB,EAA4B,OAAe,UAAS;AAC9D;AAGO,SAAS,aAAkC;AAChD,QAAM,MAAMU,YAAW,cAAc;AACrC,MAAI,CAAC,IAAK,OAAM,IAAI,MAAM,mDAAmD;AAC7E,SAAO;AACT;","names":["createContext","useCallback","useContext","useEffect","useMemo","useRef","useState","useQueryClient","auth","createContext","useContext","createContext","useContext","jsx","createContext","useMemo","useState","useRef","useCallback","useEffect","storage","useQueryClient","auth","useContext"]}